The npm application Copyright (c) npm, Inc. and Contributors Licensed on the terms of The Artistic License 2.0 Node package dependencies of the npm application Copyright (c) their respective copyright owners Licensed on their respective license terms The npm public registry at https://registry.npmjs.org and the npm website at https://www.npmjs.com Operated by npm, Inc. Use governed by terms published on https://www.npmjs.com "Node.js" Trademark Joyent, Inc., https://joyent.com Neither npm nor npm, Inc. are affiliated with Joyent, Inc. The Node.js application Project of Node Foundation, https://nodejs.org The npm Logo Copyright (c) Mathias Pettersson and Brian Hammond "Gubblebum Blocky" typeface Copyright (c) Tjarda Koster, https://jelloween.deviantart.com Used with permission -------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------- # npm - a JavaScript package manager ### Requirements You should be running a currently supported version of [Node.js](https://nodejs.org/en/download/) to run **`npm`**. For a list of which versions of Node.js are currently supported, please see the [Node.js releases](https://nodejs.org/en/about/previous-releases) page. ### Installation **`npm`** comes bundled with [**`node`**](https://nodejs.org/), & most third-party distributions, by default. Officially supported downloads/distributions can be found at: [nodejs.org/en/download](https://nodejs.org/en/download) #### Direct Download You can download & install **`npm`** directly from [**npmjs**.com](https://npmjs.com/) using our custom `install.sh` script: ```bash curl -qL https://www.npmjs.com/install.sh | sh ``` #### Node Version Managers If you're looking to manage multiple versions of **`Node.js`** &/or **`npm`**, consider using a [node version manager](https://github.com/search?q=node+version+manager+archived%3Afalse&type=repositories&ref=advsearch) ### Usage ```bash npm ``` ### Links & Resources * [**Documentation**](https://docs.npmjs.com/) - Official docs & how-tos for all things **npm** * Note: you can also search docs locally with `npm help-search ` * [**Bug Tracker**](https://github.com/npm/cli/issues) - Search or submit bugs against the CLI * [**Roadmap**](https://github.com/orgs/github/projects/4247/views/1?filterQuery=npm) - Track & follow along with our public roadmap * [**Community Feedback and Discussions**](https://github.com/orgs/community/discussions/categories/npm) - Contribute ideas & discussion around the npm registry, website & CLI * [**RFCs**](https://github.com/npm/rfcs) - Contribute ideas & specifications for the API/design of the npm CLI * [**Service Status**](https://status.npmjs.org/) - Monitor the current status & see incident reports for the website & registry * [**Project Status**](https://npm.github.io/statusboard/) - See the health of all our maintained OSS projects in one view * [**Events Calendar**](https://calendar.google.com/calendar/u/0/embed?src=npmjs.com_oonluqt8oftrt0vmgrfbg6q6go@group.calendar.google.com) - Keep track of our Open RFC calls, releases, meetups, conferences & more * [**Support**](https://www.npmjs.com/support) - Experiencing problems with the **npm** [website](https://npmjs.com) or [registry](https://registry.npmjs.org)? File a ticket [here](https://www.npmjs.com/support) ### Acknowledgments * `npm` is configured to use the **npm Public Registry** at [https://registry.npmjs.org](https://registry.npmjs.org) by default; Usage of this registry is subject to **Terms of Use** available at [https://npmjs.com/policies/terms](https://npmjs.com/policies/terms) * You can configure `npm` to use any other compatible registry you prefer. You can read more about configuring third-party registries [here](https://docs.npmjs.com/cli/v7/using-npm/registry) ### FAQ on Branding #### Is it "npm" or "NPM" or "Npm"? **`npm`** should never be capitalized unless it is being displayed in a location that is customarily all-capitals (ex. titles on `man` pages). #### Is "npm" an acronym for "Node Package Manager"? Contrary to popular belief, **`npm`** **is not** in fact an acronym for "Node Package Manager"; It is a recursive bacronymic abbreviation for **"npm is not an acronym"** (if the project was named "ninaa", then it would be an acronym). The precursor to **`npm`** was actually a bash utility named **"pm"**, which was the shortform name of **"pkgmakeinst"** - a bash function that installed various things on various platforms. If **`npm`** were to ever have been considered an acronym, it would be as "node pm" or, potentially "new pm". #!/usr/bin/env sh if [ "x$npm_config_node_gyp" = "x" ]; then node "`dirname "$0"`/../../node_modules/node-gyp/bin/node-gyp.js" "$@" else "$npm_config_node_gyp" "$@" fi if not defined npm_config_node_gyp ( node "%~dp0\..\..\node_modules\node-gyp\bin\node-gyp.js" %* ) else ( node "%npm_config_node_gyp%" %* ) #!/usr/bin/env bash # This is used by the Node.js installer, which expects the cygwin/mingw # shell script to already be present in the npm dependency folder. (set -o igncr) 2>/dev/null && set -o igncr; # cygwin encoding fix basedir=`dirname "$0"` case `uname` in *CYGWIN*) basedir=`cygpath -w "$basedir"`;; esac if [ `uname` = 'Linux' ] && type wslpath &>/dev/null ; then IS_WSL="true" fi function no_node_dir { # if this didn't work, then everything else below will fail echo "Could not determine Node.js install directory" >&2 exit 1 } NODE_EXE="$basedir/node.exe" if ! [ -x "$NODE_EXE" ]; then NODE_EXE="$basedir/node" fi if ! [ -x "$NODE_EXE" ]; then NODE_EXE=node fi # this path is passed to node.exe, so it needs to match whatever # kind of paths Node.js thinks it's using, typically win32 paths. CLI_BASEDIR="$("$NODE_EXE" -p 'require("path").dirname(process.execPath)' 2> /dev/null)" if [ $? -ne 0 ]; then # this fails under WSL 1 so add an additional message. we also suppress stderr above # because the actual error raised is not helpful. in WSL 1 node.exe cannot handle # output redirection properly. See https://github.com/microsoft/WSL/issues/2370 if [ "$IS_WSL" == "true" ]; then echo "WSL 1 is not supported. Please upgrade to WSL 2 or above." >&2 fi no_node_dir fi NPM_PREFIX_JS="$CLI_BASEDIR/node_modules/npm/bin/npm-prefix.js" NPM_CLI_JS="$CLI_BASEDIR/node_modules/npm/bin/npm-cli.js" NPM_PREFIX=`"$NODE_EXE" "$NPM_PREFIX_JS"` if [ $? -ne 0 ]; then no_node_dir fi NPM_PREFIX_NPM_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npm-cli.js" # a path that will fail -f test on any posix bash NPM_WSL_PATH="/.." # WSL can run Windows binaries, so we have to give it the win32 path # however, WSL bash tests against posix paths, so we need to construct that # to know if npm is installed globally. if [ "$IS_WSL" == "true" ]; then NPM_WSL_PATH=`wslpath "$NPM_PREFIX_NPM_CLI_JS"` fi if [ -f "$NPM_PREFIX_NPM_CLI_JS" ] || [ -f "$NPM_WSL_PATH" ]; then NPM_CLI_JS="$NPM_PREFIX_NPM_CLI_JS" fi "$NODE_EXE" "$NPM_CLI_JS" "$@" #!/usr/bin/env node require('../lib/cli.js')(process) #!/usr/bin/env node // This is a single-use bin to help windows discover the proper prefix for npm // without having to load all of npm first // It does not accept argv params const path = require('node:path') const Config = require('@npmcli/config') const { definitions, flatten, shorthands } = require('@npmcli/config/lib/definitions') const config = new Config({ npmPath: path.dirname(__dirname), // argv is explicitly not looked at since prefix is not something that can be changed via argv argv: [], definitions, flatten, shorthands, excludeNpmCwd: false, }) async function main () { try { await config.load() // eslint-disable-next-line no-console console.log(config.globalPrefix) } catch (err) { // eslint-disable-next-line no-console console.error(err) process.exit(1) } } main() :: Created by npm, please don't edit manually. @ECHO OFF SETLOCAL SET "NODE_EXE=%~dp0\node.exe" IF NOT EXIST "%NODE_EXE%" ( SET "NODE_EXE=node" ) SET "NPM_PREFIX_JS=%~dp0\node_modules\npm\bin\npm-prefix.js" SET "NPM_CLI_JS=%~dp0\node_modules\npm\bin\npm-cli.js" FOR /F "delims=" %%F IN ('CALL "%NODE_EXE%" "%NPM_PREFIX_JS%"') DO ( SET "NPM_PREFIX_NPM_CLI_JS=%%F\node_modules\npm\bin\npm-cli.js" ) IF EXIST "%NPM_PREFIX_NPM_CLI_JS%" ( SET "NPM_CLI_JS=%NPM_PREFIX_NPM_CLI_JS%" ) "%NODE_EXE%" "%NPM_CLI_JS%" %* #!/usr/bin/env pwsh $NODE_EXE="$PSScriptRoot/node.exe" if (-not (Test-Path $NODE_EXE)) { $NODE_EXE="$PSScriptRoot/node" } if (-not (Test-Path $NODE_EXE)) { $NODE_EXE="node" } $NPM_PREFIX_JS="$PSScriptRoot/node_modules/npm/bin/npm-prefix.js" $NPM_CLI_JS="$PSScriptRoot/node_modules/npm/bin/npm-cli.js" $NPM_PREFIX=(& $NODE_EXE $NPM_PREFIX_JS) if ($LASTEXITCODE -ne 0) { Write-Host "Could not determine Node.js install directory" exit 1 } $NPM_PREFIX_NPM_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npm-cli.js" if (Test-Path $NPM_PREFIX_NPM_CLI_JS) { $NPM_CLI_JS=$NPM_PREFIX_NPM_CLI_JS } # Support pipeline input if ($MyInvocation.ExpectingInput) { $input | & $NODE_EXE $NPM_CLI_JS $args } else { & $NODE_EXE $NPM_CLI_JS $args } exit $LASTEXITCODE #!/usr/bin/env bash # This is used by the Node.js installer, which expects the cygwin/mingw # shell script to already be present in the npm dependency folder. (set -o igncr) 2>/dev/null && set -o igncr; # cygwin encoding fix basedir=`dirname "$0"` case `uname` in *CYGWIN*) basedir=`cygpath -w "$basedir"`;; esac if [ `uname` = 'Linux' ] && type wslpath &>/dev/null ; then IS_WSL="true" fi function no_node_dir { # if this didn't work, then everything else below will fail echo "Could not determine Node.js install directory" >&2 exit 1 } NODE_EXE="$basedir/node.exe" if ! [ -x "$NODE_EXE" ]; then NODE_EXE="$basedir/node" fi if ! [ -x "$NODE_EXE" ]; then NODE_EXE=node fi # this path is passed to node.exe, so it needs to match whatever # kind of paths Node.js thinks it's using, typically win32 paths. CLI_BASEDIR="$("$NODE_EXE" -p 'require("path").dirname(process.execPath)' 2> /dev/null)" if [ $? -ne 0 ]; then # this fails under WSL 1 so add an additional message. we also suppress stderr above # because the actual error raised is not helpful. in WSL 1 node.exe cannot handle # output redirection properly. See https://github.com/microsoft/WSL/issues/2370 if [ "$IS_WSL" == "true" ]; then echo "WSL 1 is not supported. Please upgrade to WSL 2 or above." >&2 fi no_node_dir fi NPM_PREFIX_JS="$CLI_BASEDIR/node_modules/npm/bin/npm-prefix.js" NPX_CLI_JS="$CLI_BASEDIR/node_modules/npm/bin/npx-cli.js" NPM_PREFIX=`"$NODE_EXE" "$NPM_PREFIX_JS"` if [ $? -ne 0 ]; then no_node_dir fi NPM_PREFIX_NPX_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npx-cli.js" # a path that will fail -f test on any posix bash NPX_WSL_PATH="/.." # WSL can run Windows binaries, so we have to give it the win32 path # however, WSL bash tests against posix paths, so we need to construct that # to know if npm is installed globally. if [ "$IS_WSL" == "true" ]; then NPX_WSL_PATH=`wslpath "$NPM_PREFIX_NPX_CLI_JS"` fi if [ -f "$NPM_PREFIX_NPX_CLI_JS" ] || [ -f "$NPX_WSL_PATH" ]; then NPX_CLI_JS="$NPM_PREFIX_NPX_CLI_JS" fi "$NODE_EXE" "$NPX_CLI_JS" "$@" #!/usr/bin/env node const cli = require('../lib/cli.js') // run the resulting command as `npm exec ...args` process.argv[1] = require.resolve('./npm-cli.js') process.argv.splice(2, 0, 'exec') // TODO: remove the affordances for removed items in npm v9 const removedSwitches = new Set([ 'always-spawn', 'ignore-existing', 'shell-auto-fallback', ]) const removedOpts = new Set([ 'npm', 'node-arg', 'n', ]) const removed = new Set([ ...removedSwitches, ...removedOpts, ]) const { definitions, shorthands } = require('@npmcli/config/lib/definitions') const npmSwitches = Object.entries(definitions) .filter(([, { type }]) => type === Boolean || (Array.isArray(type) && type.includes(Boolean))) .map(([key]) => key) // things that don't take a value const switches = new Set([ ...removedSwitches, ...npmSwitches, 'no-install', 'quiet', 'q', 'version', 'v', 'help', 'h', ]) // things that do take a value const opts = new Set([ ...removedOpts, 'package', 'p', 'cache', 'userconfig', 'call', 'c', 'shell', 'npm', 'node-arg', 'n', ]) // break out of loop when we find a positional argument or -- // If we find a positional arg, we shove -- in front of it, and // let the normal npm cli handle the rest. let i let sawRemovedFlags = false for (i = 3; i < process.argv.length; i++) { const arg = process.argv[i] if (arg === '--') { break } else if (/^-/.test(arg)) { const [key, ...v] = arg.replace(/^-+/, '').split('=') switch (key) { case 'p': process.argv[i] = ['--package', ...v].join('=') break case 'shell': process.argv[i] = ['--script-shell', ...v].join('=') break case 'no-install': process.argv[i] = '--yes=false' break default: // resolve shorthands and run again if (shorthands[key] && !removed.has(key)) { const a = [...shorthands[key]] if (v.length) { a.push(v.join('=')) } process.argv.splice(i, 1, ...a) i-- continue } break } if (removed.has(key)) { // eslint-disable-next-line no-console console.error(`npx: the --${key} argument has been removed.`) sawRemovedFlags = true process.argv.splice(i, 1) i-- } if (v.length === 0 && !switches.has(key) && (opts.has(key) || !/^-/.test(process.argv[i + 1]))) { // value will be next argument, skip over it. if (removed.has(key)) { // also remove the value for the cut key. process.argv.splice(i + 1, 1) } else { i++ } } } else { // found a positional arg, put -- in front of it, and we're done process.argv.splice(i, 0, '--') break } } if (sawRemovedFlags) { // eslint-disable-next-line no-console console.error('See `npm help exec` for more information') } cli(process) :: Created by npm, please don't edit manually. @ECHO OFF SETLOCAL SET "NODE_EXE=%~dp0\node.exe" IF NOT EXIST "%NODE_EXE%" ( SET "NODE_EXE=node" ) SET "NPM_PREFIX_JS=%~dp0\node_modules\npm\bin\npm-prefix.js" SET "NPX_CLI_JS=%~dp0\node_modules\npm\bin\npx-cli.js" FOR /F "delims=" %%F IN ('CALL "%NODE_EXE%" "%NPM_PREFIX_JS%"') DO ( SET "NPM_PREFIX_NPX_CLI_JS=%%F\node_modules\npm\bin\npx-cli.js" ) IF EXIST "%NPM_PREFIX_NPX_CLI_JS%" ( SET "NPX_CLI_JS=%NPM_PREFIX_NPX_CLI_JS%" ) "%NODE_EXE%" "%NPX_CLI_JS%" %* #!/usr/bin/env pwsh $NODE_EXE="$PSScriptRoot/node.exe" if (-not (Test-Path $NODE_EXE)) { $NODE_EXE="$PSScriptRoot/node" } if (-not (Test-Path $NODE_EXE)) { $NODE_EXE="node" } $NPM_PREFIX_JS="$PSScriptRoot/node_modules/npm/bin/npm-prefix.js" $NPX_CLI_JS="$PSScriptRoot/node_modules/npm/bin/npx-cli.js" $NPM_PREFIX=(& $NODE_EXE $NPM_PREFIX_JS) if ($LASTEXITCODE -ne 0) { Write-Host "Could not determine Node.js install directory" exit 1 } $NPM_PREFIX_NPX_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npx-cli.js" if (Test-Path $NPM_PREFIX_NPX_CLI_JS) { $NPX_CLI_JS=$NPM_PREFIX_NPX_CLI_JS } # Support pipeline input if ($MyInvocation.ExpectingInput) { $input | & $NODE_EXE $NPX_CLI_JS $args } else { & $NODE_EXE $NPX_CLI_JS $args } exit $LASTEXITCODE if (require.main === module) { require('./lib/cli.js')(process) } else { throw new Error('The programmatic API was removed in npm v8.0.0') } const { log } = require('proc-log') const BaseCommand = require('./base-cmd.js') // This is the base for all commands whose execWorkspaces just gets // a list of workspace names and passes it on to new Arborist() to // be able to run a filtered Arborist.reify() at some point. class ArboristCmd extends BaseCommand { get isArboristCmd () { return true } static params = [ 'workspace', 'workspaces', 'include-workspace-root', 'install-links', ] static workspaces = true static ignoreImplicitWorkspace = false static checkDevEngines = true constructor (npm) { super(npm) const { config } = this.npm // when location isn't set and global isn't true check for a package.json at // the localPrefix and set the location to project if found const locationProject = config.get('location') === 'project' || ( config.isDefault('location') // this is different then `npm.global` which falls back to checking // location which we do not want to use here && !config.get('global') && npm.localPackage ) // if audit is not set and we are in global mode and location is not project // and we assume its not a project related context, then we set audit=false if (config.isDefault('audit') && (this.npm.global || !locationProject)) { config.set('audit', false) } else if (this.npm.global && config.get('audit')) { log.warn('config', 'includes both --global and --audit, which is currently unsupported.') } } async execWorkspaces (args) { await this.setWorkspaces() return this.exec(args) } } module.exports = ArboristCmd const { log } = require('proc-log') class BaseCommand { // these defaults can be overridden by individual commands static workspaces = false static ignoreImplicitWorkspace = true static checkDevEngines = false // these should always be overridden by individual commands static name = null static description = null static params = null // this is a static so that we can read from it without instantiating a command // which would require loading the config static get describeUsage () { const { definitions } = require('@npmcli/config/lib/definitions') const { aliases: cmdAliases } = require('./utils/cmd-list') const seenExclusive = new Set() const wrapWidth = 80 const { description, usage = [''], name, params } = this const fullUsage = [ `${description}`, '', 'Usage:', ...usage.map(u => `npm ${name} ${u}`.trim()), ] if (params) { let results = '' let line = '' for (const param of params) { /* istanbul ignore next */ if (seenExclusive.has(param)) { continue } const { exclusive } = definitions[param] let paramUsage = `${definitions[param].usage}` if (exclusive) { const exclusiveParams = [paramUsage] seenExclusive.add(param) for (const e of exclusive) { seenExclusive.add(e) exclusiveParams.push(definitions[e].usage) } paramUsage = `${exclusiveParams.join('|')}` } paramUsage = `[${paramUsage}]` if (line.length + paramUsage.length > wrapWidth) { results = [results, line].filter(Boolean).join('\n') line = '' } line = [line, paramUsage].filter(Boolean).join(' ') } fullUsage.push('') fullUsage.push('Options:') fullUsage.push([results, line].filter(Boolean).join('\n')) } const aliases = Object.entries(cmdAliases).reduce((p, [k, v]) => { return p.concat(v === name ? k : []) }, []) if (aliases.length) { const plural = aliases.length === 1 ? '' : 'es' fullUsage.push('') fullUsage.push(`alias${plural}: ${aliases.join(', ')}`) } fullUsage.push('') fullUsage.push(`Run "npm help ${name}" for more info`) return fullUsage.join('\n') } constructor (npm) { this.npm = npm const { config } = this.npm if (!this.constructor.skipConfigValidation) { config.validate() } if (config.get('workspaces') === false && config.get('workspace').length) { throw new Error('Can not use --no-workspaces and --workspace at the same time') } } get name () { return this.constructor.name } get description () { return this.constructor.description } get params () { return this.constructor.params } get usage () { return this.constructor.describeUsage } usageError (prefix = '') { if (prefix) { prefix += '\n\n' } return Object.assign(new Error(`\n${prefix}${this.usage}`), { code: 'EUSAGE', }) } // Compare the number of entries with what was expected checkExpected (entries) { if (!this.npm.config.isDefault('expect-results')) { const expected = this.npm.config.get('expect-results') if (!!entries !== !!expected) { log.warn(this.name, `Expected ${expected ? '' : 'no '}results, got ${entries}`) process.exitCode = 1 } } else if (!this.npm.config.isDefault('expect-result-count')) { const expected = this.npm.config.get('expect-result-count') if (expected !== entries) { log.warn(this.name, `Expected ${expected} result${expected === 1 ? '' : 's'}, got ${entries}`) process.exitCode = 1 } } } // Checks the devEngines entry in the package.json at this.localPrefix async checkDevEngines () { const force = this.npm.flatOptions.force const { devEngines } = await require('@npmcli/package-json') .normalize(this.npm.config.localPrefix) .then(p => p.content) .catch(() => ({})) if (typeof devEngines === 'undefined') { return } const { checkDevEngines, currentEnv } = require('npm-install-checks') const current = currentEnv.devEngines({ nodeVersion: this.npm.nodeVersion, npmVersion: this.npm.version, }) const failures = checkDevEngines(devEngines, current) const warnings = failures.filter(f => f.isWarn) const errors = failures.filter(f => f.isError) const genMsg = (failure, i = 0) => { return [...new Set([ // eslint-disable-next-line i === 0 ? 'The developer of this package has specified the following through devEngines' : '', `${failure.message}`, `${failure.errors.map(e => e.message).join('\n')}`, ])].filter(v => v).join('\n') } [...warnings, ...(force ? errors : [])].forEach((failure, i) => { const message = genMsg(failure, i) log.warn('EBADDEVENGINES', message) log.warn('EBADDEVENGINES', { current: failure.current, required: failure.required, }) }) if (force) { return } if (errors.length) { const failure = errors[0] const message = genMsg(failure) throw Object.assign(new Error(message), { engine: failure.engine, code: 'EBADDEVENGINES', current: failure.current, required: failure.required, }) } } async setWorkspaces () { const { relative } = require('node:path') const includeWorkspaceRoot = this.isArboristCmd ? false : this.npm.config.get('include-workspace-root') const prefixInsideCwd = relative(this.npm.localPrefix, process.cwd()).startsWith('..') const relativeFrom = prefixInsideCwd ? this.npm.localPrefix : process.cwd() const filters = this.npm.config.get('workspace') const getWorkspaces = require('./utils/get-workspaces.js') const ws = await getWorkspaces(filters, { path: this.npm.localPrefix, includeWorkspaceRoot, relativeFrom, }) this.workspaces = ws this.workspaceNames = [...ws.keys()] this.workspacePaths = [...ws.values()] } } module.exports = BaseCommand try { const { enableCompileCache } = require('node:module') /* istanbul ignore next */ if (enableCompileCache) { enableCompileCache() } } catch (e) { /* istanbul ignore next */ } const validateEngines = require('./cli/validate-engines.js') const cliEntry = require('node:path').resolve(__dirname, 'cli/entry.js') module.exports = (process) => validateEngines(process, () => require(cliEntry)) // Separated out for easier unit testing module.exports = async (process, validateEngines) => { const fs = require('node:fs') const now = performance.now() // set it here so that regardless of what happens later, we don't // leak any private CLI configs to other programs process.title = 'npm' // Patch the global fs module here at the app level require('graceful-fs').gracefulify(fs) const satisfies = require('semver/functions/satisfies') const ExitHandler = require('./exit-handler.js') const exitHandler = new ExitHandler({ process }) const Npm = require('../npm.js') const npm = new Npm() exitHandler.setNpm(npm) // only log node and npm paths in argv initially since argv can contain sensitive info. a cleaned version will be logged later const { log, output } = require('proc-log') log.verbose('cli', process.argv.slice(0, 2).join(' ')) log.info('using', 'npm@%s', npm.version) log.info('using', 'node@%s', process.version) // At this point we've required a few files and can be pretty sure we dont contain invalid syntax for this version of node. It's possible a lazy require would, but that's unlikely enough that it's not worth catching anymore and we attach the more important exit handlers. validateEngines.off() exitHandler.registerUncaughtHandlers() // It is now safe to log a warning if they are using a version of node that is not going to fail on syntax errors but is still unsupported and untested and might not work reliably. This is safe to use the logger now which we want since this will show up in the error log too. if (!satisfies(validateEngines.node, validateEngines.engines)) { log.warn('cli', validateEngines.unsupportedMessage) } // Now actually fire up npm and run the command. // This is how to use npm programmatically: try { const { exec, command, args } = await npm.load() if (!exec) { return exitHandler.exit() } if (!command) { output.standard(npm.usage) process.exitCode = 1 return exitHandler.exit() } // Options are prefixed by a hyphen-minus (-, \u2d). // Other dash-type chars look similar but are invalid. const nonDashArgs = npm.argv.filter(a => /^[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/.test(a)) if (nonDashArgs.length) { log.error( 'arg', 'Argument starts with non-ascii dash, this is probably invalid:', require('@npmcli/redact').redactLog(nonDashArgs.join(', ')) ) } const execPromise = npm.exec(command, args) // this is async but we dont await it, since its ok if it doesnt // finish before the command finishes running. it uses command and argv // so it must be initiated here, after the command name is set const updateNotifier = require('./update-notifier.js') // eslint-disable-next-line promise/catch-or-return updateNotifier(npm).then((msg) => (npm.updateNotification = msg)) await execPromise return exitHandler.exit() } catch (err) { return exitHandler.exit(err) } } const { log, output, META } = require('proc-log') const { errorMessage, getExitCodeFromError } = require('../utils/error-message.js') class ExitHandler { #npm = null #process = null #exited = false #exitErrorMessage = false #noNpmError = false get #hasNpm () { return !!this.#npm } get #loaded () { return !!this.#npm?.loaded } get #showExitErrorMessage () { if (!this.#loaded) { return false } if (!this.#exited) { return true } return this.#exitErrorMessage } get #notLoadedOrExited () { return !this.#loaded && !this.#exited } setNpm (npm) { this.#npm = npm } constructor ({ process }) { this.#process = process this.#process.on('exit', this.#handleProcesExitAndReset) } registerUncaughtHandlers () { this.#process.on('uncaughtException', this.#handleExit) this.#process.on('unhandledRejection', this.#handleExit) } exit (err) { this.#handleExit(err) } #handleProcesExitAndReset = (code) => { this.#handleProcessExit(code) // Reset all the state. This is only relevant for tests since // in reality the process fully exits here. this.#process.off('exit', this.#handleProcesExitAndReset) this.#process.off('uncaughtException', this.#handleExit) this.#process.off('unhandledRejection', this.#handleExit) if (this.#loaded) { this.#npm.unload() } this.#npm = null this.#exited = false this.#exitErrorMessage = false } #handleProcessExit (code) { const numCode = Number(code) || 0 // Always exit w/ a non-zero code if exit handler was not called const exitCode = this.#exited ? numCode : (numCode || 1) this.#process.exitCode = exitCode if (this.#notLoadedOrExited) { this.#logConsoleError(new Error(`Process exited unexpectedly with code: ${exitCode}`)) return } if (this.#logNoNpmError()) { return } const os = require('node:os') log.verbose('cwd', this.#process.cwd()) log.verbose('os', `${os.type()} ${os.release()}`) log.verbose('node', this.#process.version) log.verbose('npm ', `v${this.#npm.version}`) // only show the notification if it finished if (typeof this.#npm.updateNotification === 'string') { log.notice('', this.#npm.updateNotification, { [META]: true, force: true }) } if (!this.#exited) { log.error('', 'Exit handler never called!') log.error('', 'This is an error with npm itself. Please report this error at:') log.error('', ' ') if (this.#npm.silent) { output.error('') } } log.verbose('exit', exitCode) if (exitCode) { log.verbose('code', exitCode) } else { log.info('ok') } if (this.#showExitErrorMessage) { log.error('', this.#npm.exitErrorMessage()) } } #logConsoleError (err) { // Run our error message formatters on all errors even if we // have no npm or an unloaded npm. This will clean the error // and possible return a formatted message about EACCESS or something. const { summary, detail } = errorMessage(err, this.#npm) const formatted = [...new Set([...summary, ...detail].flat().filter(Boolean))].join('\n') // If we didn't get anything from the formatted message then just display the full stack // eslint-disable-next-line no-console console.error(formatted === err.message ? err.stack : formatted) } #logNoNpmError (err) { if (this.#hasNpm) { return false } // Make sure we only log this error once if (!this.#noNpmError) { this.#noNpmError = true this.#logConsoleError( new Error(`Exit prior to setting npm in exit handler`, err ? { cause: err } : {}) ) } return true } #handleExit = (err) => { this.#exited = true // No npm at all if (this.#logNoNpmError(err)) { return this.#process.exit(this.#process.exitCode || getExitCodeFromError(err) || 1) } // npm was never loaded but we still might have a config loading error or // something similar that we can run through the error message formatter // to give the user a clue as to what happened.s if (!this.#loaded) { this.#logConsoleError(new Error('Exit prior to config file resolving', { cause: err })) return this.#process.exit(this.#process.exitCode || getExitCodeFromError(err) || 1) } this.#exitErrorMessage = err?.suppressError === true ? false : !!err // Prefer the exit code of the error, then the current process exit code, // then set it to 1 if we still have an error. Otherwise we call process.exit // with undefined so that it can determine the final exit code const exitCode = err?.exitCode ?? this.#process.exitCode ?? (err ? 1 : undefined) // explicitly call process.exit now so we don't hang on things like the // update notifier, also flush stdout/err beforehand because process.exit doesn't // wait for that to happen. this.#process.stderr.write('', () => this.#process.stdout.write('', () => { this.#process.exit(exitCode) })) } } module.exports = ExitHandler // print a banner telling the user to upgrade npm to latest // but not in CI, and not if we're doing that already. // Check daily for betas, and weekly otherwise. const ciInfo = require('ci-info') const gt = require('semver/functions/gt') const gte = require('semver/functions/gte') const parse = require('semver/functions/parse') const { stat, writeFile } = require('node:fs/promises') const { resolve } = require('node:path') // update check frequency const DAILY = 1000 * 60 * 60 * 24 const WEEKLY = DAILY * 7 // don't put it in the _cacache folder, just in npm's cache const lastCheckedFile = npm => resolve(npm.flatOptions.cache, '../_update-notifier-last-checked') // Actual check for updates. This is a separate function so that we only load // this if we are doing the actual update const updateCheck = async (npm, spec, version, current) => { const pacote = require('pacote') const mani = await pacote.manifest(`npm@${spec}`, { // always prefer latest, even if doing --tag=whatever on the cmd defaultTag: 'latest', ...npm.flatOptions, cache: false, }).catch(() => null) // if pacote failed, give up if (!mani) { return null } const latest = mani.version // if the current version is *greater* than latest, we're on a 'next' // and should get the updates from that release train. // Note that this isn't another http request over the network, because // the packument will be cached by pacote from previous request. if (gt(version, latest) && spec === 'latest') { return updateNotifier(npm, `^${version}`) } // if we already have something >= the desired spec, then we're done if (gte(version, latest)) { return null } const chalk = npm.logChalk // ok! notify the user about this update they should get. // The message is saved for printing at process exit so it will not get // lost in any other messages being printed as part of the command. const update = parse(mani.version) const type = update.major !== current.major ? 'major' : update.minor !== current.minor ? 'minor' : update.patch !== current.patch ? 'patch' : 'prerelease' const typec = type === 'major' ? 'red' : type === 'minor' ? 'yellow' : 'cyan' const cmd = `npm install -g npm@${latest}` const message = `\nNew ${chalk[typec](type)} version of npm available! ` + `${chalk[typec](current)} -> ${chalk.blue(latest)}\n` + `Changelog: ${chalk.blue(`https://github.com/npm/cli/releases/tag/v${latest}`)}\n` + `To update run: ${chalk.underline(cmd)}\n` return message } const updateNotifier = async (npm, spec = 'latest') => { // if we're on a prerelease train, then updates are coming fast // check for a new one daily. otherwise, weekly. const { version } = npm const current = parse(version) // if we're on a beta train, always get the next beta if (current.prerelease.length) { spec = `^${version}` } // while on a beta train, get updates daily const duration = spec !== 'latest' ? DAILY : WEEKLY const t = new Date(Date.now() - duration) // if we don't have a file, then definitely check it. const st = await stat(lastCheckedFile(npm)).catch(() => ({ mtime: t - 1 })) // if we've already checked within the specified duration, don't check again if (!(t > st.mtime)) { return null } // intentional. do not await this. it's a best-effort update. if this // fails, it's ok. might be using /dev/null as the cache or something weird // like that. writeFile(lastCheckedFile(npm), '').catch(() => {}) return updateCheck(npm, spec, version, current) } // only update the notification timeout if we actually finished checking module.exports = npm => { if ( // opted out !npm.config.get('update-notifier') // global npm update || (npm.flatOptions.global && ['install', 'update'].includes(npm.command) && npm.argv.some(arg => /^npm(@|$)/.test(arg))) // CI || ciInfo.isCI ) { return Promise.resolve(null) } return updateNotifier(npm) } // This is separate to indicate that it should contain code we expect to work in // all versions of node >= 6. This is a best effort to catch syntax errors to // give users a good error message if they are using a node version that doesn't // allow syntax we are using such as private properties, etc. This file is // linted with ecmaVersion=6 so we don't use invalid syntax, which is set in the // .eslintrc.local.json file const { engines: { node: engines }, version } = require('../../package.json') const npm = `v${version}` module.exports = (process, getCli) => { const fs = require('node:fs') const node = process.version const unsupportedMessage = `npm ${npm} does not support Node.js ${node}. This version of npm supports the following node versions: \`${engines}\`. You can find the latest version at https://nodejs.org/.` const brokenMessage = `ERROR: npm ${npm} is known not to run on Node.js ${node}. This version of npm supports the following node versions: \`${engines}\`. You can find the latest version at https://nodejs.org/.` // coverage ignored because this is only hit in very unsupported node versions // and it's a best effort attempt to show something nice in those cases /* istanbul ignore next */ const syntaxErrorHandler = (err) => { if (err instanceof SyntaxError) { // eslint-disable-next-line no-console console.error(`${brokenMessage}\n\nERROR:`) // eslint-disable-next-line no-console console.error(err) return process.exit(1) } throw err } process.on('uncaughtException', syntaxErrorHandler) process.on('unhandledRejection', syntaxErrorHandler) // require this only after setting up the error handlers const cli = getCli() return cli(process, { node, npm, engines, unsupportedMessage, off: () => { process.off('uncaughtException', syntaxErrorHandler) process.off('unhandledRejection', syntaxErrorHandler) }, }) } const libnpmaccess = require('libnpmaccess') const npa = require('npm-package-arg') const { output } = require('proc-log') const pkgJson = require('@npmcli/package-json') const localeCompare = require('@isaacs/string-locale-compare')('en') const { otplease } = require('../utils/auth.js') const getIdentity = require('../utils/get-identity.js') const BaseCommand = require('../base-cmd.js') const commands = [ 'get', 'grant', 'list', 'revoke', 'set', ] const setCommands = [ 'status=public', 'status=private', 'mfa=none', 'mfa=publish', 'mfa=automation', '2fa=none', '2fa=publish', '2fa=automation', ] class Access extends BaseCommand { static description = 'Set access level on published packages' static name = 'access' static params = [ 'json', 'otp', 'registry', ] static usage = [ 'list packages [||] []', 'list collaborators [ []]', 'get status []', 'set status=public|private []', 'set mfa=none|publish|automation []', 'grant []', 'revoke []', ] static async completion (opts) { const argv = opts.conf.argv.remain if (argv.length === 2) { return commands } if (argv.length === 3) { switch (argv[2]) { case 'grant': return ['read-only', 'read-write'] case 'revoke': return [] case 'list': case 'ls': return ['packages', 'collaborators'] case 'get': return ['status'] case 'set': return setCommands default: throw new Error(argv[2] + ' not recognized') } } } async exec ([cmd, subcmd, ...args]) { if (!cmd) { throw this.usageError() } if (!commands.includes(cmd)) { throw this.usageError(`${cmd} is not a valid access command`) } // All commands take at least one more parameter so we can do this check up front if (!subcmd) { throw this.usageError() } switch (cmd) { case 'grant': if (!['read-only', 'read-write'].includes(subcmd)) { throw this.usageError('grant must be either `read-only` or `read-write`') } if (!args[0]) { throw this.usageError('`` argument is required') } return this.#grant(subcmd, args[0], args[1]) case 'revoke': return this.#revoke(subcmd, args[0]) case 'list': case 'ls': if (subcmd === 'packages') { return this.#listPackages(args[0], args[1]) } if (subcmd === 'collaborators') { return this.#listCollaborators(args[0], args[1]) } throw this.usageError(`list ${subcmd} is not a valid access command`) case 'get': if (subcmd !== 'status') { throw this.usageError(`get ${subcmd} is not a valid access command`) } return this.#getStatus(args[0]) case 'set': if (!setCommands.includes(subcmd)) { throw this.usageError(`set ${subcmd} is not a valid access command`) } return this.#set(subcmd, args[0]) } } async #grant (permissions, scope, pkg) { await libnpmaccess.setPermissions(scope, pkg, permissions, this.npm.flatOptions) } async #revoke (scope, pkg) { await libnpmaccess.removePermissions(scope, pkg, this.npm.flatOptions) } async #listPackages (owner, pkg) { if (!owner) { owner = await getIdentity(this.npm, this.npm.flatOptions) } const pkgs = await libnpmaccess.getPackages(owner, this.npm.flatOptions) this.#output(pkgs, pkg) } async #listCollaborators (pkg, user) { const pkgName = await this.#getPackage(pkg, false) const collabs = await libnpmaccess.getCollaborators(pkgName, this.npm.flatOptions) this.#output(collabs, user) } async #getStatus (pkg) { const pkgName = await this.#getPackage(pkg, false) const visibility = await libnpmaccess.getVisibility(pkgName, this.npm.flatOptions) this.#output({ [pkgName]: visibility.public ? 'public' : 'private' }) } async #set (subcmd, pkg) { const [subkey, subval] = subcmd.split('=') switch (subkey) { case 'mfa': case '2fa': return this.#setMfa(pkg, subval) case 'status': return this.#setStatus(pkg, subval) } } async #setMfa (pkg, level) { const pkgName = await this.#getPackage(pkg, false) await otplease(this.npm, this.npm.flatOptions, (opts) => { return libnpmaccess.setMfa(pkgName, level, opts) }) } async #setStatus (pkg, status) { // only scoped packages can have their access changed const pkgName = await this.#getPackage(pkg, true) if (status === 'private') { status = 'restricted' } await otplease(this.npm, this.npm.flatOptions, (opts) => { return libnpmaccess.setAccess(pkgName, status, opts) }) return this.#getStatus(pkgName) } async #getPackage (name, requireScope) { if (!name) { try { const { content } = await pkgJson.normalize(this.npm.prefix) name = content.name } catch (err) { if (err.code === 'ENOENT') { throw Object.assign(new Error('no package name given and no package.json found'), { code: 'ENOENT', }) } else { throw err } } } const spec = npa(name) if (requireScope && !spec.scope) { throw this.usageError('This command is only available for scoped packages.') } return name } #output (items, limiter) { const outputs = {} const lookup = { __proto__: null, read: 'read-only', write: 'read-write', } for (const item in items) { const val = items[item] outputs[item] = lookup[val] || val } if (this.npm.config.get('json')) { output.buffer(outputs) } else { for (const item of Object.keys(outputs).sort(localeCompare)) { if (!limiter || limiter === item) { output.standard(`${item}: ${outputs[item]}`) } } } } } module.exports = Access const { log, output } = require('proc-log') const { redactLog: replaceInfo } = require('@npmcli/redact') const auth = require('../utils/auth.js') const BaseCommand = require('../base-cmd.js') class AddUser extends BaseCommand { static description = 'Add a registry user account' static name = 'adduser' static params = [ 'registry', 'scope', 'auth-type', ] async exec () { const scope = this.npm.config.get('scope') let registry = this.npm.config.get('registry') if (scope) { const scopedRegistry = this.npm.config.get(`${scope}:registry`) const cliRegistry = this.npm.config.get('registry', 'cli') if (scopedRegistry && !cliRegistry) { registry = scopedRegistry } } const creds = this.npm.config.getCredentialsByURI(registry) log.notice('', `Log in on ${replaceInfo(registry)}`) const { message, newCreds } = await auth.adduser(this.npm, { ...this.npm.flatOptions, creds, registry, }) this.npm.config.delete('_token', 'user') // prevent legacy pollution this.npm.config.setCredentialsByURI(registry, newCreds) if (scope) { this.npm.config.set(scope + ':registry', registry, 'user') } await this.npm.config.save('user') output.standard(message) } } module.exports = AddUser const npmAuditReport = require('npm-audit-report') const ArboristWorkspaceCmd = require('../arborist-cmd.js') const auditError = require('../utils/audit-error.js') const { log, output } = require('proc-log') const reifyFinish = require('../utils/reify-finish.js') const VerifySignatures = require('../utils/verify-signatures.js') class Audit extends ArboristWorkspaceCmd { static description = 'Run a security audit' static name = 'audit' static params = [ 'audit-level', 'dry-run', 'force', 'json', 'package-lock-only', 'package-lock', 'omit', 'include', 'foreground-scripts', 'ignore-scripts', ...super.params, ] static usage = ['[fix|signatures]'] static async completion (opts) { const argv = opts.conf.argv.remain if (argv.length === 2) { return ['fix', 'signatures'] } switch (argv[2]) { case 'fix': case 'signatures': return [] default: throw Object.assign(new Error(argv[2] + ' not recognized'), { code: 'EUSAGE', }) } } async exec (args) { if (args[0] === 'signatures') { await this.auditSignatures() } else { await this.auditAdvisories(args) } } async auditAdvisories (args) { const fix = args[0] === 'fix' if (this.npm.config.get('package-lock') === false && fix) { throw this.usageError('fix can not be used without a package-lock') } const reporter = this.npm.config.get('json') ? 'json' : 'detail' const Arborist = require('@npmcli/arborist') const opts = { ...this.npm.flatOptions, audit: true, path: this.npm.prefix, reporter, workspaces: this.workspaceNames, } const arb = new Arborist(opts) await arb.audit({ fix }) if (fix) { await reifyFinish(this.npm, arb) } else { // will throw if there's an error, because this is an audit command auditError(this.npm, arb.auditReport) const result = npmAuditReport(arb.auditReport, { ...opts, chalk: this.npm.chalk, }) process.exitCode = process.exitCode || result.exitCode output.standard(result.report) } } async auditSignatures () { if (this.npm.global) { throw Object.assign( new Error('`npm audit signatures` does not support global packages'), { code: 'EAUDITGLOBAL', } ) } log.verbose('audit', 'loading installed dependencies') const Arborist = require('@npmcli/arborist') const opts = { ...this.npm.flatOptions, path: this.npm.prefix, workspaces: this.workspaceNames, } const arb = new Arborist(opts) const tree = await arb.loadActual() let filterSet = new Set() if (opts.workspaces && opts.workspaces.length) { filterSet = arb.workspaceDependencySet( tree, opts.workspaces, this.npm.flatOptions.includeWorkspaceRoot ) } else if (!this.npm.flatOptions.workspacesEnabled) { filterSet = arb.excludeWorkspacesDependencySet(tree) } const verify = new VerifySignatures(tree, filterSet, this.npm, { ...opts }) await verify.run() } } module.exports = Audit const PackageUrlCmd = require('../package-url-cmd.js') class Bugs extends PackageUrlCmd { static description = 'Report bugs for a package in a web browser' static name = 'bugs' getUrl (spec, mani) { if (mani.bugs) { if (typeof mani.bugs === 'string') { return mani.bugs } if (typeof mani.bugs === 'object' && mani.bugs.url) { return mani.bugs.url } if (typeof mani.bugs === 'object' && mani.bugs.email) { return `mailto:${mani.bugs.email}` } } // try to get it from the repo, if possible const info = this.hostedFromMani(mani) const infoUrl = info?.bugs() if (infoUrl) { return infoUrl } // just send them to the website, hopefully that has some info! return `https://www.npmjs.com/package/${mani.name}` } } module.exports = Bugs const cacache = require('cacache') const pacote = require('pacote') const fs = require('node:fs/promises') const { join } = require('node:path') const semver = require('semver') const BaseCommand = require('../base-cmd.js') const npa = require('npm-package-arg') const jsonParse = require('json-parse-even-better-errors') const localeCompare = require('@isaacs/string-locale-compare')('en') const { log, output } = require('proc-log') const searchCachePackage = async (path, parsed, cacheKeys) => { const searchMFH = new RegExp(`^make-fetch-happen:request-cache:.*(?', 'clean []', 'ls [@]', 'verify', ] static async completion (opts) { const argv = opts.conf.argv.remain if (argv.length === 2) { return ['add', 'clean', 'verify', 'ls'] } // TODO - eventually... switch (argv[2]) { case 'verify': case 'clean': case 'add': case 'ls': return [] } } async exec (args) { const cmd = args.shift() switch (cmd) { case 'rm': case 'clear': case 'clean': return await this.clean(args) case 'add': return await this.add(args) case 'verify': case 'check': return await this.verify() case 'ls': return await this.ls(args) default: throw this.usageError() } } // npm cache clean [pkg]* async clean (args) { const cachePath = join(this.npm.cache, '_cacache') if (args.length === 0) { if (!this.npm.config.get('force')) { throw new Error(`As of npm@5, the npm cache self-heals from corruption issues by treating integrity mismatches as cache misses. As a result, data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use \`npm cache verify\` instead. Deleting the cache can only make npm go slower, and is not likely to correct any problems you may be encountering! On the other hand, if you're debugging an issue with the installer, or race conditions that depend on the timing of writing to an empty cache, you can use \`npm install --cache /tmp/empty-cache\` to use a temporary cache instead of nuking the actual one. If you're sure you want to delete the entire cache, rerun this command with --force.`) } return fs.rm(cachePath, { recursive: true, force: true }) } for (const key of args) { let entry try { entry = await cacache.get(cachePath, key) } catch { log.warn('cache', `Not Found: ${key}`) break } output.standard(`Deleted: ${key}`) await cacache.rm.entry(cachePath, key) // XXX this could leave other entries without content! await cacache.rm.content(cachePath, entry.integrity) } } // npm cache add ... // npm cache add ... // npm cache add ... // npm cache add ... async add (args) { log.silly('cache add', 'args', args) if (args.length === 0) { throw this.usageError('First argument to `add` is required') } await Promise.all(args.map(async spec => { log.silly('cache add', 'spec', spec) // we ask pacote for the thing, and then just throw the data // away so that it tee-pipes it into the cache like it does // for a normal request. await pacote.tarball.stream(spec, stream => { stream.resume() return stream.promise() }, { ...this.npm.flatOptions }) await pacote.manifest(spec, { ...this.npm.flatOptions, fullMetadata: true, }) })) } async verify () { const cache = join(this.npm.cache, '_cacache') const prefix = cache.indexOf(process.env.HOME) === 0 ? `~${cache.slice(process.env.HOME.length)}` : cache const stats = await cacache.verify(cache) output.standard(`Cache verified and compressed (${prefix})`) output.standard(`Content verified: ${stats.verifiedContent} (${stats.keptSize} bytes)`) if (stats.badContentCount) { output.standard(`Corrupted content removed: ${stats.badContentCount}`) } if (stats.reclaimedCount) { output.standard(`Content garbage-collected: ${stats.reclaimedCount} (${stats.reclaimedSize} bytes)`) } if (stats.missingContent) { output.standard(`Missing content: ${stats.missingContent}`) } output.standard(`Index entries: ${stats.totalEntries}`) output.standard(`Finished in ${stats.runTime.total / 1000}s`) } // npm cache ls [--package ...] async ls (specs) { const cachePath = join(this.npm.cache, '_cacache') const cacheKeys = Object.keys(await cacache.ls(cachePath)) if (specs.length > 0) { // get results for each package spec specified const results = new Set() for (const spec of specs) { const parsed = npa(spec) if (parsed.rawSpec !== '' && parsed.type === 'tag') { throw this.usageError('Cannot list cache keys for a tagged package.') } const keySet = await searchCachePackage(cachePath, parsed, cacheKeys) for (const key of keySet) { results.add(key) } } [...results].sort(localeCompare).forEach(key => output.standard(key)) return } cacheKeys.sort(localeCompare).forEach(key => output.standard(key)) } } module.exports = Cache const reifyFinish = require('../utils/reify-finish.js') const runScript = require('@npmcli/run-script') const fs = require('node:fs/promises') const path = require('node:path') const { log, time } = require('proc-log') const validateLockfile = require('../utils/validate-lockfile.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') const getWorkspaces = require('../utils/get-workspaces.js') class CI extends ArboristWorkspaceCmd { static description = 'Clean install a project' static name = 'ci' // These are in the order they will show up in when running "-h" static params = [ 'install-strategy', 'legacy-bundling', 'global-style', 'omit', 'include', 'strict-peer-deps', 'foreground-scripts', 'ignore-scripts', 'audit', 'bin-links', 'fund', 'dry-run', ...super.params, ] async exec () { if (this.npm.global) { throw Object.assign(new Error('`npm ci` does not work for global packages'), { code: 'ECIGLOBAL', }) } const where = this.npm.prefix const Arborist = require('@npmcli/arborist') const opts = { ...this.npm.flatOptions, packageLock: true, // npm ci should never skip lock files path: where, save: false, // npm ci should never modify the lockfile or package.json workspaces: this.workspaceNames, } const arb = new Arborist(opts) await arb.loadVirtual().catch(er => { log.verbose('loadVirtual', er.stack) const msg = 'The `npm ci` command can only install with an existing package-lock.json or\n' + 'npm-shrinkwrap.json with lockfileVersion >= 1. Run an install with npm@5 or\n' + 'later to generate a package-lock.json file, then try again.' throw this.usageError(msg) }) // retrieves inventory of packages from loaded virtual tree (lock file) const virtualInventory = new Map(arb.virtualTree.inventory) // build ideal tree step needs to come right after retrieving the virtual // inventory since it's going to erase the previous ref to virtualTree await arb.buildIdealTree() // verifies that the packages from the ideal tree will match // the same versions that are present in the virtual tree (lock file) // throws a validation error in case of mismatches const errors = validateLockfile(virtualInventory, arb.idealTree.inventory) if (errors.length) { throw this.usageError( '`npm ci` can only install packages when your package.json and ' + 'package-lock.json or npm-shrinkwrap.json are in sync. Please ' + 'update your lock file with `npm install` ' + 'before continuing.\n\n' + errors.join('\n') ) } const dryRun = this.npm.config.get('dry-run') if (!dryRun) { const workspacePaths = await getWorkspaces([], { path: this.npm.localPrefix, includeWorkspaceRoot: true, }) // Only remove node_modules after we've successfully loaded the virtual // tree and validated the lockfile await time.start('npm-ci:rm', async () => { return await Promise.all([...workspacePaths.values()].map(async modulePath => { const fullPath = path.join(modulePath, 'node_modules') // get the list of entries so we can skip the glob for performance const entries = await fs.readdir(fullPath, null).catch(() => []) return Promise.all(entries.map(folder => { return fs.rm(path.join(fullPath, folder), { force: true, recursive: true }) })) })) }) } await arb.reify(opts) const ignoreScripts = this.npm.config.get('ignore-scripts') // run the same set of scripts that `npm install` runs. if (!ignoreScripts) { const scripts = [ 'preinstall', 'install', 'postinstall', 'prepublish', // XXX should we remove this finally?? 'preprepare', 'prepare', 'postprepare', ] const scriptShell = this.npm.config.get('script-shell') || undefined for (const event of scripts) { await runScript({ path: where, args: [], scriptShell, stdio: 'inherit', event, }) } } await reifyFinish(this.npm, arb) } } module.exports = CI // Each command has a completion function that takes an options object and a cb // The callback gets called with an error and an array of possible completions. // The options object is built up based on the environment variables set by // zsh or bash when calling a function for completion, based on the cursor // position and the command line thus far. These are: // COMP_CWORD: the index of the "word" in the command line being completed // COMP_LINE: the full command line thusfar as a string // COMP_POINT: the cursor index at the point of triggering completion // // We parse the command line with nopt, like npm does, and then create an // options object containing: // words: array of words in the command line // w: the index of the word being completed (ie, COMP_CWORD) // word: the word being completed // line: the COMP_LINE // lineLength // point: the COMP_POINT, usually equal to line length, but not always, eg if // the user has pressed the left-arrow to complete an earlier word // partialLine: the line up to the point // partialWord: the word being completed (which might be ''), up to the point // conf: a nopt parse of the command line // // When the implementation completion method returns its list of strings, // and arrays of strings, we filter that by any that start with the // partialWord, since only those can possibly be valid matches. // // Matches are wrapped with ' to escape them, if necessary, and then printed // one per line for the shell completion method to consume in IFS=$'\n' mode // as an array. const fs = require('node:fs/promises') const nopt = require('nopt') const { resolve } = require('node:path') const { output } = require('proc-log') const Npm = require('../npm.js') const { definitions, shorthands } = require('@npmcli/config/lib/definitions') const { commands, aliases, deref } = require('../utils/cmd-list.js') const { isWindowsShell } = require('../utils/is-windows.js') const BaseCommand = require('../base-cmd.js') const fileExists = (file) => fs.stat(file).then(s => s.isFile()).catch(() => false) const configNames = Object.keys(definitions) const shorthandNames = Object.keys(shorthands) const allConfs = configNames.concat(shorthandNames) class Completion extends BaseCommand { static description = 'Tab Completion for npm' static name = 'completion' // completion for the completion command static async completion (opts) { if (opts.w > 2) { return } const [bashExists, zshExists] = await Promise.all([ fileExists(resolve(process.env.HOME, '.bashrc')), fileExists(resolve(process.env.HOME, '.zshrc')), ]) const out = [] if (zshExists) { out.push(['>>', '~/.zshrc']) } if (bashExists) { out.push(['>>', '~/.bashrc']) } return out } async exec (args) { if (isWindowsShell) { const msg = 'npm completion supported only in MINGW / Git bash on Windows' throw Object.assign(new Error(msg), { code: 'ENOTSUP', }) } const { COMP_CWORD, COMP_LINE, COMP_POINT, COMP_FISH } = process.env // if the COMP_* isn't in the env, then just dump the script. if (COMP_CWORD === undefined || COMP_LINE === undefined || COMP_POINT === undefined) { return dumpScript(resolve(this.npm.npmRoot, 'lib', 'utils', 'completion.sh')) } // ok we're actually looking at the envs and outputting the suggestions // get the partial line and partial word, // if the point isn't at the end. // ie, tabbing at: npm foo b|ar const w = +COMP_CWORD const words = args.map(unescape) const word = words[w] const line = COMP_LINE const point = +COMP_POINT const partialLine = line.slice(0, point) const partialWords = words.slice(0, w) // figure out where in that last word the point is. const partialWordRaw = args[w] let i = partialWordRaw.length while (partialWordRaw.slice(0, i) !== partialLine.slice(-1 * i) && i > 0) { i-- } const partialWord = unescape(partialWordRaw.slice(0, i)) partialWords.push(partialWord) const opts = { isFish: COMP_FISH === 'true', words, w, word, line, lineLength: line.length, point, partialLine, partialWords, partialWord, raw: args, } if (partialWords.slice(0, -1).indexOf('--') === -1) { if (word.charAt(0) === '-') { return this.wrap(opts, configCompl(opts)) } if (words[w - 1] && words[w - 1].charAt(0) === '-' && !isFlag(words[w - 1])) { // awaiting a value for a non-bool config. // don't even try to do this for now return this.wrap(opts, configValueCompl(opts)) } } // try to find the npm command. // it's the first thing after all the configs. // take a little shortcut and use npm's arg parsing logic. // don't have to worry about the last arg being implicitly // boolean'ed, since the last block will catch that. const types = Object.entries(definitions).reduce((acc, [key, def]) => { acc[key] = def.type return acc }, {}) const parsed = opts.conf = nopt(types, shorthands, partialWords.slice(0, -1), 0) // check if there's a command already. const cmd = parsed.argv.remain[1] if (!cmd) { return this.wrap(opts, cmdCompl(opts, this.npm)) } Object.keys(parsed).forEach(k => this.npm.config.set(k, parsed[k])) // at this point, if words[1] is some kind of npm command, // then complete on it. // otherwise, do nothing try { const { completion } = Npm.cmd(cmd) if (completion) { const comps = await completion(opts, this.npm) return this.wrap(opts, comps) } } catch { // it wasnt a valid command, so do nothing } } // The command should respond with an array. Loop over that, // wrapping quotes around any that have spaces, and writing // them to stdout. // If any of the items are arrays, then join them with a space. // Ie, returning ['a', 'b c', ['d', 'e']] would allow it to expand // to: 'a', 'b c', or 'd' 'e' wrap (opts, compls) { // TODO this was dead code, leaving it in case we find some command we // forgot that requires this. if so *that command should fix its // completions* // compls = compls.map(w => !/\s+/.test(w) ? w : '\'' + w + '\'') if (opts.partialWord) { compls = compls.filter(c => c.startsWith(opts.partialWord)) } if (compls.length > 0) { output.standard(compls.join('\n')) } } } const dumpScript = async (p) => { const d = (await fs.readFile(p, 'utf8')).replace(/^#!.*?\n/, '') await new Promise((res, rej) => { let done = false process.stdout.on('error', er => { if (done) { return } done = true // Darwin is a pain sometimes. // // This is necessary because the "source" or "." program in // bash on OS X closes its file argument before reading // from it, meaning that you get exactly 1 write, which will // work most of the time, and will always raise an EPIPE. // // Really, one should not be tossing away EPIPE errors, or any // errors, so casually. But, without this, `. <(npm completion)` // can never ever work on OS X. // TODO Ignoring coverage, see 'non EPIPE errors cause failures' test. /* istanbul ignore next */ if (er.errno === 'EPIPE') { res() } else { rej(er) } }) process.stdout.write(d, () => { if (done) { return } done = true res() }) }) } const unescape = w => w.charAt(0) === '\'' ? w.replace(/^'|'$/g, '') : w.replace(/\\ /g, ' ') // the current word has a dash. Return the config names, // with the same number of dashes as the current word has. const configCompl = opts => { const word = opts.word const split = word.match(/^(-+)((?:no-)*)(.*)$/) const dashes = split[1] const no = split[2] const flags = configNames.filter(isFlag) return allConfs.map(c => dashes + c) .concat(flags.map(f => dashes + (no || 'no-') + f)) } // expand with the valid values of various config values. // not yet implemented. const configValueCompl = () => [] // check if the thing is a flag or not. const isFlag = word => { // shorthands never take args. const split = word.match(/^(-*)((?:no-)+)?(.*)$/) const no = split[2] const conf = split[3] const { type } = definitions[conf] return no || type === Boolean || (Array.isArray(type) && type.includes(Boolean)) || shorthands[conf] } // complete against the npm commands // if they all resolve to the same thing, just return the thing it already is const cmdCompl = (opts) => { const allCommands = commands.concat(Object.keys(aliases)) const matches = allCommands.filter(c => c.startsWith(opts.partialWord)) if (!matches.length) { return matches } const derefs = new Set([...matches.map(c => deref(c))]) if (derefs.size === 1) { return [...derefs] } return allCommands } module.exports = Completion const { mkdir, readFile, writeFile } = require('node:fs/promises') const { dirname, resolve } = require('node:path') const { spawn } = require('node:child_process') const { EOL } = require('node:os') const localeCompare = require('@isaacs/string-locale-compare')('en') const pkgJson = require('@npmcli/package-json') const { defaults, definitions } = require('@npmcli/config/lib/definitions') const { log, output } = require('proc-log') const BaseCommand = require('../base-cmd.js') const { redact } = require('@npmcli/redact') // These are the configs that we can nerf-dart. Not all of them currently even // *have* config definitions so we have to explicitly validate them here. // This is used to validate during "npm config set" const nerfDarts = [ '_auth', '_authToken', '_password', 'certfile', 'email', 'keyfile', 'username', ] // These are the config values to swap with "protected". It does not catch // every single sensitive thing a user may put in the npmrc file but it gets // the common ones. This is distinct from nerfDarts because that is used to // validate valid configs during "npm config set", and folks may have old // invalid entries lying around in a config file that we still want to protect // when running "npm config list" // This is a more general list of values to consider protected. You can not // "npm config get" them, and they will not display during "npm config list" const protected = [ 'auth', 'authToken', 'certfile', 'email', 'keyfile', 'password', 'username', ] // take an array of `[key, value, k2=v2, k3, v3, ...]` and turn into // { key: value, k2: v2, k3: v3 } const keyValues = args => { const kv = {} for (let i = 0; i < args.length; i++) { const arg = args[i].split('=') const key = arg.shift() const val = arg.length ? arg.join('=') : i < args.length - 1 ? args[++i] : '' kv[key.trim()] = val.trim() } return kv } const isProtected = (k) => { // _password if (k.startsWith('_')) { return true } if (protected.includes(k)) { return true } // //localhost:8080/:_password if (k.startsWith('//')) { if (k.includes(':_')) { return true } // //registry:_authToken or //registry:authToken for (const p of protected) { if (k.endsWith(`:${p}`) || k.endsWith(`:_${p}`)) { return true } } } return false } // Private fields are either protected or they can redacted info const isPrivate = (k, v) => isProtected(k) || redact(v) !== v const displayVar = (k, v) => `${k} = ${isProtected(k, v) ? '(protected)' : JSON.stringify(redact(v))}` class Config extends BaseCommand { static description = 'Manage the npm configuration files' static name = 'config' static usage = [ 'set = [= ...]', 'get [ [ ...]]', 'delete [ ...]', 'list [--json]', 'edit', 'fix', ] static params = [ 'json', 'global', 'editor', 'location', 'long', ] static ignoreImplicitWorkspace = false static skipConfigValidation = true static async completion (opts) { const argv = opts.conf.argv.remain if (argv[1] !== 'config') { argv.unshift('config') } if (argv.length === 2) { const cmds = ['get', 'set', 'delete', 'ls', 'rm', 'edit', 'fix'] if (opts.partialWord !== 'l') { cmds.push('list') } return cmds } const action = argv[2] switch (action) { case 'set': // todo: complete with valid values, if possible. if (argv.length > 3) { return [] } // fallthrough /* eslint no-fallthrough:0 */ case 'get': case 'delete': case 'rm': return Object.keys(definitions) case 'edit': case 'list': case 'ls': case 'fix': default: return [] } } async exec ([action, ...args]) { switch (action) { case 'set': await this.set(args) break case 'get': await this.get(args) break case 'delete': case 'rm': case 'del': await this.del(args) break case 'list': case 'ls': await (this.npm.flatOptions.json ? this.listJson() : this.list()) break case 'edit': await this.edit() break case 'fix': await this.fix() break default: throw this.usageError() } } async set (args) { if (!args.length) { throw this.usageError() } const where = this.npm.flatOptions.location for (const [key, val] of Object.entries(keyValues(args))) { log.info('config', 'set %j %j', key, val) const baseKey = key.split(':').pop() if (!this.npm.config.definitions[baseKey] && !nerfDarts.includes(baseKey)) { throw new Error(`\`${baseKey}\` is not a valid npm option`) } const deprecated = this.npm.config.definitions[baseKey]?.deprecated if (deprecated) { throw new Error( `The \`${baseKey}\` option is deprecated, and can not be set in this way${deprecated}` ) } if (val === '') { this.npm.config.delete(key, where) } else { this.npm.config.set(key, val, where) } if (!this.npm.config.validate(where)) { log.warn('config', 'omitting invalid config values') } } await this.npm.config.save(where) } async get (keys) { if (!keys.length) { return this.list() } const out = [] for (const key of keys) { const val = this.npm.config.get(key) if (isPrivate(key, val)) { throw new Error(`The ${key} option is protected, and can not be retrieved in this way`) } const pref = keys.length > 1 ? `${key}=` : '' out.push(pref + val) } output.standard(out.join('\n')) } async del (keys) { if (!keys.length) { throw this.usageError() } const where = this.npm.flatOptions.location for (const key of keys) { this.npm.config.delete(key, where) } await this.npm.config.save(where) } async edit () { const ini = require('ini') const e = this.npm.flatOptions.editor const where = this.npm.flatOptions.location const file = this.npm.config.data.get(where).source // save first, just to make sure it's synced up // this also removes all the comments from the last time we edited it. await this.npm.config.save(where) const data = ( await readFile(file, 'utf8').catch(() => '') ).replace(/\r\n/g, '\n') const entries = Object.entries(defaults) const defData = entries.reduce((str, [key, val]) => { const obj = { [key]: val } const i = ini.stringify(obj) .replace(/\r\n/g, '\n') // normalizes output from ini.stringify .replace(/\n$/m, '') .replace(/^/g, '; ') .replace(/\n/g, '\n; ') .split('\n') return str + '\n' + i }, '') const tmpData = `;;;; ; npm ${where}config file: ${file} ; this is a simple ini-formatted file ; lines that start with semi-colons are comments ; run \`npm help 7 config\` for documentation of the various options ; ; Configs like \`@scope:registry\` map a scope to a given registry url. ; ; Configs like \`///:_authToken\` are auth that is restricted ; to the registry host specified. ${data.split('\n').sort(localeCompare).join('\n').trim()} ;;;; ; all available options shown below with default values ;;;; ${defData} `.split('\n').join(EOL) await mkdir(dirname(file), { recursive: true }) await writeFile(file, tmpData, 'utf8') await new Promise((res, rej) => { const [bin, ...args] = e.split(/\s+/) const editor = spawn(bin, [...args, file], { stdio: 'inherit' }) editor.on('exit', (code) => { if (code) { return rej(new Error(`editor process exited with code: ${code}`)) } return res() }) }) } async fix () { let problems try { this.npm.config.validate() return // if validate doesn't throw we have nothing to do } catch (err) { // coverage skipped because we don't need to test rethrowing errors // istanbul ignore next if (err.code !== 'ERR_INVALID_AUTH') { throw err } problems = err.problems } if (!this.npm.config.isDefault('location')) { problems = problems.filter((problem) => { return problem.where === this.npm.config.get('location') }) } this.npm.config.repair(problems) const locations = [] output.standard('The following configuration problems have been repaired:\n') const summary = problems.map(({ action, from, to, key, where }) => { // coverage disabled for else branch because it is intentionally omitted // istanbul ignore else if (action === 'rename') { // we keep track of which configs were modified here so we know what to save later locations.push(where) return `~ \`${from}\` renamed to \`${to}\` in ${where} config` } else if (action === 'delete') { locations.push(where) return `- \`${key}\` deleted from ${where} config` } }).join('\n') output.standard(summary) return await Promise.all(locations.map((location) => this.npm.config.save(location))) } async list () { const msg = [] // long does not have a flattener const long = this.npm.config.get('long') for (const [where, { data, source }] of this.npm.config.data.entries()) { if (where === 'default' && !long) { continue } const entries = Object.entries(data).sort(([a], [b]) => localeCompare(a, b)) if (!entries.length) { continue } msg.push(`; "${where}" config from ${source}`, '') for (const [k, v] of entries) { const display = displayVar(k, v) const src = this.npm.config.find(k) msg.push(src === where ? display : `; ${display} ; overridden by ${src}`) msg.push() } msg.push('') } if (!long) { msg.push( `; node bin location = ${process.execPath}`, `; node version = ${process.version}`, `; npm local prefix = ${this.npm.localPrefix}`, `; npm version = ${this.npm.version}`, `; cwd = ${process.cwd()}`, `; HOME = ${process.env.HOME}`, '; Run `npm config ls -l` to show all defaults.' ) msg.push('') } if (!this.npm.global) { const { content } = await pkgJson.normalize(this.npm.prefix).catch(() => ({ content: {} })) if (content.publishConfig) { const pkgPath = resolve(this.npm.prefix, 'package.json') msg.push(`; "publishConfig" from ${pkgPath}`) msg.push('; This set of config values will be used at publish-time.', '') const entries = Object.entries(content.publishConfig) .sort(([a], [b]) => localeCompare(a, b)) for (const [k, value] of entries) { msg.push(displayVar(k, value)) } msg.push('') } } output.standard(msg.join('\n').trim()) } async listJson () { const publicConf = {} for (const key in this.npm.config.list[0]) { const value = this.npm.config.get(key) if (isPrivate(key, value)) { continue } publicConf[key] = value } output.buffer(publicConf) } } module.exports = Config const reifyFinish = require('../utils/reify-finish.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') // dedupe duplicated packages, or find them in the tree class Dedupe extends ArboristWorkspaceCmd { static description = 'Reduce duplication in the package tree' static name = 'dedupe' static params = [ 'install-strategy', 'legacy-bundling', 'global-style', 'strict-peer-deps', 'package-lock', 'omit', 'include', 'ignore-scripts', 'audit', 'bin-links', 'fund', 'dry-run', ...super.params, ] async exec () { if (this.npm.global) { const er = new Error('`npm dedupe` does not work in global mode.') er.code = 'EDEDUPEGLOBAL' throw er } const dryRun = this.npm.config.get('dry-run') const where = this.npm.prefix const Arborist = require('@npmcli/arborist') const opts = { ...this.npm.flatOptions, path: where, dryRun, // Saving during dedupe would only update if one of your direct // dependencies was also duplicated somewhere in your tree. It would be // confusing if running this were to also update your package.json. In // order to reduce potential confusion we set this to false. save: false, workspaces: this.workspaceNames, } const arb = new Arborist(opts) await arb.dedupe(opts) await reifyFinish(this.npm, arb) } } module.exports = Dedupe const npmFetch = require('npm-registry-fetch') const { otplease } = require('../utils/auth.js') const npa = require('npm-package-arg') const { log } = require('proc-log') const semver = require('semver') const getIdentity = require('../utils/get-identity.js') const libaccess = require('libnpmaccess') const BaseCommand = require('../base-cmd.js') class Deprecate extends BaseCommand { static description = 'Deprecate a version of a package' static name = 'deprecate' static usage = [' '] static params = [ 'registry', 'otp', 'dry-run', ] static ignoreImplicitWorkspace = true static async completion (opts, npm) { if (opts.conf.argv.remain.length > 1) { return [] } const username = await getIdentity(npm, npm.flatOptions) const packages = await libaccess.getPackages(username, npm.flatOptions) return Object.keys(packages) .filter((name) => packages[name] === 'write' && (opts.conf.argv.remain.length === 0 || name.startsWith(opts.conf.argv.remain[0]))) } async exec ([pkg, msg]) { // msg == null because '' is a valid value, it indicates undeprecate if (!pkg || msg == null) { throw this.usageError() } // fetch the data and make sure it exists. const p = npa(pkg) const spec = p.rawSpec === '*' ? '*' : p.fetchSpec if (semver.validRange(spec, true) === null) { throw new Error(`invalid version range: ${spec}`) } const uri = '/' + p.escapedName const packument = await npmFetch.json(uri, { ...this.npm.flatOptions, spec: p, query: { write: true }, }) const versions = Object.keys(packument.versions) .filter(v => semver.satisfies(v, spec, { includePrerelease: true })) const dryRun = this.npm.config.get('dry-run') if (versions.length) { for (const v of versions) { packument.versions[v].deprecated = msg if (msg) { log.notice(`deprecating ${packument.name}@${v} with message "${msg}"`) } else { log.notice(`undeprecating ${packument.name}@${v}`) } } if (!dryRun) { return otplease(this.npm, this.npm.flatOptions, opts => npmFetch(uri, { ...opts, spec: p, method: 'PUT', body: packument, ignoreBody: true, })) } } else { log.warn('deprecate', 'No version found for', p.rawSpec) } } } module.exports = Deprecate const { resolve } = require('node:path') const semver = require('semver') const libnpmdiff = require('libnpmdiff') const npa = require('npm-package-arg') const pacote = require('pacote') const pickManifest = require('npm-pick-manifest') const { log, output } = require('proc-log') const pkgJson = require('@npmcli/package-json') const BaseCommand = require('../base-cmd.js') class Diff extends BaseCommand { static description = 'The registry diff command' static name = 'diff' static usage = [ '[...]', ] static params = [ 'diff', 'diff-name-only', 'diff-unified', 'diff-ignore-all-space', 'diff-no-prefix', 'diff-src-prefix', 'diff-dst-prefix', 'diff-text', 'global', 'tag', 'workspace', 'workspaces', 'include-workspace-root', ] static workspaces = true static ignoreImplicitWorkspace = false async exec (args) { const specs = this.npm.config.get('diff').filter(d => d) if (specs.length > 2) { throw this.usageError(`Can't use more than two --diff arguments.`) } // execWorkspaces may have set this already if (!this.prefix) { this.prefix = this.npm.prefix } // this is the "top" directory, one up from node_modules // in global mode we have to walk one up from globalDir because our // node_modules is sometimes under ./lib, and in global mode we're only ever // walking through node_modules (because we will have been given a package // name already) if (this.npm.global) { this.top = resolve(this.npm.globalDir, '..') } else { this.top = this.prefix } const [a, b] = await this.retrieveSpecs(specs) log.info('diff', { src: a, dst: b }) const res = await libnpmdiff([a, b], { ...this.npm.flatOptions, diffFiles: args, where: this.top, }) return output.standard(res) } async execWorkspaces (args) { await this.setWorkspaces() for (const workspacePath of this.workspacePaths) { this.top = workspacePath this.prefix = workspacePath await this.exec(args) } } // get the package name from the packument at `path` // throws if no packument is present OR if it does not have `name` attribute async packageName () { let name try { const { content: pkg } = await pkgJson.normalize(this.prefix) name = pkg.name } catch { log.verbose('diff', 'could not read project dir package.json') } if (!name) { throw this.usageError('Needs multiple arguments to compare or run from a project dir.') } return name } async retrieveSpecs ([a, b]) { if (a && b) { const specs = await this.convertVersionsToSpecs([a, b]) return this.findVersionsByPackageName(specs) } // no arguments, defaults to comparing cwd // to its latest published registry version if (!a) { const pkgName = await this.packageName() return [ `${pkgName}@${this.npm.config.get('tag')}`, `file:${this.prefix.replace(/#/g, '%23')}`, ] } // single argument, used to compare wanted versions of an // installed dependency or to compare the cwd to a published version let noPackageJson let pkgName try { const { content: pkg } = await pkgJson.normalize(this.prefix) pkgName = pkg.name } catch { log.verbose('diff', 'could not read project dir package.json') noPackageJson = true } const missingPackageJson = this.usageError('Needs multiple arguments to compare or run from a project dir.') // using a valid semver range, that means it should just diff // the cwd against a published version to the registry using the // same project name and the provided semver range if (semver.validRange(a)) { if (!pkgName) { throw missingPackageJson } return [ `${pkgName}@${a}`, `file:${this.prefix.replace(/#/g, '%23')}`, ] } // when using a single package name as arg and it's part of the current // install tree, then retrieve the current installed version and compare // it against the same value `npm outdated` would suggest you to update to const spec = npa(a) if (spec.registry) { let actualTree let node const Arborist = require('@npmcli/arborist') try { const opts = { ...this.npm.flatOptions, path: this.top, } const arb = new Arborist(opts) actualTree = await arb.loadActual(opts) node = actualTree && actualTree.inventory.query('name', spec.name) .values().next().value } catch { log.verbose('diff', 'failed to load actual install tree') } if (!node || !node.name || !node.package || !node.package.version) { if (noPackageJson) { throw missingPackageJson } return [ `${spec.name}@${spec.fetchSpec}`, `file:${this.prefix.replace(/#/g, '%23')}`, ] } const tryRootNodeSpec = () => (actualTree && actualTree.edgesOut.get(spec.name) || {}).spec const tryAnySpec = () => { for (const edge of node.edgesIn) { return edge.spec } } const aSpec = `file:${node.realpath.replace(/#/g, '%23')}` // finds what version of the package to compare against, if a exact // version or tag was passed than it should use that, otherwise // work from the top of the arborist tree to find the original semver // range declared in the package that depends on the package. let bSpec if (spec.rawSpec !== '*') { bSpec = spec.rawSpec } else { const bTargetVersion = tryRootNodeSpec() || tryAnySpec() // figure out what to compare against, // follows same logic to npm outdated "Wanted" results const packument = await pacote.packument(spec, { ...this.npm.flatOptions, preferOnline: true, }) bSpec = pickManifest( packument, bTargetVersion, { ...this.npm.flatOptions } ).version } return [ `${spec.name}@${aSpec}`, `${spec.name}@${bSpec}`, ] } else if (spec.type === 'directory') { return [ `file:${spec.fetchSpec.replace(/#/g, '%23')}`, `file:${this.prefix.replace(/#/g, '%23')}`, ] } else { throw this.usageError(`Spec type ${spec.type} not supported.`) } } async convertVersionsToSpecs ([a, b]) { const semverA = semver.validRange(a) const semverB = semver.validRange(b) // both specs are semver versions, assume current project dir name if (semverA && semverB) { let pkgName try { const { content: pkg } = await pkgJson.normalize(this.prefix) pkgName = pkg.name } catch { log.verbose('diff', 'could not read project dir package.json') } if (!pkgName) { throw this.usageError('Needs to be run from a project dir in order to diff two versions.') } return [`${pkgName}@${a}`, `${pkgName}@${b}`] } // otherwise uses the name from the other arg to // figure out the spec.name of what to compare if (!semverA && semverB) { return [a, `${npa(a).name}@${b}`] } if (semverA && !semverB) { return [`${npa(b).name}@${a}`, b] } // no valid semver ranges used return [a, b] } async findVersionsByPackageName (specs) { let actualTree const Arborist = require('@npmcli/arborist') try { const opts = { ...this.npm.flatOptions, path: this.top, } const arb = new Arborist(opts) actualTree = await arb.loadActual(opts) } catch { log.verbose('diff', 'failed to load actual install tree') } return specs.map(i => { const spec = npa(i) if (spec.rawSpec !== '*') { return i } const node = actualTree && actualTree.inventory.query('name', spec.name) .values().next().value const res = !node || !node.package || !node.package.version ? spec.fetchSpec : `file:${node.realpath.replace(/#/g, '%23')}` return `${spec.name}@${res}` }) } } module.exports = Diff const npa = require('npm-package-arg') const npmFetch = require('npm-registry-fetch') const semver = require('semver') const { log, output } = require('proc-log') const { otplease } = require('../utils/auth.js') const pkgJson = require('@npmcli/package-json') const BaseCommand = require('../base-cmd.js') class DistTag extends BaseCommand { static description = 'Modify package distribution tags' static params = ['workspace', 'workspaces', 'include-workspace-root'] static name = 'dist-tag' static usage = [ 'add []', 'rm ', 'ls []', ] static workspaces = true static ignoreImplicitWorkspace = false static async completion (opts) { const argv = opts.conf.argv.remain if (argv.length === 2) { return ['add', 'rm', 'ls'] } switch (argv[2]) { default: return [] } } async exec ([cmdName, pkg, tag]) { const opts = { ...this.npm.flatOptions, } if (['add', 'a', 'set', 's'].includes(cmdName)) { return this.add(pkg, tag, opts) } if (['rm', 'r', 'del', 'd', 'remove'].includes(cmdName)) { return this.remove(pkg, tag, opts) } if (['ls', 'l', 'sl', 'list'].includes(cmdName)) { return this.list(pkg, opts) } if (!pkg) { // when only using the pkg name the default behavior // should be listing the existing tags return this.list(cmdName, opts) } else { throw this.usageError() } } async execWorkspaces ([cmdName, pkg, tag]) { // cmdName is some form of list // pkg is one of: // - unset // - . // - .@version if (['ls', 'l', 'sl', 'list'].includes(cmdName) && (!pkg || pkg === '.' || /^\.@/.test(pkg))) { return this.listWorkspaces() } // pkg is unset // cmdName is one of: // - unset // - . // - .@version if (!pkg && (!cmdName || cmdName === '.' || /^\.@/.test(cmdName))) { return this.listWorkspaces() } // anything else is just a regular dist-tag command // so we fallback to the non-workspaces implementation log.warn('dist-tag', 'Ignoring workspaces for specified package') return this.exec([cmdName, pkg, tag]) } async add (spec, tag, opts) { spec = npa(spec || '') const version = spec.rawSpec const defaultTag = tag || this.npm.config.get('tag') log.verbose('dist-tag add', defaultTag, 'to', spec.name + '@' + version) // make sure new spec with tag is valid, this will throw if invalid npa(`${spec.name}@${defaultTag}`) if (!spec.name || !version || !defaultTag) { throw this.usageError('must provide a spec with a name and version, and a tag to add') } const t = defaultTag.trim() if (semver.validRange(t)) { throw new Error('Tag name must not be a valid SemVer range: ' + t) } const tags = await this.fetchTags(spec, opts) if (tags[t] === version) { log.warn('dist-tag add', t, 'is already set to version', version) return } tags[t] = version const url = `/-/package/${spec.escapedName}/dist-tags/${encodeURIComponent(t)}` const reqOpts = { ...opts, method: 'PUT', body: JSON.stringify(version), headers: { 'content-type': 'application/json', }, spec, } await otplease(this.npm, reqOpts, o => npmFetch(url, o)) output.standard(`+${t}: ${spec.name}@${version}`) } async remove (spec, tag, opts) { spec = npa(spec || '') log.verbose('dist-tag del', tag, 'from', spec.name) if (!spec.name) { throw this.usageError() } const tags = await this.fetchTags(spec, opts) if (!tags[tag]) { log.info('dist-tag del', tag, 'is not a dist-tag on', spec.name) throw new Error(tag + ' is not a dist-tag on ' + spec.name) } const version = tags[tag] delete tags[tag] const url = `/-/package/${spec.escapedName}/dist-tags/${encodeURIComponent(tag)}` const reqOpts = { ...opts, method: 'DELETE', spec, } await otplease(this.npm, reqOpts, o => npmFetch(url, o)) output.standard(`-${tag}: ${spec.name}@${version}`) } async list (spec, opts) { if (!spec) { if (this.npm.global) { throw this.usageError() } const { content: { name } } = await pkgJson.normalize(this.npm.prefix) if (!name) { throw this.usageError() } return this.list(name, opts) } spec = npa(spec) try { const tags = await this.fetchTags(spec, opts) const msg = Object.keys(tags).map(k => `${k}: ${tags[k]}`).sort().join('\n') output.standard(msg) return tags } catch (err) { log.error('dist-tag ls', "Couldn't get dist-tag data for", spec) throw err } } async listWorkspaces () { await this.setWorkspaces() for (const name of this.workspaceNames) { try { output.standard(`${name}:`) await this.list(npa(name), this.npm.flatOptions) } catch { // set the exitCode directly, but ignore the error // since it will have already been logged by this.list() process.exitCode = 1 } } } async fetchTags (spec, opts) { const data = await npmFetch.json( `/-/package/${spec.escapedName}/dist-tags`, { ...opts, 'prefer-online': true, spec } ) if (data && typeof data === 'object') { delete data._etag } if (!data || !Object.keys(data).length) { throw new Error('No dist-tags found for ' + spec.name) } return data } } module.exports = DistTag const PackageUrlCmd = require('../package-url-cmd.js') class Docs extends PackageUrlCmd { static description = 'Open documentation for a package in a web browser' static name = 'docs' getUrl (spec, mani) { if (mani.homepage) { return mani.homepage } const info = this.hostedFromMani(mani) if (info) { return info.docs() } return `https://www.npmjs.com/package/${mani.name}` } } module.exports = Docs const cacache = require('cacache') const { access, lstat, readdir, constants: { R_OK, W_OK, X_OK } } = require('node:fs/promises') const npmFetch = require('make-fetch-happen') const which = require('which') const pacote = require('pacote') const { resolve } = require('node:path') const semver = require('semver') const { log, output } = require('proc-log') const ping = require('../utils/ping.js') const { defaults } = require('@npmcli/config/lib/definitions') const BaseCommand = require('../base-cmd.js') const maskLabel = mask => { const label = [] if (mask & R_OK) { label.push('readable') } if (mask & W_OK) { label.push('writable') } if (mask & X_OK) { label.push('executable') } return label.join(', ') } const subcommands = [ { // Ping is left in as a legacy command but is listed as "connection" to // make more sense to more people groups: ['connection', 'ping', 'registry'], title: 'Connecting to the registry', cmd: 'checkPing', }, { groups: ['versions'], title: 'Checking npm version', cmd: 'getLatestNpmVersion', }, { groups: ['versions'], title: 'Checking node version', cmd: 'getLatestNodejsVersion', }, { groups: ['registry'], title: 'Checking configured npm registry', cmd: 'checkNpmRegistry', }, { groups: ['environment'], title: 'Checking for git executable in PATH', cmd: 'getGitPath', }, { groups: ['environment'], title: 'Checking for global bin folder in PATH', cmd: 'getBinPath', }, { groups: ['permissions', 'cache'], title: 'Checking permissions on cached files (this may take awhile)', cmd: 'checkCachePermission', windows: false, }, { groups: ['permissions'], title: 'Checking permissions on local node_modules (this may take awhile)', cmd: 'checkLocalModulesPermission', windows: false, }, { groups: ['permissions'], title: 'Checking permissions on global node_modules (this may take awhile)', cmd: 'checkGlobalModulesPermission', windows: false, }, { groups: ['permissions'], title: 'Checking permissions on local bin folder', cmd: 'checkLocalBinPermission', windows: false, }, { groups: ['permissions'], title: 'Checking permissions on global bin folder', cmd: 'checkGlobalBinPermission', windows: false, }, { groups: ['cache'], title: 'Verifying cache contents (this may take awhile)', cmd: 'verifyCachedFiles', windows: false, }, // TODO: // group === 'dependencies'? // - ensure arborist.loadActual() runs without errors and no invalid edges // - ensure package-lock.json matches loadActual() // - verify loadActual without hidden lock file matches hidden lockfile // group === '???' // - verify all local packages have bins linked // What is the fix for these? ] class Doctor extends BaseCommand { static description = 'Check the health of your npm environment' static name = 'doctor' static params = ['registry'] static ignoreImplicitWorkspace = false static usage = [`[${subcommands.flatMap(s => s.groups) .filter((value, index, self) => self.indexOf(value) === index && value !== 'ping') .join('] [')}]`] static subcommands = subcommands async exec (args) { log.info('doctor', 'Running checkup') let allOk = true const actions = this.actions(args) const chalk = this.npm.chalk for (const { title, cmd } of actions) { this.output(title) // TODO when we have an in progress indicator that could go here let result try { result = await this[cmd]() this.output(`${chalk.green('Ok')}${result ? `\n${result}` : ''}\n`) } catch (err) { allOk = false this.output(`${chalk.red('Not ok')}\n${chalk.cyan(err)}\n`) } } if (!allOk) { if (this.npm.silent) { throw new Error('Some problems found. Check logs or disable silent mode for recommendations.') } else { throw new Error('Some problems found. See above for recommendations.') } } } async checkPing () { log.info('doctor', 'Pinging registry') try { await ping({ ...this.npm.flatOptions, retry: false }) return '' } catch (er) { if (/^E\d{3}$/.test(er.code || '')) { throw er.code.slice(1) + ' ' + er.message } else { throw er.message } } } async getLatestNpmVersion () { log.info('doctor', 'Getting npm package information') const latest = (await pacote.manifest('npm@latest', this.npm.flatOptions)).version if (semver.gte(this.npm.version, latest)) { return `current: v${this.npm.version}, latest: v${latest}` } else { throw `Use npm v${latest}` } } async getLatestNodejsVersion () { // XXX get the latest in the current major as well const current = process.version const currentRange = `^${current}` const url = 'https://nodejs.org/dist/index.json' log.info('doctor', 'Getting Node.js release information') const res = await npmFetch(url, { method: 'GET', ...this.npm.flatOptions }) const data = await res.json() let maxCurrent = '0.0.0' let maxLTS = '0.0.0' for (const { lts, version } of data) { if (lts && semver.gt(version, maxLTS)) { maxLTS = version } if (semver.satisfies(version, currentRange) && semver.gt(version, maxCurrent)) { maxCurrent = version } } const recommended = semver.gt(maxCurrent, maxLTS) ? maxCurrent : maxLTS if (semver.gte(process.version, recommended)) { return `current: ${current}, recommended: ${recommended}` } else { throw `Use node ${recommended} (current: ${current})` } } async getBinPath () { log.info('doctor', 'getBinPath', 'Finding npm global bin in your PATH') if (!process.env.PATH.includes(this.npm.globalBin)) { throw new Error(`Add ${this.npm.globalBin} to your $PATH`) } return this.npm.globalBin } async checkCachePermission () { return this.checkFilesPermission(this.npm.cache, true, R_OK) } async checkLocalModulesPermission () { return this.checkFilesPermission(this.npm.localDir, true, R_OK | W_OK, true) } async checkGlobalModulesPermission () { return this.checkFilesPermission(this.npm.globalDir, false, R_OK) } async checkLocalBinPermission () { return this.checkFilesPermission(this.npm.localBin, false, R_OK | W_OK | X_OK, true) } async checkGlobalBinPermission () { return this.checkFilesPermission(this.npm.globalBin, false, X_OK) } async checkFilesPermission (root, shouldOwn, mask, missingOk) { let ok = true try { const uid = process.getuid() const gid = process.getgid() const files = new Set([root]) for (const f of files) { const st = await lstat(f).catch(er => { // if it can't be missing, or if it can and the error wasn't that it was missing if (!missingOk || er.code !== 'ENOENT') { ok = false log.warn('doctor', 'checkFilesPermission', 'error getting info for ' + f) } }) if (!st) { continue } if (shouldOwn && (uid !== st.uid || gid !== st.gid)) { log.warn('doctor', 'checkFilesPermission', 'should be owner of ' + f) ok = false } if (!st.isDirectory() && !st.isFile()) { continue } try { await access(f, mask) } catch { ok = false const msg = `Missing permissions on ${f} (expect: ${maskLabel(mask)})` log.error('doctor', 'checkFilesPermission', msg) continue } if (st.isDirectory()) { const entries = await readdir(f).catch(() => { ok = false log.warn('doctor', 'checkFilesPermission', 'error reading directory ' + f) return [] }) for (const entry of entries) { files.add(resolve(f, entry)) } } } } finally { if (!ok) { throw ( `Check the permissions of files in ${root}` + (shouldOwn ? ' (should be owned by current user)' : '') ) } else { return '' } } } async getGitPath () { log.info('doctor', 'Finding git in your PATH') return await which('git').catch(er => { log.warn('doctor', 'getGitPath', er) throw new Error("Install git and ensure it's in your PATH.") }) } async verifyCachedFiles () { log.info('doctor', 'verifyCachedFiles', 'Verifying the npm cache') const stats = await cacache.verify(this.npm.flatOptions.cache) const { badContentCount, reclaimedCount, missingContent, reclaimedSize } = stats if (badContentCount || reclaimedCount || missingContent) { if (badContentCount) { log.warn('doctor', 'verifyCachedFiles', `Corrupted content removed: ${badContentCount}`) } if (reclaimedCount) { log.warn( 'doctor', 'verifyCachedFiles', `Content garbage-collected: ${reclaimedCount} (${reclaimedSize} bytes)` ) } if (missingContent) { log.warn('doctor', 'verifyCachedFiles', `Missing content: ${missingContent}`) } log.warn('doctor', 'verifyCachedFiles', 'Cache issues have been fixed') } log.info( 'doctor', 'verifyCachedFiles', `Verification complete. Stats: ${JSON.stringify(stats, null, 2)}` ) return `verified ${stats.verifiedContent} tarballs` } async checkNpmRegistry () { if (this.npm.flatOptions.registry !== defaults.registry) { throw `Try \`npm config set registry=${defaults.registry}\`` } else { return `using default registry (${defaults.registry})` } } output (...args) { // TODO display layer should do this if (!this.npm.silent) { output.standard(...args) } } actions (params) { return this.constructor.subcommands.filter(subcmd => { if (process.platform === 'win32' && subcmd.windows === false) { return false } if (params.length) { return params.some(param => subcmd.groups.includes(param)) } return true }) } } module.exports = Doctor const { resolve } = require('node:path') const { lstat } = require('node:fs/promises') const cp = require('node:child_process') const completion = require('../utils/installed-shallow.js') const BaseCommand = require('../base-cmd.js') const splitPackageNames = (path) => path.split('/') // combine scoped parts .reduce((parts, part) => { if (parts.length === 0) { return [part] } const lastPart = parts[parts.length - 1] // check if previous part is the first part of a scoped package if (lastPart[0] === '@' && !lastPart.includes('/')) { parts[parts.length - 1] += '/' + part } else { parts.push(part) } return parts }, []) .join('/node_modules/') .replace(/(\/node_modules)+/, '/node_modules') // npm edit // open the package folder in the $EDITOR class Edit extends BaseCommand { static description = 'Edit an installed package' static name = 'edit' static usage = ['[/...]'] static params = ['editor'] static ignoreImplicitWorkspace = false // TODO /* istanbul ignore next */ static async completion (opts, npm) { return completion(npm, opts) } async exec (args) { if (args.length !== 1) { throw this.usageError() } const path = splitPackageNames(args[0]) const dir = resolve(this.npm.dir, path) await lstat(dir) await new Promise((res, rej) => { const [bin, ...spawnArgs] = this.npm.config.get('editor').split(/\s+/) const editor = cp.spawn(bin, [...spawnArgs, dir], { stdio: 'inherit' }) editor.on('exit', async (code) => { if (code) { return rej(new Error(`editor process exited with code: ${code}`)) } await this.npm.exec('rebuild', [dir]).then(res).catch(rej) }) }) } } module.exports = Edit const { resolve } = require('node:path') const libexec = require('libnpmexec') const BaseCommand = require('../base-cmd.js') class Exec extends BaseCommand { static description = 'Run a command from a local or remote npm package' static params = [ 'package', 'call', 'workspace', 'workspaces', 'include-workspace-root', ] static name = 'exec' static usage = [ '-- [@] [args...]', '--package=[@] -- [args...]', '-c \' [args...]\'', '--package=foo -c \' [args...]\'', ] static workspaces = true static ignoreImplicitWorkspace = false static isShellout = true async exec (args) { return this.callExec(args) } async execWorkspaces (args) { await this.setWorkspaces() for (const [name, path] of this.workspaces) { const locationMsg = `in workspace ${this.npm.chalk.green(name)} at location:\n${this.npm.chalk.dim(path)}` await this.callExec(args, { name, locationMsg, runPath: path }) } } async callExec (args, { name, locationMsg, runPath } = {}) { let localBin = this.npm.localBin let pkgPath = this.npm.localPrefix // This is where libnpmexec will actually run the scripts from if (!runPath) { runPath = process.cwd() } else { // We have to consider if the workspace has its own separate versions // libnpmexec will walk up to localDir after looking here localBin = resolve(this.npm.localDir, name, 'node_modules', '.bin') // We also need to look for `bin` entries in the workspace package.json // libnpmexec will NOT look in the project root for the bin entry pkgPath = runPath } const call = this.npm.config.get('call') let globalPath const { flatOptions, globalBin, globalDir, chalk, } = this.npm const scriptShell = this.npm.config.get('script-shell') || undefined const packages = this.npm.config.get('package') const yes = this.npm.config.get('yes') // --prefix sets both of these to the same thing, meaning the global prefix // is invalid (i.e. no lib/node_modules). This is not a trivial thing to // untangle and fix so we work around it here. if (this.npm.localPrefix !== this.npm.globalPrefix) { globalPath = resolve(globalDir, '..') } if (call && args.length) { throw this.usageError() } return libexec({ ...flatOptions, // we explicitly set packageLockOnly to false because if it's true // when we try to install a missing package, we won't actually install it packageLockOnly: false, // what the user asked to run args[0] is run by default args: [...args], // copy args so they dont get mutated // specify a custom command to be run instead of args[0] call, chalk, // where to look for bins globally, if a file matches call or args[0] it is called globalBin, // where to look for packages globally, if a package matches call or args[0] it is called globalPath, // where to look for bins locally, if a file matches call or args[0] it is called localBin, locationMsg, // packages that need to be installed packages, // path where node_modules is path: this.npm.localPrefix, // where to look for package.json#bin entries first pkgPath, // cwd to run from runPath, scriptShell, yes, }) } } module.exports = Exec const { explainNode } = require('../utils/explain-dep.js') const npa = require('npm-package-arg') const semver = require('semver') const { relative, resolve } = require('node:path') const validName = require('validate-npm-package-name') const { output } = require('proc-log') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Explain extends ArboristWorkspaceCmd { static description = 'Explain installed packages' static name = 'explain' static usage = [''] static params = [ 'json', 'workspace', ] static ignoreImplicitWorkspace = false // TODO /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) } async exec (args) { if (!args.length) { throw this.usageError() } const Arborist = require('@npmcli/arborist') const arb = new Arborist({ path: this.npm.prefix, ...this.npm.flatOptions }) const tree = await arb.loadActual() if (this.npm.flatOptions.workspacesEnabled && this.workspaceNames && this.workspaceNames.length ) { this.filterSet = arb.workspaceDependencySet(tree, this.workspaceNames) } else if (!this.npm.flatOptions.workspacesEnabled) { this.filterSet = arb.excludeWorkspacesDependencySet(tree) } const nodes = new Set() for (const arg of args) { for (const node of this.getNodes(tree, arg)) { const filteredOut = this.filterSet && this.filterSet.size > 0 && !this.filterSet.has(node) if (!filteredOut) { nodes.add(node) } } } if (nodes.size === 0) { throw new Error(`No dependencies found matching ${args.join(', ')}`) } const expls = [] for (const node of nodes) { const { extraneous, dev, optional, devOptional, peer, inBundle, overridden } = node const expl = node.explain() if (extraneous) { expl.extraneous = true } else { expl.dev = dev expl.optional = optional expl.devOptional = devOptional expl.peer = peer expl.bundled = inBundle expl.overridden = overridden } expls.push(expl) } if (this.npm.flatOptions.json) { output.buffer(expls) } else { output.standard(expls.map(expl => { return explainNode(expl, Infinity, this.npm.chalk) }).join('\n\n')) } } getNodes (tree, arg) { // if it's just a name, return packages by that name const { validForOldPackages: valid } = validName(arg) if (valid) { return tree.inventory.query('packageName', arg) } // if it's a location, get that node const maybeLoc = arg.replace(/\\/g, '/').replace(/\/+$/, '') const nodeByLoc = tree.inventory.get(maybeLoc) if (nodeByLoc) { return [nodeByLoc] } // maybe a path to a node_modules folder const maybePath = relative(this.npm.prefix, resolve(maybeLoc)) .replace(/\\/g, '/').replace(/\/+$/, '') const nodeByPath = tree.inventory.get(maybePath) if (nodeByPath) { return [nodeByPath] } // otherwise, try to select all matching nodes try { return this.getNodesByVersion(tree, arg) } catch { return [] } } getNodesByVersion (tree, arg) { const spec = npa(arg, this.npm.prefix) if (spec.type !== 'version' && spec.type !== 'range') { return [] } return tree.inventory.filter(node => { return node.package.name === spec.name && semver.satisfies(node.package.version, spec.rawSpec) }) } } module.exports = Explain const pkgJson = require('@npmcli/package-json') const runScript = require('@npmcli/run-script') const { join, relative } = require('node:path') const { log, output } = require('proc-log') const completion = require('../utils/installed-shallow.js') const BaseCommand = require('../base-cmd.js') // npm explore [@] // open a subshell to the package folder. class Explore extends BaseCommand { static description = 'Browse an installed package' static name = 'explore' static usage = [' [ -- ]'] static params = ['shell'] static ignoreImplicitWorkspace = false // TODO /* istanbul ignore next */ static async completion (opts, npm) { return completion(npm, opts) } async exec (args) { if (args.length < 1 || !args[0]) { throw this.usageError() } const pkgname = args.shift() // detect and prevent any .. shenanigans const path = join(this.npm.dir, join('/', pkgname)) if (relative(path, this.npm.dir) === '') { throw this.usageError() } // run as if running a script named '_explore', which we set to either // the set of arguments, or the shell config, and let @npmcli/run-script // handle all the escaping and PATH setup stuff. const { content: pkg } = await pkgJson.normalize(path).catch(er => { log.error('explore', `It doesn't look like ${pkgname} is installed.`) throw er }) const { shell } = this.npm.flatOptions pkg.scripts = { ...(pkg.scripts || {}), _explore: args.join(' ').trim() || shell, } if (!args.length) { output.standard(`\nExploring ${path}\nType 'exit' or ^D when finished\n`) } return runScript({ ...this.npm.flatOptions, pkg, path, event: '_explore', stdio: 'inherit', }).catch(er => { process.exitCode = typeof er.code === 'number' && er.code !== 0 ? er.code : 1 // if it's not an exit error, or non-interactive, throw it const isProcExit = er.message === 'command failed' && (typeof er.code === 'number' || /^SIG/.test(er.signal || '')) if (args.length || !isProcExit) { throw er } }) } } module.exports = Explore const ArboristWorkspaceCmd = require('../arborist-cmd.js') // dedupe duplicated packages, or find them in the tree class FindDupes extends ArboristWorkspaceCmd { static description = 'Find duplication in the package tree' static name = 'find-dupes' static params = [ 'install-strategy', 'legacy-bundling', 'global-style', 'strict-peer-deps', 'package-lock', 'omit', 'include', 'ignore-scripts', 'audit', 'bin-links', 'fund', ...super.params, ] async exec () { this.npm.config.set('dry-run', true) return this.npm.exec('dedupe', []) } } module.exports = FindDupes const archy = require('archy') const pacote = require('pacote') const semver = require('semver') const { output } = require('proc-log') const npa = require('npm-package-arg') const { depth } = require('treeverse') const { readTree: getFundingInfo, normalizeFunding, isValidFunding } = require('libnpmfund') const { openUrl } = require('../utils/open-url.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') const getPrintableName = ({ name, version }) => { const printableVersion = version ? `@${version}` : '' return `${name}${printableVersion}` } const errCode = (msg, code) => Object.assign(new Error(msg), { code }) class Fund extends ArboristWorkspaceCmd { static description = 'Retrieve funding information' static name = 'fund' static params = ['json', 'browser', 'unicode', 'workspace', 'which'] static usage = ['[]'] // XXX: maybe worth making this generic for all commands? usageMessage (paramsObj = {}) { let msg = `\`npm ${this.constructor.name}` const params = Object.entries(paramsObj) if (params.length) { msg += ` ${this.constructor.usage}` } for (const [key, value] of params) { msg += ` --${key}=${value}` } return `${msg}\`` } // TODO /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) } async exec (args) { const spec = args[0] let fundingSourceNumber = this.npm.config.get('which') if (fundingSourceNumber != null) { fundingSourceNumber = parseInt(fundingSourceNumber, 10) if (isNaN(fundingSourceNumber) || fundingSourceNumber < 1) { throw errCode( `${this.usageMessage({ which: 'fundingSourceNumber' })} must be given a positive integer`, 'EFUNDNUMBER' ) } } if (this.npm.global) { throw errCode( `${this.usageMessage()} does not support global packages`, 'EFUNDGLOBAL' ) } const where = this.npm.prefix const Arborist = require('@npmcli/arborist') const arb = new Arborist({ ...this.npm.flatOptions, path: where }) const tree = await arb.loadActual() if (spec) { await this.openFundingUrl({ path: where, tree, spec, fundingSourceNumber, }) return } // TODO: add !workspacesEnabled option handling to libnpmfund const fundingInfo = getFundingInfo(tree, { ...this.flatOptions, Arborist, workspaces: this.workspaceNames, }) if (this.npm.config.get('json')) { output.buffer(fundingInfo) } else { output.standard(this.printHuman(fundingInfo)) } } printHuman (fundingInfo) { const unicode = this.npm.config.get('unicode') const seenUrls = new Map() const tree = obj => archy(obj, '', { unicode }) const result = depth({ tree: fundingInfo, // composes human readable package name // and creates a new archy item for readable output visit: ({ name, version, funding }) => { const [fundingSource] = [].concat(normalizeFunding(funding)).filter(isValidFunding) const { url } = fundingSource || {} const pkgRef = getPrintableName({ name, version }) if (!url) { return { label: pkgRef } } let item if (seenUrls.has(url)) { item = seenUrls.get(url) item.label += `${this.npm.chalk.dim(',')} ${pkgRef}` return null } item = { label: tree({ label: this.npm.chalk.blue(url), nodes: [pkgRef], }).trim(), } // stacks all packages together under the same item seenUrls.set(url, item) return item }, // puts child nodes back into returned archy // output while also filtering out missing items leave: (item, children) => { if (item) { item.nodes = children.filter(Boolean) } return item }, // turns tree-like object return by libnpmfund // into children to be properly read by treeverse getChildren: node => Object.keys(node.dependencies || {}).map(key => ({ name: key, ...node.dependencies[key], })), }) const res = tree(result) return res } async openFundingUrl ({ path, tree, spec, fundingSourceNumber }) { const arg = npa(spec, path) const retrievePackageMetadata = () => { if (arg.type === 'directory') { if (tree.path === arg.fetchSpec) { // matches cwd, e.g: npm fund . return tree.package } else { // matches any file path within current arborist inventory for (const item of tree.inventory.values()) { if (item.path === arg.fetchSpec) { return item.package } } } } else { // tries to retrieve a package from arborist inventory // by matching resulted package name from the provided spec const [item] = [...tree.inventory.query('name', arg.name)] .filter(i => semver.valid(i.package.version)) .sort((a, b) => semver.rcompare(a.package.version, b.package.version)) if (item) { return item.package } } } const { funding } = retrievePackageMetadata() || (await pacote.manifest(arg, this.npm.flatOptions).catch(() => ({}))) const validSources = [].concat(normalizeFunding(funding)).filter(isValidFunding) if (!validSources.length) { throw errCode(`No valid funding method available for: ${spec}`, 'ENOFUND') } const fundSource = fundingSourceNumber ? validSources[fundingSourceNumber - 1] : validSources.length === 1 ? validSources[0] : null if (fundSource) { return openUrl(this.npm, ...this.urlMessage(fundSource)) } const ambiguousUrlMsg = [ ...validSources.map((s, i) => `${i + 1}: ${this.urlMessage(s).reverse().join(': ')}`), `Run ${this.usageMessage({ which: '1' })}` + ', for example, to open the first funding URL listed in that package', ] if (fundingSourceNumber) { ambiguousUrlMsg.unshift(`--which=${fundingSourceNumber} is not a valid index`) } output.standard(ambiguousUrlMsg.join('\n')) } urlMessage (source) { const { type, url } = source const typePrefix = type ? `${type} funding` : 'Funding' const message = `${typePrefix} available at the following URL` return [url, message] } } module.exports = Fund const Npm = require('../npm.js') const BaseCommand = require('../base-cmd.js') class Get extends BaseCommand { static description = 'Get a value from the npm configuration' static name = 'get' static usage = ['[ ...] (See `npm config`)'] static params = ['long'] static ignoreImplicitWorkspace = false // TODO /* istanbul ignore next */ static async completion (opts) { const Config = Npm.cmd('config') return Config.completion(opts) } async exec (args) { return this.npm.exec('config', ['get'].concat(args)) } } module.exports = Get const { readFile } = require('node:fs/promises') const path = require('node:path') const { glob } = require('glob') const { output } = require('proc-log') const BaseCommand = require('../base-cmd.js') const globify = pattern => pattern.split('\\').join('/') class HelpSearch extends BaseCommand { static description = 'Search npm help documentation' static name = 'help-search' static usage = [''] static params = ['long'] async exec (args) { if (!args.length) { throw this.usageError() } const docPath = path.resolve(this.npm.npmRoot, 'docs/content') let files = await glob(`${globify(docPath)}/*/*.md`) // preserve glob@8 behavior files = files.sort((a, b) => a.localeCompare(b, 'en')) const data = await this.readFiles(files) const results = await this.searchFiles(args, data) const formatted = this.formatResults(args, results) if (!formatted.trim()) { output.standard(`No matches in help for: ${args.join(' ')}\n`) } else { output.standard(formatted) } } async readFiles (files) { const res = {} await Promise.all(files.map(async file => { res[file] = (await readFile(file, 'utf8')) .replace(/^---\n(.*\n)*?---\n/, '').trim() })) return res } async searchFiles (args, data) { const results = [] for (const [file, content] of Object.entries(data)) { const lowerCase = content.toLowerCase() // skip if no matches at all if (!args.some(a => lowerCase.includes(a.toLowerCase()))) { continue } const lines = content.split(/\n+/) // if a line has a search term, then skip it and the next line. // if the next line has a search term, then skip all 3 // otherwise, set the line to null. then remove the nulls. for (let i = 0; i < lines.length; i++) { const line = lines[i] const nextLine = lines[i + 1] let match = false if (nextLine) { match = args.some(a => nextLine.toLowerCase().includes(a.toLowerCase())) if (match) { // skip over the next line, and the line after it. i += 2 continue } } match = args.some(a => line.toLowerCase().includes(a.toLowerCase())) if (match) { // skip over the next line i++ continue } lines[i] = null } // now squish any string of nulls into a single null const pruned = lines.reduce((l, r) => { if (!(r === null && l[l.length - 1] === null)) { l.push(r) } return l }, []) if (pruned[pruned.length - 1] === null) { pruned.pop() } if (pruned[0] === null) { pruned.shift() } // now count how many args were found const found = {} let totalHits = 0 for (const line of pruned) { for (const arg of args) { const hit = (line || '').toLowerCase() .split(arg.toLowerCase()).length - 1 if (hit > 0) { found[arg] = (found[arg] || 0) + hit totalHits += hit } } } const cmd = 'npm help ' + path.basename(file, '.md').replace(/^npm-/, '') results.push({ file, cmd, lines: pruned, found: Object.keys(found), hits: found, totalHits, }) } // sort results by number of results found, then by number of hits // then by number of matching lines // coverage is ignored here because the contents of results are // nondeterministic due to either glob or readFiles or Object.entries return results.sort(/* istanbul ignore next */ (a, b) => a.found.length > b.found.length ? -1 : a.found.length < b.found.length ? 1 : a.totalHits > b.totalHits ? -1 : a.totalHits < b.totalHits ? 1 : a.lines.length > b.lines.length ? -1 : a.lines.length < b.lines.length ? 1 : 0).slice(0, 10) } formatResults (args, results) { const cols = Math.min(process.stdout.columns || Infinity, 80) + 1 const formattedOutput = results.map(res => { const out = [res.cmd] const r = Object.keys(res.hits) .map(k => `${k}:${res.hits[k]}`) .sort((a, b) => a > b ? 1 : -1) .join(' ') out.push(' '.repeat((Math.max(1, cols - out.join(' ').length - r.length - 1)))) out.push(r) if (!this.npm.config.get('long')) { return out.join('') } out.unshift('\n\n') out.push('\n') out.push('-'.repeat(cols - 1) + '\n') res.lines.forEach((line, i) => { if (line === null || i > 3) { return } const hilitLine = [] for (const arg of args) { const finder = line.toLowerCase().split(arg.toLowerCase()) let p = 0 for (const f of finder) { hilitLine.push(line.slice(p, p + f.length)) const word = line.slice(p + f.length, p + f.length + arg.length) hilitLine.push(this.npm.chalk.blue(word)) p += f.length + arg.length } } out.push(hilitLine.join('') + '\n') }) return out.join('') }).join('\n') const finalOut = results.length && !this.npm.config.get('long') ? 'Top hits for ' + (args.map(JSON.stringify).join(' ')) + '\n' + '—'.repeat(cols - 1) + '\n' + formattedOutput + '\n' + '—'.repeat(cols - 1) + '\n' + '(run with -l or --long to see more context)' : formattedOutput return finalOut.trim() } } module.exports = HelpSearch const spawn = require('@npmcli/promise-spawn') const path = require('node:path') const { openUrl } = require('../utils/open-url.js') const { glob } = require('glob') const { output, input } = require('proc-log') const localeCompare = require('@isaacs/string-locale-compare')('en') const { deref } = require('../utils/cmd-list.js') const BaseCommand = require('../base-cmd.js') const globify = pattern => pattern.split('\\').join('/') // Strips out the number from foo.7 or foo.7. or foo.7.tgz // We don't currently compress our man pages but if we ever did this would // seamlessly continue supporting it const manNumberRegex = /\.(\d+)(\.[^/\\]*)?$/ // hardcoded names for mansections // XXX: these are used in the docs workspace and should be exported // from npm so section names can changed more easily const manSectionNames = { 1: 'commands', 5: 'configuring-npm', 7: 'using-npm', } class Help extends BaseCommand { static description = 'Get help on npm' static name = 'help' static usage = [' []'] static params = ['viewer'] static async completion (opts, npm) { if (opts.conf.argv.remain.length > 2) { return [] } const g = path.resolve(npm.npmRoot, 'man/man[0-9]/*.[0-9]') let files = await glob(globify(g)) // preserve glob@8 behavior files = files.sort((a, b) => a.localeCompare(b, 'en')) return Object.keys(files.reduce(function (acc, file) { file = path.basename(file).replace(/\.[0-9]+$/, '') file = file.replace(/^npm-/, '') acc[file] = true return acc }, { help: true })) } async exec (args) { // By default we search all of our man subdirectories, but if the user has // asked for a specific one we limit the search to just there const manSearch = /^\d+$/.test(args[0]) ? `man${args.shift()}` : 'man*' if (!args.length) { return output.standard(this.npm.usage) } // npm help foo bar baz: search topics if (args.length > 1) { return this.helpSearch(args) } // `npm help package.json` const arg = (deref(args[0]) || args[0]).replace('.json', '-json') // find either section.n or npm-section.n const f = globify(path.resolve(this.npm.npmRoot, `man/${manSearch}/?(npm-)${arg}.[0-9]*`)) const [man] = await glob(f).then(r => r.sort((a, b) => { // Because the glob is (subtly) different from manNumberRegex, // we can't rely on it passing. const aManNumberMatch = a.match(manNumberRegex)?.[1] || 999 const bManNumberMatch = b.match(manNumberRegex)?.[1] || 999 if (aManNumberMatch !== bManNumberMatch) { return aManNumberMatch - bManNumberMatch } return localeCompare(a, b) })) return man ? this.viewMan(man) : this.helpSearch(args) } helpSearch (args) { return this.npm.exec('help-search', args) } async viewMan (man) { const viewer = this.npm.config.get('viewer') if (viewer === 'browser') { return openUrl(this.npm, this.htmlMan(man), 'help available at the following URL', true) } let args = ['man', [man]] if (viewer === 'woman') { args = ['emacsclient', ['-e', `(woman-find-file '${man}')`]] } try { await input.start(() => spawn(...args, { stdio: 'inherit' })) } catch (err) { if (err.code) { throw new Error(`help process exited with code: ${err.code}`) } else { throw err } } } // Returns the path to the html version of the man page htmlMan (man) { const sect = manSectionNames[man.match(manNumberRegex)[1]] const f = path.basename(man).replace(manNumberRegex, '') return 'file:///' + path.resolve(this.npm.npmRoot, `docs/output/${sect}/${f}.html`) } } module.exports = Help const { statSync } = require('node:fs') const { relative, resolve } = require('node:path') const { mkdir } = require('node:fs/promises') const initJson = require('init-package-json') const npa = require('npm-package-arg') const libexec = require('libnpmexec') const mapWorkspaces = require('@npmcli/map-workspaces') const PackageJson = require('@npmcli/package-json') const { log, output, input } = require('proc-log') const updateWorkspaces = require('../utils/update-workspaces.js') const BaseCommand = require('../base-cmd.js') const posixPath = p => p.split('\\').join('/') class Init extends BaseCommand { static description = 'Create a package.json file' static params = [ 'init-author-name', 'init-author-url', 'init-license', 'init-module', 'init-version', 'yes', 'force', 'scope', 'workspace', 'workspaces', 'workspaces-update', 'include-workspace-root', ] static name = 'init' static usage = [ ' (same as `npx create-`)', '<@scope> (same as `npx <@scope>/create`)', ] static workspaces = true static ignoreImplicitWorkspace = false async exec (args) { // npm exec style if (args.length) { return await this.execCreate(args) } // no args, uses classic init-package-json boilerplate await this.template() } async execWorkspaces (args) { // if the root package is uninitiated, take care of it first if (this.npm.flatOptions.includeWorkspaceRoot) { await this.exec(args) } // reads package.json for the top-level folder first, by doing this we // ensure the command throw if no package.json is found before trying // to create a workspace package.json file or its folders const { content: pkg } = await PackageJson.normalize(this.npm.localPrefix).catch(err => { if (err.code === 'ENOENT') { log.warn('init', 'Missing package.json. Try with `--include-workspace-root`.') } throw err }) // these are workspaces that are being created, so we cant use // this.setWorkspaces() const filters = this.npm.config.get('workspace') const wPath = filterArg => resolve(this.npm.localPrefix, filterArg) const workspacesPaths = [] // npm-exec style, runs in the context of each workspace filter if (args.length) { for (const filterArg of filters) { const path = wPath(filterArg) await mkdir(path, { recursive: true }) workspacesPaths.push(path) await this.execCreate(args, path) await this.setWorkspace(pkg, path) } return } // no args, uses classic init-package-json boilerplate for (const filterArg of filters) { const path = wPath(filterArg) await mkdir(path, { recursive: true }) workspacesPaths.push(path) await this.template(path) await this.setWorkspace(pkg, path) } // reify packages once all workspaces have been initialized await this.update(workspacesPaths) } async execCreate (args, runPath = process.cwd()) { const [initerName, ...otherArgs] = args let packageName = initerName // Only a scope, possibly with a version if (/^@[^/]+$/.test(initerName)) { const [, scope, version] = initerName.split('@') packageName = `@${scope}/create` if (version) { packageName = `${packageName}@${version}` } } else { const req = npa(initerName) if (req.type === 'git' && req.hosted) { const { user, project } = req.hosted packageName = initerName.replace(`${user}/${project}`, `${user}/create-${project}`) } else if (req.registry) { packageName = `${req.name.replace(/^(@[^/]+\/)?/, '$1create-')}@${req.rawSpec}` } else { throw Object.assign(new Error( 'Unrecognized initializer: ' + initerName + '\nFor more package binary executing power check out `npx`:' + '\nhttps://docs.npmjs.com/cli/commands/npx' ), { code: 'EUNSUPPORTED' }) } } const newArgs = [packageName, ...otherArgs] const { flatOptions, localBin, globalBin, chalk, } = this.npm const scriptShell = this.npm.config.get('script-shell') || undefined const yes = this.npm.config.get('yes') await libexec({ ...flatOptions, args: newArgs, localBin, globalBin, output, chalk, path: this.npm.localPrefix, runPath, scriptShell, yes, }) } async template (path = process.cwd()) { const initFile = this.npm.config.get('init-module') if (!this.npm.config.get('yes') && !this.npm.config.get('force')) { output.standard([ 'This utility will walk you through creating a package.json file.', 'It only covers the most common items, and tries to guess sensible defaults.', '', 'See `npm help init` for definitive documentation on these fields', 'and exactly what they do.', '', 'Use `npm install ` afterwards to install a package and', 'save it as a dependency in the package.json file.', '', 'Press ^C at any time to quit.', ].join('\n')) } try { const data = await input.read(() => initJson(path, initFile, this.npm.config)) log.silly('package data', data) return data } catch (er) { if (er.message === 'canceled') { log.warn('init', 'canceled') } else { throw er } } } async setWorkspace (pkg, workspacePath) { const workspaces = await mapWorkspaces({ cwd: this.npm.localPrefix, pkg }) // skip setting workspace if current package.json glob already satisfies it for (const wPath of workspaces.values()) { if (wPath === workspacePath) { return } } // if a create-pkg didn't generate a package.json at the workspace // folder level, it might not be recognized as a workspace by // mapWorkspaces, so we're just going to avoid touching the // top-level package.json try { statSync(resolve(workspacePath, 'package.json')) } catch { return } const pkgJson = await PackageJson.load(this.npm.localPrefix) pkgJson.update({ workspaces: [ ...(pkgJson.content.workspaces || []), posixPath(relative(this.npm.localPrefix, workspacePath)), ], }) await pkgJson.save() } async update (workspacesPaths) { // translate workspaces paths into an array containing workspaces names const workspaces = [] for (const path of workspacesPaths) { const { content: { name } } = await PackageJson.normalize(path).catch(() => ({ content: {} })) if (name) { workspaces.push(name) } } const { config, flatOptions, localPrefix, } = this.npm await updateWorkspaces({ config, flatOptions, localPrefix, npm: this.npm, workspaces, }) } } module.exports = Init const CI = require('./ci.js') // npm install-ci-test // Runs `npm ci` and then runs `npm test` class InstallCITest extends CI { static description = 'Install a project with a clean slate and run tests' static name = 'install-ci-test' async exec (args) { await this.npm.exec('ci', args) return this.npm.exec('test', []) } } module.exports = InstallCITest const Install = require('./install.js') // npm install-test // Runs `npm install` and then runs `npm test` class InstallTest extends Install { static description = 'Install package(s) and run tests' static name = 'install-test' async exec (args) { await this.npm.exec('install', args) return this.npm.exec('test', []) } } module.exports = InstallTest const { readdir } = require('node:fs/promises') const { resolve, join } = require('node:path') const { log } = require('proc-log') const runScript = require('@npmcli/run-script') const pacote = require('pacote') const checks = require('npm-install-checks') const reifyFinish = require('../utils/reify-finish.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Install extends ArboristWorkspaceCmd { static description = 'Install a package' static name = 'install' // These are in the order they will show up in when running "-h" // If adding to this list, consider adding also to ci.js static params = [ 'save', 'save-exact', 'global', 'install-strategy', 'legacy-bundling', 'global-style', 'omit', 'include', 'strict-peer-deps', 'prefer-dedupe', 'package-lock', 'package-lock-only', 'foreground-scripts', 'ignore-scripts', 'audit', 'bin-links', 'fund', 'dry-run', 'cpu', 'os', 'libc', ...super.params, ] static usage = ['[ ...]'] static async completion (opts) { const { partialWord } = opts // install can complete to a folder with a package.json, or any package. // if it has a slash, then it's gotta be a folder // if it starts with https?://, then just give up, because it's a url if (/^https?:\/\//.test(partialWord)) { // do not complete to URLs return [] } if (/\//.test(partialWord)) { // Complete fully to folder if there is exactly one match and it // is a folder containing a package.json file. If that is not the // case we return 0 matches, which will trigger the default bash // complete. const lastSlashIdx = partialWord.lastIndexOf('/') const partialName = partialWord.slice(lastSlashIdx + 1) const partialPath = partialWord.slice(0, lastSlashIdx) || '/' const isDirMatch = async sibling => { if (sibling.slice(0, partialName.length) !== partialName) { return false } try { const contents = await readdir(join(partialPath, sibling)) const result = (contents.indexOf('package.json') !== -1) return result } catch { return false } } try { const siblings = await readdir(partialPath) const matches = [] for (const sibling of siblings) { if (await isDirMatch(sibling)) { matches.push(sibling) } } if (matches.length === 1) { return [join(partialPath, matches[0])] } // no matches return [] } catch { return [] // invalid dir: no matching } } // Note: there used to be registry completion here, // but it stopped making sense somewhere around // 50,000 packages on the registry } async exec (args) { // the /path/to/node_modules/.. const globalTop = resolve(this.npm.globalDir, '..') const ignoreScripts = this.npm.config.get('ignore-scripts') const isGlobalInstall = this.npm.global const where = isGlobalInstall ? globalTop : this.npm.prefix const forced = this.npm.config.get('force') const scriptShell = this.npm.config.get('script-shell') || undefined // be very strict about engines when trying to update npm itself const npmInstall = args.find(arg => arg.startsWith('npm@') || arg === 'npm') if (isGlobalInstall && npmInstall) { const npmOptions = this.npm.flatOptions const npmManifest = await pacote.manifest(npmInstall, npmOptions) try { checks.checkEngine(npmManifest, npmManifest.version, process.version) } catch (e) { if (forced) { log.warn( 'install', `Forcing global npm install with incompatible version ${npmManifest.version} into node ${process.version}` ) } else { throw e } } } // don't try to install the prefix into itself args = args.filter(a => resolve(a) !== this.npm.prefix) // `npm i -g` => "install this package globally" if (where === globalTop && !args.length) { args = ['.'] } // throw usage error if trying to install empty package // name to global space, e.g: `npm i -g ""` if (where === globalTop && !args.every(Boolean)) { throw this.usageError() } const Arborist = require('@npmcli/arborist') const opts = { ...this.npm.flatOptions, auditLevel: null, path: where, add: args, workspaces: this.workspaceNames, } const arb = new Arborist(opts) await arb.reify(opts) if (!args.length && !isGlobalInstall && !ignoreScripts) { const scripts = [ 'preinstall', 'install', 'postinstall', 'prepublish', // XXX(npm9) should we remove this finally?? 'preprepare', 'prepare', 'postprepare', ] for (const event of scripts) { await runScript({ path: where, args: [], scriptShell, stdio: 'inherit', event, }) } } await reifyFinish(this.npm, arb) } } module.exports = Install const { readdir } = require('node:fs/promises') const { resolve } = require('node:path') const npa = require('npm-package-arg') const pkgJson = require('@npmcli/package-json') const semver = require('semver') const reifyFinish = require('../utils/reify-finish.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Link extends ArboristWorkspaceCmd { static description = 'Symlink a package folder' static name = 'link' static usage = [ '[]', ] static params = [ 'save', 'save-exact', 'global', 'install-strategy', 'legacy-bundling', 'global-style', 'strict-peer-deps', 'package-lock', 'omit', 'include', 'ignore-scripts', 'audit', 'bin-links', 'fund', 'dry-run', ...super.params, ] static async completion (opts, npm) { const dir = npm.globalDir const files = await readdir(dir) return files.filter(f => !/^[._-]/.test(f)) } async exec (args) { if (this.npm.global) { throw Object.assign( new Error( 'link should never be --global.\n' + 'Please re-run this command with --local' ), { code: 'ELINKGLOBAL' } ) } // install-links is implicitly false when running `npm link` this.npm.config.set('install-links', false) // link with no args: symlink the folder to the global location // link with package arg: symlink the global to the local args = args.filter(a => resolve(a) !== this.npm.prefix) return args.length ? this.linkInstall(args) : this.linkPkg() } async linkInstall (args) { // load current packages from the global space, // and then add symlinks installs locally const globalTop = resolve(this.npm.globalDir, '..') const Arborist = require('@npmcli/arborist') const globalOpts = { ...this.npm.flatOptions, Arborist, path: globalTop, global: true, prune: false, } const globalArb = new Arborist(globalOpts) // get only current top-level packages from the global space const globals = await globalArb.loadActual({ filter: (node, kid) => !node.isRoot || args.some(a => npa(a).name === kid), }) // any extra arg that is missing from the current // global space should be reified there first const missing = this.missingArgsFromTree(globals, args) if (missing.length) { await globalArb.reify({ ...globalOpts, add: missing, }) } // get a list of module names that should be linked in the local prefix const names = [] for (const a of args) { const arg = npa(a) if (arg.type === 'directory') { const { content } = await pkgJson.normalize(arg.fetchSpec) names.push(content.name) } else { names.push(arg.name) } } // npm link should not save=true by default unless you're // using any of --save-dev or other types const save = Boolean( (this.npm.config.find('save') !== 'default' && this.npm.config.get('save')) || this.npm.config.get('save-optional') || this.npm.config.get('save-peer') || this.npm.config.get('save-dev') || this.npm.config.get('save-prod') ) // create a new arborist instance for the local prefix and // reify all the pending names as symlinks there const localArb = new Arborist({ ...this.npm.flatOptions, prune: false, path: this.npm.prefix, save, }) await localArb.reify({ ...this.npm.flatOptions, prune: false, path: this.npm.prefix, add: names.map(l => `file:${resolve(globalTop, 'node_modules', l).replace(/#/g, '%23')}`), save, workspaces: this.workspaceNames, }) await reifyFinish(this.npm, localArb) } async linkPkg () { const wsp = this.workspacePaths const paths = wsp && wsp.length ? wsp : [this.npm.prefix] const add = paths.map(path => `file:${path.replace(/#/g, '%23')}`) const globalTop = resolve(this.npm.globalDir, '..') const Arborist = require('@npmcli/arborist') const arb = new Arborist({ ...this.npm.flatOptions, Arborist, path: globalTop, global: true, }) await arb.reify({ add, }) await reifyFinish(this.npm, arb) } // Returns a list of items that can't be fulfilled by // things found in the current arborist inventory missingArgsFromTree (tree, args) { if (tree.isLink) { return this.missingArgsFromTree(tree.target, args) } const foundNodes = [] const missing = args.filter(a => { const arg = npa(a) const nodes = tree.children.values() const argFound = [...nodes].every(node => { // TODO: write tests for unmatching version specs, this is hard to test // atm but should be simple once we have a mocked registry again if (arg.name !== node.name /* istanbul ignore next */ || ( arg.version && /* istanbul ignore next */ !semver.satisfies(node.version, arg.version) )) { foundNodes.push(node) return true } }) return argFound }) // remote nodes from the loaded tree in order // to avoid dropping them later when reifying for (const node of foundNodes) { node.parent = null } return missing } } module.exports = Link const LS = require('./ls.js') class LL extends LS { static name = 'll' static usage = ['[[<@scope>/] ...]'] async exec (args) { this.npm.config.set('long', true) return super.exec(args) } } module.exports = LL const { log, output } = require('proc-log') const { redactLog: replaceInfo } = require('@npmcli/redact') const auth = require('../utils/auth.js') const BaseCommand = require('../base-cmd.js') class Login extends BaseCommand { static description = 'Login to a registry user account' static name = 'login' static params = [ 'registry', 'scope', 'auth-type', ] async exec () { const scope = this.npm.config.get('scope') let registry = this.npm.config.get('registry') if (scope) { const scopedRegistry = this.npm.config.get(`${scope}:registry`) const cliRegistry = this.npm.config.get('registry', 'cli') if (scopedRegistry && !cliRegistry) { registry = scopedRegistry } } const creds = this.npm.config.getCredentialsByURI(registry) log.notice('', `Log in on ${replaceInfo(registry)}`) const { message, newCreds } = await auth.login(this.npm, { ...this.npm.flatOptions, creds, registry, }) this.npm.config.delete('_token', 'user') // prevent legacy pollution this.npm.config.setCredentialsByURI(registry, newCreds) if (scope) { this.npm.config.set(scope + ':registry', registry, 'user') } await this.npm.config.save('user') output.standard(message) } } module.exports = Login const npmFetch = require('npm-registry-fetch') const { getAuth } = npmFetch const { log } = require('proc-log') const BaseCommand = require('../base-cmd.js') class Logout extends BaseCommand { static description = 'Log out of the registry' static name = 'logout' static params = [ 'registry', 'scope', ] async exec () { const registry = this.npm.config.get('registry') const scope = this.npm.config.get('scope') const regRef = scope ? `${scope}:registry` : 'registry' const reg = this.npm.config.get(regRef) || registry const auth = getAuth(reg, this.npm.flatOptions) const level = this.npm.config.find(`${auth.regKey}:${auth.authKey}`) // find the config level and only delete from there if (auth.token) { log.verbose('logout', `clearing token for ${reg}`) await npmFetch(`/-/user/token/${encodeURIComponent(auth.token)}`, { ...this.npm.flatOptions, registry: reg, method: 'DELETE', ignoreBody: true, }) } else if (auth.isBasicAuth) { log.verbose('logout', `clearing user credentials for ${reg}`) } else { const msg = `not logged in to ${reg}, so can't log out!` throw Object.assign(new Error(msg), { code: 'ENEEDAUTH' }) } if (scope) { this.npm.config.delete(regRef, level) } this.npm.config.clearCredentialsByURI(reg, level) await this.npm.config.save(level) } } module.exports = Logout const { resolve, relative, sep } = require('node:path') const archy = require('archy') const { breadth } = require('treeverse') const npa = require('npm-package-arg') const { output } = require('proc-log') const ArboristWorkspaceCmd = require('../arborist-cmd.js') const localeCompare = require('@isaacs/string-locale-compare')('en') const relativePrefix = `.${sep}` const _depth = Symbol('depth') const _dedupe = Symbol('dedupe') const _filteredBy = Symbol('filteredBy') const _include = Symbol('include') const _invalid = Symbol('invalid') const _name = Symbol('name') const _missing = Symbol('missing') const _parent = Symbol('parent') const _problems = Symbol('problems') const _required = Symbol('required') const _type = Symbol('type') class LS extends ArboristWorkspaceCmd { static description = 'List installed packages' static name = 'ls' static usage = [''] static params = [ 'all', 'json', 'long', 'parseable', 'global', 'depth', 'omit', 'include', 'link', 'package-lock-only', 'unicode', ...super.params, ] // TODO /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) } async exec (args) { const all = this.npm.config.get('all') const chalk = this.npm.chalk const depth = this.npm.config.get('depth') const global = this.npm.global const json = this.npm.config.get('json') const link = this.npm.config.get('link') const long = this.npm.config.get('long') const omit = this.npm.flatOptions.omit const parseable = this.npm.config.get('parseable') const unicode = this.npm.config.get('unicode') const packageLockOnly = this.npm.config.get('package-lock-only') const workspacesEnabled = this.npm.flatOptions.workspacesEnabled const path = global ? resolve(this.npm.globalDir, '..') : this.npm.prefix const Arborist = require('@npmcli/arborist') const arb = new Arborist({ global, ...this.npm.flatOptions, legacyPeerDeps: false, path, }) const tree = await this.initTree({ arb, args, packageLockOnly }) // filters by workspaces nodes when using -w // We only have to filter the first layer of edges, so we don't // explore anything that isn't part of the selected workspace set. let wsNodes if (this.workspaceNames && this.workspaceNames.length) { wsNodes = arb.workspaceNodes(tree, this.workspaceNames) } const filterBySelectedWorkspaces = edge => { if (!workspacesEnabled && edge.from.isProjectRoot && edge.to.isWorkspace ) { return false } if (!wsNodes || !wsNodes.length) { return true } if (this.npm.flatOptions.includeWorkspaceRoot && edge.to && !edge.to.isWorkspace) { return true } if (edge.from.isProjectRoot) { return (edge.to && edge.to.isWorkspace && wsNodes.includes(edge.to.target)) } return true } const seenItems = new Set() const seenNodes = new Map() const problems = new Set() // defines special handling of printed depth when filtering with args const filterDefaultDepth = depth === null ? Infinity : depth const depthToPrint = (all || args.length) ? filterDefaultDepth : (depth || 0) // add root node of tree to list of seenNodes seenNodes.set(tree.path, tree) // tree traversal happens here, using treeverse.breadth const result = await breadth({ tree, // recursive method, `node` is going to be the current elem (starting from // the `tree` obj) that was just visited in the `visit` method below // `nodeResult` is going to be the returned `item` from `visit` getChildren (node, nodeResult) { const seenPaths = new Set() const workspace = node.isWorkspace const currentDepth = workspace ? 0 : node[_depth] const shouldSkipChildren = !(node instanceof Arborist.Node) || (currentDepth > depthToPrint) return (shouldSkipChildren) ? [] : [...(node.target).edgesOut.values()] .filter(filterBySelectedWorkspaces) .filter(currentDepth === 0 ? filterByEdgesTypes({ link, omit, }) : () => true) .map(mapEdgesToNodes({ seenPaths })) .concat(appendExtraneousChildren({ node, seenPaths })) .sort(sortAlphabetically) .map(augmentNodesWithMetadata({ args, currentDepth, nodeResult, seenNodes, })) }, // visit each `node` of the `tree`, returning an `item` - these are // the elements that will be used to build the final output visit (node) { node[_problems] = getProblems(node, { global }) const item = json ? getJsonOutputItem(node, { global, long }) : parseable ? null : getHumanOutputItem(node, { args, chalk, global, long }) // loop through list of node problems to add them to global list if (node[_include]) { for (const problem of node[_problems]) { problems.add(problem) } } seenItems.add(item) // return a promise so we don't blow the stack return Promise.resolve(item) }, }) // handle the special case of a broken package.json in the root folder const [rootError] = tree.errors.filter(e => e.code === 'EJSONPARSE' && e.path === resolve(path, 'package.json')) if (json) { output.buffer(jsonOutput({ path, problems, result, rootError, seenItems })) } else { output.standard(parseable ? parseableOutput({ seenNodes, global, long }) : humanOutput({ chalk, result, seenItems, unicode }) ) } // if filtering items, should exit with error code on no results if (result && !result[_include] && args.length) { process.exitCode = 1 } if (rootError) { throw Object.assign( new Error('Failed to parse root package.json'), { code: 'EJSONPARSE' } ) } const shouldThrow = problems.size && ![...problems].every(problem => problem.startsWith('extraneous:')) if (shouldThrow) { throw Object.assign( new Error([...problems].join('\n')), { code: 'ELSPROBLEMS' } ) } } async initTree ({ arb, args, packageLockOnly }) { const tree = await ( packageLockOnly ? arb.loadVirtual() : arb.loadActual() ) tree[_include] = args.length === 0 tree[_depth] = 0 return tree } } module.exports = LS const isGitNode = (node) => { if (!node.resolved) { return } try { const { type } = npa(node.resolved) return type === 'git' || type === 'hosted' } catch { return false } } const isOptional = (node) => node[_type] === 'optional' || node[_type] === 'peerOptional' const isExtraneous = (node, { global }) => node.extraneous && !global const getProblems = (node, { global }) => { const problems = new Set() if (node[_missing] && !isOptional(node)) { problems.add(`missing: ${node.pkgid}, required by ${node[_missing]}`) } if (node[_invalid]) { problems.add(`invalid: ${node.pkgid} ${node.path}`) } if (isExtraneous(node, { global })) { problems.add(`extraneous: ${node.pkgid} ${node.path}`) } return problems } // annotates _parent and _include metadata into the resulting // item obj allowing for filtering out results during output const augmentItemWithIncludeMetadata = (node, item) => { item[_parent] = node[_parent] item[_include] = node[_include] // append current item to its parent.nodes which is the // structure expected by archy in order to print tree if (node[_include]) { // includes all ancestors of included node let p = node[_parent] while (p) { p[_include] = true p = p[_parent] } } return item } const getHumanOutputItem = (node, { args, chalk, global, long }) => { const { pkgid, path } = node const workspacePkgId = chalk.blueBright(pkgid) let printable = node.isWorkspace ? workspacePkgId : pkgid // special formatting for top-level package name if (node.isRoot) { const hasNoPackageJson = !Object.keys(node.package).length if (hasNoPackageJson || global) { printable = path } else { printable += `${long ? '\n' : ' '}${path}` } } // TODO there is a LOT of overlap with lib/utils/explain-dep.js here const highlightDepName = args.length && node[_filteredBy] const missingColor = isOptional(node) ? chalk.yellow : chalk.red const missingMsg = `UNMET ${isOptional(node) ? 'OPTIONAL ' : ''}DEPENDENCY` const targetLocation = node.root ? relative(node.root.realpath, node.realpath) : node.targetLocation const invalid = node[_invalid] ? `invalid: ${node[_invalid]}` : '' const label = ( node[_missing] ? missingColor(missingMsg) + ' ' : '' ) + `${highlightDepName ? chalk.yellow(printable) : printable}` + ( node[_dedupe] ? ' ' + chalk.dim('deduped') : '' ) + ( invalid ? ' ' + chalk.red(invalid) : '' ) + ( isExtraneous(node, { global }) ? ' ' + chalk.red('extraneous') : '' ) + ( node.overridden ? ' ' + chalk.dim('overridden') : '' ) + (isGitNode(node) ? ` (${node.resolved})` : '') + (node.isLink ? ` -> ${relativePrefix}${targetLocation}` : '') + (long ? `\n${node.package.description || ''}` : '') return augmentItemWithIncludeMetadata(node, { label, nodes: [] }) } const getJsonOutputItem = (node, { global, long }) => { const item = {} if (node.version) { item.version = node.version } if (node.resolved) { item.resolved = node.resolved } // if the node is the project root, do not add the overridden flag. the project root can't be // overridden anyway, and if we add the flag it causes undesirable behavior when `npm ls --json` // is ran in an empty directory since we end up printing an object with only an overridden prop if (!node.isProjectRoot) { item.overridden = node.overridden } item[_name] = node.name // special formatting for top-level package name const hasPackageJson = node && node.package && Object.keys(node.package).length if (node.isRoot && hasPackageJson) { item.name = node.package.name || node.name } if (long && !node[_missing]) { item.name = item[_name] const { dependencies, ...packageInfo } = node.package Object.assign(item, packageInfo) item.extraneous = false item.path = node.path item._dependencies = { ...node.package.dependencies, ...node.package.optionalDependencies, } item.devDependencies = node.package.devDependencies || {} item.peerDependencies = node.package.peerDependencies || {} } // augment json output items with extra metadata if (isExtraneous(node, { global })) { item.extraneous = true } if (node[_invalid]) { item.invalid = node[_invalid] } if (node[_missing] && !isOptional(node)) { item.required = node[_required] item.missing = true } if (node[_include] && node[_problems] && node[_problems].size) { item.problems = [...node[_problems]] } return augmentItemWithIncludeMetadata(node, item) } const filterByEdgesTypes = ({ link, omit }) => (edge) => { for (const omitType of omit) { if (edge[omitType]) { return false } } return link ? edge.to && edge.to.isLink : true } const appendExtraneousChildren = ({ node, seenPaths }) => // extraneous children are not represented // in edges out, so here we add them to the list: [...node.children.values()] .filter(i => !seenPaths.has(i.path) && i.extraneous) const mapEdgesToNodes = ({ seenPaths }) => (edge) => { let node = edge.to // if the edge is linking to a missing node, we go ahead // and create a new obj that will represent the missing node if (edge.missing || (edge.optional && !node)) { const { name, spec } = edge const pkgid = `${name}@${spec}` node = { name, pkgid, [_missing]: edge.from.pkgid } } // keeps track of a set of seen paths to avoid the edge case in which a tree // item would appear twice given that it's a children of an extraneous item, // so it's marked extraneous but it will ALSO show up in edgesOuts of // its parent so it ends up as two diff nodes if we don't track it if (node.path) { seenPaths.add(node.path) } node[_required] = edge.spec || '*' node[_type] = edge.type if (edge.invalid) { const spec = JSON.stringify(node[_required]) const from = edge.from.location || 'the root project' node[_invalid] = (node[_invalid] ? node[_invalid] + ', ' : '') + (`${spec} from ${from}`) } return node } const filterByPositionalArgs = (args, { node }) => args.length > 0 ? args.some( (spec) => (node.satisfies && node.satisfies(spec)) ) : true const augmentNodesWithMetadata = ({ args, currentDepth, nodeResult, seenNodes, }) => (node) => { // if the original edge was a deduped dep, treeverse will fail to // revisit that node in tree traversal logic, so we make it so that // we have a diff obj for deduped nodes: if (seenNodes.has(node.path)) { const { realpath, root } = node const targetLocation = root ? relative(root.realpath, realpath) : node.targetLocation node = { name: node.name, version: node.version, pkgid: node.pkgid, package: node.package, path: node.path, isLink: node.isLink, realpath: node.realpath, targetLocation, [_type]: node[_type], [_invalid]: node[_invalid], [_missing]: node[_missing], // if it's missing, it's not deduped, it's just missing [_dedupe]: !node[_missing], } } else { // keeps track of already seen nodes in order to check for dedupes seenNodes.set(node.path, node) } // _parent is going to be a ref to a treeverse-visited node (returned from // getHumanOutputItem, getJsonOutputItem, etc) so that we have an easy // shortcut to place new nodes in their right place during tree traversal node[_parent] = nodeResult // _include is the property that allow us to filter based on position args // e.g: `npm ls foo`, `npm ls simple-output@2` // _filteredBy is used to apply extra color info to the item that // was used in args in order to filter node[_filteredBy] = node[_include] = filterByPositionalArgs(args, { node: seenNodes.get(node.path) }) // _depth keeps track of how many levels deep tree traversal currently is // so that we can `npm ls --depth=1` node[_depth] = currentDepth + 1 return node } const sortAlphabetically = ({ pkgid: a }, { pkgid: b }) => localeCompare(a, b) const humanOutput = ({ chalk, result, seenItems, unicode }) => { // we need to traverse the entire tree in order to determine which items // should be included (since a nested transitive included dep will make it // so that all its ancestors should be displayed) // here is where we put items in their expected place for archy output for (const item of seenItems) { if (item[_include] && item[_parent]) { item[_parent].nodes.push(item) } } if (!result.nodes.length) { result.nodes = ['(empty)'] } const archyOutput = archy(result, '', { unicode }) return chalk.reset(archyOutput) } const jsonOutput = ({ path, problems, result, rootError, seenItems }) => { if (problems.size) { result.problems = [...problems] } if (rootError) { result.problems = [ ...(result.problems || []), ...[`error in ${path}: Failed to parse root package.json`], ] result.invalid = true } // we need to traverse the entire tree in order to determine which items // should be included (since a nested transitive included dep will make it // so that all its ancestors should be displayed) // here is where we put items in their expected place for json output for (const item of seenItems) { // append current item to its parent item.dependencies obj in order // to provide a json object structure that represents the installed tree if (item[_include] && item[_parent]) { if (!item[_parent].dependencies) { item[_parent].dependencies = {} } item[_parent].dependencies[item[_name]] = item } } return result } const parseableOutput = ({ global, long, seenNodes }) => { let out = '' for (const node of seenNodes.values()) { if (node.path && node[_include]) { out += node.path if (long) { out += `:${node.pkgid}` out += node.path !== node.realpath ? `:${node.realpath}` : '' out += isExtraneous(node, { global }) ? ':EXTRANEOUS' : '' out += node[_invalid] ? ':INVALID' : '' out += node.overridden ? ':OVERRIDDEN' : '' } out += '\n' } } return out.trim() } const liborg = require('libnpmorg') const { otplease } = require('../utils/auth.js') const BaseCommand = require('../base-cmd.js') const { output } = require('proc-log') class Org extends BaseCommand { static description = 'Manage orgs' static name = 'org' static usage = [ 'set orgname username [developer | admin | owner]', 'rm orgname username', 'ls orgname []', ] static params = ['registry', 'otp', 'json', 'parseable'] static async completion (opts) { const argv = opts.conf.argv.remain if (argv.length === 2) { return ['set', 'rm', 'ls'] } switch (argv[2]) { case 'ls': case 'add': case 'rm': case 'set': return [] default: throw new Error(argv[2] + ' not recognized') } } async exec ([cmd, orgname, username, role]) { return otplease(this.npm, { ...this.npm.flatOptions, }, opts => { switch (cmd) { case 'add': case 'set': return this.set(orgname, username, role, opts) case 'rm': return this.rm(orgname, username, opts) case 'ls': return this.ls(orgname, username, opts) default: throw this.usageError() } }) } async set (org, user, role, opts) { role = role || 'developer' if (!org) { throw new Error('First argument `orgname` is required.') } if (!user) { throw new Error('Second argument `username` is required.') } if (!['owner', 'admin', 'developer'].find(x => x === role)) { throw new Error( 'Third argument `role` must be one of `owner`, `admin`, or `developer`, with `developer` being the default value if omitted.' ) } const memDeets = await liborg.set(org, user, role, opts) if (opts.json) { output.standard(JSON.stringify(memDeets, null, 2)) } else if (opts.parseable) { output.standard(['org', 'orgsize', 'user', 'role'].join('\t')) output.standard( [memDeets.org.name, memDeets.org.size, memDeets.user, memDeets.role].join('\t') ) } else if (!this.npm.silent) { output.standard( `Added ${memDeets.user} as ${memDeets.role} to ${memDeets.org.name}. You now have ${ memDeets.org.size } member${memDeets.org.size === 1 ? '' : 's'} in this org.` ) } return memDeets } async rm (org, user, opts) { if (!org) { throw new Error('First argument `orgname` is required.') } if (!user) { throw new Error('Second argument `username` is required.') } await liborg.rm(org, user, opts) const roster = await liborg.ls(org, opts) user = user.replace(/^[~@]?/, '') org = org.replace(/^[~@]?/, '') const userCount = Object.keys(roster).length if (opts.json) { output.buffer({ user, org, userCount, deleted: true, }) } else if (opts.parseable) { output.standard(['user', 'org', 'userCount', 'deleted'].join('\t')) output.standard([user, org, userCount, true].join('\t')) } else if (!this.npm.silent) { output.standard( `Successfully removed ${user} from ${org}. You now have ${userCount} member${ userCount === 1 ? '' : 's' } in this org.` ) } } async ls (org, user, opts) { if (!org) { throw new Error('First argument `orgname` is required.') } let roster = await liborg.ls(org, opts) if (user) { const newRoster = {} if (roster[user]) { newRoster[user] = roster[user] } roster = newRoster } if (opts.json) { output.buffer(roster) } else if (opts.parseable) { output.standard(['user', 'role'].join('\t')) Object.keys(roster).forEach(u => { output.standard([u, roster[u]].join('\t')) }) } else if (!this.npm.silent) { const chalk = this.npm.chalk for (const u of Object.keys(roster).sort()) { output.standard(`${u} - ${chalk.cyan(roster[u])}`) } } } } module.exports = Org const { resolve } = require('node:path') const { stripVTControlCharacters } = require('node:util') const pacote = require('pacote') const table = require('text-table') const npa = require('npm-package-arg') const pickManifest = require('npm-pick-manifest') const { output } = require('proc-log') const localeCompare = require('@isaacs/string-locale-compare')('en') const ArboristWorkspaceCmd = require('../arborist-cmd.js') const safeNpa = (spec) => { try { return npa(spec) } catch { return null } } // This string is load bearing and is shared with Arborist const MISSING = 'MISSING' class Outdated extends ArboristWorkspaceCmd { static description = 'Check for outdated packages' static name = 'outdated' static usage = ['[ ...]'] static params = [ 'all', 'json', 'long', 'parseable', 'global', 'workspace', ] #tree #list = [] #edges = new Set() #filterSet async exec (args) { const Arborist = require('@npmcli/arborist') const arb = new Arborist({ ...this.npm.flatOptions, path: this.npm.global ? resolve(this.npm.globalDir, '..') : this.npm.prefix, }) this.#tree = await arb.loadActual() if (this.workspaceNames?.length) { this.#filterSet = arb.workspaceDependencySet( this.#tree, this.workspaceNames, this.npm.flatOptions.includeWorkspaceRoot ) } else if (!this.npm.flatOptions.workspacesEnabled) { this.#filterSet = arb.excludeWorkspacesDependencySet(this.#tree) } if (args.length) { for (const arg of args) { // specific deps this.#getEdges(this.#tree.inventory.query('name', arg), 'edgesIn') } } else { if (this.npm.config.get('all')) { // all deps in tree this.#getEdges(this.#tree.inventory.values(), 'edgesOut') } // top-level deps this.#getEdges() } await Promise.all([...this.#edges].map((e) => this.#getOutdatedInfo(e))) // sorts list alphabetically by name and then dependent const outdated = this.#list .sort((a, b) => localeCompare(a.name, b.name) || localeCompare(a.dependent, b.dependent)) if (outdated.length) { process.exitCode = 1 } if (this.npm.config.get('json')) { output.buffer(this.#json(outdated)) return } const res = this.npm.config.get('parseable') ? this.#parseable(outdated) : this.#pretty(outdated) if (res) { output.standard(res) } } #getEdges (nodes, type) { // when no nodes are provided then it should only read direct deps // from the root node and its workspaces direct dependencies if (!nodes) { this.#getEdgesOut(this.#tree) this.#getWorkspacesEdges() return } for (const node of nodes) { if (type === 'edgesOut') { this.#getEdgesOut(node) } else { this.#getEdgesIn(node) } } } #getEdgesIn (node) { for (const edge of node.edgesIn) { this.#trackEdge(edge) } } #getEdgesOut (node) { // TODO: normalize usage of edges and avoid looping through nodes here const edges = this.npm.global ? node.children.values() : node.edgesOut.values() for (const edge of edges) { this.#trackEdge(edge) } } #trackEdge (edge) { if (edge.from && this.#filterSet?.size > 0 && !this.#filterSet.has(edge.from.target)) { return } this.#edges.add(edge) } #getWorkspacesEdges () { if (this.npm.global) { return } for (const edge of this.#tree.edgesOut.values()) { if (edge?.to?.target?.isWorkspace) { this.#getEdgesOut(edge.to.target) } } } async #getPackument (spec) { return pacote.packument(spec, { ...this.npm.flatOptions, fullMetadata: this.npm.config.get('long'), preferOnline: true, }) } async #getOutdatedInfo (edge) { const alias = safeNpa(edge.spec)?.subSpec const spec = npa(alias ? alias.name : edge.name) const node = edge.to || edge const { path, location, package: { version: current } = {} } = node const type = edge.optional ? 'optionalDependencies' : edge.peer ? 'peerDependencies' : edge.dev ? 'devDependencies' : 'dependencies' for (const omitType of this.npm.flatOptions.omit) { if (node[omitType]) { return } } // deps different from prod not currently // on disk are not included in the output if (edge.error === MISSING && type !== 'dependencies') { return } // if it's not a range, version, or tag, skip it if (!safeNpa(`${edge.name}@${edge.spec}`)?.registry) { return null } try { const packument = await this.#getPackument(spec) const expected = alias ? alias.fetchSpec : edge.spec const wanted = pickManifest(packument, expected, this.npm.flatOptions) const latest = pickManifest(packument, '*', this.npm.flatOptions) if (!current || current !== wanted.version || wanted.version !== latest.version) { this.#list.push({ name: alias ? edge.spec.replace('npm', edge.name) : edge.name, path, type, current, location, wanted: wanted.version, latest: latest.version, workspaceDependent: edge.from?.isWorkspace ? edge.from.pkgid : null, dependent: edge.from?.name ?? 'global', homepage: packument.homepage, }) } } catch (err) { // silently catch and ignore ETARGET, E403 & // E404 errors, deps are just skipped if (!['ETARGET', 'E404', 'E404'].includes(err.code)) { throw err } } } // formatting functions #pretty (list) { if (!list.length) { return } const long = this.npm.config.get('long') const { bold, yellow, red, cyan, blue } = this.npm.chalk return table([ [ 'Package', 'Current', 'Wanted', 'Latest', 'Location', 'Depended by', ...long ? ['Package Type', 'Homepage'] : [], ].map(h => bold.underline(h)), ...list.map((d) => [ d.current === d.wanted ? yellow(d.name) : red(d.name), d.current ?? 'MISSING', cyan(d.wanted), blue(d.latest), d.location ?? '-', d.workspaceDependent ? blue(d.workspaceDependent) : d.dependent, ...long ? [d.type, blue(d.homepage ?? '')] : [], ]), ], { align: ['l', 'r', 'r', 'r', 'l'], stringLength: s => stripVTControlCharacters(s).length, }) } // --parseable creates output like this: // :::: #parseable (list) { return list.map(d => [ d.path, `${d.name}@${d.wanted}`, d.current ? `${d.name}@${d.current}` : 'MISSING', `${d.name}@${d.latest}`, d.dependent, ...this.npm.config.get('long') ? [d.type, d.homepage] : [], ].join(':')).join('\n') } #json (list) { // TODO(BREAKING_CHANGE): this should just return an array. It's a list and // turing it into an object with keys is lossy since multiple items in the // list could have the same key. For now we hack that by only changing // top level values into arrays if they have multiple outdated items return list.reduce((acc, d) => { const dep = { current: d.current, wanted: d.wanted, latest: d.latest, dependent: d.dependent, location: d.path, ...this.npm.config.get('long') ? { type: d.type, homepage: d.homepage } : {}, } acc[d.name] = acc[d.name] // If this item alread has an outdated dep then we turn it into an array ? (Array.isArray(acc[d.name]) ? acc[d.name] : [acc[d.name]]).concat(dep) : dep return acc }, {}) } } module.exports = Outdated const npa = require('npm-package-arg') const npmFetch = require('npm-registry-fetch') const pacote = require('pacote') const { log, output } = require('proc-log') const { otplease } = require('../utils/auth.js') const pkgJson = require('@npmcli/package-json') const BaseCommand = require('../base-cmd.js') const { redact } = require('@npmcli/redact') const readJson = async (path) => { try { const { content } = await pkgJson.normalize(path) return content } catch { return {} } } class Owner extends BaseCommand { static description = 'Manage package owners' static name = 'owner' static params = [ 'registry', 'otp', 'workspace', 'workspaces', ] static usage = [ 'add ', 'rm ', 'ls ', ] static workspaces = true static ignoreImplicitWorkspace = false static async completion (opts, npm) { const argv = opts.conf.argv.remain if (argv.length > 3) { return [] } if (argv[1] !== 'owner') { argv.unshift('owner') } if (argv.length === 2) { return ['add', 'rm', 'ls'] } // reaches registry in order to autocomplete rm if (argv[2] === 'rm') { if (npm.global) { return [] } const { name } = await readJson(npm.prefix) if (!name) { return [] } const spec = npa(name) const data = await pacote.packument(spec, { ...npm.flatOptions, fullMetadata: true, }) if (data && data.maintainers && data.maintainers.length) { return data.maintainers.map(m => m.name) } } return [] } async exec ([action, ...args]) { if (action === 'ls' || action === 'list') { await this.ls(args[0]) } else if (action === 'add') { await this.changeOwners(args[0], args[1], 'add') } else if (action === 'rm' || action === 'remove') { await this.changeOwners(args[0], args[1], 'rm') } else { throw this.usageError() } } async execWorkspaces ([action, ...args]) { await this.setWorkspaces() // ls pkg or owner add/rm package if ((action === 'ls' && args.length > 0) || args.length > 1) { const implicitWorkspaces = this.npm.config.get('workspace', 'default') if (implicitWorkspaces.length === 0) { log.warn(`Ignoring specified workspace(s)`) } return this.exec([action, ...args]) } for (const [name] of this.workspaces) { if (action === 'ls' || action === 'list') { await this.ls(name) } else if (action === 'add') { await this.changeOwners(args[0], name, 'add') } else if (action === 'rm' || action === 'remove') { await this.changeOwners(args[0], name, 'rm') } else { throw this.usageError() } } } async ls (pkg) { pkg = await this.getPkg(this.npm.prefix, pkg) const spec = npa(pkg) try { const packumentOpts = { ...this.npm.flatOptions, fullMetadata: true, preferOnline: true } const { maintainers } = await pacote.packument(spec, packumentOpts) if (!maintainers || !maintainers.length) { output.standard('no admin found') } else { output.standard(maintainers.map(m => `${m.name} <${m.email}>`).join('\n')) } } catch (err) { log.error('owner ls', "Couldn't get owner data", redact(pkg)) throw err } } async getPkg (prefix, pkg) { if (!pkg) { if (this.npm.global) { throw this.usageError() } const { name } = await readJson(prefix) if (!name) { throw this.usageError() } return name } return pkg } async changeOwners (user, pkg, addOrRm) { if (!user) { throw this.usageError() } pkg = await this.getPkg(this.npm.prefix, pkg) log.verbose(`owner ${addOrRm}`, '%s to %s', user, pkg) const spec = npa(pkg) const uri = `/-/user/org.couchdb.user:${encodeURIComponent(user)}` let u try { u = await npmFetch.json(uri, this.npm.flatOptions) } catch (err) { log.error('owner mutate', `Error getting user data for ${user}`) throw err } // normalize user data u = { name: u.name, email: u.email } const data = await pacote.packument(spec, { ...this.npm.flatOptions, fullMetadata: true, preferOnline: true, }) const owners = data.maintainers || [] let maintainers if (addOrRm === 'add') { const existing = owners.find(o => o.name === u.name) if (existing) { log.info( 'owner add', `Already a package owner: ${existing.name} <${existing.email}>` ) return } maintainers = [ ...owners, u, ] } else { maintainers = owners.filter(o => o.name !== u.name) if (maintainers.length === owners.length) { log.info('owner rm', 'Not a package owner: ' + u.name) return false } if (!maintainers.length) { throw Object.assign( new Error( 'Cannot remove all owners of a package. Add someone else first.' ), { code: 'EOWNERRM' } ) } } const dataPath = `/${spec.escapedName}/-rev/${encodeURIComponent(data._rev)}` try { const res = await otplease(this.npm, this.npm.flatOptions, opts => { return npmFetch.json(dataPath, { ...opts, method: 'PUT', body: { _id: data._id, _rev: data._rev, maintainers, }, spec, }) }) if (addOrRm === 'add') { output.standard(`+ ${user} (${spec.name})`) } else { output.standard(`- ${user} (${spec.name})`) } return res } catch (err) { throw Object.assign( new Error('Failed to update package: ' + JSON.stringify(err.message)), { code: 'EOWNERMUTATE' } ) } } } module.exports = Owner const pacote = require('pacote') const libpack = require('libnpmpack') const npa = require('npm-package-arg') const { log, output } = require('proc-log') const { getContents, logTar } = require('../utils/tar.js') const BaseCommand = require('../base-cmd.js') class Pack extends BaseCommand { static description = 'Create a tarball from a package' static name = 'pack' static params = [ 'dry-run', 'json', 'pack-destination', 'workspace', 'workspaces', 'include-workspace-root', 'ignore-scripts', ] static usage = [''] static workspaces = true static ignoreImplicitWorkspace = false async exec (args) { if (args.length === 0) { args = ['.'] } const unicode = this.npm.config.get('unicode') const json = this.npm.config.get('json') const Arborist = require('@npmcli/arborist') // Get the manifests and filenames first so we can bail early on manifest // errors before making any tarballs const manifests = [] for (const arg of args) { const spec = npa(arg) const manifest = await pacote.manifest(spec, { ...this.npm.flatOptions, Arborist }) if (!manifest._id) { throw new Error('Invalid package, must have name and version') } manifests.push({ arg, manifest }) } // Load tarball names up for printing afterward to isolate from the // noise generated during packing const tarballs = [] for (const { arg, manifest } of manifests) { const tarballData = await libpack(arg, { ...this.npm.flatOptions, foregroundScripts: this.npm.config.isDefault('foreground-scripts') ? true : this.npm.config.get('foreground-scripts'), prefix: this.npm.localPrefix, workspaces: this.workspacePaths, }) tarballs.push(await getContents(manifest, tarballData)) } for (const [index, tar] of Object.entries(tarballs)) { // XXX(BREAKING_CHANGE): publish outputs a json object with package // names as keys. Pack should do the same here instead of an array logTar(tar, { unicode, json, key: index }) if (!json) { output.standard(tar.filename.replace(/^@/, '').replace(/\//, '-')) } } } async execWorkspaces (args) { // If they either ask for nothing, or explicitly include '.' in the args, // we effectively translate that into each workspace requested const useWorkspaces = args.length === 0 || args.includes('.') if (!useWorkspaces) { log.warn('Ignoring workspaces for specified package(s)') return this.exec(args) } await this.setWorkspaces() return this.exec([...this.workspacePaths, ...args.filter(a => a !== '.')]) } } module.exports = Pack const { redact } = require('@npmcli/redact') const { log, output } = require('proc-log') const pingUtil = require('../utils/ping.js') const BaseCommand = require('../base-cmd.js') class Ping extends BaseCommand { static description = 'Ping npm registry' static params = ['registry'] static name = 'ping' async exec () { const cleanRegistry = redact(this.npm.config.get('registry')) log.notice('PING', cleanRegistry) const start = Date.now() const details = await pingUtil({ ...this.npm.flatOptions }) const time = Date.now() - start log.notice('PONG', `${time}ms`) if (this.npm.config.get('json')) { output.buffer({ registry: cleanRegistry, time, details, }) } else if (Object.keys(details).length) { log.notice('PONG', JSON.stringify(details, null, 2)) } } } module.exports = Ping const { output } = require('proc-log') const PackageJson = require('@npmcli/package-json') const BaseCommand = require('../base-cmd.js') const Queryable = require('../utils/queryable.js') class Pkg extends BaseCommand { static description = 'Manages your package.json' static name = 'pkg' static usage = [ 'set = [= ...]', 'get [ [ ...]]', 'delete [ ...]', 'set [[].= ...]', 'set [[].= ...]', 'fix', ] static params = [ 'force', 'json', 'workspace', 'workspaces', ] static workspaces = true static ignoreImplicitWorkspace = false async exec (args, { path = this.npm.localPrefix, workspace } = {}) { if (this.npm.global) { throw Object.assign( new Error(`There's no package.json file to manage on global mode`), { code: 'EPKGGLOBAL' } ) } const [cmd, ..._args] = args switch (cmd) { case 'get': return this.get(_args, { path, workspace }) case 'set': return this.set(_args, { path, workspace }).then(p => p.save()) case 'delete': return this.delete(_args, { path, workspace }).then(p => p.save()) case 'fix': return PackageJson.fix(path).then(p => p.save()) default: throw this.usageError() } } async execWorkspaces (args) { await this.setWorkspaces() for (const [workspace, path] of this.workspaces.entries()) { await this.exec(args, { path, workspace }) } } async get (args, { path, workspace }) { this.npm.config.set('json', true) const pkgJson = await PackageJson.load(path) let result = pkgJson.content if (args.length) { result = new Queryable(result).query(args) // in case there's only a single argument and a single result from the query // just prints that one element to stdout. // TODO(BREAKING_CHANGE): much like other places where we unwrap single // item arrays this should go away. it makes the behavior unknown for users // who don't already know the shape of the data. if (Object.keys(result).length === 1 && args.length === 1) { result = result[args] } } // The display layer is responsible for calling JSON.stringify on the result // TODO: https://github.com/npm/cli/issues/5508 a raw mode has been requested similar // to jq -r. If that was added then this method should no longer set `json:true` all the time output.buffer(workspace ? { [workspace]: result } : result) } async set (args, { path }) { const setError = () => this.usageError('npm pkg set expects a key=value pair of args.') if (!args.length) { throw setError() } const force = this.npm.config.get('force') const json = this.npm.config.get('json') const pkgJson = await PackageJson.load(path) const q = new Queryable(pkgJson.content) for (const arg of args) { const [key, ...rest] = arg.split('=') const value = rest.join('=') if (!key || !value) { throw setError() } q.set(key, json ? JSON.parse(value) : value, { force }) } return pkgJson.update(q.toJSON()) } async delete (args, { path }) { const setError = () => this.usageError('npm pkg delete expects key args.') if (!args.length) { throw setError() } const pkgJson = await PackageJson.load(path) const q = new Queryable(pkgJson.content) for (const key of args) { if (!key) { throw setError() } q.delete(key) } return pkgJson.update(q.toJSON()) } } module.exports = Pkg const { output } = require('proc-log') const BaseCommand = require('../base-cmd.js') class Prefix extends BaseCommand { static description = 'Display prefix' static name = 'prefix' static params = ['global'] async exec () { return output.standard(this.npm.prefix) } } module.exports = Prefix const { inspect } = require('node:util') const { URL } = require('node:url') const { log, output } = require('proc-log') const { get, set, createToken } = require('npm-profile') const qrcodeTerminal = require('qrcode-terminal') const { otplease } = require('../utils/auth.js') const readUserInfo = require('../utils/read-user-info.js') const BaseCommand = require('../base-cmd.js') const qrcode = url => new Promise((resolve) => qrcodeTerminal.generate(url, resolve)) const knownProfileKeys = [ 'name', 'email', 'two-factor auth', 'fullname', 'homepage', 'freenode', 'twitter', 'github', 'created', 'updated', ] const writableProfileKeys = [ 'email', 'password', 'fullname', 'homepage', 'freenode', 'twitter', 'github', ] class Profile extends BaseCommand { static description = 'Change settings on your registry profile' static name = 'profile' static usage = [ 'enable-2fa [auth-only|auth-and-writes]', 'disable-2fa', 'get []', 'set ', ] static params = [ 'registry', 'json', 'parseable', 'otp', ] static async completion (opts) { var argv = opts.conf.argv.remain if (!argv[2]) { return ['enable-2fa', 'disable-2fa', 'get', 'set'] } switch (argv[2]) { case 'enable-2fa': case 'enable-tfa': return ['auth-and-writes', 'auth-only'] case 'disable-2fa': case 'disable-tfa': case 'get': case 'set': return [] default: throw new Error(argv[2] + ' not recognized') } } async exec (args) { if (args.length === 0) { throw this.usageError() } const [subcmd, ...opts] = args switch (subcmd) { case 'enable-2fa': case 'enable-tfa': case 'enable2fa': case 'enabletfa': return this.enable2fa(opts) case 'disable-2fa': case 'disable-tfa': case 'disable2fa': case 'disabletfa': return this.disable2fa() case 'get': return this.get(opts) case 'set': return this.set(opts) default: throw new Error('Unknown profile command: ' + subcmd) } } async get (args) { const tfa = 'two-factor auth' const info = await get({ ...this.npm.flatOptions }) if (!info.cidr_whitelist) { delete info.cidr_whitelist } if (this.npm.config.get('json')) { output.buffer(info) return } // clean up and format key/values for output const cleaned = {} for (const key of knownProfileKeys) { cleaned[key] = info[key] || '' } const unknownProfileKeys = Object.keys(info).filter((k) => !(k in cleaned)) for (const key of unknownProfileKeys) { cleaned[key] = info[key] || '' } delete cleaned.tfa delete cleaned.email_verified cleaned.email += info.email_verified ? ' (verified)' : '(unverified)' if (info.tfa && !info.tfa.pending) { cleaned[tfa] = info.tfa.mode } else { cleaned[tfa] = 'disabled' } if (args.length) { const values = args // comma or space separated .join(',') .split(/,/) .filter((arg) => arg.trim() !== '') .map((arg) => cleaned[arg]) .join('\t') output.standard(values) } else { if (this.npm.config.get('parseable')) { for (const key of Object.keys(info)) { if (key === 'tfa') { output.standard(`${key}\t${cleaned[tfa]}`) } else { output.standard(`${key}\t${info[key]}`) } } } else { for (const [key, value] of Object.entries(cleaned)) { output.standard(`${key}: ${value}`) } } } } async set (args) { const conf = { ...this.npm.flatOptions } const prop = (args[0] || '').toLowerCase().trim() let value = args.length > 1 ? args.slice(1).join(' ') : null const readPasswords = async () => { const newpassword = await readUserInfo.password('New password: ') const confirmedpassword = await readUserInfo.password(' Again: ') if (newpassword !== confirmedpassword) { log.warn('profile', 'Passwords do not match, please try again.') return readPasswords() } return newpassword } if (prop !== 'password' && value === null) { throw new Error('npm profile set ') } if (prop === 'password' && value !== null) { throw new Error( 'npm profile set password\n' + 'Do not include your current or new passwords on the command line.') } if (writableProfileKeys.indexOf(prop) === -1) { throw new Error(`"${prop}" is not a property we can set. ` + `Valid properties are: ` + writableProfileKeys.join(', ')) } if (prop === 'password') { const current = await readUserInfo.password('Current password: ') const newpassword = await readPasswords() value = { old: current, new: newpassword } } // FIXME: Work around to not clear everything other than what we're setting const user = await get(conf) const newUser = {} for (const key of writableProfileKeys) { newUser[key] = user[key] } newUser[prop] = value const result = await otplease(this.npm, conf, c => set(newUser, c)) if (this.npm.config.get('json')) { output.buffer({ [prop]: result[prop] }) } else if (this.npm.config.get('parseable')) { output.standard(prop + '\t' + result[prop]) } else if (result[prop] != null) { output.standard('Set', prop, 'to', result[prop]) } else { output.standard('Set', prop) } } async enable2fa (args) { if (args.length > 1) { throw new Error('npm profile enable-2fa [auth-and-writes|auth-only]') } const mode = args[0] || 'auth-and-writes' if (mode !== 'auth-only' && mode !== 'auth-and-writes') { throw new Error( `Invalid two-factor authentication mode "${mode}".\n` + 'Valid modes are:\n' + ' auth-only - Require two-factor authentication only when logging in\n' + ' auth-and-writes - Require two-factor authentication when logging in ' + 'AND when publishing' ) } if (this.npm.config.get('json') || this.npm.config.get('parseable')) { throw new Error( 'Enabling two-factor authentication is an interactive operation and ' + (this.npm.config.get('json') ? 'JSON' : 'parseable') + ' output mode is not available' ) } const info = { tfa: { mode: mode, }, } // if they're using legacy auth currently then we have to // update them to a bearer token before continuing. const creds = this.npm.config.getCredentialsByURI(this.npm.config.get('registry')) const auth = {} if (creds.token) { auth.token = creds.token } else if (creds.username) { auth.basic = { username: creds.username, password: creds.password } } else if (creds.auth) { const basic = Buffer.from(creds.auth, 'base64').toString().split(':', 2) auth.basic = { username: basic[0], password: basic[1] } } if (!auth.basic && !auth.token) { throw new Error( 'You need to be logged in to registry ' + `${this.npm.config.get('registry')} in order to enable 2fa` ) } if (auth.basic) { log.info('profile', 'Updating authentication to bearer token') const result = await createToken( auth.basic.password, false, [], { ...this.npm.flatOptions } ) if (!result.token) { throw new Error( `Your registry ${this.npm.config.get('registry')} does not seem to ` + 'support bearer tokens. Bearer tokens are required for ' + 'two-factor authentication' ) } this.npm.config.setCredentialsByURI( this.npm.config.get('registry'), { token: result.token } ) await this.npm.config.save('user') } log.notice('profile', 'Enabling two factor authentication for ' + mode) const password = await readUserInfo.password() info.tfa.password = password log.info('profile', 'Determine if tfa is pending') const userInfo = await get({ ...this.npm.flatOptions }) const conf = { ...this.npm.flatOptions } if (userInfo && userInfo.tfa && userInfo.tfa.pending) { log.info('profile', 'Resetting two-factor authentication') await set({ tfa: { password, mode: 'disable' } }, conf) } else if (userInfo && userInfo.tfa) { if (!conf.otp) { conf.otp = await readUserInfo.otp( 'Enter one-time password: ' ) } } log.info('profile', 'Setting two-factor authentication to ' + mode) const challenge = await set(info, conf) if (challenge.tfa === null) { output.standard('Two factor authentication mode changed to: ' + mode) return } const badResponse = typeof challenge.tfa !== 'string' || !/^otpauth:[/][/]/.test(challenge.tfa) if (badResponse) { throw new Error( 'Unknown error enabling two-factor authentication. Expected otpauth URL' + ', got: ' + inspect(challenge.tfa) ) } const otpauth = new URL(challenge.tfa) const secret = otpauth.searchParams.get('secret') const code = await qrcode(challenge.tfa) output.standard( 'Scan into your authenticator app:\n' + code + '\n Or enter code:', secret ) const interactiveOTP = await readUserInfo.otp('And an OTP code from your authenticator: ') log.info('profile', 'Finalizing two-factor authentication') const result = await set({ tfa: [interactiveOTP] }, conf) output.standard( '2FA successfully enabled. Below are your recovery codes, ' + 'please print these out.' ) output.standard( 'You will need these to recover access to your account ' + 'if you lose your authentication device.' ) for (const tfaCode of result.tfa) { output.standard('\t' + tfaCode) } } async disable2fa () { const conf = { ...this.npm.flatOptions } const info = await get(conf) if (!info.tfa || info.tfa.pending) { output.standard('Two factor authentication not enabled.') return } const password = await readUserInfo.password() if (!conf.otp) { const msg = 'Enter one-time password: ' conf.otp = await readUserInfo.otp(msg) } log.info('profile', 'disabling tfa') await set({ tfa: { password: password, mode: 'disable' } }, conf) if (this.npm.config.get('json')) { output.buffer({ tfa: false }) } else if (this.npm.config.get('parseable')) { output.standard('tfa\tfalse') } else { output.standard('Two factor authentication disabled.') } } } module.exports = Profile const reifyFinish = require('../utils/reify-finish.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') // prune extraneous packages class Prune extends ArboristWorkspaceCmd { static description = 'Remove extraneous packages' static name = 'prune' static params = [ 'omit', 'include', 'dry-run', 'json', 'foreground-scripts', 'ignore-scripts', ...super.params, ] static usage = ['[[<@scope>/]...]'] async exec () { const where = this.npm.prefix const Arborist = require('@npmcli/arborist') const opts = { ...this.npm.flatOptions, path: where, workspaces: this.workspaceNames, } const arb = new Arborist(opts) await arb.prune(opts) await reifyFinish(this.npm, arb) } } module.exports = Prune const { log, output } = require('proc-log') const semver = require('semver') const pack = require('libnpmpack') const libpub = require('libnpmpublish').publish const runScript = require('@npmcli/run-script') const pacote = require('pacote') const npa = require('npm-package-arg') const npmFetch = require('npm-registry-fetch') const { redactLog: replaceInfo } = require('@npmcli/redact') const { otplease } = require('../utils/auth.js') const { getContents, logTar } = require('../utils/tar.js') // for historical reasons, publishConfig in package.json can contain ANY config // keys that npm supports in .npmrc files and elsewhere. We *may* want to // revisit this at some point, and have a minimal set that's a SemVer-major // change that ought to get a RFC written on it. const { flatten } = require('@npmcli/config/lib/definitions') const pkgJson = require('@npmcli/package-json') const BaseCommand = require('../base-cmd.js') class Publish extends BaseCommand { static description = 'Publish a package' static name = 'publish' static params = [ 'tag', 'access', 'dry-run', 'otp', 'workspace', 'workspaces', 'include-workspace-root', 'provenance', ] static usage = [''] static workspaces = true static ignoreImplicitWorkspace = false async exec (args) { if (args.length === 0) { args = ['.'] } if (args.length !== 1) { throw this.usageError() } await this.#publish(args) } async execWorkspaces (args) { const useWorkspaces = args.length === 0 || args.includes('.') if (!useWorkspaces) { log.warn('Ignoring workspaces for specified package(s)') return this.exec(args) } await this.setWorkspaces() for (const [name, workspace] of this.workspaces.entries()) { try { await this.#publish([workspace], { workspace: name }) } catch (err) { if (err.code !== 'EPRIVATE') { throw err } log.warn('publish', `Skipping workspace ${this.npm.chalk.cyan(name)}, marked as ${this.npm.chalk.bold('private')}`) } } } async #publish (args, { workspace } = {}) { log.verbose('publish', replaceInfo(args)) const unicode = this.npm.config.get('unicode') const dryRun = this.npm.config.get('dry-run') const json = this.npm.config.get('json') const defaultTag = this.npm.config.get('tag') const ignoreScripts = this.npm.config.get('ignore-scripts') const { silent } = this.npm if (semver.validRange(defaultTag)) { throw new Error('Tag name must not be a valid SemVer range: ' + defaultTag.trim()) } const opts = { ...this.npm.flatOptions, progress: false } // you can publish name@version, ./foo.tgz, etc. // even though the default is the 'file:.' cwd. const spec = npa(args[0]) let manifest = await this.#getManifest(spec, opts) // only run scripts for directory type publishes if (spec.type === 'directory' && !ignoreScripts) { await runScript({ event: 'prepublishOnly', path: spec.fetchSpec, stdio: 'inherit', pkg: manifest, }) } // we pass dryRun: true to libnpmpack so it doesn't write the file to disk const tarballData = await pack(spec, { ...opts, foregroundScripts: this.npm.config.isDefault('foreground-scripts') ? true : this.npm.config.get('foreground-scripts'), dryRun: true, prefix: this.npm.localPrefix, workspaces: this.workspacePaths, }) const pkgContents = await getContents(manifest, tarballData) const logPkg = () => logTar(pkgContents, { unicode, json, key: workspace }) // The purpose of re-reading the manifest is in case it changed, // so that we send the latest and greatest thing to the registry // note that publishConfig might have changed as well! manifest = await this.#getManifest(spec, opts, true) const force = this.npm.config.get('force') const isDefaultTag = this.npm.config.isDefault('tag') && !manifest.publishConfig?.tag if (!force) { const isPreRelease = Boolean(semver.parse(manifest.version).prerelease.length) if (isPreRelease && isDefaultTag) { throw new Error('You must specify a tag using --tag when publishing a prerelease version.') } } // If we are not in JSON mode then we show the user the contents of the tarball // before it is published so they can see it while their otp is pending if (!json) { logPkg() } const resolved = npa.resolve(manifest.name, manifest.version) // make sure tag is valid, this will throw if invalid npa(`${manifest.name}@${defaultTag}`) const registry = npmFetch.pickRegistry(resolved, opts) const creds = this.npm.config.getCredentialsByURI(registry) const noCreds = !(creds.token || creds.username || creds.certfile && creds.keyfile) const outputRegistry = replaceInfo(registry) // if a workspace package is marked private then we skip it if (workspace && manifest.private) { throw Object.assign( new Error(`This package has been marked as private Remove the 'private' field from the package.json to publish it.`), { code: 'EPRIVATE' } ) } if (noCreds) { const msg = `This command requires you to be logged in to ${outputRegistry}` if (dryRun) { log.warn('', `${msg} (dry-run)`) } else { throw Object.assign(new Error(msg), { code: 'ENEEDAUTH' }) } } if (!force) { const { highestVersion, versions } = await this.#registryVersions(resolved, registry) /* eslint-disable-next-line max-len */ const highestVersionIsGreater = !!highestVersion && semver.gte(highestVersion, manifest.version) if (versions.includes(manifest.version)) { throw new Error(`You cannot publish over the previously published versions: ${manifest.version}.`) } if (highestVersionIsGreater && isDefaultTag) { throw new Error(`Cannot implicitly apply the "latest" tag because previously published version ${highestVersion} is higher than the new version ${manifest.version}. You must specify a tag using --tag.`) } } const access = opts.access === null ? 'default' : opts.access let msg = `Publishing to ${outputRegistry} with tag ${defaultTag} and ${access} access` if (dryRun) { msg = `${msg} (dry-run)` } log.notice('', msg) if (!dryRun) { await otplease(this.npm, opts, o => libpub(manifest, tarballData, o)) } // In json mode we dont log until the publish has completed as this will // add it to the output only if completes successfully if (json) { logPkg() } if (spec.type === 'directory' && !ignoreScripts) { await runScript({ event: 'publish', path: spec.fetchSpec, stdio: 'inherit', pkg: manifest, }) await runScript({ event: 'postpublish', path: spec.fetchSpec, stdio: 'inherit', pkg: manifest, }) } if (!json && !silent) { output.standard(`+ ${pkgContents.id}`) } } async #registryVersions (spec, registry) { try { const packument = await pacote.packument(spec, { ...this.npm.flatOptions, preferOnline: true, registry, }) if (typeof packument?.versions === 'undefined') { return { versions: [], highestVersion: null } } const ordered = Object.keys(packument?.versions) .flatMap(v => { const s = new semver.SemVer(v) if ((s.prerelease.length > 0) || packument.versions[v].deprecated) { return [] } return s }) .sort((a, b) => b.compare(a)) const highestVersion = ordered.length >= 1 ? ordered[0].version : null const versions = ordered.map(v => v.version) return { versions, highestVersion } } catch (e) { return { versions: [], highestVersion: null } } } // if it's a directory, read it from the file system // otherwise, get the full metadata from whatever it is // XXX can't pacote read the manifest from a directory? async #getManifest (spec, opts, logWarnings = false) { let manifest if (spec.type === 'directory') { const changes = [] const pkg = await pkgJson.fix(spec.fetchSpec, { changes }) if (changes.length && logWarnings) { log.warn('publish', 'npm auto-corrected some errors in your package.json when publishing. Please run "npm pkg fix" to address these errors.') log.warn('publish', `errors corrected:\n${changes.join('\n')}`) } // Prepare is the special function for publishing, different than normalize const { content } = await pkg.prepare() manifest = content } else { manifest = await pacote.manifest(spec, { ...opts, fullmetadata: true, fullReadJson: true, }) } if (manifest.publishConfig) { const cliFlags = this.npm.config.data.get('cli').raw // Filter out properties set in CLI flags to prioritize them over // corresponding `publishConfig` settings const filteredPublishConfig = Object.fromEntries( Object.entries(manifest.publishConfig).filter(([key]) => !(key in cliFlags))) flatten(filteredPublishConfig, opts) } return manifest } } module.exports = Publish const { resolve } = require('node:path') const BaseCommand = require('../base-cmd.js') const { log, output } = require('proc-log') class QuerySelectorItem { constructor (node) { // all enumerable properties from the target Object.assign(this, node.target.package) // append extra info this.pkgid = node.target.pkgid this.location = node.target.location this.path = node.target.path this.realpath = node.target.realpath this.resolved = node.target.resolved this.from = [] this.to = [] this.dev = node.target.dev this.inBundle = node.target.inBundle this.deduped = this.from.length > 1 this.overridden = node.overridden this.queryContext = node.queryContext for (const edge of node.target.edgesIn) { this.from.push(edge.from.location) } for (const [, edge] of node.target.edgesOut) { if (edge.to) { this.to.push(edge.to.location) } } } } class Query extends BaseCommand { #response = [] // response is the query response #seen = new Set() // paths we've seen so we can keep response deduped static description = 'Retrieve a filtered list of packages' static name = 'query' static usage = [''] static workspaces = true static ignoreImplicitWorkspace = false static params = [ 'global', 'workspace', 'workspaces', 'include-workspace-root', 'package-lock-only', 'expect-results', ] constructor (...args) { super(...args) this.npm.config.set('json', true) } async exec (args) { const packageLock = this.npm.config.get('package-lock-only') const Arborist = require('@npmcli/arborist') const arb = new Arborist({ ...this.npm.flatOptions, // one dir up from wherever node_modules lives path: resolve(this.npm.dir, '..'), forceActual: !packageLock, }) let tree if (packageLock) { try { tree = await arb.loadVirtual() } catch (err) { log.verbose('loadVirtual', err.stack) throw this.usageError( 'A package lock or shrinkwrap file is required in package-lock-only mode' ) } } else { tree = await arb.loadActual() } await this.#queryTree(tree, args[0]) this.#output() } async execWorkspaces (args) { await this.setWorkspaces() const Arborist = require('@npmcli/arborist') const arb = new Arborist({ ...this.npm.flatOptions, path: this.npm.prefix, }) // FIXME: Workspace support in query does not work as expected so this does not // do the same package-lock-only check as this.exec(). // https://github.com/npm/cli/pull/6732#issuecomment-1708804921 const tree = await arb.loadActual() for (const path of this.workspacePaths) { const wsTree = path === tree.root.path ? tree // --includes-workspace-root : await tree.querySelectorAll(`.workspace:path(${path})`).then(r => r[0].target) await this.#queryTree(wsTree, args[0]) } this.#output() } #output () { this.checkExpected(this.#response.length) output.buffer(this.#response) } // builds a normalized inventory async #queryTree (tree, arg) { const items = await tree.querySelectorAll(arg, this.npm.flatOptions) for (const node of items) { const { location } = node.target if (!location || !this.#seen.has(location)) { const item = new QuerySelectorItem(node) this.#response.push(item) if (location) { this.#seen.add(item.location) } } } } } module.exports = Query const { resolve } = require('node:path') const { output } = require('proc-log') const npa = require('npm-package-arg') const semver = require('semver') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Rebuild extends ArboristWorkspaceCmd { static description = 'Rebuild a package' static name = 'rebuild' static params = [ 'global', 'bin-links', 'foreground-scripts', 'ignore-scripts', ...super.params, ] static usage = ['[] ...]'] // TODO /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) } async exec (args) { const globalTop = resolve(this.npm.globalDir, '..') const where = this.npm.global ? globalTop : this.npm.prefix const Arborist = require('@npmcli/arborist') const arb = new Arborist({ ...this.npm.flatOptions, path: where, // TODO when extending ReifyCmd // workspaces: this.workspaceNames, }) if (args.length) { // get the set of nodes matching the name that we want rebuilt const tree = await arb.loadActual() const specs = args.map(arg => { const spec = npa(arg) if (spec.rawSpec === '*') { return spec } if (spec.type !== 'range' && spec.type !== 'version' && spec.type !== 'directory') { throw new Error('`npm rebuild` only supports SemVer version/range specifiers') } return spec }) const nodes = tree.inventory.filter(node => this.isNode(specs, node)) await arb.rebuild({ nodes }) } else { await arb.rebuild() } output.standard('rebuilt dependencies successfully') } isNode (specs, node) { return specs.some(spec => { if (spec.type === 'directory') { return node.path === spec.fetchSpec } if (spec.name !== node.name) { return false } if (spec.rawSpec === '' || spec.rawSpec === '*') { return true } const { version } = node.package // TODO: add tests for a package with missing version return semver.satisfies(version, spec.fetchSpec) }) } } module.exports = Rebuild const { URL } = require('node:url') const PackageUrlCmd = require('../package-url-cmd.js') class Repo extends PackageUrlCmd { static description = 'Open package repository page in the browser' static name = 'repo' getUrl (spec, mani) { const r = mani.repository const rurl = !r ? null : typeof r === 'string' ? r : typeof r === 'object' && typeof r.url === 'string' ? r.url : null if (!rurl) { throw Object.assign(new Error('no repository'), { pkgid: spec, }) } const info = this.hostedFromMani(mani) const url = info ? info.browse(mani.repository.directory) : unknownHostedUrl(rurl) if (!url) { throw Object.assign(new Error('no repository: could not get url'), { pkgid: spec, }) } return url } } module.exports = Repo const unknownHostedUrl = url => { try { const { protocol, hostname, pathname, } = new URL(url) /* istanbul ignore next - URL ctor should prevent this */ if (!protocol || !hostname) { return null } const proto = /(git\+)http:$/.test(protocol) ? 'http:' : 'https:' const path = pathname.replace(/\.git$/, '') return `${proto}//${hostname}${path}` } catch { return null } } const LifecycleCmd = require('../lifecycle-cmd.js') // This ends up calling run-script(['restart', ...args]) class Restart extends LifecycleCmd { static description = 'Restart a package' static name = 'restart' static params = [ 'ignore-scripts', 'script-shell', ] } module.exports = Restart const { output } = require('proc-log') const BaseCommand = require('../base-cmd.js') class Root extends BaseCommand { static description = 'Display npm root' static name = 'root' static params = ['global'] async exec () { output.standard(this.npm.dir) } } module.exports = Root const { output } = require('proc-log') const pkgJson = require('@npmcli/package-json') const BaseCommand = require('../base-cmd.js') const { getError } = require('../utils/error-message.js') const { outputError } = require('../utils/output-error.js') class RunScript extends BaseCommand { static description = 'Run arbitrary package scripts' static params = [ 'workspace', 'workspaces', 'include-workspace-root', 'if-present', 'ignore-scripts', 'foreground-scripts', 'script-shell', ] static name = 'run-script' static usage = [' [-- ]'] static workspaces = true static ignoreImplicitWorkspace = false static isShellout = true static checkDevEngines = true static async completion (opts, npm) { const argv = opts.conf.argv.remain if (argv.length === 2) { const { content: { scripts = {} } } = await pkgJson.normalize(npm.localPrefix) .catch(() => ({ content: {} })) if (opts.isFish) { return Object.keys(scripts).map(s => `${s}\t${scripts[s].slice(0, 30)}`) } return Object.keys(scripts) } } async exec (args) { if (args.length) { await this.#run(args, { path: this.npm.localPrefix }) } else { await this.#list(this.npm.localPrefix) } } async execWorkspaces (args) { await this.setWorkspaces() const ws = [...this.workspaces.entries()] for (const [workspace, path] of ws) { const last = path === ws.at(-1)[1] if (!args.length) { const newline = await this.#list(path, { workspace }) if (newline && !last) { output.standard('') } continue } const pkg = await pkgJson.normalize(path).then(p => p.content) try { await this.#run(args, { path, pkg, workspace }) } catch (e) { const err = getError(e, { npm: this.npm, command: null }) outputError({ ...err, error: [ ['', `Lifecycle script \`${args[0]}\` failed with error:`], ...err.error, ['workspace', pkg._id || pkg.name], ['location', path], ], }) process.exitCode = err.exitCode if (!last) { output.error('') } } } } async #run ([event, ...args], { path, pkg, workspace }) { const runScript = require('@npmcli/run-script') pkg ??= await pkgJson.normalize(path).then(p => p.content) const { scripts = {} } = pkg if (event === 'restart' && !scripts.restart) { scripts.restart = 'npm stop --if-present && npm start' } else if (event === 'env' && !scripts.env) { const { isWindowsShell } = require('../utils/is-windows.js') scripts.env = isWindowsShell ? 'SET' : 'env' } pkg.scripts = scripts if ( !Object.prototype.hasOwnProperty.call(scripts, event) && !(event === 'start' && (await runScript.isServerPackage(path))) ) { if (this.npm.config.get('if-present')) { return } const suggestions = require('../utils/did-you-mean.js')(pkg, event) const wsArg = workspace && path !== this.npm.localPrefix ? ` --workspace=${pkg._id || pkg.name}` : '' throw new Error([ `Missing script: "${event}"${suggestions}\n`, 'To see a list of scripts, run:', ` npm run${wsArg}`, ].join('\n')) } // positional args only added to the main event, not pre/post const events = [[event, args]] if (!this.npm.config.get('ignore-scripts')) { if (scripts[`pre${event}`]) { events.unshift([`pre${event}`, []]) } if (scripts[`post${event}`]) { events.push([`post${event}`, []]) } } for (const [ev, evArgs] of events) { await runScript({ path, // this || undefined is because runScript will be unhappy with the // default null value scriptShell: this.npm.config.get('script-shell') || undefined, stdio: 'inherit', pkg, event: ev, args: evArgs, }) } } async #list (path, { workspace } = {}) { const { scripts = {}, name, _id } = await pkgJson.normalize(path).then(p => p.content) const scriptEntries = Object.entries(scripts) if (this.npm.silent) { return } if (this.npm.config.get('json')) { output.buffer(workspace ? { [workspace]: scripts } : scripts) return } if (!scriptEntries.length) { return } if (this.npm.config.get('parseable')) { output.standard(scriptEntries .map((s) => (workspace ? [workspace, ...s] : s).join(':')) .join('\n') .trim()) return } const cmdList = [ 'prepare', 'prepublishOnly', 'prepack', 'postpack', 'dependencies', 'preinstall', 'install', 'postinstall', 'prepublish', 'publish', 'postpublish', 'prerestart', 'restart', 'postrestart', 'prestart', 'start', 'poststart', 'prestop', 'stop', 'poststop', 'pretest', 'test', 'posttest', 'preuninstall', 'uninstall', 'postuninstall', 'preversion', 'version', 'postversion', ] const [cmds, runScripts] = scriptEntries.reduce((acc, s) => { acc[cmdList.includes(s[0]) ? 0 : 1].push(s) return acc }, [[], []]) const { reset, bold, cyan, dim, blue } = this.npm.chalk const pkgId = `in ${cyan(_id || name)}` const title = (t) => reset(bold(t)) if (cmds.length) { output.standard(`${title('Lifecycle scripts')} included ${pkgId}:`) for (const [k, v] of cmds) { output.standard(` ${k}`) output.standard(` ${dim(v)}`) } } if (runScripts.length) { const via = `via \`${blue('npm run-script')}\`:` if (!cmds.length) { output.standard(`${title('Scripts')} available ${pkgId} ${via}`) } else { output.standard(`available ${via}`) } for (const [k, v] of runScripts) { output.standard(` ${k}`) output.standard(` ${dim(v)}`) } } // Return true to indicate that something was output for this path // that should be separated from others return true } } module.exports = RunScript const localeCompare = require('@isaacs/string-locale-compare')('en') const BaseCommand = require('../base-cmd.js') const { log, output } = require('proc-log') const { cyclonedxOutput } = require('../utils/sbom-cyclonedx.js') const { spdxOutput } = require('../utils/sbom-spdx.js') const SBOM_FORMATS = ['cyclonedx', 'spdx'] class SBOM extends BaseCommand { #response = {} // response is the sbom response static description = 'Generate a Software Bill of Materials (SBOM)' static name = 'sbom' static workspaces = true static params = [ 'omit', 'package-lock-only', 'sbom-format', 'sbom-type', 'workspace', 'workspaces', ] async exec () { const sbomFormat = this.npm.config.get('sbom-format') const packageLockOnly = this.npm.config.get('package-lock-only') if (!sbomFormat) { throw this.usageError(`Must specify --sbom-format flag with one of: ${SBOM_FORMATS.join(', ')}.`) } const opts = { ...this.npm.flatOptions, path: this.npm.prefix, forceActual: true, } const Arborist = require('@npmcli/arborist') const arb = new Arborist(opts) const tree = packageLockOnly ? await arb.loadVirtual(opts).catch(() => { throw this.usageError('A package lock or shrinkwrap file is required in package-lock-only mode') }) : await arb.loadActual(opts) // Collect the list of selected workspaces in the project const wsNodes = this.workspaceNames?.length ? arb.workspaceNodes(tree, this.workspaceNames) : null // Build the selector and query the tree for the list of nodes const selector = this.#buildSelector({ wsNodes }) log.info('sbom', `Using dependency selector: ${selector}`) const items = await tree.querySelectorAll(selector) const errors = items.flatMap(node => detectErrors(node)) if (errors.length) { throw Object.assign(new Error([...new Set(errors)].join('\n')), { code: 'ESBOMPROBLEMS', }) } // Populate the response with the list of unique nodes (sorted by location) this.#buildResponse(items.sort((a, b) => localeCompare(a.location, b.location))) // TODO(BREAKING_CHANGE): all sbom output is in json mode but setting it before // any of the errors will cause those to be thrown in json mode. this.npm.config.set('json', true) output.buffer(this.#response) } async execWorkspaces (args) { await this.setWorkspaces() return this.exec(args) } // Build the selector from all of the specified filter options #buildSelector ({ wsNodes }) { let selector const omit = this.npm.flatOptions.omit const workspacesEnabled = this.npm.flatOptions.workspacesEnabled // If omit is specified, omit all nodes and their children which match the // specified selectors const omits = omit.reduce((acc, o) => `${acc}:not(.${o})`, '') if (!workspacesEnabled) { // If workspaces are disabled, omit all workspace nodes and their children selector = `:root > :not(.workspace)${omits},:root > :not(.workspace) *${omits},:extraneous` } else if (wsNodes && wsNodes.length > 0) { // If one or more workspaces are selected, select only those workspaces and their children selector = wsNodes.map(ws => `#${ws.name},#${ws.name} *${omits}`).join(',') } else { selector = `:root *${omits},:extraneous` } // Always include the root node return `:root,${selector}` } // builds a normalized inventory #buildResponse (items) { const sbomFormat = this.npm.config.get('sbom-format') const packageType = this.npm.config.get('sbom-type') const packageLockOnly = this.npm.config.get('package-lock-only') this.#response = sbomFormat === 'cyclonedx' ? cyclonedxOutput({ npm: this.npm, nodes: items, packageType, packageLockOnly }) : spdxOutput({ npm: this.npm, nodes: items, packageType }) } } const detectErrors = (node) => { const errors = [] // Look for missing dependencies (that are NOT optional), or invalid dependencies for (const edge of node.edgesOut.values()) { if (edge.missing && !(edge.type === 'optional' || edge.type === 'peerOptional')) { errors.push(`missing: ${edge.name}@${edge.spec}, required by ${edge.from.pkgid}`) } if (edge.invalid) { /* istanbul ignore next */ const spec = edge.spec || '*' const from = edge.from.pkgid errors.push(`invalid: ${edge.to.pkgid}, ${spec} required by ${from}`) } } return errors } module.exports = SBOM const Pipeline = require('minipass-pipeline') const libSearch = require('libnpmsearch') const { log, output } = require('proc-log') const formatSearchStream = require('../utils/format-search-stream.js') const BaseCommand = require('../base-cmd.js') class Search extends BaseCommand { static description = 'Search for packages' static name = 'search' static params = [ 'json', 'color', 'parseable', 'description', 'searchlimit', 'searchopts', 'searchexclude', 'registry', 'prefer-online', 'prefer-offline', 'offline', ] static usage = [' [ ...]'] async exec (args) { const opts = { ...this.npm.flatOptions, ...this.npm.flatOptions.search, include: args.map(s => s.toLowerCase()).filter(Boolean), exclude: this.npm.flatOptions.search.exclude.split(/\s+/), } if (opts.include.length === 0) { throw new Error('search must be called with arguments') } // Used later to figure out whether we had any packages go out let anyOutput = false // Grab a configured output stream that will spit out packages in the desired format. const outputStream = formatSearchStream({ args, // --searchinclude options are not highlighted ...opts, npm: this.npm, }) log.silly('search', 'searching packages') const p = new Pipeline( libSearch.stream(opts.include, opts), outputStream ) p.on('data', chunk => { if (!anyOutput) { anyOutput = true } output.standard(chunk.toString('utf8')) }) await p.promise() if (!anyOutput && !this.npm.config.get('json') && !this.npm.config.get('parseable')) { output.standard('No matches found for ' + (args.map(JSON.stringify).join(' '))) } log.silly('search', 'search completed') } } module.exports = Search const Npm = require('../npm.js') const BaseCommand = require('../base-cmd.js') class Set extends BaseCommand { static description = 'Set a value in the npm configuration' static name = 'set' static usage = ['= [= ...] (See `npm config`)'] static params = ['global', 'location'] static ignoreImplicitWorkspace = false // TODO /* istanbul ignore next */ static async completion (opts) { const Config = Npm.cmd('config') return Config.completion(opts) } async exec (args) { if (!args.length) { throw this.usageError() } return this.npm.exec('config', ['set'].concat(args)) } } module.exports = Set const { resolve, basename } = require('node:path') const { unlink } = require('node:fs/promises') const { log } = require('proc-log') const BaseCommand = require('../base-cmd.js') class Shrinkwrap extends BaseCommand { static description = 'Lock down dependency versions for publication' static name = 'shrinkwrap' static ignoreImplicitWorkspace = false async exec () { // if has a npm-shrinkwrap.json, nothing to do // if has a package-lock.json, rename to npm-shrinkwrap.json // if has neither, load the actual tree and save that as npm-shrinkwrap.json // // loadVirtual, fall back to loadActual // rename shrinkwrap file type, and tree.meta.save() if (this.npm.global) { const er = new Error('`npm shrinkwrap` does not work for global packages') er.code = 'ESHRINKWRAPGLOBAL' throw er } const Arborist = require('@npmcli/arborist') const path = this.npm.prefix const sw = resolve(path, 'npm-shrinkwrap.json') const arb = new Arborist({ ...this.npm.flatOptions, path }) const tree = await arb.loadVirtual().catch(() => arb.loadActual()) const { meta } = tree const newFile = meta.hiddenLockfile || !meta.loadedFromDisk const oldFilename = meta.filename const notSW = !newFile && basename(oldFilename) !== 'npm-shrinkwrap.json' // The computed lockfile version of a hidden lockfile is always 3 // even if the actual value of the property is a different. // When shrinkwrap is run with only a hidden lockfile we want to // set the shrinkwrap lockfile version as whatever was explicitly // requested with a fallback to the actual value from the hidden // lockfile. if (meta.hiddenLockfile) { meta.lockfileVersion = arb.options.lockfileVersion || meta.originalLockfileVersion } meta.hiddenLockfile = false meta.filename = sw await meta.save() const updatedVersion = meta.originalLockfileVersion !== meta.lockfileVersion ? meta.lockfileVersion : null if (newFile) { let message = 'created a lockfile as npm-shrinkwrap.json' if (updatedVersion) { message += ` with version ${updatedVersion}` } log.notice('', message) } else if (notSW) { await unlink(oldFilename) let message = 'package-lock.json has been renamed to npm-shrinkwrap.json' if (updatedVersion) { message += ` and updated to version ${updatedVersion}` } log.notice('', message) } else if (updatedVersion) { log.notice('', `npm-shrinkwrap.json updated to version ${updatedVersion}`) } else { log.notice('', 'npm-shrinkwrap.json up to date') } } } module.exports = Shrinkwrap const npmFetch = require('npm-registry-fetch') const npa = require('npm-package-arg') const { log, output } = require('proc-log') const getIdentity = require('../utils/get-identity') const BaseCommand = require('../base-cmd.js') class Star extends BaseCommand { static description = 'Mark your favorite packages' static name = 'star' static usage = ['[...]'] static params = [ 'registry', 'unicode', 'otp', ] static ignoreImplicitWorkspace = false async exec (args) { if (!args.length) { throw this.usageError() } // if we're unstarring, then show an empty star image // otherwise, show the full star image const unicode = this.npm.config.get('unicode') const full = unicode ? '\u2605 ' : '(*)' const empty = unicode ? '\u2606 ' : '( )' const show = this.name === 'star' ? full : empty const pkgs = args.map(npa) const username = await getIdentity(this.npm, this.npm.flatOptions) for (const pkg of pkgs) { const fullData = await npmFetch.json(pkg.escapedName, { ...this.npm.flatOptions, spec: pkg, query: { write: true }, preferOnline: true, }) const body = { _id: fullData._id, _rev: fullData._rev, users: fullData.users || {}, } if (this.name === 'star') { log.info('star', 'starring', body._id) body.users[username] = true log.verbose('star', 'starring', body) } else { delete body.users[username] log.info('unstar', 'unstarring', body._id) log.verbose('unstar', 'unstarring', body) } const data = await npmFetch.json(pkg.escapedName, { ...this.npm.flatOptions, spec: pkg, method: 'PUT', body, }) output.standard(show + ' ' + pkg.name) log.verbose('star', data) return data } } } module.exports = Star const npmFetch = require('npm-registry-fetch') const { log, output } = require('proc-log') const getIdentity = require('../utils/get-identity.js') const BaseCommand = require('../base-cmd.js') class Stars extends BaseCommand { static description = 'View packages marked as favorites' static name = 'stars' static usage = ['[]'] static params = ['registry'] static ignoreImplicitWorkspace = false async exec ([user]) { try { if (!user) { user = await getIdentity(this.npm, this.npm.flatOptions) } const { rows } = await npmFetch.json('/-/_view/starredByUser', { ...this.npm.flatOptions, query: { key: `"${user}"` }, }) if (rows.length === 0) { log.warn('stars', 'user has not starred any packages') } for (const row of rows) { output.standard(row.value) } } catch (err) { if (err.code === 'ENEEDAUTH') { log.warn('stars', 'auth is required to look up your username') } throw err } } } module.exports = Stars const LifecycleCmd = require('../lifecycle-cmd.js') // This ends up calling run-script(['start', ...args]) class Start extends LifecycleCmd { static description = 'Start a package' static name = 'start' static params = [ 'ignore-scripts', 'script-shell', ] } module.exports = Start const LifecycleCmd = require('../lifecycle-cmd.js') // This ends up calling run-script(['stop', ...args]) class Stop extends LifecycleCmd { static description = 'Stop a package' static name = 'stop' static params = [ 'ignore-scripts', 'script-shell', ] } module.exports = Stop const columns = require('cli-columns') const libteam = require('libnpmteam') const { output } = require('proc-log') const { otplease } = require('../utils/auth.js') const BaseCommand = require('../base-cmd.js') class Team extends BaseCommand { static description = 'Manage organization teams and team memberships' static name = 'team' static usage = [ 'create [--otp ]', 'destroy [--otp ]', 'add [--otp ]', 'rm [--otp ]', 'ls |', ] static params = [ 'registry', 'otp', 'parseable', 'json', ] static ignoreImplicitWorkspace = false static async completion (opts) { const { conf: { argv: { remain: argv } } } = opts const subcommands = ['create', 'destroy', 'add', 'rm', 'ls'] if (argv.length === 2) { return subcommands } if (subcommands.includes(argv[2])) { return [] } throw new Error(argv[2] + ' not recognized') } async exec ([cmd, entity = '', user = '']) { // Entities are in the format : // XXX: "description" option to libnpmteam is used as a description of the // team, but in npm's options, this is a boolean meaning "show the // description in npm search output". Hence its being set to null here. await otplease(this.npm, { ...this.npm.flatOptions }, opts => { entity = entity.replace(/^@/, '') switch (cmd) { case 'create': return this.create(entity, opts) case 'destroy': return this.destroy(entity, opts) case 'add': return this.add(entity, user, opts) case 'rm': return this.rm(entity, user, opts) case 'ls': { const match = entity.match(/[^:]+:.+/) if (match) { return this.listUsers(entity, opts) } else { return this.listTeams(entity, opts) } } default: throw this.usageError() } }) } async create (entity, opts) { await libteam.create(entity, opts) if (opts.json) { output.buffer({ created: true, team: entity, }) } else if (opts.parseable) { output.standard(`${entity}\tcreated`) } else if (!this.npm.silent) { output.standard(`+@${entity}`) } } async destroy (entity, opts) { await libteam.destroy(entity, opts) if (opts.json) { output.buffer({ deleted: true, team: entity, }) } else if (opts.parseable) { output.standard(`${entity}\tdeleted`) } else if (!this.npm.silent) { output.standard(`-@${entity}`) } } async add (entity, user, opts) { await libteam.add(user, entity, opts) if (opts.json) { output.buffer({ added: true, team: entity, user, }) } else if (opts.parseable) { output.standard(`${user}\t${entity}\tadded`) } else if (!this.npm.silent) { output.standard(`${user} added to @${entity}`) } } async rm (entity, user, opts) { await libteam.rm(user, entity, opts) if (opts.json) { output.buffer({ removed: true, team: entity, user, }) } else if (opts.parseable) { output.standard(`${user}\t${entity}\tremoved`) } else if (!this.npm.silent) { output.standard(`${user} removed from @${entity}`) } } async listUsers (entity, opts) { const users = (await libteam.lsUsers(entity, opts)).sort() if (opts.json) { output.buffer(users) } else if (opts.parseable) { output.standard(users.join('\n')) } else if (!this.npm.silent) { const plural = users.length === 1 ? '' : 's' const more = users.length === 0 ? '' : ':\n' output.standard(`\n@${entity} has ${users.length} user${plural}${more}`) output.standard(columns(users, { padding: 1 })) } } async listTeams (entity, opts) { const teams = (await libteam.lsTeams(entity, opts)).sort() if (opts.json) { output.buffer(teams) } else if (opts.parseable) { output.standard(teams.join('\n')) } else if (!this.npm.silent) { const plural = teams.length === 1 ? '' : 's' const more = teams.length === 0 ? '' : ':\n' output.standard(`\n@${entity} has ${teams.length} team${plural}${more}`) output.standard(columns(teams.map(t => `@${t}`), { padding: 1 })) } } } module.exports = Team const LifecycleCmd = require('../lifecycle-cmd.js') // This ends up calling run-script(['test', ...args]) class Test extends LifecycleCmd { static description = 'Test a package' static name = 'test' static params = [ 'ignore-scripts', 'script-shell', ] } module.exports = Test const { log, output } = require('proc-log') const { listTokens, createToken, removeToken } = require('npm-profile') const { otplease } = require('../utils/auth.js') const readUserInfo = require('../utils/read-user-info.js') const BaseCommand = require('../base-cmd.js') class Token extends BaseCommand { static description = 'Manage your authentication tokens' static name = 'token' static usage = ['list', 'revoke ', 'create [--read-only] [--cidr=list]'] static params = ['read-only', 'cidr', 'registry', 'otp'] static async completion (opts) { const argv = opts.conf.argv.remain const subcommands = ['list', 'revoke', 'create'] if (argv.length === 2) { return subcommands } if (subcommands.includes(argv[2])) { return [] } throw new Error(argv[2] + ' not recognized') } async exec (args) { if (args.length === 0) { return this.list() } switch (args[0]) { case 'list': case 'ls': return this.list() case 'rm': case 'delete': case 'revoke': case 'remove': return this.rm(args.slice(1)) case 'create': return this.create(args.slice(1)) default: throw this.usageError(`${args[0]} is not a recognized subcommand.`) } } async list () { const json = this.npm.config.get('json') const parseable = this.npm.config.get('parseable') log.info('token', 'getting list') const tokens = await listTokens(this.npm.flatOptions) if (json) { output.buffer(tokens) return } if (parseable) { output.standard(['key', 'token', 'created', 'readonly', 'CIDR whitelist'].join('\t')) tokens.forEach(token => { output.standard( [ token.key, token.token, token.created, token.readonly ? 'true' : 'false', token.cidr_whitelist ? token.cidr_whitelist.join(',') : '', ].join('\t') ) }) return } this.generateTokenIds(tokens, 6) const chalk = this.npm.chalk for (const token of tokens) { const level = token.readonly ? 'Read only token' : 'Publish token' const created = String(token.created).slice(0, 10) output.standard(`${chalk.blue(level)} ${token.token}… with id ${chalk.cyan(token.id)} created ${created}`) if (token.cidr_whitelist) { output.standard(`with IP whitelist: ${chalk.green(token.cidr_whitelist.join(','))}`) } output.standard() } } async rm (args) { if (args.length === 0) { throw this.usageError('`` argument is required.') } const json = this.npm.config.get('json') const parseable = this.npm.config.get('parseable') const toRemove = [] const opts = { ...this.npm.flatOptions } log.info('token', `removing ${toRemove.length} tokens`) const tokens = await listTokens(opts) args.forEach(id => { const matches = tokens.filter(token => token.key.indexOf(id) === 0) if (matches.length === 1) { toRemove.push(matches[0].key) } else if (matches.length > 1) { throw new Error( `Token ID "${id}" was ambiguous, a new token may have been created since you last ran \`npm token list\`.` ) } else { const tokenMatches = tokens.some(t => id.indexOf(t.token) === 0) if (!tokenMatches) { throw new Error(`Unknown token id or value "${id}".`) } toRemove.push(id) } }) await Promise.all( toRemove.map(key => { return otplease(this.npm, opts, c => removeToken(key, c)) }) ) if (json) { output.buffer(toRemove) } else if (parseable) { output.standard(toRemove.join('\t')) } else { output.standard('Removed ' + toRemove.length + ' token' + (toRemove.length !== 1 ? 's' : '')) } } async create () { const json = this.npm.config.get('json') const parseable = this.npm.config.get('parseable') const cidr = this.npm.config.get('cidr') const readonly = this.npm.config.get('read-only') const validCIDR = await this.validateCIDRList(cidr) const password = await readUserInfo.password() log.info('token', 'creating') const result = await otplease( this.npm, { ...this.npm.flatOptions }, c => createToken(password, readonly, validCIDR, c) ) delete result.key delete result.updated if (json) { output.buffer(result) } else if (parseable) { Object.keys(result).forEach(k => output.standard(k + '\t' + result[k])) } else { const chalk = this.npm.chalk // Identical to list const level = result.readonly ? 'read only' : 'publish' output.standard(`Created ${chalk.blue(level)} token ${result.token}`) if (result.cidr_whitelist?.length) { output.standard(`with IP whitelist: ${chalk.green(result.cidr_whitelist.join(','))}`) } } } invalidCIDRError (msg) { return Object.assign(new Error(msg), { code: 'EINVALIDCIDR' }) } generateTokenIds (tokens, minLength) { for (const token of tokens) { token.id = token.key for (let ii = minLength; ii < token.key.length; ++ii) { const match = tokens.some( ot => ot !== token && ot.key.slice(0, ii) === token.key.slice(0, ii) ) if (!match) { token.id = token.key.slice(0, ii) break } } } } async validateCIDRList (cidrs) { const { v4: isCidrV4, v6: isCidrV6 } = await import('is-cidr') const maybeList = [].concat(cidrs).filter(Boolean) const list = maybeList.length === 1 ? maybeList[0].split(/,\s*/) : maybeList for (const cidr of list) { if (isCidrV6(cidr)) { throw this.invalidCIDRError( `CIDR whitelist can only contain IPv4 addresses${cidr} is IPv6` ) } if (!isCidrV4(cidr)) { throw this.invalidCIDRError(`CIDR whitelist contains invalid CIDR entry: ${cidr}`) } } return list } } module.exports = Token const Deprecate = require('./deprecate.js') class Undeprecate extends Deprecate { static description = 'Undeprecate a version of a package' static name = 'undeprecate' static usage = [''] async exec ([pkg]) { return super.exec([pkg, '']) } } module.exports = Undeprecate const { resolve } = require('node:path') const pkgJson = require('@npmcli/package-json') const reifyFinish = require('../utils/reify-finish.js') const completion = require('../utils/installed-shallow.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Uninstall extends ArboristWorkspaceCmd { static description = 'Remove a package' static name = 'uninstall' static params = ['save', 'global', ...super.params] static usage = ['[<@scope>/]...'] static ignoreImplicitWorkspace = false // TODO /* istanbul ignore next */ static async completion (opts, npm) { return completion(npm, opts) } async exec (args) { if (!args.length) { if (!this.npm.global) { throw new Error('Must provide a package name to remove') } else { try { const { content: pkg } = await pkgJson.normalize(this.npm.localPrefix) args.push(pkg.name) } catch (er) { if (er.code !== 'ENOENT' && er.code !== 'ENOTDIR') { throw er } else { throw this.usageError() } } } } // the /path/to/node_modules/.. const path = this.npm.global ? resolve(this.npm.globalDir, '..') : this.npm.localPrefix const Arborist = require('@npmcli/arborist') const opts = { ...this.npm.flatOptions, path, rm: args, workspaces: this.workspaceNames, } const arb = new Arborist(opts) await arb.reify(opts) await reifyFinish(this.npm, arb) } } module.exports = Uninstall const libaccess = require('libnpmaccess') const libunpub = require('libnpmpublish').unpublish const npa = require('npm-package-arg') const pacote = require('pacote') const { output, log } = require('proc-log') const pkgJson = require('@npmcli/package-json') const { flatten } = require('@npmcli/config/lib/definitions') const getIdentity = require('../utils/get-identity.js') const { otplease } = require('../utils/auth.js') const BaseCommand = require('../base-cmd.js') const LAST_REMAINING_VERSION_ERROR = 'Refusing to delete the last version of the package. ' + 'It will block from republishing a new version for 24 hours.\n' + 'Run with --force to do this.' class Unpublish extends BaseCommand { static description = 'Remove a package from the registry' static name = 'unpublish' static params = ['dry-run', 'force', 'workspace', 'workspaces'] static usage = ['[]'] static workspaces = true static ignoreImplicitWorkspace = false static async getKeysOfVersions (name, opts) { const packument = await pacote.packument(name, { ...opts, spec: name, query: { write: true }, }) return Object.keys(packument.versions) } static async completion (args, npm) { const { partialWord, conf } = args if (conf.argv.remain.length >= 3) { return [] } const opts = { ...npm.flatOptions } const username = await getIdentity(npm, { ...opts }).catch(() => null) if (!username) { return [] } const access = await libaccess.getPackages(username, opts) // do a bit of filtering at this point, so that we don't need // to fetch versions for more than one thing, but also don't // accidentally unpublish a whole project let pkgs = Object.keys(access) if (!partialWord || !pkgs.length) { return pkgs } const pp = npa(partialWord).name pkgs = pkgs.filter(p => !p.indexOf(pp)) if (pkgs.length > 1) { return pkgs } const versions = await Unpublish.getKeysOfVersions(pkgs[0], opts) if (!versions.length) { return pkgs } else { return versions.map(v => `${pkgs[0]}@${v}`) } } async exec (args, { localPrefix } = {}) { if (args.length > 1) { throw this.usageError() } // workspace mode if (!localPrefix) { localPrefix = this.npm.localPrefix } const force = this.npm.config.get('force') const { silent } = this.npm const dryRun = this.npm.config.get('dry-run') let spec if (args.length) { spec = npa(args[0]) if (spec.type !== 'version' && spec.rawSpec !== '*') { throw this.usageError( 'Can only unpublish a single version, or the entire project.\n' + 'Tags and ranges are not supported.' ) } } log.silly('unpublish', 'args[0]', args[0]) log.silly('unpublish', 'spec', spec) if (spec?.rawSpec === '*' && !force) { throw this.usageError( 'Refusing to delete entire project.\n' + 'Run with --force to do this.' ) } const opts = { ...this.npm.flatOptions } let manifest try { const { content } = await pkgJson.prepare(localPrefix) manifest = content } catch (err) { if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { if (!spec) { // We needed a local package.json to figure out what package to // unpublish throw this.usageError() } } else { // folks should know if ANY local package.json had a parsing error. // They may be relying on `publishConfig` to be loading and we don't // want to ignore errors in that case. throw err } } let pkgVersion // for cli output if (spec) { pkgVersion = spec.type === 'version' ? `@${spec.rawSpec}` : '' } else { spec = npa.resolve(manifest.name, manifest.version) log.verbose('unpublish', manifest) pkgVersion = manifest.version ? `@${manifest.version}` : '' if (!manifest.version && !force) { throw this.usageError( 'Refusing to delete entire project.\n' + 'Run with --force to do this.' ) } } // If localPrefix has a package.json with a name that matches the package // being unpublished, load up the publishConfig if (manifest?.name === spec.name && manifest.publishConfig) { const cliFlags = this.npm.config.data.get('cli').raw // Filter out properties set in CLI flags to prioritize them over // corresponding `publishConfig` settings const filteredPublishConfig = Object.fromEntries( Object.entries(manifest.publishConfig).filter(([key]) => !(key in cliFlags))) flatten(filteredPublishConfig, opts) } const versions = await Unpublish.getKeysOfVersions(spec.name, opts) if (versions.length === 1 && spec.rawSpec === versions[0] && !force) { throw this.usageError(LAST_REMAINING_VERSION_ERROR) } if (versions.length === 1) { pkgVersion = '' } if (!dryRun) { await otplease(this.npm, opts, o => libunpub(spec, o)) } if (!silent) { output.standard(`- ${spec.name}${pkgVersion}`) } } async execWorkspaces (args) { await this.setWorkspaces() for (const path of this.workspacePaths) { await this.exec(args, { localPrefix: path }) } } } module.exports = Unpublish const Star = require('./star.js') class Unstar extends Star { static description = 'Remove an item from your favorite packages' static name = 'unstar' } module.exports = Unstar const path = require('node:path') const { log } = require('proc-log') const reifyFinish = require('../utils/reify-finish.js') const ArboristWorkspaceCmd = require('../arborist-cmd.js') class Update extends ArboristWorkspaceCmd { static description = 'Update packages' static name = 'update' static params = [ 'save', 'global', 'install-strategy', 'legacy-bundling', 'global-style', 'omit', 'include', 'strict-peer-deps', 'package-lock', 'foreground-scripts', 'ignore-scripts', 'audit', 'bin-links', 'fund', 'dry-run', ...super.params, ] static usage = ['[...]'] // TODO /* istanbul ignore next */ static async completion (opts, npm) { const completion = require('../utils/installed-deep.js') return completion(npm, opts) } async exec (args) { const update = args.length === 0 ? true : args const global = path.resolve(this.npm.globalDir, '..') const where = this.npm.global ? global : this.npm.prefix // In the context of `npm update` the save // config value should default to `false` const save = this.npm.config.isDefault('save') ? false : this.npm.config.get('save') if (this.npm.config.get('depth')) { log.warn('update', 'The --depth option no longer has any effect. See RFC0019.\n' + 'https://github.com/npm/rfcs/blob/latest/implemented/0019-remove-update-depth-option.md') } const Arborist = require('@npmcli/arborist') const opts = { ...this.npm.flatOptions, path: where, save, workspaces: this.workspaceNames, } const arb = new Arborist(opts) await arb.reify({ ...opts, update }) await reifyFinish(this.npm, arb) } } module.exports = Update const { resolve } = require('node:path') const { readFile } = require('node:fs/promises') const { output } = require('proc-log') const BaseCommand = require('../base-cmd.js') class Version extends BaseCommand { static description = 'Bump a package version' static name = 'version' static params = [ 'allow-same-version', 'commit-hooks', 'git-tag-version', 'json', 'preid', 'sign-git-tag', 'workspace', 'workspaces', 'workspaces-update', 'include-workspace-root', ] static workspaces = true static ignoreImplicitWorkspace = false static usage = ['[ | major | minor | patch | premajor | preminor | prepatch | prerelease | from-git]'] static async completion (opts) { const { conf: { argv: { remain }, }, } = opts if (remain.length > 2) { return [] } return [ 'major', 'minor', 'patch', 'premajor', 'preminor', 'prepatch', 'prerelease', 'from-git', ] } async exec (args) { switch (args.length) { case 0: return this.list() case 1: return this.change(args) default: throw this.usageError() } } async execWorkspaces (args) { switch (args.length) { case 0: return this.listWorkspaces() case 1: return this.changeWorkspaces(args) default: throw this.usageError() } } async change (args) { const libnpmversion = require('libnpmversion') const prefix = this.npm.config.get('tag-version-prefix') const version = await libnpmversion(args[0], { ...this.npm.flatOptions, path: this.npm.prefix, }) return output.standard(`${prefix}${version}`) } async changeWorkspaces (args) { const updateWorkspaces = require('../utils/update-workspaces.js') const libnpmversion = require('libnpmversion') const prefix = this.npm.config.get('tag-version-prefix') const { config, flatOptions, localPrefix, } = this.npm await this.setWorkspaces() const updatedWorkspaces = [] for (const [name, path] of this.workspaces) { output.standard(name) const version = await libnpmversion(args[0], { ...flatOptions, 'git-tag-version': false, path, }) updatedWorkspaces.push(name) output.standard(`${prefix}${version}`) } return updateWorkspaces({ config, flatOptions, localPrefix, npm: this.npm, workspaces: updatedWorkspaces, }) } async list (results = {}) { const pj = resolve(this.npm.prefix, 'package.json') const pkg = await readFile(pj, 'utf8') .then(data => JSON.parse(data)) .catch(() => ({})) if (pkg.name && pkg.version) { results[pkg.name] = pkg.version } results.npm = this.npm.version for (const [key, version] of Object.entries(process.versions)) { results[key] = version } if (this.npm.config.get('json')) { output.buffer(results) } else { output.standard(results) } } async listWorkspaces () { const results = {} await this.setWorkspaces() for (const path of this.workspacePaths) { const pj = resolve(path, 'package.json') // setWorkspaces has already parsed package.json so we know it won't error const pkg = await readFile(pj, 'utf8').then(data => JSON.parse(data)) if (pkg.name && pkg.version) { results[pkg.name] = pkg.version } } return this.list(results) } } module.exports = Version const columns = require('cli-columns') const { readFile } = require('node:fs/promises') const jsonParse = require('json-parse-even-better-errors') const { log, output, META } = require('proc-log') const npa = require('npm-package-arg') const { resolve } = require('node:path') const formatBytes = require('../utils/format-bytes.js') const relativeDate = require('tiny-relative-date') const semver = require('semver') const { inspect } = require('node:util') const { packument } = require('pacote') const Queryable = require('../utils/queryable.js') const BaseCommand = require('../base-cmd.js') const { getError } = require('../utils/error-message.js') const { jsonError, outputError } = require('../utils/output-error.js') const readJson = file => readFile(file, 'utf8').then(jsonParse) class View extends BaseCommand { static description = 'View registry info' static name = 'view' static params = [ 'json', 'workspace', 'workspaces', 'include-workspace-root', ] static workspaces = true static ignoreImplicitWorkspace = false static usage = ['[] [[.subfield]...]'] static async completion (opts, npm) { if (opts.conf.argv.remain.length <= 2) { // There used to be registry completion here, but it stopped // making sense somewhere around 50,000 packages on the registry return } // have the package, get the fields const config = { ...npm.flatOptions, fullMetadata: true, preferOnline: true, } const spec = npa(opts.conf.argv.remain[2]) const pckmnt = await packument(spec, config) const defaultTag = npm.config.get('tag') const dv = pckmnt.versions[pckmnt['dist-tags'][defaultTag]] pckmnt.versions = Object.keys(pckmnt.versions).sort(semver.compareLoose) return getCompletionFields(pckmnt).concat(getCompletionFields(dv)) } async exec (args) { let { pkg, local, rest } = parseArgs(args) if (local) { if (this.npm.global) { throw new Error('Cannot use view command in global mode.') } const dir = this.npm.prefix const manifest = await readJson(resolve(dir, 'package.json')) if (!manifest.name) { throw new Error('Invalid package.json, no "name" field') } // put the version back if it existed pkg = `${manifest.name}${pkg.slice(1)}` } await this.#viewPackage(pkg, rest) } async execWorkspaces (args) { const { pkg, local, rest } = parseArgs(args) if (!local) { log.warn('Ignoring workspaces for specified package(s)') return this.exec([pkg, ...rest]) } const json = this.npm.config.get('json') await this.setWorkspaces() for (const name of this.workspaceNames) { try { await this.#viewPackage(`${name}${pkg.slice(1)}`, rest, { workspace: true }) } catch (e) { const err = getError(e, { npm: this.npm, command: this }) if (err.code !== 'E404') { throw e } if (json) { output.buffer({ [META]: true, jsonError: { [name]: jsonError(err, this.npm) } }) } else { outputError(err) } process.exitCode = err.exitCode } } } async #viewPackage (name, args, { workspace } = {}) { const wholePackument = !args.length const json = this.npm.config.get('json') // If we are viewing many packages and outputting individual fields then // output the name before doing any async activity if (!json && !wholePackument && workspace) { output.standard(`${name}:`) } const [pckmnt, data] = await this.#getData(name, args, wholePackument) if (!json && wholePackument) { // pretty view (entire packument) for (const v of data) { output.standard(this.#prettyView(pckmnt, Object.values(v)[0][Queryable.ALL])) } return } const res = this.#packageOutput(cleanData(data, wholePackument), pckmnt._id) if (res) { if (json) { output.buffer(workspace ? { [name]: res } : res) } else { output.standard(res) } } } async #getData (pkg, args) { const spec = npa(pkg) const pckmnt = await packument(spec, { ...this.npm.flatOptions, preferOnline: true, fullMetadata: true, }) // get the data about this package let version = this.npm.config.get('tag') // rawSpec is the git url if this is from git if (spec.type !== 'git' && spec.type !== 'directory' && spec.rawSpec !== '*') { version = spec.rawSpec } if (pckmnt['dist-tags']?.[version]) { version = pckmnt['dist-tags'][version] } if (pckmnt.time?.unpublished) { const u = pckmnt.time.unpublished throw Object.assign(new Error(`Unpublished on ${u.time}`), { statusCode: 404, code: 'E404', pkgid: pckmnt._id, }) } const versions = pckmnt.versions || {} pckmnt.versions = Object.keys(versions).filter(v => { if (semver.valid(v)) { return true } log.info('view', `Ignoring invalid version: ${v}`) return false }).sort(semver.compareLoose) // remove readme unless we asked for it if (args.indexOf('readme') === -1) { delete pckmnt.readme } const data = Object.entries(versions) .filter(([v]) => semver.satisfies(v, version, true)) .flatMap(([, v]) => { // remove readme unless we asked for it if (args.indexOf('readme') !== -1) { delete v.readme } return showFields({ data: pckmnt, version: v, fields: args, json: this.npm.config.get('json'), }) }) // No data has been pushed because no data is matching the specified version if (!data.length && version !== 'latest') { throw Object.assign(new Error(`No match found for version ${version}`), { statusCode: 404, code: 'E404', pkgid: `${pckmnt._id}@${version}`, }) } return [pckmnt, data] } #packageOutput (data, name) { const json = this.npm.config.get('json') const versions = Object.keys(data) const includeVersions = versions.length > 1 let includeFields const res = versions.flatMap((v) => { const fields = Object.entries(data[v]) includeFields ||= (fields.length > 1) const msg = json ? {} : [] for (let [f, d] of fields) { d = cleanup(d) if (json) { msg[f] = d continue } if (includeVersions || includeFields || typeof d !== 'string') { d = inspect(d, { showHidden: false, depth: 5, colors: this.npm.color, maxArrayLength: null, }) } if (f && includeFields) { f += ' = ' } msg.push(`${includeVersions ? `${name}@${v} ` : ''}${includeFields ? f : ''}${d}`) } return msg }) if (json) { // TODO(BREAKING_CHANGE): all unwrapping should be removed. Users should know // based on their arguments if they can expect an array or an object. And this // unwrapping can break that assumption. Eg `npm view abbrev@^2` should always // return an array, but currently since there is only one version matching `^2` // this will return a single object instead. const first = Object.keys(res[0] || {}) const jsonRes = first.length === 1 ? res.map(m => m[first[0]]) : res if (jsonRes.length === 0) { return } if (jsonRes.length === 1) { return jsonRes[0] } return jsonRes } return res.join('\n').trim() } #prettyView (packu, manifest) { // More modern, pretty printing of default view const unicode = this.npm.config.get('unicode') const chalk = this.npm.chalk const deps = Object.entries(manifest.dependencies || {}).map(([k, dep]) => `${chalk.blue(k)}: ${dep}` ) // Sort dist-tags by publish time, then tag name, keeping latest at the top of the list const distTags = Object.entries(packu['dist-tags']) .sort(([aTag, aVer], [bTag, bVer]) => { const aTime = aTag === 'latest' ? Infinity : Date.parse(packu.time[aVer]) const bTime = bTag === 'latest' ? Infinity : Date.parse(packu.time[bVer]) if (aTime === bTime) { return aTag > bTag ? -1 : 1 } return aTime > bTime ? -1 : 1 }) .map(([k, t]) => `${chalk.blue(k)}: ${t}`) const site = manifest.homepage?.url || manifest.homepage const bins = Object.keys(manifest.bin || {}) const licenseField = manifest.license || 'Proprietary' const license = typeof licenseField === 'string' ? licenseField : (licenseField.type || 'Proprietary') const res = [] res.push('') res.push([ chalk.underline.cyan(`${manifest.name}@${manifest.version}`), license.toLowerCase().trim() === 'proprietary' ? chalk.red(license) : chalk.green(license), `deps: ${deps.length ? chalk.cyan(deps.length) : chalk.cyan('none')}`, `versions: ${chalk.cyan(packu.versions.length + '')}`, ].join(' | ')) manifest.description && res.push(manifest.description) if (site) { res.push(chalk.blue(site)) } manifest.deprecated && res.push( `\n${chalk.redBright('DEPRECATED')}${unicode ? ' âš ï¸ ' : '!!'} - ${manifest.deprecated}` ) if (packu.keywords?.length) { res.push(`\nkeywords: ${ packu.keywords.map(k => chalk.cyan(k)).join(', ') }`) } if (bins.length) { res.push(`\nbin: ${chalk.cyan(bins.join(', '))}`) } res.push('\ndist') res.push(`.tarball: ${chalk.blue(manifest.dist.tarball)}`) res.push(`.shasum: ${chalk.green(manifest.dist.shasum)}`) if (manifest.dist.integrity) { res.push(`.integrity: ${chalk.green(manifest.dist.integrity)}`) } if (manifest.dist.unpackedSize) { res.push(`.unpackedSize: ${chalk.blue(formatBytes(manifest.dist.unpackedSize, true))}`) } if (deps.length) { const maxDeps = 24 res.push('\ndependencies:') res.push(columns(deps.slice(0, maxDeps), { padding: 1 })) if (deps.length > maxDeps) { res.push(chalk.dim(`(...and ${deps.length - maxDeps} more.)`)) } } if (packu.maintainers?.length) { res.push('\nmaintainers:') packu.maintainers.forEach(u => res.push(`- ${unparsePerson({ name: chalk.blue(u.name), email: chalk.dim(u.email) })}`) ) } res.push('\ndist-tags:') const maxTags = 12 res.push(columns(distTags.slice(0, maxTags), { padding: 1, sort: false })) if (distTags.length > maxTags) { res.push(chalk.dim(`(...and ${distTags.length - maxTags} more.)`)) } const publisher = manifest._npmUser && unparsePerson({ name: chalk.blue(manifest._npmUser.name), email: chalk.dim(manifest._npmUser.email), }) if (publisher || packu.time) { let publishInfo = 'published' if (packu.time) { publishInfo += ` ${chalk.cyan(relativeDate(packu.time[manifest.version]))}` } if (publisher) { publishInfo += ` by ${publisher}` } res.push('') res.push(publishInfo) } return res.join('\n') } } module.exports = View function parseArgs (args) { if (!args.length) { args = ['.'] } const pkg = args.shift() return { pkg, local: /^\.@/.test(pkg) || pkg === '.', rest: args, } } function cleanData (obj, wholePackument) { // JSON formatted output (JSON or specific attributes from packument) const data = obj.reduce((acc, cur) => { if (cur) { Object.entries(cur).forEach(([k, v]) => { acc[k] ||= {} Object.keys(v).forEach((t) => { acc[k][t] = cur[k][t] }) }) } return acc }, {}) if (wholePackument) { const cleaned = Object.entries(data).reduce((acc, [k, v]) => { acc[k] = v[Queryable.ALL] return acc }, {}) log.silly('view', cleaned) return cleaned } return data } // return whatever was printed function showFields ({ data, version, fields, json }) { const o = [data, version].reduce((acc, s) => { Object.entries(s).forEach(([k, v]) => { acc[k] = v }) return acc }, {}) const queryable = new Queryable(o) if (!fields.length) { return { [version.version]: queryable.query(Queryable.ALL) } } return fields.map((field) => { const s = queryable.query(field, { unwrapSingleItemArrays: !json }) if (s) { return { [version.version]: s } } }) } function cleanup (data) { if (Array.isArray(data)) { return data.map(cleanup) } if (!data || typeof data !== 'object') { return data } const keys = Object.keys(data) if (keys.length <= 3 && data.name && ( (keys.length === 1) || (keys.length === 3 && data.email && data.url) || (keys.length === 2 && (data.email || data.url)) )) { data = unparsePerson(data) } return data } const unparsePerson = (d) => `${d.name}${d.email ? ` <${d.email}>` : ''}${d.url ? ` (${d.url})` : ''}` function getCompletionFields (d, f = [], pref = []) { Object.entries(d).forEach(([k, v]) => { if (k.charAt(0) === '_' || k.indexOf('.') !== -1) { return } const p = pref.concat(k).join('.') f.push(p) if (Array.isArray(v)) { v.forEach((val, i) => { const pi = p + '[' + i + ']' if (val && typeof val === 'object') { getCompletionFields(val, f, [p]) } else { f.push(pi) } }) return } if (typeof v === 'object') { getCompletionFields(v, f, [p]) } }) return f } const { output } = require('proc-log') const getIdentity = require('../utils/get-identity.js') const BaseCommand = require('../base-cmd.js') class Whoami extends BaseCommand { static description = 'Display npm username' static name = 'whoami' static params = ['registry'] async exec () { const username = await getIdentity(this.npm, { ...this.npm.flatOptions }) if (this.npm.config.get('json')) { output.buffer(username) } else { output.standard(username) } } } module.exports = Whoami const BaseCommand = require('./base-cmd.js') // The implementation of commands that are just "run a script" // restart, start, stop, test class LifecycleCmd extends BaseCommand { static usage = ['[-- ]'] static isShellout = true static workspaces = true static ignoreImplicitWorkspace = false async exec (args) { return this.npm.exec('run-script', [this.constructor.name, ...args]) } async execWorkspaces (args) { return this.npm.exec('run-script', [this.constructor.name, ...args]) } } module.exports = LifecycleCmd const { resolve, dirname, join } = require('node:path') const Config = require('@npmcli/config') const which = require('which') const fs = require('node:fs/promises') const { definitions, flatten, shorthands } = require('@npmcli/config/lib/definitions') const usage = require('./utils/npm-usage.js') const LogFile = require('./utils/log-file.js') const Timers = require('./utils/timers.js') const Display = require('./utils/display.js') const { log, time, output, META } = require('proc-log') const { redactLog: replaceInfo } = require('@npmcli/redact') const pkg = require('../package.json') const { deref } = require('./utils/cmd-list.js') const { jsonError, outputError } = require('./utils/output-error.js') class Npm { static get version () { return pkg.version } static cmd (c) { const command = deref(c) if (!command) { throw Object.assign(new Error(`Unknown command ${c}`), { code: 'EUNKNOWNCOMMAND', command: c, }) } return require(`./commands/${command}.js`) } unrefPromises = [] updateNotification = null argv = [] #command = null #runId = new Date().toISOString().replace(/[.:]/g, '_') #title = 'npm' #argvClean = [] #npmRoot = null #display = null #logFile = new LogFile() #timers = new Timers() // all these options are only used by tests in order to make testing more // closely resemble real world usage. for now, npm has no programmatic API so // it is ok to add stuff here, but we should not rely on it more than // necessary. XXX: make these options not necessary by refactoring @npmcli/config // - npmRoot: this is where npm looks for docs files and the builtin config // - argv: this allows tests to extend argv in the same way the argv would // be passed in via a CLI arg. // - excludeNpmCwd: this is a hack to get @npmcli/config to stop walking up // dirs to set a local prefix when it encounters the `npmRoot`. this // allows tests created by tap inside this repo to not set the local // prefix to `npmRoot` since that is the first dir it would encounter when // doing implicit detection constructor ({ stdout = process.stdout, stderr = process.stderr, npmRoot = dirname(__dirname), argv = [], excludeNpmCwd = false, } = {}) { this.#display = new Display({ stdout, stderr }) this.#npmRoot = npmRoot this.config = new Config({ npmPath: this.#npmRoot, definitions, flatten, shorthands, argv: [...process.argv, ...argv], excludeNpmCwd, }) } async load () { let err try { return await time.start('npm:load', () => this.#load()) } catch (e) { err = e } return this.#handleError(err) } async #load () { await time.start('npm:load:whichnode', async () => { // TODO should we throw here? const node = await which(process.argv[0]).catch(() => {}) if (node && node.toUpperCase() !== process.execPath.toUpperCase()) { log.verbose('node symlink', node) process.execPath = node this.config.execPath = node } }) await time.start('npm:load:configload', () => this.config.load()) // npm --versions if (this.config.get('versions', 'cli')) { this.argv = ['version'] this.config.set('usage', false, 'cli') } else { this.argv = [...this.config.parsedArgv.remain] } // Remove first argv since that is our command as typed // Note that this might not be the actual name of the command // due to aliases, etc. But we use the raw form of it later // in user output so it must be preserved as is. const commandArg = this.argv.shift() // This is the actual name of the command that will be run or // undefined if deref could not find a match const command = deref(commandArg) await this.#display.load({ command, loglevel: this.config.get('loglevel'), stdoutColor: this.color, stderrColor: this.logColor, timing: this.config.get('timing'), unicode: this.config.get('unicode'), progress: this.flatOptions.progress, json: this.config.get('json'), heading: this.config.get('heading'), }) process.env.COLOR = this.color ? '1' : '0' // npm -v // return from here early so we dont create any caches/logfiles/timers etc if (this.config.get('version', 'cli')) { output.standard(this.version) return { exec: false } } // mkdir this separately since the logs dir can be set to // a different location. if this fails, then we don't have // a cache dir, but we don't want to fail immediately since // the command might not need a cache dir (like `npm --version`) await time.start('npm:load:mkdirpcache', () => fs.mkdir(this.cache, { recursive: true }) .catch((e) => log.verbose('cache', `could not create cache: ${e}`))) // it's ok if this fails. user might have specified an invalid dir // which we will tell them about at the end if (this.config.get('logs-max') > 0) { await time.start('npm:load:mkdirplogs', () => fs.mkdir(this.#logsDir, { recursive: true }) .catch((e) => log.verbose('logfile', `could not create logs-dir: ${e}`))) } // note: this MUST be shorter than the actual argv length, because it // uses the same memory, so node will truncate it if it's too long. // We time this because setting process.title is slow sometimes but we // have to do it for security reasons. But still helpful to know how slow it is. time.start('npm:load:setTitle', () => { const { parsedArgv: { cooked, remain } } = this.config // Secrets are mostly in configs, so title is set using only the positional args // to keep those from being leaked. We still do a best effort replaceInfo. this.#title = ['npm'].concat(replaceInfo(remain)).join(' ').trim() process.title = this.#title // The cooked argv is also logged separately for debugging purposes. It is // cleaned as a best effort by replacing known secrets like basic auth // password and strings that look like npm tokens. XXX: for this to be // safer the config should create a sanitized version of the argv as it // has the full context of what each option contains. this.#argvClean = replaceInfo(cooked) log.verbose('title', this.title) log.verbose('argv', this.#argvClean.map(JSON.stringify).join(' ')) }) // logFile.load returns a promise that resolves when old logs are done being cleaned. // We save this promise to an array so that we can await it in tests to ensure more // deterministic logging behavior. The process will also hang open if this were to // take a long time to resolve, but that is why process.exit is called explicitly // in the exit-handler. this.unrefPromises.push(this.#logFile.load({ command, path: this.logPath, logsMax: this.config.get('logs-max'), timing: this.config.get('timing'), })) this.#timers.load({ path: this.logPath, timing: this.config.get('timing'), }) const configScope = this.config.get('scope') if (configScope && !/^@/.test(configScope)) { this.config.set('scope', `@${configScope}`, this.config.find('scope')) } if (this.config.get('force')) { log.warn('using --force', 'Recommended protections disabled.') } return { exec: true, command: commandArg, args: this.argv } } async exec (cmd, args = this.argv) { if (!this.#command) { let err try { await this.#exec(cmd, args) } catch (e) { err = e } return this.#handleError(err) } else { return this.#exec(cmd, args) } } // Call an npm command async #exec (cmd, args) { const Command = this.constructor.cmd(cmd) const command = new Command(this) // since 'test', 'start', 'stop', etc. commands re-enter this function // to call the run-script command, we need to only set it one time. if (!this.#command) { this.#command = command process.env.npm_command = this.command } if (this.config.get('usage')) { return output.standard(command.usage) } let execWorkspaces = false const hasWsConfig = this.config.get('workspaces') || this.config.get('workspace').length // if cwd is a workspace, the default is set to [that workspace] const implicitWs = this.config.get('workspace', 'default').length // (-ws || -w foo) && (cwd is not a workspace || command is not ignoring implicit workspaces) if (hasWsConfig && (!implicitWs || !Command.ignoreImplicitWorkspace)) { if (this.global) { throw new Error('Workspaces not supported for global packages') } if (!Command.workspaces) { throw Object.assign(new Error('This command does not support workspaces.'), { code: 'ENOWORKSPACES', }) } execWorkspaces = true } if (command.checkDevEngines && !this.global) { await command.checkDevEngines() } return time.start(`command:${cmd}`, () => execWorkspaces ? command.execWorkspaces(args) : command.exec(args)) } // This gets called at the end of the exit handler and // during any tests to cleanup all of our listeners // Everything in here should be synchronous unload () { this.#timers.off() this.#display.off() this.#logFile.off() } finish (err) { // Finish all our timer work, this will write the file if requested, end timers, etc this.#timers.finish({ id: this.#runId, command: this.#argvClean, logfiles: this.logFiles, version: this.version, }) output.flush({ [META]: true, // json can be set during a command so we send the // final value of it to the display layer here json: this.loaded && this.config.get('json'), jsonError: jsonError(err, this), }) } exitErrorMessage () { if (this.logFiles.length) { return `A complete log of this run can be found in: ${this.logFiles}` } const logsMax = this.config.get('logs-max') if (logsMax <= 0) { // user specified no log file return `Log files were not written due to the config logs-max=${logsMax}` } // could be an error writing to the directory return `Log files were not written due to an error writing to the directory: ${this.#logsDir}` + '\nYou can rerun the command with `--loglevel=verbose` to see the logs in your terminal' } async #handleError (err) { if (err) { // Get the local package if it exists for a more helpful error message const localPkg = await require('@npmcli/package-json') .normalize(this.localPrefix) .then(p => p.content) .catch(() => null) Object.assign(err, this.#getError(err, { pkg: localPkg })) } this.finish(err) if (err) { throw err } } #getError (rawErr, opts) { const { files = [], ...error } = require('./utils/error-message.js').getError(rawErr, { npm: this, command: this.#command, ...opts, }) const { writeFileSync } = require('node:fs') for (const [file, content] of files) { const filePath = `${this.logPath}${file}` const fileContent = `'Log files:\n${this.logFiles.join('\n')}\n\n${content.trim()}\n` try { writeFileSync(filePath, fileContent) error.detail.push(['', `\n\nFor a full report see:\n${filePath}`]) } catch (fileErr) { log.warn('', `Could not write error message to ${file} due to ${fileErr}`) } } outputError(error) return error } get title () { return this.#title } get loaded () { return this.config.loaded } get version () { return this.constructor.version } get command () { return this.#command?.name } get flatOptions () { const { flat } = this.config flat.nodeVersion = process.version flat.npmVersion = pkg.version if (this.command) { flat.npmCommand = this.command } return flat } // color and logColor are a special derived values that takes into // consideration not only the config, but whether or not we are operating // in a tty with the associated output (stdout/stderr) get color () { return this.flatOptions.color } get logColor () { return this.flatOptions.logColor } get noColorChalk () { return this.#display.chalk.noColor } get chalk () { return this.#display.chalk.stdout } get logChalk () { return this.#display.chalk.stderr } get global () { return this.config.get('global') || this.config.get('location') === 'global' } get silent () { return this.flatOptions.silent } get lockfileVersion () { return 2 } get started () { return this.#timers.started } get logFiles () { return this.#logFile.files } get #logsDir () { return this.config.get('logs-dir') || join(this.cache, '_logs') } get logPath () { return resolve(this.#logsDir, `${this.#runId}-`) } get npmRoot () { return this.#npmRoot } get cache () { return this.config.get('cache') } get globalPrefix () { return this.config.globalPrefix } get localPrefix () { return this.config.localPrefix } get localPackage () { return this.config.localPackage } get globalDir () { return process.platform !== 'win32' ? resolve(this.globalPrefix, 'lib', 'node_modules') : resolve(this.globalPrefix, 'node_modules') } get localDir () { return resolve(this.localPrefix, 'node_modules') } get dir () { return this.global ? this.globalDir : this.localDir } get globalBin () { const b = this.globalPrefix return process.platform !== 'win32' ? resolve(b, 'bin') : b } get localBin () { return resolve(this.dir, '.bin') } get bin () { return this.global ? this.globalBin : this.localBin } get prefix () { return this.global ? this.globalPrefix : this.localPrefix } get usage () { return usage(this) } } module.exports = Npm const pacote = require('pacote') const { openUrl } = require('./utils/open-url.js') const { log } = require('proc-log') const BaseCommand = require('./base-cmd.js') // Base command for opening urls from a package manifest (bugs, docs, repo) class PackageUrlCommand extends BaseCommand { static params = [ 'browser', 'registry', 'workspace', 'workspaces', 'include-workspace-root', ] static workspaces = true static ignoreImplicitWorkspace = false static usage = ['[ [ ...]]'] async exec (args) { if (!args || !args.length) { args = ['.'] } for (const arg of args) { // XXX It is very odd that `where` is how pacote knows to look anywhere // other than the cwd. const opts = { ...this.npm.flatOptions, where: this.npm.localPrefix, fullMetadata: true, } const mani = await pacote.manifest(arg, opts) const url = this.getUrl(arg, mani) log.silly(this.name, 'url', url) await openUrl(this.npm, url, `${mani.name} ${this.name} available at the following URL`) } } async execWorkspaces (args) { if (args && args.length) { return this.exec(args) } await this.setWorkspaces() return this.exec(this.workspacePaths) } // given a manifest, try to get the hosted git info from it based on // repository (if a string) or repository.url (if an object) returns null // if it's not a valid repo, or not a known hosted repo hostedFromMani (mani) { const hostedGitInfo = require('hosted-git-info') const r = mani.repository const rurl = !r ? null : typeof r === 'string' ? r : typeof r === 'object' && typeof r.url === 'string' ? r.url : null // hgi returns undefined sometimes, but let's always return null here return (rurl && hostedGitInfo.fromUrl(rurl.replace(/^git\+/, ''))) || null } } module.exports = PackageUrlCommand const { log, output } = require('proc-log') const { redactLog: replaceInfo } = require('@npmcli/redact') // print an error or just nothing if the audit report has an error // this is called by the audit command, and by the reify-output util // prints a JSON version of the error if it's --json // returns 'true' if there was an error, false otherwise const auditError = (npm, report) => { if (!report || !report.error) { return false } if (npm.command !== 'audit') { return true } const { error } = report // ok, we care about it, then log.warn('audit', error.message) const { body: errBody } = error const body = Buffer.isBuffer(errBody) ? errBody.toString() : errBody if (npm.flatOptions.json) { output.buffer({ message: error.message, method: error.method, uri: replaceInfo(error.uri), headers: error.headers, statusCode: error.statusCode, body, }) } else { output.standard(body) } throw 'audit endpoint returned an error' } module.exports = auditError const { webAuthOpener, adduserWeb, loginWeb, loginCouch, adduserCouch } = require('npm-profile') const { log } = require('proc-log') const { createOpener } = require('../utils/open-url.js') const read = require('../utils/read-user-info.js') const otplease = async (npm, opts, fn) => { try { return await fn(opts) } catch (err) { if (!process.stdin.isTTY || !process.stdout.isTTY) { throw err } // web otp if (err.code === 'EOTP' && err.body?.authUrl && err.body?.doneUrl) { const { token: otp } = await webAuthOpener( createOpener(npm, 'Authenticate your account at'), err.body.authUrl, err.body.doneUrl, opts ) return await fn({ ...opts, otp }) } // classic otp if (err.code === 'EOTP' || (err.code === 'E401' && /one-time pass/.test(err.body))) { const otp = await read.otp('This operation requires a one-time password.\nEnter OTP:') return await fn({ ...opts, otp }) } throw err } } const adduser = async (npm, { creds, ...opts }) => { const authType = npm.config.get('auth-type') let res if (authType === 'web') { try { res = await adduserWeb(createOpener(npm, 'Create your account at'), opts) } catch (err) { if (err.code === 'ENYI') { log.verbose('web add user not supported, trying couch') } else { throw err } } } // auth type !== web or ENYI error w/ web adduser if (!res) { const username = await read.username('Username:', creds.username) const password = await read.password('Password:', creds.password) const email = await read.email('Email: (this IS public) ', creds.email) // npm registry quirk: If you "add" an existing user with their current // password, it's effectively a login, and if that account has otp you'll // be prompted for it. res = await otplease(npm, opts, (reqOpts) => adduserCouch(username, email, password, reqOpts)) } // We don't know the username if it was a web login, all we can reliably log is scope and registry const message = `Logged in${opts.scope ? ` to scope ${opts.scope}` : ''} on ${opts.registry}.` log.info('adduser', message) return { message, newCreds: { token: res.token }, } } const login = async (npm, { creds, ...opts }) => { const authType = npm.config.get('auth-type') let res if (authType === 'web') { try { res = await loginWeb(createOpener(npm, 'Login at'), opts) } catch (err) { if (err.code === 'ENYI') { log.verbose('web login not supported, trying couch') } else { throw err } } } // auth type !== web or ENYI error w/ web login if (!res) { const username = await read.username('Username:', creds.username) const password = await read.password('Password:', creds.password) res = await otplease(npm, opts, (reqOpts) => loginCouch(username, password, reqOpts)) } // We don't know the username if it was a web login, all we can reliably log is scope and registry const message = `Logged in${opts.scope ? ` to scope ${opts.scope}` : ''} on ${opts.registry}.` log.info('login', message) return { message, newCreds: { token: res.token }, } } module.exports = { adduser, login, otplease, } const abbrev = require('abbrev') // These correspond to filenames in lib/commands // Please keep this list sorted alphabetically const commands = [ 'access', 'adduser', 'audit', 'bugs', 'cache', 'ci', 'completion', 'config', 'dedupe', 'deprecate', 'diff', 'dist-tag', 'docs', 'doctor', 'edit', 'exec', 'explain', 'explore', 'find-dupes', 'fund', 'get', 'help', 'help-search', 'init', 'install', 'install-ci-test', 'install-test', 'link', 'll', 'login', 'logout', 'ls', 'org', 'outdated', 'owner', 'pack', 'ping', 'pkg', 'prefix', 'profile', 'prune', 'publish', 'query', 'rebuild', 'repo', 'restart', 'root', 'run-script', 'sbom', 'search', 'set', 'shrinkwrap', 'star', 'stars', 'start', 'stop', 'team', 'test', 'token', 'undeprecate', 'uninstall', 'unpublish', 'unstar', 'update', 'version', 'view', 'whoami', ] // These must resolve to an entry in commands const aliases = { // aliases author: 'owner', home: 'docs', issues: 'bugs', info: 'view', show: 'view', find: 'search', add: 'install', unlink: 'uninstall', remove: 'uninstall', rm: 'uninstall', r: 'uninstall', // short names for common things un: 'uninstall', rb: 'rebuild', list: 'ls', ln: 'link', create: 'init', i: 'install', it: 'install-test', cit: 'install-ci-test', up: 'update', c: 'config', s: 'search', se: 'search', tst: 'test', t: 'test', ddp: 'dedupe', v: 'view', run: 'run-script', 'clean-install': 'ci', 'clean-install-test': 'install-ci-test', x: 'exec', why: 'explain', la: 'll', verison: 'version', ic: 'ci', // typos innit: 'init', // manually abbrev so that install-test doesn't make insta stop working in: 'install', ins: 'install', inst: 'install', insta: 'install', instal: 'install', isnt: 'install', isnta: 'install', isntal: 'install', isntall: 'install', 'install-clean': 'ci', 'isntall-clean': 'ci', hlep: 'help', 'dist-tags': 'dist-tag', upgrade: 'update', udpate: 'update', rum: 'run-script', sit: 'install-ci-test', urn: 'run-script', ogr: 'org', 'add-user': 'adduser', } const deref = (c) => { if (!c) { return } // Translate camelCase to snake-case (i.e. installTest to install-test) if (c.match(/[A-Z]/)) { c = c.replace(/([A-Z])/g, m => '-' + m.toLowerCase()) } // if they asked for something exactly we are done if (commands.includes(c)) { return c } // if they asked for a direct alias if (aliases[c]) { return aliases[c] } const abbrevs = abbrev(commands.concat(Object.keys(aliases))) // first deref the abbrev, if there is one // then resolve any aliases // so `npm install-cl` will resolve to `install-clean` then to `ci` let a = abbrevs[c] while (aliases[a]) { a = aliases[a] } return a } module.exports = { aliases, commands, deref, } # npm completions for Fish shell # This script is a work in progress and does not fall under the normal semver contract as the rest of npm. # __fish_npm_needs_command taken from: # https://stackoverflow.com/questions/16657803/creating-autocomplete-script-with-sub-commands function __fish_npm_needs_command set -l cmd (commandline -opc) if test (count $cmd) -eq 1 return 0 end return 1 end # Taken from https://github.com/fish-shell/fish-shell/blob/HEAD/share/completions/npm.fish function __fish_complete_npm -d "Complete the commandline using npm's 'completion' tool" # tell npm we are fish shell set -lx COMP_FISH true if command -sq npm # npm completion is bash-centric, so we need to translate fish's "commandline" stuff to bash's $COMP_* stuff # COMP_LINE is an array with the words in the commandline set -lx COMP_LINE (commandline -opc) # COMP_CWORD is the index of the current word in COMP_LINE # bash starts arrays with 0, so subtract 1 set -lx COMP_CWORD (math (count $COMP_LINE) - 1) # COMP_POINT is the index of point/cursor when the commandline is viewed as a string set -lx COMP_POINT (commandline -C) # If the cursor is after the last word, the empty token will disappear in the expansion # Readd it if test (commandline -ct) = "" set COMP_CWORD (math $COMP_CWORD + 1) set COMP_LINE $COMP_LINE "" end command npm completion -- $COMP_LINE 2>/dev/null end end # flush out what ships with fish complete -e npm #!/bin/bash ###-begin-npm-completion-### # # npm command completion script # # Installation: npm completion >> ~/.bashrc (or ~/.zshrc) # Or, maybe: npm completion > /usr/local/etc/bash_completion.d/npm # if type complete &>/dev/null; then _npm_completion () { local words cword if type _get_comp_words_by_ref &>/dev/null; then _get_comp_words_by_ref -n = -n @ -n : -w words -i cword else cword="$COMP_CWORD" words=("${COMP_WORDS[@]}") fi local si="$IFS" if ! IFS=$'\n' COMPREPLY=($(COMP_CWORD="$cword" \ COMP_LINE="$COMP_LINE" \ COMP_POINT="$COMP_POINT" \ npm completion -- "${words[@]}" \ 2>/dev/null)); then local ret=$? IFS="$si" return $ret fi IFS="$si" if type __ltrim_colon_completions &>/dev/null; then __ltrim_colon_completions "${words[cword]}" fi } complete -o default -F _npm_completion npm elif type compdef &>/dev/null; then _npm_completion() { local si=$IFS compadd -- $(COMP_CWORD=$((CURRENT-1)) \ COMP_LINE=$BUFFER \ COMP_POINT=0 \ npm completion -- "${words[@]}" \ 2>/dev/null) IFS=$si } compdef _npm_completion npm elif type compctl &>/dev/null; then _npm_completion () { local cword line point words si read -Ac words read -cn cword let cword-=1 read -l line read -ln point si="$IFS" if ! IFS=$'\n' reply=($(COMP_CWORD="$cword" \ COMP_LINE="$line" \ COMP_POINT="$point" \ npm completion -- "${words[@]}" \ 2>/dev/null)); then local ret=$? IFS="$si" return $ret fi IFS="$si" } compctl -K _npm_completion npm fi ###-end-npm-completion-### const Npm = require('../npm') const { distance } = require('fastest-levenshtein') const { commands } = require('./cmd-list.js') const runScripts = ['stop', 'start', 'test', 'restart'] const isClose = (scmd, cmd) => distance(scmd, cmd) < scmd.length * 0.4 const didYouMean = (pkg, scmd) => { const { scripts = {}, bin = {} } = pkg || {} const best = [ ...commands .filter(cmd => isClose(scmd, cmd) && scmd !== cmd) .map(str => [str, Npm.cmd(str).description]), ...Object.keys(scripts) // We would already be suggesting this in `npm x` so omit them here .filter(cmd => isClose(scmd, cmd) && !runScripts.includes(cmd)) .map(str => [`run ${str}`, `run the "${str}" package script`]), ...Object.keys(bin) .filter(cmd => isClose(scmd, cmd)) .map(str => [`exec ${str}`, `run the "${str}" command from either this or a remote npm package`]), ] if (best.length === 0) { return '' } return `\n\nDid you mean ${best.length === 1 ? 'this' : 'one of these'}?\n` + best.slice(0, 3).map(([msg, comment]) => ` npm ${msg} # ${comment}`).join('\n') } module.exports = didYouMean const { log, output, input, META } = require('proc-log') const { explain } = require('./explain-eresolve.js') const { formatWithOptions } = require('./format') // This is the general approach to color: // Eventually this will be exposed somewhere we can refer to these by name. // Foreground colors only. Never set the background color. /* * Black # (Don't use) * Red # Danger * Green # Success * Yellow # Warning * Blue # Accent * Magenta # Done * Cyan # Emphasis * White # (Don't use) */ // Translates log levels to chalk colors const COLOR_PALETTE = ({ chalk: c }) => ({ heading: c.bold, title: c.blueBright, timing: c.magentaBright, // loglevels error: c.red, warn: c.yellow, notice: c.cyanBright, http: c.green, info: c.cyan, verbose: c.blue, silly: c.blue.dim, }) const LEVEL_OPTIONS = { silent: { index: 0, }, error: { index: 1, }, warn: { index: 2, }, notice: { index: 3, }, http: { index: 4, }, info: { index: 5, }, verbose: { index: 6, }, silly: { index: 7, }, } const LEVEL_METHODS = { ...LEVEL_OPTIONS, [log.KEYS.timing]: { show: ({ timing, index }) => !!timing && index !== 0, }, } const setBlocking = (stream) => { // Copied from https://github.com/yargs/set-blocking // https://raw.githubusercontent.com/yargs/set-blocking/master/LICENSE.txt /* istanbul ignore next - we trust that this works */ if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') { stream._handle.setBlocking(true) } return stream } // These are important // This is the key that is returned to the user for errors const ERROR_KEY = 'error' // This is the key producers use to indicate that there // is a json error that should be merged into the finished output const JSON_ERROR_KEY = 'jsonError' const isPlainObject = (v) => v && typeof v === 'object' && !Array.isArray(v) const getArrayOrObject = (items) => { if (items.length) { const foundNonObject = items.find(o => !isPlainObject(o)) // Non-objects and arrays cant be merged, so just return the first item if (foundNonObject) { return foundNonObject } // We use objects with 0,1,2,etc keys to merge array if (items.every((o, i) => Object.hasOwn(o, i))) { return Object.assign([], ...items) } } // Otherwise its an object with all object items merged together return Object.assign({}, ...items.filter(o => isPlainObject(o))) } const getJsonBuffer = ({ [JSON_ERROR_KEY]: metaError }, buffer) => { const items = [] // meta also contains the meta object passed to flush const errors = metaError ? [metaError] : [] // index 1 is the meta, 2 is the logged argument for (const [, { [JSON_ERROR_KEY]: error }, obj] of buffer) { if (obj) { items.push(obj) } if (error) { errors.push(error) } } if (!items.length && !errors.length) { return null } const res = getArrayOrObject(items) // This skips any error checking since we can only set an error property // on an object that can be stringified // XXX(BREAKING_CHANGE): remove this in favor of always returning an object with result and error keys if (isPlainObject(res) && errors.length) { // This is not ideal. JSON output has always been keyed at the root with an `error` // key, so we cant change that without it being a breaking change. At the same time // some commands output arbitrary keys at the top level of the output, such as package // names. So the output could already have the same key. The choice here is to overwrite // it with our error since that is (probably?) more important. // XXX(BREAKING_CHANGE): all json output should be keyed under well known keys, eg `result` and `error` if (res[ERROR_KEY]) { log.warn('', `overwriting existing ${ERROR_KEY} on json output`) } res[ERROR_KEY] = getArrayOrObject(errors) } return res } const withMeta = (handler) => (level, ...args) => { let meta = {} const last = args.at(-1) if (last && typeof last === 'object' && Object.hasOwn(last, META)) { meta = args.pop() } return handler(level, meta, ...args) } class Display { #logState = { buffering: true, buffer: [], } #outputState = { buffering: true, buffer: [], } // colors #noColorChalk #stdoutChalk #stdoutColor #stderrChalk #stderrColor #logColors // progress #progress // options #command #levelIndex #timing #json #heading #silent // display streams #stdout #stderr constructor ({ stdout, stderr }) { this.#stdout = setBlocking(stdout) this.#stderr = setBlocking(stderr) // Handlers are set immediately so they can buffer all events process.on('log', this.#logHandler) process.on('output', this.#outputHandler) process.on('input', this.#inputHandler) this.#progress = new Progress({ stream: stderr }) } off () { process.off('log', this.#logHandler) this.#logState.buffer.length = 0 process.off('output', this.#outputHandler) this.#outputState.buffer.length = 0 process.off('input', this.#inputHandler) this.#progress.off() } get chalk () { return { noColor: this.#noColorChalk, stdout: this.#stdoutChalk, stderr: this.#stderrChalk, } } async load ({ command, heading, json, loglevel, progress, stderrColor, stdoutColor, timing, unicode, }) { // get createSupportsColor from chalk directly if this lands // https://github.com/chalk/chalk/pull/600 const [{ Chalk }, { createSupportsColor }] = await Promise.all([ import('chalk'), import('supports-color'), ]) // we get the chalk level based on a null stream meaning chalk will only use // what it knows about the environment to get color support since we already // determined in our definitions that we want to show colors. const level = Math.max(createSupportsColor(null).level, 1) this.#noColorChalk = new Chalk({ level: 0 }) this.#stdoutColor = stdoutColor this.#stdoutChalk = stdoutColor ? new Chalk({ level }) : this.#noColorChalk this.#stderrColor = stderrColor this.#stderrChalk = stderrColor ? new Chalk({ level }) : this.#noColorChalk this.#logColors = COLOR_PALETTE({ chalk: this.#stderrChalk }) this.#command = command this.#levelIndex = LEVEL_OPTIONS[loglevel].index this.#timing = timing this.#json = json this.#heading = heading this.#silent = this.#levelIndex <= 0 // Emit resume event on the logs which will flush output log.resume() output.flush() this.#progress.load({ unicode, enabled: !!progress && !this.#silent, }) } // STREAM WRITES // Write formatted and (non-)colorized output to streams #write (stream, options, ...args) { const colors = stream === this.#stdout ? this.#stdoutColor : this.#stderrColor const value = formatWithOptions({ colors, ...options }, ...args) this.#progress.write(() => stream.write(value)) } // HANDLERS // Arrow function assigned to a private class field so it can be passed // directly as a listener and still reference "this" #logHandler = withMeta((level, meta, ...args) => { switch (level) { case log.KEYS.resume: this.#logState.buffering = false this.#logState.buffer.forEach((item) => this.#tryWriteLog(...item)) this.#logState.buffer.length = 0 break case log.KEYS.pause: this.#logState.buffering = true break default: if (this.#logState.buffering) { this.#logState.buffer.push([level, meta, ...args]) } else { this.#tryWriteLog(level, meta, ...args) } break } }) // Arrow function assigned to a private class field so it can be passed // directly as a listener and still reference "this" #outputHandler = withMeta((level, meta, ...args) => { this.#json = typeof meta.json === 'boolean' ? meta.json : this.#json switch (level) { case output.KEYS.flush: { this.#outputState.buffering = false if (this.#json) { const json = getJsonBuffer(meta, this.#outputState.buffer) if (json) { this.#writeOutput(output.KEYS.standard, meta, JSON.stringify(json, null, 2)) } } else { this.#outputState.buffer.forEach((item) => this.#writeOutput(...item)) } this.#outputState.buffer.length = 0 break } case output.KEYS.buffer: this.#outputState.buffer.push([output.KEYS.standard, meta, ...args]) break default: if (this.#outputState.buffering) { this.#outputState.buffer.push([level, meta, ...args]) } else { // HACK: Check if the argument looks like a run-script banner. This can be // replaced with proc-log.META in @npmcli/run-script if (typeof args[0] === 'string' && args[0].startsWith('\n> ') && args[0].endsWith('\n')) { if (this.#silent || ['exec', 'explore'].includes(this.#command)) { // Silent mode and some specific commands always hide run script banners break } else if (this.#json) { // In json mode, change output to stderr since we dont want to break json // parsing on stdout if the user is piping to jq or something. // XXX: in a future (breaking?) change it might make sense for run-script to // always output these banners with proc-log.output.error if we think they // align closer with "logging" instead of "output" level = output.KEYS.error } } this.#writeOutput(level, meta, ...args) } break } }) #inputHandler = withMeta((level, meta, ...args) => { switch (level) { case input.KEYS.start: log.pause() this.#outputState.buffering = true this.#progress.off() break case input.KEYS.end: log.resume() output.flush() this.#progress.resume() break case input.KEYS.read: { // The convention when calling input.read is to pass in a single fn that returns // the promise to await. resolve and reject are provided by proc-log const [res, rej, p] = args return input.start(() => p() .then(res) .catch(rej) // Any call to procLog.input.read will render a prompt to the user, so we always // add a single newline of output to stdout to move the cursor to the next line .finally(() => output.standard(''))) } } }) // OUTPUT #writeOutput (level, meta, ...args) { switch (level) { case output.KEYS.standard: this.#write(this.#stdout, {}, ...args) break case output.KEYS.error: this.#write(this.#stderr, {}, ...args) break } } // LOGS #tryWriteLog (level, meta, ...args) { try { // Also (and this is a really inexcusable kludge), we patch the // log.warn() method so that when we see a peerDep override // explanation from Arborist, we can replace the object with a // highly abbreviated explanation of what's being overridden. // TODO: this could probably be moved to arborist now that display is refactored const [heading, message, expl] = args if (level === log.KEYS.warn && heading === 'ERESOLVE' && expl && typeof expl === 'object') { this.#writeLog(level, meta, heading, message) this.#writeLog(level, meta, '', explain(expl, this.#stderrChalk, 2)) return } this.#writeLog(level, meta, ...args) } catch (ex) { try { // if it crashed once, it might again! this.#writeLog(log.KEYS.verbose, meta, '', `attempt to log crashed`, ...args, ex) } catch (ex2) { // This happens if the object has an inspect method that crashes so just console.error // with the errors but don't do anything else that might error again. // eslint-disable-next-line no-console console.error(`attempt to log crashed`, ex, ex2) } } } #writeLog (level, meta, ...args) { const levelOpts = LEVEL_METHODS[level] const show = levelOpts.show ?? (({ index }) => levelOpts.index <= index) const force = meta.force && !this.#silent if (force || show({ index: this.#levelIndex, timing: this.#timing })) { // this mutates the array so we can pass args directly to format later const title = args.shift() const prefix = [ this.#logColors.heading(this.#heading), this.#logColors[level](level), title ? this.#logColors.title(title) : null, ] this.#write(this.#stderr, { prefix }, ...args) } } } class Progress { // Taken from https://github.com/sindresorhus/cli-spinners // MIT License // Copyright (c) Sindre Sorhus (https://sindresorhus.com) static dots = { duration: 80, frames: ['â ‹', 'â ™', 'â ¹', 'â ¸', 'â ¼', 'â ´', 'â ¦', 'â §', 'â ‡', 'â '] } static lines = { duration: 130, frames: ['-', '\\', '|', '/'] } #stream #spinner #enabled = false #frameIndex = 0 #lastUpdate = 0 #interval #timeout // We are rendering is enabled option is set and we are not waiting for the render timeout get #rendering () { return this.#enabled && !this.#timeout } // We are spinning if enabled option is set and the render interval has been set get #spinning () { return this.#enabled && this.#interval } constructor ({ stream }) { this.#stream = stream } load ({ enabled, unicode }) { this.#enabled = enabled this.#spinner = unicode ? Progress.dots : Progress.lines // Dont render the spinner for short durations this.#render(200) } off () { if (!this.#enabled) { return } clearTimeout(this.#timeout) this.#timeout = null clearInterval(this.#interval) this.#interval = null this.#frameIndex = 0 this.#lastUpdate = 0 this.#clearSpinner() } resume () { this.#render() } // If we are currenting rendering the spinner we clear it // before writing our line and then re-render the spinner after. // If not then all we need to do is write the line write (write) { if (this.#spinning) { this.#clearSpinner() } write() if (this.#spinning) { this.#render() } } #render (ms) { if (ms) { this.#timeout = setTimeout(() => { this.#timeout = null this.#renderSpinner() }, ms) // Make sure this timeout does not keep the process open this.#timeout.unref() } else { this.#renderSpinner() } } #renderSpinner () { if (!this.#rendering) { return } // We always attempt to render immediately but we only request to move to the next // frame if it has been longer than our spinner frame duration since our last update this.#renderFrame(Date.now() - this.#lastUpdate >= this.#spinner.duration) clearInterval(this.#interval) this.#interval = setInterval(() => this.#renderFrame(true), this.#spinner.duration) } #renderFrame (next) { if (next) { this.#lastUpdate = Date.now() this.#frameIndex++ if (this.#frameIndex >= this.#spinner.frames.length) { this.#frameIndex = 0 } } this.#clearSpinner() this.#stream.write(this.#spinner.frames[this.#frameIndex]) } #clearSpinner () { // Move to the start of the line and clear the rest of the line this.#stream.cursorTo(0) this.#stream.clearLine(1) } } module.exports = Display const { format } = require('node:util') const { resolve } = require('node:path') const { redactLog: replaceInfo } = require('@npmcli/redact') const { log } = require('proc-log') const errorMessage = (er, npm) => { const summary = [] const detail = [] const files = [] er.message &&= replaceInfo(er.message) er.stack &&= replaceInfo(er.stack) switch (er.code) { case 'ERESOLVE': { const { report } = require('./explain-eresolve.js') summary.push(['ERESOLVE', er.message]) detail.push(['', '']) // XXX(display): error messages are logged so we use the logColor since that is based // on stderr. This should be handled solely by the display layer so it could also be // printed to stdout if necessary. const { explanation, file } = report(er, npm.logChalk, npm.noColorChalk) detail.push(['', explanation]) files.push(['eresolve-report.txt', file]) break } case 'ENOLOCK': { const cmd = npm.command || '' summary.push([cmd, 'This command requires an existing lockfile.']) detail.push([cmd, 'Try creating one first with: npm i --package-lock-only']) detail.push([cmd, `Original error: ${er.message}`]) break } case 'ENOAUDIT': summary.push(['audit', er.message]) break case 'ECONNREFUSED': summary.push(['', er]) detail.push(['', [ '', 'If you are behind a proxy, please make sure that the', "'proxy' config is set properly. See: 'npm help config'", ].join('\n')]) break case 'EACCES': case 'EPERM': { const isCachePath = typeof er.path === 'string' && npm.loaded && er.path.startsWith(npm.config.get('cache')) const isCacheDest = typeof er.dest === 'string' && npm.loaded && er.dest.startsWith(npm.config.get('cache')) if (process.platform !== 'win32' && (isCachePath || isCacheDest)) { // user probably doesn't need this, but still add it to the debug log log.verbose(er.stack) summary.push(['', [ '', 'Your cache folder contains root-owned files, due to a bug in', 'previous versions of npm which has since been addressed.', '', 'To permanently fix this problem, please run:', ` sudo chown -R ${process.getuid()}:${process.getgid()} "${npm.config.get('cache')}"`, ].join('\n')]) } else { summary.push(['', er]) detail.push(['', [ '', 'The operation was rejected by your operating system.', ...process.platform === 'win32' ? [ "It's possible that the file was already in use (by a text editor or antivirus),", 'or that you lack permissions to access it.', ] : [ 'It is likely you do not have the permissions to access this file as the current user', ], '', 'If you believe this might be a permissions issue, please double-check the', 'permissions of the file and its containing directories, or try running', 'the command again as root/Administrator.', ].join('\n')]) } break } case 'ENOGIT': summary.push(['', er.message]) detail.push(['', [ '', 'Failed using git.', 'Please check if you have git installed and in your PATH.', ].join('\n')]) break case 'EJSONPARSE': // Check whether we ran into a conflict in our own package.json if (er.path === resolve(npm.prefix, 'package.json')) { const { isDiff } = require('parse-conflict-json') const txt = require('node:fs').readFileSync(er.path, 'utf8').replace(/\r\n/g, '\n') if (isDiff(txt)) { detail.push(['', [ 'Merge conflict detected in your package.json.', '', 'Please resolve the package.json conflict and retry.', ].join('\n')]) break } } summary.push(['JSON.parse', er.message]) detail.push(['JSON.parse', [ 'Failed to parse JSON data.', 'Note: package.json must be actual JSON, not just JavaScript.', ].join('\n')]) break case 'EOTP': case 'E401': // E401 is for places where we accidentally neglect OTP stuff if (er.code === 'EOTP' || /one-time pass/.test(er.message)) { summary.push(['', 'This operation requires a one-time password from your authenticator.']) detail.push(['', [ 'You can provide a one-time password by passing --otp= to the command you ran.', 'If you already provided a one-time password then it is likely that you either typoed', 'it, or it timed out. Please try again.', ].join('\n')]) } else { // npm ERR! code E401 // npm ERR! Unable to authenticate, need: Basic const auth = !er.headers || !er.headers['www-authenticate'] ? [] : er.headers['www-authenticate'].map(au => au.split(/[,\s]+/))[0] if (auth.includes('Bearer')) { summary.push(['', 'Unable to authenticate, your authentication token seems to be invalid.', ]) detail.push(['', [ 'To correct this please try logging in again with:', ' npm login', ].join('\n')]) } else if (auth.includes('Basic')) { summary.push(['', 'Incorrect or missing password.']) detail.push(['', [ 'If you were trying to login, change your password, create an', 'authentication token or enable two-factor authentication then', 'that means you likely typed your password in incorrectly.', 'Please try again, or recover your password at:', ' https://www.npmjs.com/forgot', '', 'If you were doing some other operation then your saved credentials are', 'probably out of date. To correct this please try logging in again with:', ' npm login', ].join('\n')]) } else { summary.push(['', er.message || er]) } } break case 'E404': // There's no need to have 404 in the message as well. summary.push(['404', er.message.replace(/^404\s+/, '')]) if (er.pkgid && er.pkgid !== '-') { const pkg = er.pkgid.replace(/(?!^)@.*$/, '') detail.push(['404', '']) detail.push(['404', '', `'${replaceInfo(er.pkgid)}' is not in this registry.`]) const nameValidator = require('validate-npm-package-name') const valResult = nameValidator(pkg) if (!valResult.validForNewPackages) { detail.push(['404', 'This package name is not valid, because', '']) const errorsArray = [...(valResult.errors || []), ...(valResult.warnings || [])] errorsArray.forEach((item, idx) => detail.push(['404', ' ' + (idx + 1) + '. ' + item])) } detail.push(['404', '']) detail.push(['404', 'Note that you can also install from a']) detail.push(['404', 'tarball, folder, http url, or git url.']) } break case 'EPUBLISHCONFLICT': summary.push(['publish fail', 'Cannot publish over existing version.']) detail.push(['publish fail', "Update the 'version' field in package.json and try again."]) detail.push(['publish fail', '']) detail.push(['publish fail', 'To automatically increment version numbers, see:']) detail.push(['publish fail', ' npm help version']) break case 'EISGIT': summary.push(['git', er.message]) summary.push(['git', ` ${er.path}`]) detail.push(['git', [ 'Refusing to remove it. Update manually,', 'or move it out of the way first.', ].join('\n')]) break case 'EBADDEVENGINES': { const { current, required } = er summary.push(['EBADDEVENGINES', er.message]) detail.push(['EBADDEVENGINES', { current, required }]) break } case 'EBADPLATFORM': { const actual = er.current const expected = { ...er.required } const checkedKeys = [] for (const key in expected) { if (Array.isArray(expected[key]) && expected[key].length > 0) { expected[key] = expected[key].join(',') checkedKeys.push(key) } else if (expected[key] === undefined || Array.isArray(expected[key]) && expected[key].length === 0) { delete expected[key] delete actual[key] } else { checkedKeys.push(key) } } const longestKey = Math.max(...checkedKeys.map((key) => key.length)) const detailEntry = [] for (const key of checkedKeys) { const padding = key.length === longestKey ? 1 : 1 + (longestKey - key.length) // padding + 1 because 'actual' is longer than 'valid' detailEntry.push(`Valid ${key}:${' '.repeat(padding + 1)}${expected[key]}`) detailEntry.push(`Actual ${key}:${' '.repeat(padding)}${actual[key]}`) } summary.push(['notsup', format( 'Unsupported platform for %s: wanted %j (current: %j)', er.pkgid, expected, actual )]) detail.push(['notsup', detailEntry.join('\n')]) break } case 'EEXIST': summary.push(['', er.message]) summary.push(['', 'File exists: ' + (er.dest || er.path)]) detail.push(['', 'Remove the existing file and try again, or run npm']) detail.push(['', 'with --force to overwrite files recklessly.']) break case 'ENEEDAUTH': summary.push(['need auth', er.message]) detail.push(['need auth', 'You need to authorize this machine using `npm adduser`']) break case 'ECONNRESET': case 'ENOTFOUND': case 'ETIMEDOUT': case 'ERR_SOCKET_TIMEOUT': case 'EAI_FAIL': summary.push(['network', er.message]) detail.push(['network', [ 'This is a problem related to network connectivity.', 'In most cases you are behind a proxy or have bad network settings.', '', 'If you are behind a proxy, please make sure that the', "'proxy' config is set properly. See: 'npm help config'", ].join('\n')]) break case 'ETARGET': summary.push(['notarget', er.message]) detail.push(['notarget', [ 'In most cases you or one of your dependencies are requesting', "a package version that doesn't exist.", ].join('\n')]) break case 'E403': summary.push(['403', er.message]) detail.push(['403', [ 'In most cases, you or one of your dependencies are requesting', 'a package version that is forbidden by your security policy, or', 'on a server you do not have access to.', ].join('\n')]) break case 'EBADENGINE': summary.push(['engine', er.message]) summary.push(['engine', 'Not compatible with your version of node/npm: ' + er.pkgid]) detail.push(['notsup', [ 'Not compatible with your version of node/npm: ' + er.pkgid, 'Required: ' + JSON.stringify(er.required), 'Actual: ' + JSON.stringify({ npm: npm.version, node: process.version }), ].join('\n')]) break case 'ENOSPC': summary.push(['nospc', er.message]) detail.push(['nospc', [ 'There appears to be insufficient space on your system to finish.', 'Clear up some disk space and try again.', ].join('\n')]) break case 'EROFS': summary.push(['rofs', er.message]) detail.push(['rofs', [ 'Often virtualized file systems, or other file systems', "that don't support symlinks, give this error.", ].join('\n')]) break case 'ENOENT': summary.push(['enoent', er.message]) detail.push(['enoent', [ 'This is related to npm not being able to find a file.', er.file ? `\nCheck if the file '${er.file}' is present.` : '', ].join('\n')]) break case 'EMISSINGARG': case 'EUNKNOWNTYPE': case 'EINVALIDTYPE': case 'ETOOMANYARGS': summary.push(['typeerror', er.stack]) detail.push(['typeerror', [ 'This is an error with npm itself. Please report this error at:', ' https://github.com/npm/cli/issues', ].join('\n')]) break default: summary.push(['', er.message || er]) if (er.cause) { detail.push(['cause', er.cause.message]) } if (er.signal) { detail.push(['signal', er.signal]) } if (er.cmd && Array.isArray(er.args)) { detail.push(['command', ...[er.cmd, ...er.args.map(replaceInfo)]]) } if (er.stdout) { detail.push(['', er.stdout.trim()]) } if (er.stderr) { detail.push(['', er.stderr.trim()]) } break } return { summary, detail, files, } } const getExitCodeFromError = (err) => { if (typeof err?.errno === 'number') { return err.errno } else if (typeof err?.code === 'number') { return err.code } } const getError = (err, { npm, command, pkg }) => { // if we got a command that just shells out to something else, then it // will presumably print its own errors and exit with a proper status // code if there's a problem. If we got an error with a code=0, then... // something else went wrong along the way, so maybe an npm problem? if (command?.constructor?.isShellout && typeof err.code === 'number' && err.code) { return { exitCode: err.code, suppressError: true, } } // XXX: we should stop throwing strings if (typeof err === 'string') { return { exitCode: 1, suppressError: true, summary: [['', err]], } } // XXX: we should stop throwing other non-errors if (!(err instanceof Error)) { return { exitCode: 1, suppressError: true, summary: [['weird error', err]], } } if (err.code === 'EUNKNOWNCOMMAND') { const suggestions = require('./did-you-mean.js')(pkg, err.command) return { exitCode: 1, suppressError: true, standard: [ `Unknown command: "${err.command}"`, suggestions, 'To see a list of supported npm commands, run:', ' npm help', ], } } // Anything after this is not suppressed and get more logged information // add a code to the error if it doesnt have one and mutate some properties // so they have redacted information err.code ??= err.message.match(/^(?:Error: )?(E[A-Z]+)/)?.[1] // this mutates the error and redacts stack/message const { summary, detail, files } = errorMessage(err, npm) return { err, code: err.code, exitCode: getExitCodeFromError(err) || 1, suppressError: false, summary, detail, files, verbose: ['type', 'stack', 'statusCode', 'pkgid'] .filter(k => err[k]) .map(k => [k, replaceInfo(err[k])]), error: ['code', 'syscall', 'file', 'path', 'dest', 'errno'] .filter(k => err[k]) .map(k => [k, err[k]]), } } module.exports = { getExitCodeFromError, errorMessage, getError, } const { relative } = require('node:path') const explainNode = (node, depth, chalk) => printNode(node, chalk) + explainDependents(node, depth, chalk) + explainLinksIn(node, depth, chalk) const colorType = (type, chalk) => { const style = type === 'extraneous' ? chalk.red : type === 'dev' ? chalk.blue : type === 'optional' ? chalk.magenta : type === 'peer' ? chalk.magentaBright : type === 'bundled' ? chalk.underline.cyan : type === 'workspace' ? chalk.blueBright : type === 'overridden' ? chalk.dim : /* istanbul ignore next */ s => s return style(type) } const printNode = (node, chalk) => { const extra = [] for (const meta of ['extraneous', 'dev', 'optional', 'peer', 'bundled', 'overridden']) { if (node[meta]) { extra.push(` ${colorType(meta, chalk)}`) } } const pkgid = node.isWorkspace ? chalk.blueBright(`${node.name}@${node.version}`) : `${node.name}@${node.version}` return `${pkgid}${extra.join('')}` + (node.location ? chalk.dim(`\n${node.location}`) : '') } const explainLinksIn = ({ linksIn }, depth, chalk) => { if (!linksIn || !linksIn.length || depth <= 0) { return '' } const messages = linksIn.map(link => explainNode(link, depth - 1, chalk)) const str = '\n' + messages.join('\n') return str.split('\n').join('\n ') } const explainDependents = ({ dependents }, depth, chalk) => { if (!dependents || !dependents.length || depth <= 0) { return '' } const max = Math.ceil(depth / 2) const messages = dependents.slice(0, max) .map(edge => explainEdge(edge, depth, chalk)) // show just the names of the first 5 deps that overflowed the list if (dependents.length > max) { let len = 0 const maxLen = 50 const showNames = [] for (let i = max; i < dependents.length; i++) { const { from: { name: depName = 'the root project' } } = dependents[i] len += depName.length if (len >= maxLen && i < dependents.length - 1) { showNames.push('...') break } showNames.push(depName) } const show = `(${showNames.join(', ')})` messages.push(`${dependents.length - max} more ${show}`) } const str = '\n' + messages.join('\n') return str.split('\n').join('\n ') } const explainEdge = ({ name, type, bundled, from, spec, rawSpec, overridden }, depth, chalk) => { let dep = type === 'workspace' ? chalk.bold(relative(from.location, spec.slice('file:'.length))) : `${name}@"${spec}"` if (overridden) { dep = `${colorType('overridden', chalk)} ${dep} (was "${rawSpec}")` } const fromMsg = ` from ${explainFrom(from, depth, chalk)}` return (type === 'prod' ? '' : `${colorType(type, chalk)} `) + (bundled ? `${colorType('bundled', chalk)} ` : '') + `${dep}${fromMsg}` } const explainFrom = (from, depth, chalk) => { if (!from.name && !from.version) { return 'the root project' } return printNode(from, chalk) + explainDependents(from, depth - 1, chalk) + explainLinksIn(from, depth - 1, chalk) } module.exports = { explainNode, printNode, explainEdge } // this is called when an ERESOLVE error is caught in the exit-handler, // or when there's a log.warn('eresolve', msg, explanation), to turn it // into a human-intelligible explanation of what's wrong and how to fix. const { explainEdge, explainNode, printNode } = require('./explain-dep.js') // expl is an explanation object that comes from Arborist. It looks like: // Depth is how far we want to want to descend into the object making a report. // The full report (ie, depth=Infinity) is always written to the cache folder // at ${cache}/eresolve-report.txt along with full json. const explain = (expl, chalk, depth) => { const { edge, dep, current, peerConflict, currentEdge } = expl const out = [] const whileInstalling = dep && dep.whileInstalling || current && current.whileInstalling || edge && edge.from && edge.from.whileInstalling if (whileInstalling) { out.push('While resolving: ' + printNode(whileInstalling, chalk)) } // it "should" be impossible for an ERESOLVE explanation to lack both // current and currentEdge, but better to have a less helpful error // than a crashing failure. if (current) { out.push('Found: ' + explainNode(current, depth, chalk)) } else if (peerConflict && peerConflict.current) { out.push('Found: ' + explainNode(peerConflict.current, depth, chalk)) } else if (currentEdge) { out.push('Found: ' + explainEdge(currentEdge, depth, chalk)) } else /* istanbul ignore else - should always have one */ if (edge) { out.push('Found: ' + explainEdge(edge, depth, chalk)) } out.push('\nCould not resolve dependency:\n' + explainEdge(edge, depth, chalk)) if (peerConflict) { const heading = '\nConflicting peer dependency:' const pc = explainNode(peerConflict.peer, depth, chalk) out.push(heading + ' ' + pc) } return out.join('\n') } // generate a full verbose report and tell the user how to fix it const report = (expl, chalk, noColorChalk) => { const flags = [ expl.strictPeerDeps ? '--no-strict-peer-deps' : '', '--force', '--legacy-peer-deps', ].filter(Boolean) const or = (arr) => arr.length <= 2 ? arr.join(' or ') : arr.map((v, i, l) => i + 1 === l.length ? `or ${v}` : v).join(', ') const fix = `Fix the upstream dependency conflict, or retry this command with ${or(flags)} to accept an incorrect (and potentially broken) dependency resolution.` return { explanation: `${explain(expl, chalk, 4)}\n\n${fix}`, file: `# npm resolution error report\n\n${explain(expl, noColorChalk, Infinity)}\n\n${fix}`, } } module.exports = { explain, report, } // Convert bytes to printable output, for file reporting in tarballs // Only supports up to GB because that's way larger than anything the registry // supports anyways. const formatBytes = (bytes, space = true) => { let spacer = '' if (space) { spacer = ' ' } if (bytes < 1000) { // B return `${bytes}${spacer}B` } if (bytes < 1000000) { // kB return `${(bytes / 1000).toFixed(1)}${spacer}kB` } if (bytes < 1000000000) { // MB return `${(bytes / 1000000).toFixed(1)}${spacer}MB` } // GB return `${(bytes / 1000000000).toFixed(1)}${spacer}GB` } module.exports = formatBytes const { stripVTControlCharacters: strip } = require('node:util') const { Minipass } = require('minipass') // This module consumes package data in the following format: // // { // name: String, // description: String, // maintainers: [{ username: String, email: String }], // keywords: String | [String], // version: String, // date: Date // can be null, // } // // The returned stream will format this package data // into a byte stream of formatted, displayable output. function filter (data, exclude) { const words = [data.name] .concat(data.maintainers.map(m => m.username)) .concat(data.keywords || []) .map(f => f?.trim?.()) .filter(Boolean) .join(' ') .toLowerCase() if (exclude.find(pattern => { // Treats both /foo and /foo/ as regex searches if (pattern.startsWith('/')) { if (pattern.endsWith('/')) { pattern = pattern.slice(0, -1) } return words.match(new RegExp(pattern.slice(1))) } return words.includes(pattern) })) { return false } return true } module.exports = (opts) => { return opts.json ? new JSONOutputStream(opts) : new TextOutputStream(opts) } class JSONOutputStream extends Minipass { #didFirst = false #exclude constructor (opts) { super() this.#exclude = opts.exclude } write (obj) { if (!filter(obj, this.#exclude)) { return } if (!this.#didFirst) { super.write('[\n') this.#didFirst = true } else { super.write('\n,\n') } return super.write(JSON.stringify(obj)) } end () { super.write(this.#didFirst ? ']\n' : '\n[]\n') super.end() } } class TextOutputStream extends Minipass { #args #chalk #exclude #parseable constructor (opts) { super() // Consider a search for "cowboys" and "boy". If we highlight "boys" first the "cowboys" string will no longer string match because of the ansi highlighting added to "boys". If we highlight "boy" second then the ansi reset at the end will make the highlighting only on "cowboy" with a normal "s". Neither is perfect but at least the first option doesn't do partial highlighting. So, we sort strings smaller to larger this.#args = opts.args .map(s => s.toLowerCase()) .filter(Boolean) .sort((a, b) => a.length - b.length) this.#chalk = opts.npm.chalk this.#exclude = opts.exclude this.#parseable = opts.parseable } write (data) { if (!filter(data, this.#exclude)) { return } // Normalize const pkg = { authors: data.maintainers.map((m) => `${strip(m.username)}`).join(' '), publisher: strip(data.publisher?.username || ''), date: data.date ? data.date.toISOString().slice(0, 10) : 'prehistoric', description: strip(data.description ?? ''), keywords: [], name: strip(data.name), version: data.version, } if (Array.isArray(data.keywords)) { pkg.keywords = data.keywords.map(strip) } else if (typeof data.keywords === 'string') { pkg.keywords = strip(data.keywords.replace(/[,\s]+/, ' ')).split(' ') } let output if (this.#parseable) { output = [pkg.name, pkg.description, pkg.author, pkg.date, pkg.version, pkg.keywords] .filter(Boolean) .map(col => ('' + col).replace(/\t/g, ' ')).join('\t') return super.write(output) } const keywords = pkg.keywords.map(k => { if (this.#args.includes(k)) { return this.#chalk.cyan(k) } else { return k } }).join(' ') const description = this.#highlight(pkg.description) let name if (this.#args.includes(pkg.name)) { name = this.#chalk.cyan(pkg.name) } else { name = this.#highlight(pkg.name) name = this.#chalk.blue(name) } if (description.length) { output = `${name}\n${description}\n` } else { output = `${name}\n` } if (pkg.publisher) { output += `Version ${this.#chalk.blue(pkg.version)} published ${this.#chalk.blue(pkg.date)} by ${this.#chalk.blue(pkg.publisher)}\n` } else { output += `Version ${this.#chalk.blue(pkg.version)} published ${this.#chalk.blue(pkg.date)} by ${this.#chalk.yellow('???')}\n` } output += `Maintainers: ${pkg.authors}\n` if (keywords) { output += `Keywords: ${keywords}\n` } output += `${this.#chalk.blue(`https://npm.im/${pkg.name}`)}\n` return super.write(output) } #highlight (input) { let output = input for (const arg of this.#args) { let i = output.toLowerCase().indexOf(arg) while (i > -1) { const highlit = this.#chalk.cyan(output.slice(i, i + arg.length)) output = [ output.slice(0, i), highlit, output.slice(i + arg.length), ].join('') i = output.toLowerCase().indexOf(arg, i + highlit.length) } } return output } } const { formatWithOptions: baseFormatWithOptions } = require('node:util') // These are most assuredly not a mistake // https://eslint.org/docs/latest/rules/no-control-regex // \x00 through \x1f, \x7f through \x9f, not including \x09 \x0a \x0b \x0d /* eslint-disable-next-line no-control-regex */ const HAS_C01 = /[\x00-\x08\x0c\x0e-\x1f\x7f-\x9f]/ // Allows everything up to '[38;5;255m' in 8 bit notation const ALLOWED_SGR = /^\[[0-9;]{0,8}m/ // '[38;5;255m'.length const SGR_MAX_LEN = 10 // Strips all ANSI C0 and C1 control characters (except for SGR up to 8 bit) function STRIP_C01 (str) { if (!HAS_C01.test(str)) { return str } let result = '' for (let i = 0; i < str.length; i++) { const char = str[i] const code = char.charCodeAt(0) if (!HAS_C01.test(char)) { // Most characters are in this set so continue early if we can result = `${result}${char}` } else if (code === 27 && ALLOWED_SGR.test(str.slice(i + 1, i + SGR_MAX_LEN + 1))) { // \x1b with allowed SGR result = `${result}\x1b` } else if (code <= 31) { // escape all other C0 control characters besides \x7f result = `${result}^${String.fromCharCode(code + 64)}` } else { // hasC01 ensures this is now a C1 control character or \x7f result = `${result}^${String.fromCharCode(code - 64)}` } } return result } const formatWithOptions = ({ prefix: prefixes = [], eol = '\n', ...options }, ...args) => { const prefix = prefixes.filter(p => p != null).join(' ') const formatted = STRIP_C01(baseFormatWithOptions(options, ...args)) // Splitting could be changed to only `\n` once we are sure we only emit unix newlines. // The eol param to this function will put the correct newlines in place for the returned string. const lines = formatted.split(/\r?\n/) return lines.reduce((acc, l) => `${acc}${prefix}${prefix && l ? ' ' : ''}${l}${eol}`, '') } module.exports = { formatWithOptions } const npmFetch = require('npm-registry-fetch') module.exports = async (npm, opts) => { const { registry } = opts // First, check if we have a user/pass-based auth const creds = npm.config.getCredentialsByURI(registry) if (creds.username) { return creds.username } // No username, but we have other credentials; fetch the username from registry if (creds.token || creds.certfile && creds.keyfile) { const registryData = await npmFetch.json('/-/whoami', { ...opts }) if (typeof registryData?.username === 'string') { return registryData.username } } // At this point, even if they have a credentials object, it doesn't have a // valid token. throw Object.assign( new Error('This command requires you to be logged in.'), { code: 'ENEEDAUTH' } ) } const { resolve, relative } = require('node:path') const mapWorkspaces = require('@npmcli/map-workspaces') const { minimatch } = require('minimatch') const pkgJson = require('@npmcli/package-json') // minimatch wants forward slashes only for glob patterns const globify = pattern => pattern.split('\\').join('/') // Returns an Map of paths to workspaces indexed by workspace name // { foo => '/path/to/foo' } const getWorkspaces = async (filters, { path, includeWorkspaceRoot, relativeFrom }) => { // TODO we need a better error to be bubbled up here if this call fails const { content: pkg } = await pkgJson.normalize(path) const workspaces = await mapWorkspaces({ cwd: path, pkg }) let res = new Map() if (includeWorkspaceRoot) { res.set(pkg.name, path) } if (!filters.length) { res = new Map([...res, ...workspaces]) } for (const filterArg of filters) { for (const [workspaceName, workspacePath] of workspaces.entries()) { let relativePath = relative(relativeFrom, workspacePath) if (filterArg.startsWith('./')) { relativePath = `./${relativePath}` } const relativeFilter = relative(path, filterArg) if (filterArg === workspaceName || resolve(relativeFrom, filterArg) === workspacePath || minimatch(relativePath, `${globify(relativeFilter)}/*`) || minimatch(relativePath, `${globify(filterArg)}/*`) ) { res.set(workspaceName, workspacePath) } } } if (!res.size) { let msg = '!' if (filters.length) { msg = `:\n ${filters.reduce( (acc, filterArg) => `${acc} --workspace=${filterArg}`, '')}` } throw new Error(`No workspaces found${msg}`) } return res } module.exports = getWorkspaces const { resolve } = require('node:path') const localeCompare = require('@isaacs/string-locale-compare')('en') const installedDeep = async (npm) => { const Arborist = require('@npmcli/arborist') const { depth, global, prefix, workspacesEnabled, } = npm.flatOptions const getValues = (tree) => [...tree.inventory.values()] .filter(i => i.location !== '' && !i.isRoot) .map(i => { return i }) .filter(i => (i.depth - 1) <= depth) .sort((a, b) => (a.depth - b.depth) || localeCompare(a.name, b.name)) const res = new Set() const gArb = new Arborist({ global: true, path: resolve(npm.globalDir, '..'), workspacesEnabled, }) const gTree = await gArb.loadActual({ global: true }) for (const node of getValues(gTree)) { res.add(global ? node.name : [node.name, '-g']) } if (!global) { const arb = new Arborist({ global: false, path: prefix, workspacesEnabled }) const tree = await arb.loadActual() for (const node of getValues(tree)) { res.add(node.name) } } return [...res] } module.exports = installedDeep const { readdirScoped } = require('@npmcli/fs') const installedShallow = async (npm, opts) => { const names = async global => { const paths = await readdirScoped(global ? npm.globalDir : npm.localDir) return paths.map(p => p.replace(/\\/g, '/')) } const { conf: { argv: { remain } } } = opts if (remain.length > 3) { return null } const { global } = npm.flatOptions const locals = global ? [] : await names(false) const globals = (await names(true)).map(n => global ? n : `${n} -g`) return [...locals, ...globals] } module.exports = installedShallow const isWindowsShell = (process.platform === 'win32') && !/^MINGW(32|64)$/.test(process.env.MSYSTEM) && process.env.TERM !== 'cygwin' exports.isWindowsShell = isWindowsShell const os = require('node:os') const { join, dirname, basename } = require('node:path') const fsMiniPass = require('fs-minipass') const fs = require('node:fs/promises') const { log } = require('proc-log') const { formatWithOptions } = require('./format') const padZero = (n, length) => n.toString().padStart(length.toString().length, '0') class LogFiles { // Default to an array so we can buffer // initial writes before we know the cache location #logStream = [] // We cap log files at a certain number of log events per file. // Note that each log event can write more than one line to the // file. Then we rotate log files once this number of events is reached #MAX_LOGS_PER_FILE = null // Now that we write logs continuously we need to have a backstop // here for infinite loops that still log. This is also partially handled // by the config.get('max-files') option, but this is a failsafe to // prevent runaway log file creation #MAX_FILES_PER_PROCESS = null #fileLogCount = 0 #totalLogCount = 0 #path = null #logsMax = null #files = [] #timing = false constructor ({ maxLogsPerFile = 50_000, maxFilesPerProcess = 5, } = {}) { this.#MAX_LOGS_PER_FILE = maxLogsPerFile this.#MAX_FILES_PER_PROCESS = maxFilesPerProcess this.on() } on () { process.on('log', this.#logHandler) } off () { process.off('log', this.#logHandler) this.#endStream() } load ({ command, path, logsMax = Infinity, timing } = {}) { if (['completion'].includes(command)) { return } // dir is user configurable and is required to exist so // this can error if the dir is missing or not configured correctly this.#path = path this.#logsMax = logsMax this.#timing = timing // Log stream has already ended if (!this.#logStream) { return } log.verbose('logfile', `logs-max:${logsMax} dir:${this.#path}`) // Write the contents of our array buffer to our new file stream and // set that as the new log logstream for future writes // if logs max is 0 then the user does not want a log file if (this.#logsMax > 0) { const initialFile = this.#openLogFile() if (initialFile) { for (const item of this.#logStream) { const formatted = this.#formatLogItem(...item) if (formatted !== null) { initialFile.write(formatted) } } this.#logStream = initialFile } } log.verbose('logfile', this.files[0] || 'no logfile created') // Kickoff cleaning process, even if we aren't writing a logfile. // This is async but it will always ignore the current logfile // Return the result so it can be awaited in tests return this.#cleanLogs() } get files () { return this.#files } get #isBuffered () { return Array.isArray(this.#logStream) } #endStream (output) { if (this.#logStream && !this.#isBuffered) { this.#logStream.end(output) this.#logStream = null } } #logHandler = (level, ...args) => { // Ignore pause and resume events since we // write everything to the log file if (level === 'pause' || level === 'resume') { return } // If the stream is ended then do nothing if (!this.#logStream) { return } if (this.#isBuffered) { // Cant do anything but buffer the output if we dont // have a file stream yet this.#logStream.push([level, ...args]) return } const logOutput = this.#formatLogItem(level, ...args) if (logOutput === null) { return } // Open a new log file if we've written too many logs to this one if (this.#fileLogCount >= this.#MAX_LOGS_PER_FILE) { // Write last chunk to the file and close it this.#endStream(logOutput) if (this.#files.length >= this.#MAX_FILES_PER_PROCESS) { // but if its way too many then we just stop listening this.off() } else { // otherwise we are ready for a new file for the next event this.#logStream = this.#openLogFile() } } else { this.#logStream.write(logOutput) } } #formatLogItem (level, title, ...args) { // Only right timing logs to logfile if explicitly requests if (level === log.KEYS.timing && !this.#timing) { return null } this.#fileLogCount += 1 const prefix = [this.#totalLogCount++, level, title || null] return formatWithOptions({ prefix, eol: os.EOL, colors: false }, ...args) } #getLogFilePath (count = '') { return `${this.#path}debug-${count}.log` } #openLogFile () { // Count in filename will be 0 indexed const count = this.#files.length try { // Pad with zeros so that our log files are always sorted properly // We never want to write files ending in `-9.log` and `-10.log` because // log file cleaning is done by deleting the oldest so in this example // `-10.log` would be deleted next const f = this.#getLogFilePath(padZero(count, this.#MAX_FILES_PER_PROCESS)) // Some effort was made to make the async, but we need to write logs // during process.on('exit') which has to be synchronous. So in order // to never drop log messages, it is easiest to make it sync all the time // and this was measured to be about 1.5% slower for 40k lines of output const logStream = new fsMiniPass.WriteStreamSync(f, { flags: 'a' }) if (count > 0) { // Reset file log count if we are opening // after our first file this.#fileLogCount = 0 } this.#files.push(logStream.path) return logStream } catch (e) { // If the user has a readonly logdir then we don't want to // warn this on every command so it should be verbose log.verbose('logfile', `could not be created: ${e}`) } } async #cleanLogs () { // module to clean out the old log files // this is a best-effort attempt. if a rm fails, we just // log a message about it and move on. We do return a // Promise that succeeds when we've tried to delete everything, // just for the benefit of testing this function properly. try { const logPath = this.#getLogFilePath() const patternFileName = basename(logPath) // tell glob to only match digits .replace(/\d/g, 'd') // Handle the old (prior to 8.2.0) log file names which did not have a // counter suffix .replace('-.log', '') let files = await fs.readdir( dirname(logPath), { withFileTypes: true, encoding: 'utf-8', }) files = files.sort((a, b) => basename(a.name).localeCompare(basename(b.name), 'en')) const logFiles = [] for (const file of files) { if (!file.isFile()) { continue } const genericFileName = file.name.replace(/\d/g, 'd') const filePath = join(dirname(logPath), basename(file.name)) // Always ignore the currently written files if ( genericFileName.includes(patternFileName) && genericFileName.endsWith('.log') && !this.#files.includes(filePath) ) { logFiles.push(filePath) } } const toDelete = logFiles.length - this.#logsMax if (toDelete <= 0) { return } log.silly('logfile', `start cleaning logs, removing ${toDelete} files`) for (const file of logFiles.slice(0, toDelete)) { try { await fs.rm(file, { force: true }) } catch (e) { log.silly('logfile', 'error removing log file', file, e) } } } catch (e) { // Disable cleanup failure warnings when log writing is disabled if (this.#logsMax > 0) { log.verbose('logfile', 'error cleaning log files', e) } } finally { log.silly('logfile', 'done cleaning log files') } } } module.exports = LogFiles const { commands } = require('./cmd-list') const COL_MAX = 60 const COL_MIN = 24 const COL_GUTTER = 16 const INDENT = 4 const indent = (repeat = INDENT) => ' '.repeat(repeat) const indentNewline = (repeat) => `\n${indent(repeat)}` module.exports = (npm) => { const browser = npm.config.get('viewer') === 'browser' ? ' (in a browser)' : '' const allCommands = npm.config.get('long') ? cmdUsages(npm.constructor) : cmdNames() return `npm Usage: npm install install all the dependencies in your project npm install add the dependency to your project npm test run this project's tests npm run run the script named npm -h quick help on npm -l display usage info for all commands npm help search for help on ${browser} npm help npm more involved overview${browser} All commands: ${allCommands} Specify configs in the ini-formatted file: ${indent() + npm.config.get('userconfig')} or on the command line via: npm --key=value More configuration info: npm help config Configuration fields: npm help 7 config npm@${npm.version} ${npm.npmRoot}` } const cmdNames = () => { const out = [''] const line = !process.stdout.columns ? COL_MAX : Math.min(COL_MAX, Math.max(process.stdout.columns - COL_GUTTER, COL_MIN)) let l = 0 for (const c of commands) { if (out[l].length + c.length + 2 < line) { out[l] += ', ' + c } else { out[l++] += ',' out[l] = c } } return indentNewline() + out.join(indentNewline()).slice(2) } const cmdUsages = (Npm) => { // return a string of : let maxLen = 0 const set = [] for (const c of commands) { set.push([c, Npm.cmd(c).describeUsage.split('\n')]) maxLen = Math.max(maxLen, c.length) } return set.map(([name, usageLines]) => { const gutter = indent(maxLen - name.length + 1) const usage = usageLines.join(indentNewline(INDENT + maxLen + 1)) return indentNewline() + name + gutter + usage }).join('\n') } const { open } = require('@npmcli/promise-spawn') const { output, input } = require('proc-log') const { URL } = require('node:url') const readline = require('node:readline/promises') const { once } = require('node:events') const assertValidUrl = (url) => { try { if (!/^https?:$/.test(new URL(url).protocol)) { throw new Error() } } catch { throw new Error('Invalid URL: ' + url) } } const outputMsg = (json, title, url) => { if (json) { output.buffer({ title, url }) } else { output.standard(`${title}:\n${url}`) } } // attempt to open URL in web-browser, print address otherwise: const openUrl = async (npm, url, title, isFile) => { url = encodeURI(url) const browser = npm.config.get('browser') const json = npm.config.get('json') if (browser === false) { outputMsg(json, title, url) return } // We pass this in as true from the help command so we know we don't have to // check the protocol if (!isFile) { assertValidUrl(url) } try { await input.start(() => open(url, { command: browser === true ? null : browser, })) } catch (err) { if (err.code !== 127) { throw err } outputMsg(json, title, url) } } // Prompt to open URL in browser if possible const openUrlPrompt = async (npm, url, title, prompt, { signal }) => { const browser = npm.config.get('browser') const json = npm.config.get('json') assertValidUrl(url) outputMsg(json, title, url) if (browser === false || !process.stdin.isTTY || !process.stdout.isTTY) { return } const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }) try { await input.read(() => Promise.race([ rl.question(prompt, { signal }), once(rl, 'error'), once(rl, 'SIGINT').then(() => { throw new Error('canceled') }), ])) rl.close() await openUrl(npm, url, 'Browser unavailable. Please open the URL manually') } catch (err) { rl.close() if (err.name !== 'AbortError') { throw err } } } // Rearrange arguments and return a function that takes the two arguments // returned from the npm-profile methods that take an opener const createOpener = (npm, title, prompt = 'Press ENTER to open in the browser...') => (url, opts) => openUrlPrompt(npm, url, title, prompt, opts) module.exports = { openUrl, openUrlPrompt, createOpener, } const { log, output } = require('proc-log') const outputError = ({ standard = [], verbose = [], error = [], summary = [], detail = [] }) => { for (const line of standard) { // Each output line is just a single string output.standard(line) } for (const line of verbose) { log.verbose(...line) } for (const line of [...error, ...summary, ...detail]) { log.error(...line) } } const jsonError = (error, npm) => { if (error && npm?.loaded && npm?.config.get('json')) { return { code: error.code, summary: (error.summary || []).map(l => l.slice(1).join(' ')).join('\n').trim(), detail: (error.detail || []).map(l => l.slice(1).join(' ')).join('\n').trim(), } } } module.exports = { outputError, jsonError, } // ping the npm registry // used by the ping and doctor commands const npmFetch = require('npm-registry-fetch') module.exports = async (flatOptions) => { const res = await npmFetch('/-/ping', { ...flatOptions, cache: false }) return res.json().catch(() => ({})) } const util = require('node:util') const _delete = Symbol('delete') const _append = Symbol('append') const sqBracketsMatcher = str => str.match(/(.+)\[([^\]]+)\]\.?(.*)$/) // replaces any occurrence of an empty-brackets (e.g: []) with a special // Symbol(append) to represent it, this is going to be useful for the setter // method that will push values to the end of the array when finding these const replaceAppendSymbols = str => { const matchEmptyBracket = str.match(/^(.*)\[\]\.?(.*)$/) if (matchEmptyBracket) { const [, pre, post] = matchEmptyBracket return [...replaceAppendSymbols(pre), _append, post].filter(Boolean) } return [str] } const parseKeys = key => { const sqBracketItems = new Set() sqBracketItems.add(_append) const parseSqBrackets = str => { const index = sqBracketsMatcher(str) // once we find square brackets, we recursively parse all these if (index) { const preSqBracketPortion = index[1] // we want to have a `new String` wrapper here in order to differentiate // between multiple occurrences of the same string, e.g: // foo.bar[foo.bar] should split into { foo: { bar: { 'foo.bar': {} } } /* eslint-disable-next-line no-new-wrappers */ const foundKey = new String(index[2]) const postSqBracketPortion = index[3] // we keep track of items found during this step to make sure // we don't try to split-separate keys that were defined within // square brackets, since the key name itself might contain dots sqBracketItems.add(foundKey) // returns an array that contains either dot-separate items (that will // be split apart during the next step OR the fully parsed keys // read from square brackets, e.g: // foo.bar[1.0.0].a.b -> ['foo.bar', '1.0.0', 'a.b'] return [ ...parseSqBrackets(preSqBracketPortion), foundKey, ...(postSqBracketPortion ? parseSqBrackets(postSqBracketPortion) : []), ] } // at the end of parsing, any usage of the special empty-bracket syntax // (e.g: foo.array[]) has not yet been parsed, here we'll take care // of parsing it and adding a special symbol to represent it in // the resulting list of keys return replaceAppendSymbols(str) } const res = [] // starts by parsing items defined as square brackets, those might be // representing properties that have a dot in the name or just array // indexes, e.g: foo[1.0.0] or list[0] const sqBracketKeys = parseSqBrackets(key.trim()) for (const k of sqBracketKeys) { // keys parsed from square brackets should just be added to list of // resulting keys as they might have dots as part of the key if (sqBracketItems.has(k)) { res.push(k) } else { // splits the dot-sep property names and add them to the list of keys /* eslint-disable-next-line no-new-wrappers */ for (const splitKey of k.split('.')) { res.push(String(splitKey)) } } } // returns an ordered list of strings in which each entry // represents a key in an object defined by the previous entry return res } const getter = ({ data, key }, { unwrapSingleItemArrays = true } = {}) => { // keys are a list in which each entry represents the name of // a property that should be walked through the object in order to // return the final found value const keys = parseKeys(key) let _data = data let label = '' for (const k of keys) { // empty-bracket-shortcut-syntax is not supported on getter if (k === _append) { throw Object.assign(new Error('Empty brackets are not valid syntax for retrieving values.'), { code: 'EINVALIDSYNTAX', }) } // extra logic to take into account printing array, along with its // special syntax in which using a dot-sep property name after an // arry will expand it's results, e.g: // arr.name -> arr[0].name=value, arr[1].name=value, ... const maybeIndex = Number(k) if (Array.isArray(_data) && !Number.isInteger(maybeIndex)) { _data = _data.reduce((acc, i, index) => { acc[`${label}[${index}].${k}`] = i[k] return acc }, {}) return _data } else { if (!Object.hasOwn(_data, k)) { return undefined } _data = _data[k] } label += k } // these are some legacy expectations from // the old API consumed by lib/view.js if (unwrapSingleItemArrays && Array.isArray(_data) && _data.length <= 1) { _data = _data[0] } return { [key]: _data, } } const setter = ({ data, key, value, force }) => { // setter goes to recursively transform the provided data obj, // setting properties from the list of parsed keys, e.g: // ['foo', 'bar', 'baz'] -> { foo: { bar: { baz: {} } } const keys = parseKeys(key) const setKeys = (_data, _key) => { // handles array indexes, converting valid integers to numbers, // note that occurrences of Symbol(append) will throw, // so we just ignore these for now let maybeIndex = Number.NaN try { maybeIndex = Number(_key) } catch { // leave it NaN } if (!Number.isNaN(maybeIndex)) { _key = maybeIndex } // creates new array in case key is an index // and the array obj is not yet defined const keyIsAnArrayIndex = _key === maybeIndex || _key === _append const dataHasNoItems = !Object.keys(_data).length if (keyIsAnArrayIndex && dataHasNoItems && !Array.isArray(_data)) { _data = [] } // converting from array to an object is also possible, in case the // user is using force mode, we should also convert existing arrays // to an empty object if the current _data is an array if (force && Array.isArray(_data) && !keyIsAnArrayIndex) { _data = { ..._data } } // the _append key is a special key that is used to represent // the empty-bracket notation, e.g: arr[] -> arr[arr.length] if (_key === _append) { if (!Array.isArray(_data)) { throw Object.assign(new Error(`Can't use append syntax in non-Array element`), { code: 'ENOAPPEND', }) } _key = _data.length } // retrieves the next data object to recursively iterate on, // throws if trying to override a literal value or add props to an array const next = () => { const haveContents = !force && _data[_key] != null && value !== _delete const shouldNotOverrideLiteralValue = !(typeof _data[_key] === 'object') // if the next obj to recurse is an array and the next key to be // appended to the resulting obj is not an array index, then it // should throw since we can't append arbitrary props to arrays const shouldNotAddPropsToArrays = typeof keys[0] !== 'symbol' && Array.isArray(_data[_key]) && Number.isNaN(Number(keys[0])) const overrideError = haveContents && shouldNotOverrideLiteralValue if (overrideError) { throw Object.assign( new Error(`Property ${_key} already exists and is not an Array or Object.`), { code: 'EOVERRIDEVALUE' } ) } const addPropsToArrayError = haveContents && shouldNotAddPropsToArrays if (addPropsToArrayError) { throw Object.assign(new Error(`Can't add property ${key} to an Array.`), { code: 'ENOADDPROP', }) } return typeof _data[_key] === 'object' ? _data[_key] || {} : {} } // sets items from the parsed array of keys as objects, recurses to // setKeys in case there are still items to be handled, otherwise it // just sets the original value set by the user if (keys.length) { _data[_key] = setKeys(next(), keys.shift()) } else { // handles special deletion cases for obj props / array items if (value === _delete) { if (Array.isArray(_data)) { _data.splice(_key, 1) } else { delete _data[_key] } } else { // finally, sets the value in its right place _data[_key] = value } } return _data } setKeys(data, keys.shift()) } class Queryable { static ALL = '' #data = null constructor (obj) { if (!obj || typeof obj !== 'object') { throw Object.assign(new Error('Queryable needs an object to query properties from.'), { code: 'ENOQUERYABLEOBJ', }) } this.#data = obj } query (queries, opts) { // this ugly interface here is meant to be a compatibility layer // with the legacy API lib/view.js is consuming, if at some point // we refactor that command then we can revisit making this nicer if (queries === Queryable.ALL) { return { [Queryable.ALL]: this.#data } } const q = query => getter({ data: this.#data, key: query, }, opts) if (Array.isArray(queries)) { let res = {} for (const query of queries) { res = { ...res, ...q(query) } } return res } else { return q(queries) } } // return the value for a single query if found, otherwise returns undefined get (query) { const obj = this.query(query) if (obj) { return obj[query] } } // creates objects along the way for the provided `query` parameter // and assigns `value` to the last property of the query chain set (query, value, { force } = {}) { setter({ data: this.#data, key: query, value, force, }) } // deletes the value of the property found at `query` delete (query) { setter({ data: this.#data, key: query, value: _delete, }) } toJSON () { return this.#data } [util.inspect.custom] () { return this.toJSON() } } module.exports = Queryable const { read: _read } = require('read') const userValidate = require('npm-user-validate') const { log, input } = require('proc-log') const otpPrompt = `This command requires a one-time password (OTP) from your authenticator app. Enter one below. You can also pass one on the command line by appending --otp=123456. For more information, see: https://docs.npmjs.com/getting-started/using-two-factor-authentication Enter OTP: ` const passwordPrompt = 'npm password: ' const usernamePrompt = 'npm username: ' const emailPrompt = 'email (this IS public): ' const read = (...args) => input.read(() => _read(...args)) function readOTP (msg = otpPrompt, otp, isRetry) { if (isRetry && otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp)) { return otp.replace(/\s+/g, '') } return read({ prompt: msg, default: otp || '' }) .then((rOtp) => readOTP(msg, rOtp, true)) } function readPassword (msg = passwordPrompt, password, isRetry) { if (isRetry && password) { return password } return read({ prompt: msg, silent: true, default: password || '' }) .then((rPassword) => readPassword(msg, rPassword, true)) } function readUsername (msg = usernamePrompt, username, isRetry) { if (isRetry && username) { const error = userValidate.username(username) if (error) { log.warn(error.message) } else { return Promise.resolve(username.trim()) } } return read({ prompt: msg, default: username || '' }) .then((rUsername) => readUsername(msg, rUsername, true)) } function readEmail (msg = emailPrompt, email, isRetry) { if (isRetry && email) { const error = userValidate.email(email) if (error) { log.warn(error.message) } else { return email.trim() } } return read({ prompt: msg, default: email || '' }) .then((username) => readEmail(msg, username, true)) } module.exports = { otp: readOTP, password: readPassword, username: readUsername, email: readEmail, } const reifyOutput = require('./reify-output.js') const ini = require('ini') const { writeFile } = require('node:fs/promises') const { resolve } = require('node:path') const reifyFinish = async (npm, arb) => { await saveBuiltinConfig(npm, arb) reifyOutput(npm, arb) } const saveBuiltinConfig = async (npm, arb) => { const { options: { global }, actualTree } = arb if (!global) { return } // if we are using a builtin config, and just installed npm as // a top-level global package, we have to preserve that config. const npmNode = actualTree.inventory.get('node_modules/npm') if (!npmNode) { return } const builtinConf = npm.config.data.get('builtin') if (builtinConf.loadError) { return } const content = ini.stringify(builtinConf.raw).trim() + '\n' await writeFile(resolve(npmNode.path, 'npmrc'), content) } module.exports = reifyFinish // pass in an arborist object, and it'll output the data about what // was done, what was audited, etc. // // added ## packages, removed ## packages, and audited ## packages in 19.157s // // 1 package is looking for funding // run `npm fund` for details // // found 37 vulnerabilities (5 low, 7 moderate, 25 high) // run `npm audit fix` to fix them, or `npm audit` for details const { log, output } = require('proc-log') const { depth } = require('treeverse') const ms = require('ms') const npmAuditReport = require('npm-audit-report') const { readTree: getFundingInfo } = require('libnpmfund') const auditError = require('./audit-error.js') // TODO: output JSON if flatOptions.json is true const reifyOutput = (npm, arb) => { const { diff, actualTree } = arb // note: fails and crashes if we're running audit fix and there was an error // which is a good thing, because there's no point printing all this other // stuff in that case! const auditReport = auditError(npm, arb.auditReport) ? null : arb.auditReport // don't print any info in --silent mode, but we still need to // set the exitCode properly from the audit report, if we have one. if (npm.silent) { getAuditReport(npm, auditReport) return } const summary = { added: 0, removed: 0, changed: 0, audited: auditReport && !auditReport.error ? actualTree.inventory.size : 0, funding: 0, } if (diff) { const showDiff = npm.config.get('dry-run') || npm.config.get('long') const chalk = npm.chalk depth({ tree: diff, visit: d => { switch (d.action) { case 'REMOVE': if (showDiff) { output.standard(`${chalk.blue('remove')} ${d.actual.name} ${d.actual.package.version}`) } summary.removed++ break case 'ADD': if (showDiff) { output.standard(`${chalk.green('add')} ${d.ideal.name} ${d.ideal.package.version}`) } actualTree.inventory.has(d.ideal) && summary.added++ break case 'CHANGE': if (showDiff) { output.standard(`${chalk.cyan('change')} ${d.actual.name} ${d.actual.package.version} => ${d.ideal.package.version}`) } summary.changed++ break default: return } const node = d.actual || d.ideal log.silly(d.action, node.location) }, getChildren: d => d.children, }) } if (npm.flatOptions.fund) { const fundingInfo = getFundingInfo(actualTree, { countOnly: true }) summary.funding = fundingInfo.length } if (npm.flatOptions.json) { if (auditReport) { // call this to set the exit code properly getAuditReport(npm, auditReport) summary.audit = npm.command === 'audit' ? auditReport : auditReport.toJSON().metadata } output.buffer(summary) } else { packagesChangedMessage(npm, summary) packagesFundingMessage(npm, summary) printAuditReport(npm, auditReport) } } // if we're running `npm audit fix`, then we print the full audit report // at the end if there's still stuff, because it's silly for `npm audit` // to tell you to run `npm audit` for details. otherwise, use the summary // report. if we get here, we know it's not quiet or json. // If the loglevel is silent, then we just run the report // to get the exitCode set appropriately. const printAuditReport = (npm, report) => { const res = getAuditReport(npm, report) if (!res || !res.report) { return } output.standard(`\n${res.report}`) } const getAuditReport = (npm, report) => { if (!report) { return } // when in silent mode, we print nothing. the JSON output is // going to just JSON.stringify() the report object. const reporter = npm.silent ? 'quiet' : npm.flatOptions.json ? 'quiet' : npm.command !== 'audit' ? 'install' : 'detail' const defaultAuditLevel = npm.command !== 'audit' ? 'none' : 'low' const auditLevel = npm.flatOptions.auditLevel || defaultAuditLevel const res = npmAuditReport(report, { reporter, ...npm.flatOptions, auditLevel, chalk: npm.chalk, }) if (npm.command === 'audit') { process.exitCode = process.exitCode || res.exitCode } return res } const packagesChangedMessage = (npm, { added, removed, changed, audited }) => { const msg = ['\n'] if (added === 0 && removed === 0 && changed === 0) { msg.push('up to date') if (audited) { msg.push(', ') } } else { if (added) { msg.push(`added ${added} package${added === 1 ? '' : 's'}`) } if (removed) { if (added) { msg.push(', ') } if (added && !audited && !changed) { msg.push('and ') } msg.push(`removed ${removed} package${removed === 1 ? '' : 's'}`) } if (changed) { if (added || removed) { msg.push(', ') } if (!audited && (added || removed)) { msg.push('and ') } msg.push(`changed ${changed} package${changed === 1 ? '' : 's'}`) } if (audited) { msg.push(', and ') } } if (audited) { msg.push(`audited ${audited} package${audited === 1 ? '' : 's'}`) } msg.push(` in ${ms(Date.now() - npm.started)}`) output.standard(msg.join('')) } const packagesFundingMessage = (npm, { funding }) => { if (!funding) { return } output.standard('') const pkg = funding === 1 ? 'package' : 'packages' const is = funding === 1 ? 'is' : 'are' output.standard(`${funding} ${pkg} ${is} looking for funding`) output.standard(' run `npm fund` for details') } module.exports = reifyOutput const crypto = require('node:crypto') const normalizeData = require('normalize-package-data') const parseLicense = require('spdx-expression-parse') const npa = require('npm-package-arg') const ssri = require('ssri') const CYCLONEDX_SCHEMA = 'http://cyclonedx.org/schema/bom-1.5.schema.json' const CYCLONEDX_FORMAT = 'CycloneDX' const CYCLONEDX_SCHEMA_VERSION = '1.5' const PROP_BUNDLED = 'cdx:npm:package:bundled' const PROP_DEVELOPMENT = 'cdx:npm:package:development' const PROP_EXTRANEOUS = 'cdx:npm:package:extraneous' const PROP_PRIVATE = 'cdx:npm:package:private' const REF_VCS = 'vcs' const REF_WEBSITE = 'website' const REF_ISSUE_TRACKER = 'issue-tracker' const REF_DISTRIBUTION = 'distribution' const ALGO_MAP = { sha1: 'SHA-1', sha256: 'SHA-256', sha384: 'SHA-384', sha512: 'SHA-512', } const cyclonedxOutput = ({ npm, nodes, packageType, packageLockOnly }) => { const rootNode = nodes.find(node => node.isRoot) const childNodes = nodes.filter(node => !node.isRoot && !node.isLink) const uuid = crypto.randomUUID() // Create list of child nodes w/ unique IDs const childNodeMap = new Map() for (const item of childNodes) { const id = toCyclonedxID(item) if (!childNodeMap.has(id)) { childNodeMap.set(id, item) } } const uniqueChildNodes = Array.from(childNodeMap.values()) const deps = [rootNode, ...uniqueChildNodes] .map(node => toCyclonedxDependency(node, nodes)) const bom = { $schema: CYCLONEDX_SCHEMA, bomFormat: CYCLONEDX_FORMAT, specVersion: CYCLONEDX_SCHEMA_VERSION, serialNumber: `urn:uuid:${uuid}`, version: 1, metadata: { timestamp: new Date().toISOString(), lifecycles: [ { phase: packageLockOnly ? 'pre-build' : 'build' }, ], tools: [ { vendor: 'npm', name: 'cli', version: npm.version, }, ], component: toCyclonedxItem(rootNode, { packageType }), }, components: uniqueChildNodes.map(toCyclonedxItem), dependencies: deps, } return bom } const toCyclonedxItem = (node, { packageType }) => { packageType = packageType || 'library' // Calculate purl from package spec let spec = npa(node.pkgid) spec = (spec.type === 'alias') ? spec.subSpec : spec const purl = npa.toPurl(spec) + (isGitNode(node) ? `?vcs_url=${node.resolved}` : '') if (node.package) { normalizeData(node.package) } let parsedLicense try { let license = node.package?.license if (license) { if (typeof license === 'object') { license = license.type } } parsedLicense = parseLicense(license) } catch { parsedLicense = null } const component = { 'bom-ref': toCyclonedxID(node), type: packageType, name: node.name, version: node.version, scope: (node.optional || node.devOptional) ? 'optional' : 'required', author: (typeof node.package?.author === 'object') ? node.package.author.name : (node.package?.author || undefined), description: node.package?.description || undefined, purl: purl, properties: [], externalReferences: [], } if (node.integrity) { const integrity = ssri.parse(node.integrity, { single: true }) component.hashes = [{ alg: ALGO_MAP[integrity.algorithm] || /* istanbul ignore next */ 'SHA-512', content: integrity.hexDigest(), }] } if (node.dev === true) { component.properties.push(prop(PROP_DEVELOPMENT)) } if (node.package?.private === true) { component.properties.push(prop(PROP_PRIVATE)) } if (node.extraneous === true) { component.properties.push(prop(PROP_EXTRANEOUS)) } if (node.inBundle === true) { component.properties.push(prop(PROP_BUNDLED)) } if (!node.isLink && node.resolved) { component.externalReferences.push(extRef(REF_DISTRIBUTION, node.resolved)) } if (node.package?.repository?.url) { component.externalReferences.push(extRef(REF_VCS, node.package.repository.url)) } if (node.package?.homepage) { component.externalReferences.push(extRef(REF_WEBSITE, node.package.homepage)) } if (node.package?.bugs?.url) { component.externalReferences.push(extRef(REF_ISSUE_TRACKER, node.package.bugs.url)) } // If license is a single SPDX license, use the license field if (parsedLicense?.license) { component.licenses = [{ license: { id: parsedLicense.license } }] // If license is a conjunction, use the expression field } else if (parsedLicense?.conjunction) { component.licenses = [{ expression: node.package.license }] } return component } const toCyclonedxDependency = (node, nodes) => { return { ref: toCyclonedxID(node), dependsOn: [...node.edgesOut.values()] // Filter out edges that are linking to nodes not in the list .filter(edge => nodes.find(n => n === edge.to)) .map(edge => toCyclonedxID(edge.to)) .filter(id => id), } } const toCyclonedxID = (node) => `${node.packageName}@${node.version}` const prop = (name) => ({ name, value: 'true' }) const extRef = (type, url) => ({ type, url }) const isGitNode = (node) => { if (!node.resolved) { return } try { const { type } = npa(node.resolved) return type === 'git' || type === 'hosted' } catch { /* istanbul ignore next */ return false } } module.exports = { cyclonedxOutput } const crypto = require('node:crypto') const normalizeData = require('normalize-package-data') const npa = require('npm-package-arg') const ssri = require('ssri') const SPDX_SCHEMA_VERSION = 'SPDX-2.3' const SPDX_DATA_LICENSE = 'CC0-1.0' const SPDX_IDENTIFER = 'SPDXRef-DOCUMENT' const NO_ASSERTION = 'NOASSERTION' const REL_DESCRIBES = 'DESCRIBES' const REL_PREREQ = 'PREREQUISITE_FOR' const REL_OPTIONAL = 'OPTIONAL_DEPENDENCY_OF' const REL_DEV = 'DEV_DEPENDENCY_OF' const REL_DEP = 'DEPENDENCY_OF' const REF_CAT_PACKAGE_MANAGER = 'PACKAGE-MANAGER' const REF_TYPE_PURL = 'purl' const spdxOutput = ({ npm, nodes, packageType }) => { const rootNode = nodes.find(node => node.isRoot) const childNodes = nodes.filter(node => !node.isRoot && !node.isLink) const rootID = rootNode.pkgid const uuid = crypto.randomUUID() const ns = `http://spdx.org/spdxdocs/${npa(rootID).escapedName}-${rootNode.version}-${uuid}` // Create list of child nodes w/ unique IDs const childNodeMap = new Map() for (const item of childNodes) { const id = toSpdxID(item) if (!childNodeMap.has(id)) { childNodeMap.set(id, item) } } const uniqueChildNodes = Array.from(childNodeMap.values()) const relationships = [] const seen = new Set() for (let node of nodes) { if (node.isLink) { node = node.target } if (seen.has(node)) { continue } seen.add(node) const rels = [...node.edgesOut.values()] // Filter out edges that are linking to nodes not in the list .filter(edge => nodes.find(n => n === edge.to)) .map(edge => toSpdxRelationship(node, edge)) .filter(rel => rel) relationships.push(...rels) } const extraRelationships = nodes.filter(node => node.extraneous) .map(node => toSpdxRelationship(rootNode, { to: node, type: 'optional' })) relationships.push(...extraRelationships) const bom = { spdxVersion: SPDX_SCHEMA_VERSION, dataLicense: SPDX_DATA_LICENSE, SPDXID: SPDX_IDENTIFER, name: rootID, documentNamespace: ns, creationInfo: { created: new Date().toISOString(), creators: [ `Tool: npm/cli-${npm.version}`, ], }, documentDescribes: [toSpdxID(rootNode)], packages: [toSpdxItem(rootNode, { packageType }), ...uniqueChildNodes.map(toSpdxItem)], relationships: [ { spdxElementId: SPDX_IDENTIFER, relatedSpdxElement: toSpdxID(rootNode), relationshipType: REL_DESCRIBES, }, ...relationships, ], } return bom } const toSpdxItem = (node, { packageType }) => { normalizeData(node.package) // Calculate purl from package spec let spec = npa(node.pkgid) spec = (spec.type === 'alias') ? spec.subSpec : spec const purl = npa.toPurl(spec) + (isGitNode(node) ? `?vcs_url=${node.resolved}` : '') /* For workspace nodes, use the location from their linkNode */ let location = node.location if (node.isWorkspace && node.linksIn.size > 0) { location = node.linksIn.values().next().value.location } let license = node.package?.license if (license) { if (typeof license === 'object') { license = license.type } } const pkg = { name: node.packageName, SPDXID: toSpdxID(node), versionInfo: node.version, packageFileName: location, description: node.package?.description || undefined, primaryPackagePurpose: packageType ? packageType.toUpperCase() : undefined, downloadLocation: (node.isLink ? undefined : node.resolved) || NO_ASSERTION, filesAnalyzed: false, homepage: node.package?.homepage || NO_ASSERTION, licenseDeclared: license || NO_ASSERTION, externalRefs: [ { referenceCategory: REF_CAT_PACKAGE_MANAGER, referenceType: REF_TYPE_PURL, referenceLocator: purl, }, ], } if (node.integrity) { const integrity = ssri.parse(node.integrity, { single: true }) pkg.checksums = [{ algorithm: integrity.algorithm.toUpperCase(), checksumValue: integrity.hexDigest(), }] } return pkg } const toSpdxRelationship = (node, edge) => { let type switch (edge.type) { case 'peer': type = REL_PREREQ break case 'optional': type = REL_OPTIONAL break case 'dev': type = REL_DEV break default: type = REL_DEP } return { spdxElementId: toSpdxID(edge.to), relatedSpdxElement: toSpdxID(node), relationshipType: type, } } const toSpdxID = (node) => { let name = node.packageName // Strip leading @ for scoped packages name = name.replace(/^@/, '') // Replace slashes with dots name = name.replace(/\//g, '.') return `SPDXRef-Package-${name}-${node.version}` } const isGitNode = (node) => { if (!node.resolved) { return } try { const { type } = npa(node.resolved) return type === 'git' || type === 'hosted' } catch { /* istanbul ignore next */ return false } } module.exports = { spdxOutput } const tar = require('tar') const ssri = require('ssri') const { log, output } = require('proc-log') const formatBytes = require('./format-bytes.js') const localeCompare = require('@isaacs/string-locale-compare')('en', { sensitivity: 'case', numeric: true, }) const logTar = (tarball, { unicode = false, json, key } = {}) => { if (json) { output.buffer(key == null ? tarball : { [key]: tarball }) return } log.notice('') log.notice('', `${unicode ? '📦 ' : 'package:'} ${tarball.name}@${tarball.version}`) log.notice('Tarball Contents') if (tarball.files.length) { log.notice( '', tarball.files.map(f => /^node_modules\//.test(f.path) ? null : `${formatBytes(f.size, false)} ${f.path}` ).filter(f => f).join('\n') ) } if (tarball.bundled.length) { log.notice('Bundled Dependencies') tarball.bundled.forEach(name => log.notice('', name)) } log.notice('Tarball Details') log.notice('', `name: ${tarball.name}`) log.notice('', `version: ${tarball.version}`) if (tarball.filename) { log.notice('', `filename: ${tarball.filename}`) } log.notice('', `package size: ${formatBytes(tarball.size)}`) log.notice('', `unpacked size: ${formatBytes(tarball.unpackedSize)}`) log.notice('', `shasum: ${tarball.shasum}`) log.notice('', `integrity: ${tarball.integrity.toString().slice(0, 20)}[...]${tarball.integrity.toString().slice(80)}`) if (tarball.bundled.length) { log.notice('', `bundled deps: ${tarball.bundled.length}`) log.notice('', `bundled files: ${tarball.entryCount - tarball.files.length}`) log.notice('', `own files: ${tarball.files.length}`) } log.notice('', `total files: ${tarball.entryCount}`) log.notice('', '') } const getContents = async (manifest, tarball) => { const files = [] const bundled = new Set() let totalEntries = 0 let totalEntrySize = 0 // reads contents of tarball const stream = tar.t({ onentry (entry) { totalEntries++ totalEntrySize += entry.size const p = entry.path if (p.startsWith('package/node_modules/') && p !== 'package/node_modules/') { const name = p.match(/^package\/node_modules\/((?:@[^/]+\/)?[^/]+)/)[1] bundled.add(name) } files.push({ path: entry.path.replace(/^package\//, ''), size: entry.size, mode: entry.mode, }) }, }) stream.end(tarball) const integrity = ssri.fromData(tarball, { algorithms: ['sha1', 'sha512'], }) const comparator = ({ path: a }, { path: b }) => localeCompare(a, b) const isUpper = str => { const ch = str.charAt(0) return ch === ch.toUpperCase() } const uppers = files.filter(file => isUpper(file.path)) const others = files.filter(file => !isUpper(file.path)) uppers.sort(comparator) others.sort(comparator) const shasum = integrity.sha1[0].hexDigest() return { id: manifest._id || `${manifest.name}@${manifest.version}`, name: manifest.name, version: manifest.version, size: tarball.length, unpackedSize: totalEntrySize, shasum, integrity: ssri.parse(integrity.sha512[0]), // @scope/packagename.tgz => scope-packagename.tgz // we can safely use these global replace rules due to npm package naming rules filename: `${manifest.name.replace('@', '').replace('/', '-')}-${manifest.version}.tgz`, files: uppers.concat(others), entryCount: totalEntries, bundled: Array.from(bundled), } } module.exports = { logTar, getContents } const EE = require('node:events') const fs = require('node:fs') const { log, time } = require('proc-log') const INITIAL_TIMER = 'npm' class Timers extends EE { #file #timing #unfinished = new Map() #finished = {} constructor () { super() this.on() time.start(INITIAL_TIMER) this.started = this.#unfinished.get(INITIAL_TIMER) } on () { process.on('time', this.#timeHandler) } off () { process.off('time', this.#timeHandler) } load ({ path, timing } = {}) { this.#timing = timing this.#file = `${path}timing.json` } finish (metadata) { time.end(INITIAL_TIMER) for (const [name, timer] of this.#unfinished) { log.silly('unfinished npm timer', name, timer) } if (!this.#timing) { // Not in timing mode, nothing else to do here return } try { this.#writeFile(metadata) log.info('timing', `Timing info written to: ${this.#file}`) } catch (e) { log.warn('timing', `could not write timing file: ${e}`) } } #writeFile (metadata) { const globalStart = this.started const globalEnd = this.#finished[INITIAL_TIMER] const content = { metadata, timers: this.#finished, // add any unfinished timers with their relative start/end unfinishedTimers: [...this.#unfinished.entries()].reduce((acc, [name, start]) => { acc[name] = [start - globalStart, globalEnd - globalStart] return acc }, {}), } fs.writeFileSync(this.#file, JSON.stringify(content) + '\n') } #timeHandler = (level, name) => { const now = Date.now() switch (level) { case time.KEYS.start: this.#unfinished.set(name, now) break case time.KEYS.end: { if (this.#unfinished.has(name)) { const ms = now - this.#unfinished.get(name) this.#finished[name] = ms this.#unfinished.delete(name) log.timing(name, `Completed in ${ms}ms`) } else { log.silly('timing', `Tried to end timer that doesn't exist: ${name}`) } } } } } module.exports = Timers 'use strict' const reifyFinish = require('../utils/reify-finish.js') async function updateWorkspaces ({ config, flatOptions, localPrefix, npm, workspaces, }) { if (!flatOptions.workspacesUpdate || !workspaces.length) { return } // default behavior is to not save by default in order to avoid // race condition problems when publishing multiple workspaces // that have dependencies on one another, it might still be useful // in some cases, which then need to set --save const save = config.isDefault('save') ? false : config.get('save') // runs a minimalistic reify update, targeting only the workspaces // that had version updates and skipping fund/audit/save const opts = { ...flatOptions, audit: false, fund: false, path: localPrefix, save, } const Arborist = require('@npmcli/arborist') const arb = new Arborist(opts) await arb.reify({ ...opts, update: workspaces }) await reifyFinish(npm, arb) } module.exports = updateWorkspaces // compares the inventory of package items in the tree // that is about to be installed (idealTree) with the inventory // of items stored in the package-lock file (virtualTree) // // Returns empty array if no errors found or an array populated // with an entry for each validation error found. function validateLockfile (virtualTree, idealTree) { const errors = [] // loops through the inventory of packages resulted by ideal tree, // for each package compares the versions with the version stored in the // package-lock and adds an error to the list in case of mismatches for (const [key, entry] of idealTree.entries()) { const lock = virtualTree.get(key) if (!lock) { errors.push(`Missing: ${entry.name}@${entry.version} from lock file`) continue } if (entry.version !== lock.version) { errors.push(`Invalid: lock file's ${lock.name}@${lock.version} does ` + `not satisfy ${entry.name}@${entry.version}`) } } return errors } module.exports = validateLockfile const npmFetch = require('npm-registry-fetch') const localeCompare = require('@isaacs/string-locale-compare')('en') const npa = require('npm-package-arg') const pacote = require('pacote') const tufClient = require('@sigstore/tuf') const { log, output } = require('proc-log') const sortAlphabetically = (a, b) => localeCompare(a.name, b.name) class VerifySignatures { constructor (tree, filterSet, npm, opts) { this.tree = tree this.filterSet = filterSet this.npm = npm this.opts = opts this.keys = new Map() this.invalid = [] this.missing = [] this.checkedPackages = new Set() this.auditedWithKeysCount = 0 this.verifiedSignatureCount = 0 this.verifiedAttestationCount = 0 this.exitCode = 0 } async run () { const start = process.hrtime.bigint() const { default: pMap } = await import('p-map') // Find all deps in tree const { edges, registries } = this.getEdgesOut(this.tree.inventory.values(), this.filterSet) if (edges.size === 0) { throw new Error('found no installed dependencies to audit') } const tuf = await tufClient.initTUF({ cachePath: this.opts.tufCache, retry: this.opts.retry, timeout: this.opts.timeout, }) await Promise.all([...registries].map(registry => this.setKeys({ registry, tuf }))) log.verbose('verifying registry signatures') await pMap(edges, (e) => this.getVerifiedInfo(e), { concurrency: 20, stopOnError: true }) // Didn't find any dependencies that could be verified, e.g. only local // deps, missing version, not on a registry etc. if (!this.auditedWithKeysCount) { throw new Error('found no dependencies to audit that were installed from ' + 'a supported registry') } const invalid = this.invalid.sort(sortAlphabetically) const missing = this.missing.sort(sortAlphabetically) const hasNoInvalidOrMissing = invalid.length === 0 && missing.length === 0 if (!hasNoInvalidOrMissing) { process.exitCode = 1 } if (this.npm.config.get('json')) { output.buffer({ invalid, missing }) return } const end = process.hrtime.bigint() const elapsed = end - start const auditedPlural = this.auditedWithKeysCount > 1 ? 's' : '' const timing = `audited ${this.auditedWithKeysCount} package${auditedPlural} in ` + `${Math.floor(Number(elapsed) / 1e9)}s` output.standard(timing) output.standard('') const verifiedBold = this.npm.chalk.bold('verified') if (this.verifiedSignatureCount) { if (this.verifiedSignatureCount === 1) { output.standard(`${this.verifiedSignatureCount} package has a ${verifiedBold} registry signature`) } else { output.standard(`${this.verifiedSignatureCount} packages have ${verifiedBold} registry signatures`) } output.standard('') } if (this.verifiedAttestationCount) { if (this.verifiedAttestationCount === 1) { output.standard(`${this.verifiedAttestationCount} package has a ${verifiedBold} attestation`) } else { output.standard(`${this.verifiedAttestationCount} packages have ${verifiedBold} attestations`) } output.standard('') } if (missing.length) { const missingClr = this.npm.chalk.redBright('missing') if (missing.length === 1) { output.standard(`1 package has a ${missingClr} registry signature but the registry is providing signing keys:`) } else { output.standard(`${missing.length} packages have ${missingClr} registry signatures but the registry is providing signing keys:`) } output.standard('') missing.map(m => output.standard(`${this.npm.chalk.red(`${m.name}@${m.version}`)} (${m.registry})`) ) } if (invalid.length) { if (missing.length) { output.standard('') } const invalidClr = this.npm.chalk.redBright('invalid') // We can have either invalid signatures or invalid provenance const invalidSignatures = this.invalid.filter(i => i.code === 'EINTEGRITYSIGNATURE') if (invalidSignatures.length) { if (invalidSignatures.length === 1) { output.standard(`1 package has an ${invalidClr} registry signature:`) } else { output.standard(`${invalidSignatures.length} packages have ${invalidClr} registry signatures:`) } output.standard('') invalidSignatures.map(i => output.standard(`${this.npm.chalk.red(`${i.name}@${i.version}`)} (${i.registry})`) ) output.standard('') } const invalidAttestations = this.invalid.filter(i => i.code === 'EATTESTATIONVERIFY') if (invalidAttestations.length) { if (invalidAttestations.length === 1) { output.standard(`1 package has an ${invalidClr} attestation:`) } else { output.standard(`${invalidAttestations.length} packages have ${invalidClr} attestations:`) } output.standard('') invalidAttestations.map(i => output.standard(`${this.npm.chalk.red(`${i.name}@${i.version}`)} (${i.registry})`) ) output.standard('') } if (invalid.length === 1) { output.standard(`Someone might have tampered with this package since it was published on the registry!`) } else { output.standard(`Someone might have tampered with these packages since they were published on the registry!`) } output.standard('') } } getEdgesOut (nodes, filterSet) { const edges = new Set() const registries = new Set() for (const node of nodes) { for (const edge of node.edgesOut.values()) { const filteredOut = edge.from && filterSet && filterSet.size > 0 && !filterSet.has(edge.from.target) if (!filteredOut) { const spec = this.getEdgeSpec(edge) if (spec) { // Prefetch and cache public keys from used registries registries.add(this.getSpecRegistry(spec)) } edges.add(edge) } } } return { edges, registries } } async setKeys ({ registry, tuf }) { const { host, pathname } = new URL(registry) // Strip any trailing slashes from pathname const regKey = `${host}${pathname.replace(/\/$/, '')}/keys.json` let keys = await tuf.getTarget(regKey) .then((target) => JSON.parse(target)) .then(({ keys: ks }) => ks.map((key) => ({ ...key, keyid: key.keyId, pemkey: `-----BEGIN PUBLIC KEY-----\n${key.publicKey.rawBytes}\n-----END PUBLIC KEY-----`, expires: key.publicKey.validFor.end || null, }))).catch(err => { if (err.code === 'TUF_FIND_TARGET_ERROR') { return null } else { throw err } }) // If keys not found in Sigstore TUF repo, fallback to registry keys API if (!keys) { keys = await npmFetch.json('/-/npm/v1/keys', { ...this.npm.flatOptions, registry, }).then(({ keys: ks }) => ks.map((key) => ({ ...key, pemkey: `-----BEGIN PUBLIC KEY-----\n${key.key}\n-----END PUBLIC KEY-----`, }))).catch(err => { if (err.code === 'E404' || err.code === 'E400') { return null } else { throw err } }) } if (keys) { this.keys.set(registry, keys) } } getEdgeType (edge) { return edge.optional ? 'optionalDependencies' : edge.peer ? 'peerDependencies' : edge.dev ? 'devDependencies' : 'dependencies' } getEdgeSpec (edge) { let name = edge.name try { name = npa(edge.spec).subSpec.name } catch { // leave it as edge.name } try { return npa(`${name}@${edge.spec}`) } catch { // Skip packages with invalid spec } } buildRegistryConfig (registry) { const keys = this.keys.get(registry) || [] const parsedRegistry = new URL(registry) const regKey = `//${parsedRegistry.host}${parsedRegistry.pathname}` return { [`${regKey}:_keys`]: keys, } } getSpecRegistry (spec) { return npmFetch.pickRegistry(spec, this.npm.flatOptions) } getValidPackageInfo (edge) { const type = this.getEdgeType(edge) // Skip potentially optional packages that are not on disk, as these could // be omitted during install if (edge.error === 'MISSING' && type !== 'dependencies') { return } const spec = this.getEdgeSpec(edge) // Skip invalid version requirements if (!spec) { return } const node = edge.to || edge const { version } = node.package || {} if (node.isWorkspace || // Skip local workspaces packages !version || // Skip packages that don't have a installed version, e.g. optonal dependencies !spec.registry) { // Skip if not from registry, e.g. git package return } for (const omitType of this.npm.config.get('omit')) { if (node[omitType]) { return } } return { name: spec.name, version, type, location: node.location, registry: this.getSpecRegistry(spec), } } async verifySignatures (name, version, registry) { const { _integrity: integrity, _signatures, _attestations, _resolved: resolved, } = await pacote.manifest(`${name}@${version}`, { verifySignatures: true, verifyAttestations: true, ...this.buildRegistryConfig(registry), ...this.npm.flatOptions, }) const signatures = _signatures || [] const result = { integrity, signatures, attestations: _attestations, resolved, } return result } async getVerifiedInfo (edge) { const info = this.getValidPackageInfo(edge) if (!info) { return } const { name, version, location, registry, type } = info if (this.checkedPackages.has(location)) { // we already did or are doing this one return } this.checkedPackages.add(location) // We only "audit" or verify the signature, or the presence of it, on // packages whose registry returns signing keys const keys = this.keys.get(registry) || [] if (keys.length) { this.auditedWithKeysCount += 1 } try { const { integrity, signatures, attestations, resolved } = await this.verifySignatures( name, version, registry ) // Currently we only care about missing signatures on registries that provide a public key // We could make this configurable in the future with a strict/paranoid mode if (signatures.length) { this.verifiedSignatureCount += 1 } else if (keys.length) { this.missing.push({ integrity, location, name, registry, resolved, version, }) } // Track verified attestations separately to registry signatures, as all // packages on registries with signing keys are expected to have registry // signatures, but not all packages have provenance and publish attestations. if (attestations) { this.verifiedAttestationCount += 1 } } catch (e) { if (e.code === 'EINTEGRITYSIGNATURE' || e.code === 'EATTESTATIONVERIFY') { this.invalid.push({ code: e.code, message: e.message, integrity: e.integrity, keyid: e.keyid, location, name, registry, resolved: e.resolved, signature: e.signature, predicateType: e.predicateType, type, version, }) } else { throw e } } } } module.exports = VerifySignatures Copyright (c) 2015, Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict'; const align = { right: alignRight, center: alignCenter }; const top = 0; const right = 1; const bottom = 2; const left = 3; class UI { constructor(opts) { var _a; this.width = opts.width; /* c8 ignore start */ this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; /* c8 ignore stop */ this.rows = []; } span(...args) { const cols = this.div(...args); cols.span = true; } resetOutput() { this.rows = []; } div(...args) { if (args.length === 0) { this.div(''); } if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { return this.applyLayoutDSL(args[0]); } const cols = args.map(arg => { if (typeof arg === 'string') { return this.colFromString(arg); } return arg; }); this.rows.push(cols); return cols; } shouldApplyLayoutDSL(...args) { return args.length === 1 && typeof args[0] === 'string' && /[\t\n]/.test(args[0]); } applyLayoutDSL(str) { const rows = str.split('\n').map(row => row.split('\t')); let leftColumnWidth = 0; // simple heuristic for layout, make sure the // second column lines up along the left-hand. // don't allow the first column to take up more // than 50% of the screen. rows.forEach(columns => { if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); } }); // generate a table: // replacing ' ' with padding calculations. // using the algorithmically generated width. rows.forEach(columns => { this.div(...columns.map((r, i) => { return { text: r.trim(), padding: this.measurePadding(r), width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined }; })); }); return this.rows[this.rows.length - 1]; } colFromString(text) { return { text, padding: this.measurePadding(text) }; } measurePadding(str) { // measure padding without ansi escape codes const noAnsi = mixin.stripAnsi(str); return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; } toString() { const lines = []; this.rows.forEach(row => { this.rowToString(row, lines); }); // don't display any lines with the // hidden flag set. return lines .filter(line => !line.hidden) .map(line => line.text) .join('\n'); } rowToString(row, lines) { this.rasterize(row).forEach((rrow, r) => { let str = ''; rrow.forEach((col, c) => { const { width } = row[c]; // the width with padding. const wrapWidth = this.negatePadding(row[c]); // the width without padding. let ts = col; // temporary string used during alignment/padding. if (wrapWidth > mixin.stringWidth(col)) { ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); } // align the string within its column. if (row[c].align && row[c].align !== 'left' && this.wrap) { const fn = align[row[c].align]; ts = fn(ts, wrapWidth); if (mixin.stringWidth(ts) < wrapWidth) { /* c8 ignore start */ const w = width || 0; /* c8 ignore stop */ ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); } } // apply border and padding to string. const padding = row[c].padding || [0, 0, 0, 0]; if (padding[left]) { str += ' '.repeat(padding[left]); } str += addBorder(row[c], ts, '| '); str += ts; str += addBorder(row[c], ts, ' |'); if (padding[right]) { str += ' '.repeat(padding[right]); } // if prior row is span, try to render the // current row on the prior line. if (r === 0 && lines.length > 0) { str = this.renderInline(str, lines[lines.length - 1]); } }); // remove trailing whitespace. lines.push({ text: str.replace(/ +$/, ''), span: row.span }); }); return lines; } // if the full 'source' can render in // the target line, do so. renderInline(source, previousLine) { const match = source.match(/^ */); /* c8 ignore start */ const leadingWhitespace = match ? match[0].length : 0; /* c8 ignore stop */ const target = previousLine.text; const targetTextWidth = mixin.stringWidth(target.trimEnd()); if (!previousLine.span) { return source; } // if we're not applying wrapping logic, // just always append to the span. if (!this.wrap) { previousLine.hidden = true; return target + source; } if (leadingWhitespace < targetTextWidth) { return source; } previousLine.hidden = true; return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); } rasterize(row) { const rrows = []; const widths = this.columnWidths(row); let wrapped; // word wrap all columns, and create // a data-structure that is easy to rasterize. row.forEach((col, c) => { // leave room for left and right padding. col.width = widths[c]; if (this.wrap) { wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); } else { wrapped = col.text.split('\n'); } if (col.border) { wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); } // add top and bottom padding. if (col.padding) { wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); } wrapped.forEach((str, r) => { if (!rrows[r]) { rrows.push([]); } const rrow = rrows[r]; for (let i = 0; i < c; i++) { if (rrow[i] === undefined) { rrow.push(''); } } rrow.push(str); }); }); return rrows; } negatePadding(col) { /* c8 ignore start */ let wrapWidth = col.width || 0; /* c8 ignore stop */ if (col.padding) { wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); } if (col.border) { wrapWidth -= 4; } return wrapWidth; } columnWidths(row) { if (!this.wrap) { return row.map(col => { return col.width || mixin.stringWidth(col.text); }); } let unset = row.length; let remainingWidth = this.width; // column widths can be set in config. const widths = row.map(col => { if (col.width) { unset--; remainingWidth -= col.width; return col.width; } return undefined; }); // any unset widths should be calculated. /* c8 ignore start */ const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; /* c8 ignore stop */ return widths.map((w, i) => { if (w === undefined) { return Math.max(unsetWidth, _minWidth(row[i])); } return w; }); } } function addBorder(col, ts, style) { if (col.border) { if (/[.']-+[.']/.test(ts)) { return ''; } if (ts.trim().length !== 0) { return style; } return ' '; } return ''; } // calculates the minimum width of // a column, based on padding preferences. function _minWidth(col) { const padding = col.padding || []; const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); if (col.border) { return minWidth + 4; } return minWidth; } function getWindowWidth() { /* c8 ignore start */ if (typeof process === 'object' && process.stdout && process.stdout.columns) { return process.stdout.columns; } return 80; } /* c8 ignore stop */ function alignRight(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); if (strWidth < width) { return ' '.repeat(width - strWidth) + str; } return str; } function alignCenter(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); /* c8 ignore start */ if (strWidth >= width) { return str; } /* c8 ignore stop */ return ' '.repeat((width - strWidth) >> 1) + str; } let mixin; function cliui(opts, _mixin) { mixin = _mixin; return new UI({ /* c8 ignore start */ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), wrap: opts === null || opts === void 0 ? void 0 : opts.wrap /* c8 ignore stop */ }); } // Bootstrap cliui with CommonJS dependencies: const stringWidth = require('string-width-cjs'); const stripAnsi = require('strip-ansi-cjs'); const wrap = require('wrap-ansi-cjs'); function ui(opts) { return cliui(opts, { stringWidth, stripAnsi, wrap }); } module.exports = ui; interface UIOptions { width: number; wrap?: boolean; rows?: string[]; } interface Column { text: string; width?: number; align?: "right" | "left" | "center"; padding: number[]; border?: boolean; } interface ColumnArray extends Array { span: boolean; } interface Line { hidden?: boolean; text: string; span?: boolean; } declare class UI { width: number; wrap: boolean; rows: ColumnArray[]; constructor(opts: UIOptions); span(...args: ColumnArray): void; resetOutput(): void; div(...args: (Column | string)[]): ColumnArray; private shouldApplyLayoutDSL; private applyLayoutDSL; private colFromString; private measurePadding; toString(): string; rowToString(row: ColumnArray, lines: Line[]): Line[]; // if the full 'source' can render in // the target line, do so. private renderInline; private rasterize; private negatePadding; private columnWidths; } declare function ui(opts: UIOptions): UI; export { ui as default }; 'use strict'; const align = { right: alignRight, center: alignCenter }; const top = 0; const right = 1; const bottom = 2; const left = 3; export class UI { constructor(opts) { var _a; this.width = opts.width; /* c8 ignore start */ this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; /* c8 ignore stop */ this.rows = []; } span(...args) { const cols = this.div(...args); cols.span = true; } resetOutput() { this.rows = []; } div(...args) { if (args.length === 0) { this.div(''); } if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { return this.applyLayoutDSL(args[0]); } const cols = args.map(arg => { if (typeof arg === 'string') { return this.colFromString(arg); } return arg; }); this.rows.push(cols); return cols; } shouldApplyLayoutDSL(...args) { return args.length === 1 && typeof args[0] === 'string' && /[\t\n]/.test(args[0]); } applyLayoutDSL(str) { const rows = str.split('\n').map(row => row.split('\t')); let leftColumnWidth = 0; // simple heuristic for layout, make sure the // second column lines up along the left-hand. // don't allow the first column to take up more // than 50% of the screen. rows.forEach(columns => { if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); } }); // generate a table: // replacing ' ' with padding calculations. // using the algorithmically generated width. rows.forEach(columns => { this.div(...columns.map((r, i) => { return { text: r.trim(), padding: this.measurePadding(r), width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined }; })); }); return this.rows[this.rows.length - 1]; } colFromString(text) { return { text, padding: this.measurePadding(text) }; } measurePadding(str) { // measure padding without ansi escape codes const noAnsi = mixin.stripAnsi(str); return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; } toString() { const lines = []; this.rows.forEach(row => { this.rowToString(row, lines); }); // don't display any lines with the // hidden flag set. return lines .filter(line => !line.hidden) .map(line => line.text) .join('\n'); } rowToString(row, lines) { this.rasterize(row).forEach((rrow, r) => { let str = ''; rrow.forEach((col, c) => { const { width } = row[c]; // the width with padding. const wrapWidth = this.negatePadding(row[c]); // the width without padding. let ts = col; // temporary string used during alignment/padding. if (wrapWidth > mixin.stringWidth(col)) { ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); } // align the string within its column. if (row[c].align && row[c].align !== 'left' && this.wrap) { const fn = align[row[c].align]; ts = fn(ts, wrapWidth); if (mixin.stringWidth(ts) < wrapWidth) { /* c8 ignore start */ const w = width || 0; /* c8 ignore stop */ ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); } } // apply border and padding to string. const padding = row[c].padding || [0, 0, 0, 0]; if (padding[left]) { str += ' '.repeat(padding[left]); } str += addBorder(row[c], ts, '| '); str += ts; str += addBorder(row[c], ts, ' |'); if (padding[right]) { str += ' '.repeat(padding[right]); } // if prior row is span, try to render the // current row on the prior line. if (r === 0 && lines.length > 0) { str = this.renderInline(str, lines[lines.length - 1]); } }); // remove trailing whitespace. lines.push({ text: str.replace(/ +$/, ''), span: row.span }); }); return lines; } // if the full 'source' can render in // the target line, do so. renderInline(source, previousLine) { const match = source.match(/^ */); /* c8 ignore start */ const leadingWhitespace = match ? match[0].length : 0; /* c8 ignore stop */ const target = previousLine.text; const targetTextWidth = mixin.stringWidth(target.trimEnd()); if (!previousLine.span) { return source; } // if we're not applying wrapping logic, // just always append to the span. if (!this.wrap) { previousLine.hidden = true; return target + source; } if (leadingWhitespace < targetTextWidth) { return source; } previousLine.hidden = true; return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); } rasterize(row) { const rrows = []; const widths = this.columnWidths(row); let wrapped; // word wrap all columns, and create // a data-structure that is easy to rasterize. row.forEach((col, c) => { // leave room for left and right padding. col.width = widths[c]; if (this.wrap) { wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); } else { wrapped = col.text.split('\n'); } if (col.border) { wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); } // add top and bottom padding. if (col.padding) { wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); } wrapped.forEach((str, r) => { if (!rrows[r]) { rrows.push([]); } const rrow = rrows[r]; for (let i = 0; i < c; i++) { if (rrow[i] === undefined) { rrow.push(''); } } rrow.push(str); }); }); return rrows; } negatePadding(col) { /* c8 ignore start */ let wrapWidth = col.width || 0; /* c8 ignore stop */ if (col.padding) { wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); } if (col.border) { wrapWidth -= 4; } return wrapWidth; } columnWidths(row) { if (!this.wrap) { return row.map(col => { return col.width || mixin.stringWidth(col.text); }); } let unset = row.length; let remainingWidth = this.width; // column widths can be set in config. const widths = row.map(col => { if (col.width) { unset--; remainingWidth -= col.width; return col.width; } return undefined; }); // any unset widths should be calculated. /* c8 ignore start */ const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; /* c8 ignore stop */ return widths.map((w, i) => { if (w === undefined) { return Math.max(unsetWidth, _minWidth(row[i])); } return w; }); } } function addBorder(col, ts, style) { if (col.border) { if (/[.']-+[.']/.test(ts)) { return ''; } if (ts.trim().length !== 0) { return style; } return ' '; } return ''; } // calculates the minimum width of // a column, based on padding preferences. function _minWidth(col) { const padding = col.padding || []; const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); if (col.border) { return minWidth + 4; } return minWidth; } function getWindowWidth() { /* c8 ignore start */ if (typeof process === 'object' && process.stdout && process.stdout.columns) { return process.stdout.columns; } return 80; } /* c8 ignore stop */ function alignRight(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); if (strWidth < width) { return ' '.repeat(width - strWidth) + str; } return str; } function alignCenter(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); /* c8 ignore start */ if (strWidth >= width) { return str; } /* c8 ignore stop */ return ' '.repeat((width - strWidth) >> 1) + str; } let mixin; export function cliui(opts, _mixin) { mixin = _mixin; return new UI({ /* c8 ignore start */ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), wrap: opts === null || opts === void 0 ? void 0 : opts.wrap /* c8 ignore stop */ }); } // Bootstrap cliui with ESM dependencies: import { cliui } from './build/lib/index.js' import stringWidth from 'string-width' import stripAnsi from 'strip-ansi' import wrap from 'wrap-ansi' export default function ui (opts) { return cliui(opts, { stringWidth, stripAnsi, wrap }) } export default function ansiRegex({onlyFirst = false} = {}) { // Valid string terminator sequences are BEL, ESC\, and 0x9c const ST = '(?:\\u0007|\\u001B\\u005C|\\u009C)'; const pattern = [ `[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?${ST})`, '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))', ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); } MIT License Copyright (c) Sindre Sorhus (https://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. { "name": "ansi-regex", "version": "6.1.0", "description": "Regular expression for matching ANSI escape codes", "license": "MIT", "repository": "chalk/ansi-regex", "funding": "https://github.com/chalk/ansi-regex?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "types": "./index.d.ts", "sideEffects": false, "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "devDependencies": { "ansi-escapes": "^5.0.0", "ava": "^3.15.0", "tsd": "^0.21.0", "xo": "^0.54.2" } } Copyright Mathias Bynens 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. "use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]/g; }; "use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F9D1}(?:\u200D(?:\u{1F91D}\u200D\u{1F9D1}|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-\u{1F6CF}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6F0}\u{1F6F3}])\uFE0F|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}\u200D\u{1F466}|\u{1F635}\u200D\u{1F4AB}|\u{1F62E}\u200D\u{1F4A8}|\u{1F415}\u200D\u{1F9BA}|\u{1F9D1}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F469}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F1FD}\u{1F1F0}|\u{1F1F6}\u{1F1E6}|\u{1F1F4}\u{1F1F2}|\u{1F408}\u200D\u2B1B|\u2764\uFE0F\u200D[\u{1F525}\u{1FA79}]|\u{1F441}\uFE0F|\u{1F3F3}\uFE0F|\u{1F1FF}[\u{1F1E6}\u{1F1F2}\u{1F1FC}]|\u{1F1FE}[\u{1F1EA}\u{1F1F9}]|\u{1F1FC}[\u{1F1EB}\u{1F1F8}]|\u{1F1FB}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1EE}\u{1F1F3}\u{1F1FA}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1F8}[\u{1F1E6}-\u{1F1EA}\u{1F1EC}-\u{1F1F4}\u{1F1F7}-\u{1F1F9}\u{1F1FB}\u{1F1FD}-\u{1F1FF}]|\u{1F1F7}[\u{1F1EA}\u{1F1F4}\u{1F1F8}\u{1F1FA}\u{1F1FC}]|\u{1F1F5}[\u{1F1E6}\u{1F1EA}-\u{1F1ED}\u{1F1F0}-\u{1F1F3}\u{1F1F7}-\u{1F1F9}\u{1F1FC}\u{1F1FE}]|\u{1F1F3}[\u{1F1E6}\u{1F1E8}\u{1F1EA}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F4}\u{1F1F5}\u{1F1F7}\u{1F1FA}\u{1F1FF}]|\u{1F1F2}[\u{1F1E6}\u{1F1E8}-\u{1F1ED}\u{1F1F0}-\u{1F1FF}]|\u{1F1F1}[\u{1F1E6}-\u{1F1E8}\u{1F1EE}\u{1F1F0}\u{1F1F7}-\u{1F1FB}\u{1F1FE}]|\u{1F1F0}[\u{1F1EA}\u{1F1EC}-\u{1F1EE}\u{1F1F2}\u{1F1F3}\u{1F1F5}\u{1F1F7}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1ED}[\u{1F1F0}\u{1F1F2}\u{1F1F3}\u{1F1F7}\u{1F1F9}\u{1F1FA}]|\u{1F1EC}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EE}\u{1F1F1}-\u{1F1F3}\u{1F1F5}-\u{1F1FA}\u{1F1FC}\u{1F1FE}]|\u{1F1EB}[\u{1F1EE}-\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1F7}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}-\u{1F1FA}]|\u{1F1E9}[\u{1F1EA}\u{1F1EC}\u{1F1EF}\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1FF}]|\u{1F1E8}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1EE}\u{1F1F0}-\u{1F1F5}\u{1F1F7}\u{1F1FA}-\u{1F1FF}]|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1E6}[\u{1F1E8}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F2}\u{1F1F4}\u{1F1F6}-\u{1F1FA}\u{1F1FC}\u{1F1FD}\u{1F1FF}]|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]/gu; }; "use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F9D1}(?:\u200D(?:\u{1F91D}\u200D\u{1F9D1}|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-\u{1F6CF}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6F0}\u{1F6F3}])\uFE0F|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}\u200D\u{1F466}|\u{1F635}\u200D\u{1F4AB}|\u{1F62E}\u200D\u{1F4A8}|\u{1F415}\u200D\u{1F9BA}|\u{1F9D1}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F469}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F1FD}\u{1F1F0}|\u{1F1F6}\u{1F1E6}|\u{1F1F4}\u{1F1F2}|\u{1F408}\u200D\u2B1B|\u2764\uFE0F\u200D[\u{1F525}\u{1FA79}]|\u{1F441}\uFE0F|\u{1F3F3}\uFE0F|\u{1F1FF}[\u{1F1E6}\u{1F1F2}\u{1F1FC}]|\u{1F1FE}[\u{1F1EA}\u{1F1F9}]|\u{1F1FC}[\u{1F1EB}\u{1F1F8}]|\u{1F1FB}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1EE}\u{1F1F3}\u{1F1FA}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1F8}[\u{1F1E6}-\u{1F1EA}\u{1F1EC}-\u{1F1F4}\u{1F1F7}-\u{1F1F9}\u{1F1FB}\u{1F1FD}-\u{1F1FF}]|\u{1F1F7}[\u{1F1EA}\u{1F1F4}\u{1F1F8}\u{1F1FA}\u{1F1FC}]|\u{1F1F5}[\u{1F1E6}\u{1F1EA}-\u{1F1ED}\u{1F1F0}-\u{1F1F3}\u{1F1F7}-\u{1F1F9}\u{1F1FC}\u{1F1FE}]|\u{1F1F3}[\u{1F1E6}\u{1F1E8}\u{1F1EA}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F4}\u{1F1F5}\u{1F1F7}\u{1F1FA}\u{1F1FF}]|\u{1F1F2}[\u{1F1E6}\u{1F1E8}-\u{1F1ED}\u{1F1F0}-\u{1F1FF}]|\u{1F1F1}[\u{1F1E6}-\u{1F1E8}\u{1F1EE}\u{1F1F0}\u{1F1F7}-\u{1F1FB}\u{1F1FE}]|\u{1F1F0}[\u{1F1EA}\u{1F1EC}-\u{1F1EE}\u{1F1F2}\u{1F1F3}\u{1F1F5}\u{1F1F7}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1ED}[\u{1F1F0}\u{1F1F2}\u{1F1F3}\u{1F1F7}\u{1F1F9}\u{1F1FA}]|\u{1F1EC}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EE}\u{1F1F1}-\u{1F1F3}\u{1F1F5}-\u{1F1FA}\u{1F1FC}\u{1F1FE}]|\u{1F1EB}[\u{1F1EE}-\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1F7}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}-\u{1F1FA}]|\u{1F1E9}[\u{1F1EA}\u{1F1EC}\u{1F1EF}\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1FF}]|\u{1F1E8}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1EE}\u{1F1F0}-\u{1F1F5}\u{1F1F7}\u{1F1FA}-\u{1F1FF}]|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1E6}[\u{1F1E8}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F2}\u{1F1F4}\u{1F1F6}-\u{1F1FA}\u{1F1FC}\u{1F1FD}\u{1F1FF}]|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; "use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F9D1}(?:\u200D(?:\u{1F91D}\u200D\u{1F9D1}|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-\u{1F6CF}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6F0}\u{1F6F3}])\uFE0F|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}\u200D\u{1F466}|\u{1F635}\u200D\u{1F4AB}|\u{1F62E}\u200D\u{1F4A8}|\u{1F415}\u200D\u{1F9BA}|\u{1F9D1}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F469}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F1FD}\u{1F1F0}|\u{1F1F6}\u{1F1E6}|\u{1F1F4}\u{1F1F2}|\u{1F408}\u200D\u2B1B|\u2764\uFE0F\u200D[\u{1F525}\u{1FA79}]|\u{1F441}\uFE0F|\u{1F3F3}\uFE0F|\u{1F1FF}[\u{1F1E6}\u{1F1F2}\u{1F1FC}]|\u{1F1FE}[\u{1F1EA}\u{1F1F9}]|\u{1F1FC}[\u{1F1EB}\u{1F1F8}]|\u{1F1FB}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1EE}\u{1F1F3}\u{1F1FA}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1F8}[\u{1F1E6}-\u{1F1EA}\u{1F1EC}-\u{1F1F4}\u{1F1F7}-\u{1F1F9}\u{1F1FB}\u{1F1FD}-\u{1F1FF}]|\u{1F1F7}[\u{1F1EA}\u{1F1F4}\u{1F1F8}\u{1F1FA}\u{1F1FC}]|\u{1F1F5}[\u{1F1E6}\u{1F1EA}-\u{1F1ED}\u{1F1F0}-\u{1F1F3}\u{1F1F7}-\u{1F1F9}\u{1F1FC}\u{1F1FE}]|\u{1F1F3}[\u{1F1E6}\u{1F1E8}\u{1F1EA}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F4}\u{1F1F5}\u{1F1F7}\u{1F1FA}\u{1F1FF}]|\u{1F1F2}[\u{1F1E6}\u{1F1E8}-\u{1F1ED}\u{1F1F0}-\u{1F1FF}]|\u{1F1F1}[\u{1F1E6}-\u{1F1E8}\u{1F1EE}\u{1F1F0}\u{1F1F7}-\u{1F1FB}\u{1F1FE}]|\u{1F1F0}[\u{1F1EA}\u{1F1EC}-\u{1F1EE}\u{1F1F2}\u{1F1F3}\u{1F1F5}\u{1F1F7}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1ED}[\u{1F1F0}\u{1F1F2}\u{1F1F3}\u{1F1F7}\u{1F1F9}\u{1F1FA}]|\u{1F1EC}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EE}\u{1F1F1}-\u{1F1F3}\u{1F1F5}-\u{1F1FA}\u{1F1FC}\u{1F1FE}]|\u{1F1EB}[\u{1F1EE}-\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1F7}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}-\u{1F1FA}]|\u{1F1E9}[\u{1F1EA}\u{1F1EC}\u{1F1EF}\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1FF}]|\u{1F1E8}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1EE}\u{1F1F0}-\u{1F1F5}\u{1F1F7}\u{1F1FA}-\u{1F1FF}]|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1E6}[\u{1F1E8}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F2}\u{1F1F4}\u{1F1F6}-\u{1F1FA}\u{1F1FC}\u{1F1FD}\u{1F1FF}]|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]\uFE0F?/gu; }; "use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; { "name": "emoji-regex", "version": "9.2.2", "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", "homepage": "https://mths.be/emoji-regex", "main": "index.js", "types": "index.d.ts", "keywords": [ "unicode", "regex", "regexp", "regular expressions", "code points", "symbols", "characters", "emoji" ], "license": "MIT", "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "repository": { "type": "git", "url": "https://github.com/mathiasbynens/emoji-regex.git" }, "bugs": "https://github.com/mathiasbynens/emoji-regex/issues", "files": [ "LICENSE-MIT.txt", "index.js", "index.d.ts", "RGI_Emoji.js", "RGI_Emoji.d.ts", "text.js", "text.d.ts", "es2015" ], "scripts": { "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src es2015_types -D -d ./es2015; node script/inject-sequences.js", "test": "mocha", "test:watch": "npm run test -- --watch" }, "devDependencies": { "@babel/cli": "^7.4.4", "@babel/core": "^7.4.4", "@babel/plugin-proposal-unicode-property-regex": "^7.4.4", "@babel/preset-env": "^7.4.4", "@unicode/unicode-13.0.0": "^1.0.3", "mocha": "^6.1.4", "regexgen": "^1.3.0" } } "use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F?/g; }; import stripAnsi from 'strip-ansi'; import eastAsianWidth from 'eastasianwidth'; import emojiRegex from 'emoji-regex'; export default function stringWidth(string, options = {}) { if (typeof string !== 'string' || string.length === 0) { return 0; } options = { ambiguousIsNarrow: true, ...options }; string = stripAnsi(string); if (string.length === 0) { return 0; } string = string.replace(emojiRegex(), ' '); const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2; let width = 0; for (const character of string) { const codePoint = character.codePointAt(0); // Ignore control characters if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { continue; } // Ignore combining characters if (codePoint >= 0x300 && codePoint <= 0x36F) { continue; } const code = eastAsianWidth.eastAsianWidth(character); switch (code) { case 'F': case 'W': width += 2; break; case 'A': width += ambiguousCharacterWidth; break; default: width += 1; } } return width; } MIT License Copyright (c) Sindre Sorhus (https://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. { "name": "string-width", "version": "5.1.2", "description": "Get the visual width of a string - the number of columns required to display it", "license": "MIT", "repository": "sindresorhus/string-width", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "string", "character", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width" ], "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" }, "devDependencies": { "ava": "^3.15.0", "tsd": "^0.14.0", "xo": "^0.38.2" } } import ansiRegex from 'ansi-regex'; const regex = ansiRegex(); export default function stripAnsi(string) { if (typeof string !== 'string') { throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); } // Even though the regex is global, we don't need to reset the `.lastIndex` // because unlike `.exec()` and `.test()`, `.replace()` does it automatically // and doing it manually has a performance penalty. return string.replace(regex, ''); } MIT License Copyright (c) Sindre Sorhus (https://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. { "name": "strip-ansi", "version": "7.1.0", "description": "Strip ANSI escape codes from a string", "license": "MIT", "repository": "chalk/strip-ansi", "funding": "https://github.com/chalk/strip-ansi?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "strip", "trim", "remove", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "dependencies": { "ansi-regex": "^6.0.1" }, "devDependencies": { "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" } } { "name": "@isaacs/cliui", "version": "8.0.2", "description": "easily create complex multi-column command-line-interfaces", "main": "build/index.cjs", "exports": { ".": [ { "import": "./index.mjs", "require": "./build/index.cjs" }, "./build/index.cjs" ] }, "type": "module", "module": "./index.mjs", "scripts": { "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", "test": "c8 mocha ./test/*.cjs", "test:esm": "c8 mocha ./test/**/*.mjs", "postest": "check", "coverage": "c8 report --check-coverage", "precompile": "rimraf build", "compile": "tsc", "postcompile": "npm run build:cjs", "build:cjs": "rollup -c", "prepare": "npm run compile" }, "repository": "yargs/cliui", "standard": { "ignore": [ "**/example/**" ], "globals": [ "it" ] }, "keywords": [ "cli", "command-line", "layout", "design", "console", "wrap", "table" ], "author": "Ben Coe ", "license": "ISC", "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" }, "devDependencies": { "@types/node": "^14.0.27", "@typescript-eslint/eslint-plugin": "^4.0.0", "@typescript-eslint/parser": "^4.0.0", "c8": "^7.3.0", "chai": "^4.2.0", "chalk": "^4.1.0", "cross-env": "^7.0.2", "eslint": "^7.6.0", "eslint-plugin-import": "^2.22.0", "eslint-plugin-node": "^11.1.0", "gts": "^3.0.0", "mocha": "^10.0.0", "rimraf": "^3.0.2", "rollup": "^2.23.1", "rollup-plugin-ts": "^3.0.2", "standardx": "^7.0.0", "typescript": "^4.0.0" }, "files": [ "build", "index.mjs", "!*.d.ts" ], "engines": { "node": ">=12" } } The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WriteStreamSync = exports.WriteStream = exports.ReadStreamSync = exports.ReadStream = void 0; const events_1 = __importDefault(require("events")); const fs_1 = __importDefault(require("fs")); const minipass_1 = require("minipass"); const writev = fs_1.default.writev; const _autoClose = Symbol('_autoClose'); const _close = Symbol('_close'); const _ended = Symbol('_ended'); const _fd = Symbol('_fd'); const _finished = Symbol('_finished'); const _flags = Symbol('_flags'); const _flush = Symbol('_flush'); const _handleChunk = Symbol('_handleChunk'); const _makeBuf = Symbol('_makeBuf'); const _mode = Symbol('_mode'); const _needDrain = Symbol('_needDrain'); const _onerror = Symbol('_onerror'); const _onopen = Symbol('_onopen'); const _onread = Symbol('_onread'); const _onwrite = Symbol('_onwrite'); const _open = Symbol('_open'); const _path = Symbol('_path'); const _pos = Symbol('_pos'); const _queue = Symbol('_queue'); const _read = Symbol('_read'); const _readSize = Symbol('_readSize'); const _reading = Symbol('_reading'); const _remain = Symbol('_remain'); const _size = Symbol('_size'); const _write = Symbol('_write'); const _writing = Symbol('_writing'); const _defaultFlag = Symbol('_defaultFlag'); const _errored = Symbol('_errored'); class ReadStream extends minipass_1.Minipass { [_errored] = false; [_fd]; [_path]; [_readSize]; [_reading] = false; [_size]; [_remain]; [_autoClose]; constructor(path, opt) { opt = opt || {}; super(opt); this.readable = true; this.writable = false; if (typeof path !== 'string') { throw new TypeError('path must be a string'); } this[_errored] = false; this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined; this[_path] = path; this[_readSize] = opt.readSize || 16 * 1024 * 1024; this[_reading] = false; this[_size] = typeof opt.size === 'number' ? opt.size : Infinity; this[_remain] = this[_size]; this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true; if (typeof this[_fd] === 'number') { this[_read](); } else { this[_open](); } } get fd() { return this[_fd]; } get path() { return this[_path]; } //@ts-ignore write() { throw new TypeError('this is a readable stream'); } //@ts-ignore end() { throw new TypeError('this is a readable stream'); } [_open]() { fs_1.default.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)); } [_onopen](er, fd) { if (er) { this[_onerror](er); } else { this[_fd] = fd; this.emit('open', fd); this[_read](); } } [_makeBuf]() { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])); } [_read]() { if (!this[_reading]) { this[_reading] = true; const buf = this[_makeBuf](); /* c8 ignore start */ if (buf.length === 0) { return process.nextTick(() => this[_onread](null, 0, buf)); } /* c8 ignore stop */ fs_1.default.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => this[_onread](er, br, b)); } } [_onread](er, br, buf) { this[_reading] = false; if (er) { this[_onerror](er); } else if (this[_handleChunk](br, buf)) { this[_read](); } } [_close]() { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd]; this[_fd] = undefined; fs_1.default.close(fd, er => er ? this.emit('error', er) : this.emit('close')); } } [_onerror](er) { this[_reading] = true; this[_close](); this.emit('error', er); } [_handleChunk](br, buf) { let ret = false; // no effect if infinite this[_remain] -= br; if (br > 0) { ret = super.write(br < buf.length ? buf.subarray(0, br) : buf); } if (br === 0 || this[_remain] <= 0) { ret = false; this[_close](); super.end(); } return ret; } emit(ev, ...args) { switch (ev) { case 'prefinish': case 'finish': return false; case 'drain': if (typeof this[_fd] === 'number') { this[_read](); } return false; case 'error': if (this[_errored]) { return false; } this[_errored] = true; return super.emit(ev, ...args); default: return super.emit(ev, ...args); } } } exports.ReadStream = ReadStream; class ReadStreamSync extends ReadStream { [_open]() { let threw = true; try { this[_onopen](null, fs_1.default.openSync(this[_path], 'r')); threw = false; } finally { if (threw) { this[_close](); } } } [_read]() { let threw = true; try { if (!this[_reading]) { this[_reading] = true; do { const buf = this[_makeBuf](); /* c8 ignore start */ const br = buf.length === 0 ? 0 : fs_1.default.readSync(this[_fd], buf, 0, buf.length, null); /* c8 ignore stop */ if (!this[_handleChunk](br, buf)) { break; } } while (true); this[_reading] = false; } threw = false; } finally { if (threw) { this[_close](); } } } [_close]() { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd]; this[_fd] = undefined; fs_1.default.closeSync(fd); this.emit('close'); } } } exports.ReadStreamSync = ReadStreamSync; class WriteStream extends events_1.default { readable = false; writable = true; [_errored] = false; [_writing] = false; [_ended] = false; [_queue] = []; [_needDrain] = false; [_path]; [_mode]; [_autoClose]; [_fd]; [_defaultFlag]; [_flags]; [_finished] = false; [_pos]; constructor(path, opt) { opt = opt || {}; super(opt); this[_path] = path; this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined; this[_mode] = opt.mode === undefined ? 0o666 : opt.mode; this[_pos] = typeof opt.start === 'number' ? opt.start : undefined; this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true; // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== undefined ? 'r+' : 'w'; this[_defaultFlag] = opt.flags === undefined; this[_flags] = opt.flags === undefined ? defaultFlag : opt.flags; if (this[_fd] === undefined) { this[_open](); } } emit(ev, ...args) { if (ev === 'error') { if (this[_errored]) { return false; } this[_errored] = true; } return super.emit(ev, ...args); } get fd() { return this[_fd]; } get path() { return this[_path]; } [_onerror](er) { this[_close](); this[_writing] = true; this.emit('error', er); } [_open]() { fs_1.default.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)); } [_onopen](er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w'; this[_open](); } else if (er) { this[_onerror](er); } else { this[_fd] = fd; this.emit('open', fd); if (!this[_writing]) { this[_flush](); } } } end(buf, enc) { if (buf) { //@ts-ignore this.write(buf, enc); } this[_ended] = true; // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') { this[_onwrite](null, 0); } return this; } write(buf, enc) { if (typeof buf === 'string') { buf = Buffer.from(buf, enc); } if (this[_ended]) { this.emit('error', new Error('write() after end()')); return false; } if (this[_fd] === undefined || this[_writing] || this[_queue].length) { this[_queue].push(buf); this[_needDrain] = true; return false; } this[_writing] = true; this[_write](buf); return true; } [_write](buf) { fs_1.default.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)); } [_onwrite](er, bw) { if (er) { this[_onerror](er); } else { if (this[_pos] !== undefined && typeof bw === 'number') { this[_pos] += bw; } if (this[_queue].length) { this[_flush](); } else { this[_writing] = false; if (this[_ended] && !this[_finished]) { this[_finished] = true; this[_close](); this.emit('finish'); } else if (this[_needDrain]) { this[_needDrain] = false; this.emit('drain'); } } } } [_flush]() { if (this[_queue].length === 0) { if (this[_ended]) { this[_onwrite](null, 0); } } else if (this[_queue].length === 1) { this[_write](this[_queue].pop()); } else { const iovec = this[_queue]; this[_queue] = []; writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)); } } [_close]() { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd]; this[_fd] = undefined; fs_1.default.close(fd, er => er ? this.emit('error', er) : this.emit('close')); } } } exports.WriteStream = WriteStream; class WriteStreamSync extends WriteStream { [_open]() { let fd; // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs_1.default.openSync(this[_path], this[_flags], this[_mode]); } catch (er) { if (er?.code === 'ENOENT') { this[_flags] = 'w'; return this[_open](); } else { throw er; } } } else { fd = fs_1.default.openSync(this[_path], this[_flags], this[_mode]); } this[_onopen](null, fd); } [_close]() { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd]; this[_fd] = undefined; fs_1.default.closeSync(fd); this.emit('close'); } } [_write](buf) { // throw the original, but try to close if it fails let threw = true; try { this[_onwrite](null, fs_1.default.writeSync(this[_fd], buf, 0, buf.length, this[_pos])); threw = false; } finally { if (threw) { try { this[_close](); } catch { // ok error } } } } } exports.WriteStreamSync = WriteStreamSync; //# sourceMappingURL=index.js.map{ "type": "commonjs" } import EE from 'events'; import fs from 'fs'; import { Minipass } from 'minipass'; const writev = fs.writev; const _autoClose = Symbol('_autoClose'); const _close = Symbol('_close'); const _ended = Symbol('_ended'); const _fd = Symbol('_fd'); const _finished = Symbol('_finished'); const _flags = Symbol('_flags'); const _flush = Symbol('_flush'); const _handleChunk = Symbol('_handleChunk'); const _makeBuf = Symbol('_makeBuf'); const _mode = Symbol('_mode'); const _needDrain = Symbol('_needDrain'); const _onerror = Symbol('_onerror'); const _onopen = Symbol('_onopen'); const _onread = Symbol('_onread'); const _onwrite = Symbol('_onwrite'); const _open = Symbol('_open'); const _path = Symbol('_path'); const _pos = Symbol('_pos'); const _queue = Symbol('_queue'); const _read = Symbol('_read'); const _readSize = Symbol('_readSize'); const _reading = Symbol('_reading'); const _remain = Symbol('_remain'); const _size = Symbol('_size'); const _write = Symbol('_write'); const _writing = Symbol('_writing'); const _defaultFlag = Symbol('_defaultFlag'); const _errored = Symbol('_errored'); export class ReadStream extends Minipass { [_errored] = false; [_fd]; [_path]; [_readSize]; [_reading] = false; [_size]; [_remain]; [_autoClose]; constructor(path, opt) { opt = opt || {}; super(opt); this.readable = true; this.writable = false; if (typeof path !== 'string') { throw new TypeError('path must be a string'); } this[_errored] = false; this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined; this[_path] = path; this[_readSize] = opt.readSize || 16 * 1024 * 1024; this[_reading] = false; this[_size] = typeof opt.size === 'number' ? opt.size : Infinity; this[_remain] = this[_size]; this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true; if (typeof this[_fd] === 'number') { this[_read](); } else { this[_open](); } } get fd() { return this[_fd]; } get path() { return this[_path]; } //@ts-ignore write() { throw new TypeError('this is a readable stream'); } //@ts-ignore end() { throw new TypeError('this is a readable stream'); } [_open]() { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)); } [_onopen](er, fd) { if (er) { this[_onerror](er); } else { this[_fd] = fd; this.emit('open', fd); this[_read](); } } [_makeBuf]() { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])); } [_read]() { if (!this[_reading]) { this[_reading] = true; const buf = this[_makeBuf](); /* c8 ignore start */ if (buf.length === 0) { return process.nextTick(() => this[_onread](null, 0, buf)); } /* c8 ignore stop */ fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => this[_onread](er, br, b)); } } [_onread](er, br, buf) { this[_reading] = false; if (er) { this[_onerror](er); } else if (this[_handleChunk](br, buf)) { this[_read](); } } [_close]() { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd]; this[_fd] = undefined; fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')); } } [_onerror](er) { this[_reading] = true; this[_close](); this.emit('error', er); } [_handleChunk](br, buf) { let ret = false; // no effect if infinite this[_remain] -= br; if (br > 0) { ret = super.write(br < buf.length ? buf.subarray(0, br) : buf); } if (br === 0 || this[_remain] <= 0) { ret = false; this[_close](); super.end(); } return ret; } emit(ev, ...args) { switch (ev) { case 'prefinish': case 'finish': return false; case 'drain': if (typeof this[_fd] === 'number') { this[_read](); } return false; case 'error': if (this[_errored]) { return false; } this[_errored] = true; return super.emit(ev, ...args); default: return super.emit(ev, ...args); } } } export class ReadStreamSync extends ReadStream { [_open]() { let threw = true; try { this[_onopen](null, fs.openSync(this[_path], 'r')); threw = false; } finally { if (threw) { this[_close](); } } } [_read]() { let threw = true; try { if (!this[_reading]) { this[_reading] = true; do { const buf = this[_makeBuf](); /* c8 ignore start */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null); /* c8 ignore stop */ if (!this[_handleChunk](br, buf)) { break; } } while (true); this[_reading] = false; } threw = false; } finally { if (threw) { this[_close](); } } } [_close]() { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd]; this[_fd] = undefined; fs.closeSync(fd); this.emit('close'); } } } export class WriteStream extends EE { readable = false; writable = true; [_errored] = false; [_writing] = false; [_ended] = false; [_queue] = []; [_needDrain] = false; [_path]; [_mode]; [_autoClose]; [_fd]; [_defaultFlag]; [_flags]; [_finished] = false; [_pos]; constructor(path, opt) { opt = opt || {}; super(opt); this[_path] = path; this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined; this[_mode] = opt.mode === undefined ? 0o666 : opt.mode; this[_pos] = typeof opt.start === 'number' ? opt.start : undefined; this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true; // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== undefined ? 'r+' : 'w'; this[_defaultFlag] = opt.flags === undefined; this[_flags] = opt.flags === undefined ? defaultFlag : opt.flags; if (this[_fd] === undefined) { this[_open](); } } emit(ev, ...args) { if (ev === 'error') { if (this[_errored]) { return false; } this[_errored] = true; } return super.emit(ev, ...args); } get fd() { return this[_fd]; } get path() { return this[_path]; } [_onerror](er) { this[_close](); this[_writing] = true; this.emit('error', er); } [_open]() { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)); } [_onopen](er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w'; this[_open](); } else if (er) { this[_onerror](er); } else { this[_fd] = fd; this.emit('open', fd); if (!this[_writing]) { this[_flush](); } } } end(buf, enc) { if (buf) { //@ts-ignore this.write(buf, enc); } this[_ended] = true; // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') { this[_onwrite](null, 0); } return this; } write(buf, enc) { if (typeof buf === 'string') { buf = Buffer.from(buf, enc); } if (this[_ended]) { this.emit('error', new Error('write() after end()')); return false; } if (this[_fd] === undefined || this[_writing] || this[_queue].length) { this[_queue].push(buf); this[_needDrain] = true; return false; } this[_writing] = true; this[_write](buf); return true; } [_write](buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)); } [_onwrite](er, bw) { if (er) { this[_onerror](er); } else { if (this[_pos] !== undefined && typeof bw === 'number') { this[_pos] += bw; } if (this[_queue].length) { this[_flush](); } else { this[_writing] = false; if (this[_ended] && !this[_finished]) { this[_finished] = true; this[_close](); this.emit('finish'); } else if (this[_needDrain]) { this[_needDrain] = false; this.emit('drain'); } } } } [_flush]() { if (this[_queue].length === 0) { if (this[_ended]) { this[_onwrite](null, 0); } } else if (this[_queue].length === 1) { this[_write](this[_queue].pop()); } else { const iovec = this[_queue]; this[_queue] = []; writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)); } } [_close]() { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd]; this[_fd] = undefined; fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')); } } } export class WriteStreamSync extends WriteStream { [_open]() { let fd; // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs.openSync(this[_path], this[_flags], this[_mode]); } catch (er) { if (er?.code === 'ENOENT') { this[_flags] = 'w'; return this[_open](); } else { throw er; } } } else { fd = fs.openSync(this[_path], this[_flags], this[_mode]); } this[_onopen](null, fd); } [_close]() { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd]; this[_fd] = undefined; fs.closeSync(fd); this.emit('close'); } } [_write](buf) { // throw the original, but try to close if it fails let threw = true; try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])); threw = false; } finally { if (threw) { try { this[_close](); } catch { // ok error } } } } } //# sourceMappingURL=index.js.map{ "type": "module" } { "name": "@isaacs/fs-minipass", "version": "4.0.1", "main": "./dist/commonjs/index.js", "scripts": { "prepare": "tshy", "pretest": "npm run prepare", "test": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "format": "prettier --write . --loglevel warn", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "keywords": [], "author": "Isaac Z. Schlueter", "license": "ISC", "repository": { "type": "git", "url": "https://github.com/npm/fs-minipass.git" }, "description": "fs read and write streams based on minipass", "dependencies": { "minipass": "^7.0.4" }, "devDependencies": { "@types/node": "^20.11.30", "mutate-fs": "^2.1.1", "prettier": "^3.2.5", "tap": "^18.7.1", "tshy": "^1.12.0", "typedoc": "^0.25.12" }, "files": [ "dist" ], "engines": { "node": ">=18.0.0" }, "tshy": { "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "types": "./dist/commonjs/index.d.ts", "type": "module", "prettier": { "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" } } The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const hasIntl = typeof Intl === 'object' && !!Intl const Collator = hasIntl && Intl.Collator const cache = new Map() const collatorCompare = (locale, opts) => { const collator = new Collator(locale, opts) return (a, b) => collator.compare(a, b) } const localeCompare = (locale, opts) => (a, b) => a.localeCompare(b, locale, opts) const knownOptions = [ 'sensitivity', 'numeric', 'ignorePunctuation', 'caseFirst', ] const { hasOwnProperty } = Object.prototype module.exports = (locale, options = {}) => { if (!locale || typeof locale !== 'string') throw new TypeError('locale required') const opts = knownOptions.reduce((opts, k) => { if (hasOwnProperty.call(options, k)) { opts[k] = options[k] } return opts }, {}) const key = `${locale}\n${JSON.stringify(opts)}` if (cache.has(key)) return cache.get(key) const compare = hasIntl ? collatorCompare(locale, opts) : localeCompare(locale, opts) cache.set(key, compare) return compare } { "name": "@isaacs/string-locale-compare", "version": "1.1.0", "files": [ "index.js" ], "main": "index.js", "description": "Compare strings with Intl.Collator if available, falling back to String.localeCompare otherwise", "repository": { "type": "git", "url": "git+https://github.com/isaacs/string-locale-compare" }, "author": "Isaac Z. Schlueter (https://izs.me)", "license": "ISC", "scripts": { "test": "tap", "snap": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags" }, "tap": { "check-coverage": true }, "devDependencies": { "tap": "^15.0.9" } } 'use strict' const net = require('net') const tls = require('tls') const { once } = require('events') const timers = require('timers/promises') const { normalizeOptions, cacheOptions } = require('./options') const { getProxy, getProxyAgent, proxyCache } = require('./proxy.js') const Errors = require('./errors.js') const { Agent: AgentBase } = require('agent-base') module.exports = class Agent extends AgentBase { #options #timeouts #proxy #noProxy #ProxyAgent constructor (options = {}) { const { timeouts, proxy, noProxy, ...normalizedOptions } = normalizeOptions(options) super(normalizedOptions) this.#options = normalizedOptions this.#timeouts = timeouts if (proxy) { this.#proxy = new URL(proxy) this.#noProxy = noProxy this.#ProxyAgent = getProxyAgent(proxy) } } get proxy () { return this.#proxy ? { url: this.#proxy } : {} } #getProxy (options) { if (!this.#proxy) { return } const proxy = getProxy(`${options.protocol}//${options.host}:${options.port}`, { proxy: this.#proxy, noProxy: this.#noProxy, }) if (!proxy) { return } const cacheKey = cacheOptions({ ...options, ...this.#options, timeouts: this.#timeouts, proxy, }) if (proxyCache.has(cacheKey)) { return proxyCache.get(cacheKey) } let ProxyAgent = this.#ProxyAgent if (Array.isArray(ProxyAgent)) { ProxyAgent = this.isSecureEndpoint(options) ? ProxyAgent[1] : ProxyAgent[0] } const proxyAgent = new ProxyAgent(proxy, { ...this.#options, socketOptions: { family: this.#options.family }, }) proxyCache.set(cacheKey, proxyAgent) return proxyAgent } // takes an array of promises and races them against the connection timeout // which will throw the necessary error if it is hit. This will return the // result of the promise race. async #timeoutConnection ({ promises, options, timeout }, ac = new AbortController()) { if (timeout) { const connectionTimeout = timers.setTimeout(timeout, null, { signal: ac.signal }) .then(() => { throw new Errors.ConnectionTimeoutError(`${options.host}:${options.port}`) }).catch((err) => { if (err.name === 'AbortError') { return } throw err }) promises.push(connectionTimeout) } let result try { result = await Promise.race(promises) ac.abort() } catch (err) { ac.abort() throw err } return result } async connect (request, options) { // if the connection does not have its own lookup function // set, then use the one from our options options.lookup ??= this.#options.lookup let socket let timeout = this.#timeouts.connection const isSecureEndpoint = this.isSecureEndpoint(options) const proxy = this.#getProxy(options) if (proxy) { // some of the proxies will wait for the socket to fully connect before // returning so we have to await this while also racing it against the // connection timeout. const start = Date.now() socket = await this.#timeoutConnection({ options, timeout, promises: [proxy.connect(request, options)], }) // see how much time proxy.connect took and subtract it from // the timeout if (timeout) { timeout = timeout - (Date.now() - start) } } else { socket = (isSecureEndpoint ? tls : net).connect(options) } socket.setKeepAlive(this.keepAlive, this.keepAliveMsecs) socket.setNoDelay(this.keepAlive) const abortController = new AbortController() const { signal } = abortController const connectPromise = socket[isSecureEndpoint ? 'secureConnecting' : 'connecting'] ? once(socket, isSecureEndpoint ? 'secureConnect' : 'connect', { signal }) : Promise.resolve() await this.#timeoutConnection({ options, timeout, promises: [ connectPromise, once(socket, 'error', { signal }).then((err) => { throw err[0] }), ], }, abortController) if (this.#timeouts.idle) { socket.setTimeout(this.#timeouts.idle, () => { socket.destroy(new Errors.IdleTimeoutError(`${options.host}:${options.port}`)) }) } return socket } addRequest (request, options) { const proxy = this.#getProxy(options) // it would be better to call proxy.addRequest here but this causes the // http-proxy-agent to call its super.addRequest which causes the request // to be added to the agent twice. since we only support 3 agents // currently (see the required agents in proxy.js) we have manually // checked that the only public methods we need to call are called in the // next block. this could change in the future and presumably we would get // failing tests until we have properly called the necessary methods on // each of our proxy agents if (proxy?.setRequestProps) { proxy.setRequestProps(request, options) } request.setHeader('connection', this.keepAlive ? 'keep-alive' : 'close') if (this.#timeouts.response) { let responseTimeout request.once('finish', () => { setTimeout(() => { request.destroy(new Errors.ResponseTimeoutError(request, this.#proxy)) }, this.#timeouts.response) }) request.once('response', () => { clearTimeout(responseTimeout) }) } if (this.#timeouts.transfer) { let transferTimeout request.once('response', (res) => { setTimeout(() => { res.destroy(new Errors.TransferTimeoutError(request, this.#proxy)) }, this.#timeouts.transfer) res.once('close', () => { clearTimeout(transferTimeout) }) }) } return super.addRequest(request, options) } } 'use strict' const { LRUCache } = require('lru-cache') const dns = require('dns') // this is a factory so that each request can have its own opts (i.e. ttl) // while still sharing the cache across all requests const cache = new LRUCache({ max: 50 }) const getOptions = ({ family = 0, hints = dns.ADDRCONFIG, all = false, verbatim = undefined, ttl = 5 * 60 * 1000, lookup = dns.lookup, }) => ({ // hints and lookup are returned since both are top level properties to (net|tls).connect hints, lookup: (hostname, ...args) => { const callback = args.pop() // callback is always last arg const lookupOptions = args[0] ?? {} const options = { family, hints, all, verbatim, ...(typeof lookupOptions === 'number' ? { family: lookupOptions } : lookupOptions), } const key = JSON.stringify({ hostname, ...options }) if (cache.has(key)) { const cached = cache.get(key) return process.nextTick(callback, null, ...cached) } lookup(hostname, options, (err, ...result) => { if (err) { return callback(err) } cache.set(key, result, { ttl }) return callback(null, ...result) }) }, }) module.exports = { cache, getOptions, } 'use strict' class InvalidProxyProtocolError extends Error { constructor (url) { super(`Invalid protocol \`${url.protocol}\` connecting to proxy \`${url.host}\``) this.code = 'EINVALIDPROXY' this.proxy = url } } class ConnectionTimeoutError extends Error { constructor (host) { super(`Timeout connecting to host \`${host}\``) this.code = 'ECONNECTIONTIMEOUT' this.host = host } } class IdleTimeoutError extends Error { constructor (host) { super(`Idle timeout reached for host \`${host}\``) this.code = 'EIDLETIMEOUT' this.host = host } } class ResponseTimeoutError extends Error { constructor (request, proxy) { let msg = 'Response timeout ' if (proxy) { msg += `from proxy \`${proxy.host}\` ` } msg += `connecting to host \`${request.host}\`` super(msg) this.code = 'ERESPONSETIMEOUT' this.proxy = proxy this.request = request } } class TransferTimeoutError extends Error { constructor (request, proxy) { let msg = 'Transfer timeout ' if (proxy) { msg += `from proxy \`${proxy.host}\` ` } msg += `for \`${request.host}\`` super(msg) this.code = 'ETRANSFERTIMEOUT' this.proxy = proxy this.request = request } } module.exports = { InvalidProxyProtocolError, ConnectionTimeoutError, IdleTimeoutError, ResponseTimeoutError, TransferTimeoutError, } 'use strict' const { LRUCache } = require('lru-cache') const { normalizeOptions, cacheOptions } = require('./options') const { getProxy, proxyCache } = require('./proxy.js') const dns = require('./dns.js') const Agent = require('./agents.js') const agentCache = new LRUCache({ max: 20 }) const getAgent = (url, { agent, proxy, noProxy, ...options } = {}) => { // false has meaning so this can't be a simple truthiness check if (agent != null) { return agent } url = new URL(url) const proxyForUrl = getProxy(url, { proxy, noProxy }) const normalizedOptions = { ...normalizeOptions(options), proxy: proxyForUrl, } const cacheKey = cacheOptions({ ...normalizedOptions, secureEndpoint: url.protocol === 'https:', }) if (agentCache.has(cacheKey)) { return agentCache.get(cacheKey) } const newAgent = new Agent(normalizedOptions) agentCache.set(cacheKey, newAgent) return newAgent } module.exports = { getAgent, Agent, // these are exported for backwards compatability HttpAgent: Agent, HttpsAgent: Agent, cache: { proxy: proxyCache, agent: agentCache, dns: dns.cache, clear: () => { proxyCache.clear() agentCache.clear() dns.cache.clear() }, }, } 'use strict' const dns = require('./dns') const normalizeOptions = (opts) => { const family = parseInt(opts.family ?? '0', 10) const keepAlive = opts.keepAlive ?? true const normalized = { // nodejs http agent options. these are all the defaults // but kept here to increase the likelihood of cache hits // https://nodejs.org/api/http.html#new-agentoptions keepAliveMsecs: keepAlive ? 1000 : undefined, maxSockets: opts.maxSockets ?? 15, maxTotalSockets: Infinity, maxFreeSockets: keepAlive ? 256 : undefined, scheduling: 'fifo', // then spread the rest of the options ...opts, // we already set these to their defaults that we want family, keepAlive, // our custom timeout options timeouts: { // the standard timeout option is mapped to our idle timeout // and then deleted below idle: opts.timeout ?? 0, connection: 0, response: 0, transfer: 0, ...opts.timeouts, }, // get the dns options that go at the top level of socket connection ...dns.getOptions({ family, ...opts.dns }), } // remove timeout since we already used it to set our own idle timeout delete normalized.timeout return normalized } const createKey = (obj) => { let key = '' const sorted = Object.entries(obj).sort((a, b) => a[0] - b[0]) for (let [k, v] of sorted) { if (v == null) { v = 'null' } else if (v instanceof URL) { v = v.toString() } else if (typeof v === 'object') { v = createKey(v) } key += `${k}:${v}:` } return key } const cacheOptions = ({ secureEndpoint, ...options }) => createKey({ secureEndpoint: !!secureEndpoint, // socket connect options family: options.family, hints: options.hints, localAddress: options.localAddress, // tls specific connect options strictSsl: secureEndpoint ? !!options.rejectUnauthorized : false, ca: secureEndpoint ? options.ca : null, cert: secureEndpoint ? options.cert : null, key: secureEndpoint ? options.key : null, // http agent options keepAlive: options.keepAlive, keepAliveMsecs: options.keepAliveMsecs, maxSockets: options.maxSockets, maxTotalSockets: options.maxTotalSockets, maxFreeSockets: options.maxFreeSockets, scheduling: options.scheduling, // timeout options timeouts: options.timeouts, // proxy proxy: options.proxy, }) module.exports = { normalizeOptions, cacheOptions, } 'use strict' const { HttpProxyAgent } = require('http-proxy-agent') const { HttpsProxyAgent } = require('https-proxy-agent') const { SocksProxyAgent } = require('socks-proxy-agent') const { LRUCache } = require('lru-cache') const { InvalidProxyProtocolError } = require('./errors.js') const PROXY_CACHE = new LRUCache({ max: 20 }) const SOCKS_PROTOCOLS = new Set(SocksProxyAgent.protocols) const PROXY_ENV_KEYS = new Set(['https_proxy', 'http_proxy', 'proxy', 'no_proxy']) const PROXY_ENV = Object.entries(process.env).reduce((acc, [key, value]) => { key = key.toLowerCase() if (PROXY_ENV_KEYS.has(key)) { acc[key] = value } return acc }, {}) const getProxyAgent = (url) => { url = new URL(url) const protocol = url.protocol.slice(0, -1) if (SOCKS_PROTOCOLS.has(protocol)) { return SocksProxyAgent } if (protocol === 'https' || protocol === 'http') { return [HttpProxyAgent, HttpsProxyAgent] } throw new InvalidProxyProtocolError(url) } const isNoProxy = (url, noProxy) => { if (typeof noProxy === 'string') { noProxy = noProxy.split(',').map((p) => p.trim()).filter(Boolean) } if (!noProxy || !noProxy.length) { return false } const hostSegments = url.hostname.split('.').reverse() return noProxy.some((no) => { const noSegments = no.split('.').filter(Boolean).reverse() if (!noSegments.length) { return false } for (let i = 0; i < noSegments.length; i++) { if (hostSegments[i] !== noSegments[i]) { return false } } return true }) } const getProxy = (url, { proxy, noProxy }) => { url = new URL(url) if (!proxy) { proxy = url.protocol === 'https:' ? PROXY_ENV.https_proxy : PROXY_ENV.https_proxy || PROXY_ENV.http_proxy || PROXY_ENV.proxy } if (!noProxy) { noProxy = PROXY_ENV.no_proxy } if (!proxy || isNoProxy(url, noProxy)) { return null } return new URL(proxy) } module.exports = { getProxyAgent, getProxy, proxyCache: PROXY_CACHE, } { "name": "@npmcli/agent", "version": "3.0.0", "description": "the http/https agent used by the npm cli", "main": "lib/index.js", "scripts": { "gencerts": "bash scripts/create-cert.sh", "test": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "author": "GitHub Inc.", "license": "ISC", "bugs": { "url": "https://github.com/npm/agent/issues" }, "homepage": "https://github.com/npm/agent#readme", "files": [ "bin/", "lib/" ], "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.1", "publish": "true" }, "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^10.0.1", "socks-proxy-agent": "^8.0.3" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.1", "minipass-fetch": "^3.0.3", "nock": "^13.2.7", "socksv5": "^0.0.6", "tap": "^16.3.0" }, "repository": { "type": "git", "url": "git+https://github.com/npm/agent.git" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # @npmcli/arborist [![npm version](https://img.shields.io/npm/v/@npmcli/arborist.svg)](https://npm.im/@npmcli/arborist) [![license](https://img.shields.io/npm/l/@npmcli/arborist.svg)](https://npm.im/@npmcli/arborist) [![CI - @npmcli/arborist](https://github.com/npm/cli/actions/workflows/ci-npmcli-arborist.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-npmcli-arborist.yml) Inspect and manage `node_modules` trees. ![a tree with the word ARBORIST superimposed on it](https://raw.githubusercontent.com/npm/arborist/main/docs/logo.svg?sanitize=true) There's more documentation [in the docs folder](https://github.com/npm/cli/tree/latest/workspaces/arborist/docs). ## USAGE ```js const Arborist = require('@npmcli/arborist') const arb = new Arborist({ // options object // where we're doing stuff. defaults to cwd. path: '/path/to/package/root', // url to the default registry. defaults to npm's default registry registry: 'https://registry.npmjs.org', // scopes can be mapped to a different registry '@foo:registry': 'https://registry.foo.com/', // Auth can be provided in a couple of different ways. If none are // provided, then requests are anonymous, and private packages will 404. // Arborist doesn't do anything with these, it just passes them down // the chain to pacote and npm-registry-fetch. // Safest: a bearer token provided by a registry: // 1. an npm auth token, used with the default registry token: 'deadbeefcafebad', // 2. an alias for the same thing: _authToken: 'deadbeefcafebad', // insecure options: // 3. basic auth, username:password, base64 encoded auth: 'aXNhYWNzOm5vdCBteSByZWFsIHBhc3N3b3Jk', // 4. username and base64 encoded password username: 'isaacs', password: 'bm90IG15IHJlYWwgcGFzc3dvcmQ=', // auth configs can also be scoped to a given registry with this // rather unusual pattern: '//registry.foo.com:token': 'blahblahblah', '//basic.auth.only.foo.com:_auth': 'aXNhYWNzOm5vdCBteSByZWFsIHBhc3N3b3Jk', '//registry.foo.com:always-auth': true, }) // READING // returns a promise. reads the actual contents of node_modules arb.loadActual().then(tree => { // tree is also stored at arb.virtualTree }) // read just what the package-lock.json/npm-shrinkwrap says // This *also* loads the yarn.lock file, but that's only relevant // when building the ideal tree. arb.loadVirtual().then(tree => { // tree is also stored at arb.virtualTree // now arb.virtualTree is loaded // this fails if there's no package-lock.json or package.json in the folder // note that loading this way should only be done if there's no // node_modules folder }) // OPTIMIZING AND DESIGNING // build an ideal tree from the package.json and various lockfiles. arb.buildIdealTree(options).then(() => { // next step is to reify that ideal tree onto disk. // options can be: // rm: array of package names to remove at top level // add: Array of package specifiers to add at the top level. Each of // these will be resolved with pacote.manifest if the name can't be // determined from the spec. (Eg, `github:foo/bar` vs `foo@somespec`.) // The dep will be saved in the location where it already exists, // (or pkg.dependencies) unless a different saveType is specified. // saveType: Save added packages in a specific dependency set. // - null (default) Wherever they exist already, or 'dependencies' // - prod: definitely in 'dependencies' // - optional: in 'optionalDependencies' // - dev: devDependencies // - peer: save in peerDependencies, and remove any optional flag from // peerDependenciesMeta if one exists // - peerOptional: save in peerDependencies, and add a // peerDepsMeta[name].optional flag // saveBundle: add newly added deps to the bundleDependencies list // update: Either `true` to just go ahead and update everything, or an // object with any or all of the following fields: // - all: boolean. set to true to just update everything // - names: names of packages update (like `npm update foo`) // prune: boolean, default true. Prune extraneous nodes from the tree. // preferDedupe: prefer to deduplicate packages if possible, rather than // choosing a newer version of a dependency. Defaults to false, ie, // always try to get the latest and greatest deps. // legacyBundling: Nest every dep under the node requiring it, npm v2 style. // No unnecessary deduplication. Default false. // At the end of this process, arb.idealTree is set. }) // WRITING // Make the idealTree be the thing that's on disk arb.reify({ // write the lockfile(s) back to disk, and package.json with any updates // defaults to 'true' save: true, }).then(() => { // node modules has been written to match the idealTree }) ``` ## DATA STRUCTURES A `node_modules` tree is a logical graph of dependencies overlaid on a physical tree of folders. A `Node` represents a package folder on disk, either at the root of the package, or within a `node_modules` folder. The physical structure of the folder tree is represented by the `node.parent` reference to the containing folder, and `node.children` map of nodes within its `node_modules` folder, where the key in the map is the name of the folder in `node_modules`, and the value is the child node. A node without a parent is a top of tree. A `Link` represents a symbolic link to a package on disk. This can be a symbolic link to a package folder within the current tree, or elsewhere on disk. The `link.target` is a reference to the actual node. Links differ from Nodes in that dependencies are resolved from the _target_ location, rather than from the link location. An `Edge` represents a dependency relationship. Each node has an `edgesIn` set, and an `edgesOut` map. Each edge has a `type` which specifies what kind of dependency it represents: `'prod'` for regular dependencies, `'peer'` for peerDependencies, `'dev'` for devDependencies, and `'optional'` for optionalDependencies. `edge.from` is a reference to the node that has the dependency, and `edge.to` is a reference to the node that requires the dependency. As nodes are moved around in the tree, the graph edges are automatically updated to point at the new module resolution targets. In other words, `edge.from`, `edge.name`, and `edge.spec` are immutable; `edge.to` is updated automatically when a node's parent changes. ### class Node All arborist trees are `Node` objects. A `Node` refers to a package folder, which may have children in `node_modules`. * `node.name` The name of this node's folder in `node_modules`. * `node.parent` Physical parent node in the tree. The package in whose `node_modules` folder this package lives. Null if node is top of tree. Setting `node.parent` will automatically update `node.location` and all graph edges affected by the move. * `node.meta` A `Shrinkwrap` object which looks up `resolved` and `integrity` values for all modules in this tree. Only relevant on `root` nodes. * `node.children` Map of packages located in the node's `node_modules` folder. * `node.package` The contents of this node's `package.json` file. * `node.path` File path to this package. If the node is a link, then this is the path to the link, not to the link target. If the node is _not_ a link, then this matches `node.realpath`. * `node.realpath` The full real filepath on disk where this node lives. * `node.location` A slash-normalized relative path from the root node to this node's path. * `node.isLink` Whether this represents a symlink. Always `false` for Node objects, always `true` for Link objects. * `node.isRoot` True if this node is a root node. (Ie, if `node.root === node`.) * `node.root` The root node where we are working. If not assigned to some other value, resolves to the node itself. (Ie, the root node's `root` property refers to itself.) * `node.isTop` True if this node is the top of its tree (ie, has no `parent`, false otherwise). * `node.top` The top node in this node's tree. This will be equal to `node.root` for simple trees, but link targets will frequently be outside of (or nested somewhere within) a `node_modules` hierarchy, and so will have a different `top`. * `node.dev`, `node.optional`, `node.devOptional`, `node.peer`, Indicators as to whether this node is a dev, optional, and/or peer dependency. These flags are relevant when pruning dependencies out of the tree or deciding what to reify. See **Package Dependency Flags** below for explanations. * `node.edgesOut` Edges in the dependency graph indicating nodes that this node depends on, which resolve its dependencies. * `node.edgesIn` Edges in the dependency graph indicating nodes that depend on this node. * `extraneous` True if this package is not required by any other for any reason. False for top of tree. * `node.resolve(name)` Identify the node that will be returned when code in this package runs `require(name)` * `node.errors` Array of errors encountered while parsing package.json or version specifiers. ### class Link Link objects represent a symbolic link within the `node_modules` folder. They have most of the same properties and methods as `Node` objects, with a few differences. * `link.target` A Node object representing the package that the link references. If this is a Node already present within the tree, then it will be the same object. If it's outside of the tree, then it will be treated as the top of its own tree. * `link.isLink` Always true. * `link.children` This is always an empty map, since links don't have their own children directly. ### class Edge Edge objects represent a dependency relationship a package node to the point in the tree where the dependency will be loaded. As nodes are moved within the tree, Edges automatically update to point to the appropriate location. * `new Edge({ from, type, name, spec })` Creates a new edge with the specified fields. After instantiation, none of the fields can be changed directly. * `edge.from` The node that has the dependency. * `edge.type` The type of dependency. One of `'prod'`, `'dev'`, `'peer'`, or `'optional'`. * `edge.name` The name of the dependency. Ie, the key in the relevant `package.json` dependencies object. * `edge.spec` The specifier that is required. This can be a version, range, tag name, git url, or tarball URL. Any specifier allowed by npm is supported. * `edge.to` Automatically set to the node in the tree that matches the `name` field. * `edge.valid` True if `edge.to` satisfies the specifier. * `edge.error` A string indicating the type of error if there is a problem, or `null` if it's valid. Values, in order of precedence: * `DETACHED` Indicates that the edge has been detached from its `edge.from` node, typically because a new edge was created when a dependency specifier was modified. * `MISSING` Indicates that the dependency is unmet. Note that this is _not_ set for unmet dependencies of the `optional` type. * `PEER LOCAL` Indicates that a `peerDependency` is found in the node's local `node_modules` folder, and the node is not the top of the tree. This violates the `peerDependency` contract, because it means that the dependency is not a peer. * `INVALID` Indicates that the dependency does not satisfy `edge.spec`. * `edge.reload()` Re-resolve to find the appropriate value for `edge.to`. Called automatically from the `Node` class when the tree is mutated. ### Package Dependency Flags The dependency type of a node can be determined efficiently by looking at the `dev`, `optional`, and `devOptional` flags on the node object. These are updated by arborist when necessary whenever the tree is modified in such a way that the dependency graph can change, and are relevant when pruning nodes from the tree. ``` | extraneous | peer | dev | optional | devOptional | meaning | prune? | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | | | | production dep | never | |------------+------+-----+----------+-------------+---------------------+-------------------| | X | N/A | N/A | N/A | N/A | nothing depends on | always | | | | | | | this, it is trash | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | X | | X | devDependency, or | if pruning dev | | | | | | not in lock | only depended upon | | | | | | | | by devDependencies | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | | X | X | optionalDependency, | if pruning | | | | | | not in lock | or only depended on | optional | | | | | | | by optionalDeps | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | X | X | X | Optional dependency | if pruning EITHER | | | | | | not in lock | of dep(s) in the | dev OR optional | | | | | | | dev hierarchy | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | | | X | BOTH a non-optional | if pruning BOTH | | | | | | in lock | dep within the dev | dev AND optional | | | | | | | hierarchy, AND a | | | | | | | | dep within the | | | | | | | | optional hierarchy | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | | | | peer dependency, or | if pruning peers | | | | | | | only depended on by | | | | | | | | peer dependencies | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | X | | X | peer dependency of | if pruning peer | | | | | | not in lock | dev node hierarchy | OR dev deps | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | | X | X | peer dependency of | if pruning peer | | | | | | not in lock | optional nodes, or | OR optional deps | | | | | | | peerOptional dep | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | X | X | X | peer optional deps | if pruning peer | | | | | | not in lock | of the dev dep | OR optional OR | | | | | | | hierarchy | dev | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | | | X | BOTH a non-optional | if pruning peers | | | | | | in lock | peer dep within the | OR: | | | | | | | dev hierarchy, AND | BOTH optional | | | | | | | a peer optional dep | AND dev deps | +------------+------+-----+----------+-------------+---------------------+-------------------+ ``` * If none of these flags are set, then the node is required by the dependency and/or peerDependency hierarchy. It should not be pruned. * If _both_ `node.dev` and `node.optional` are set, then the node is an optional dependency of one of the packages in the devDependency hierarchy. It should be pruned if _either_ dev or optional deps are being removed. * If `node.dev` is set, but `node.optional` is not, then the node is required in the devDependency hierarchy. It should be pruned if dev dependencies are being removed. * If `node.optional` is set, but `node.dev` is not, then the node is required in the optionalDependency hierarchy. It should be pruned if optional dependencies are being removed. * If `node.devOptional` is set, then the node is a (non-optional) dependency within the devDependency hierarchy, _and_ a dependency within the `optionalDependency` hierarchy. It should be pruned if _both_ dev and optional dependencies are being removed. * If `node.peer` is set, then all the same semantics apply as above, except that the dep is brought in by a peer dep at some point, rather than a normal non-peer dependency. Note: `devOptional` is only set in the shrinkwrap/package-lock file if _neither_ `dev` nor `optional` are set, as it would be redundant. ## BIN Arborist ships with a cli that can be used to run arborist specific commands outside of the context of the npm CLI. This script is currently not part of the public API and is subject to breaking changes outside of major version bumps. To see the usage run: ``` npx @npmcli/arborist --help ``` const Arborist = require('../') const printTree = require('./lib/print-tree.js') module.exports = (options, time) => new Arborist(options) .loadActual(options) .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (options.save) { await tree.meta.save() } if (options.saveHidden) { tree.meta.hiddenLockfile = true tree.meta.filename = options.path + '/node_modules/.package-lock.json' await tree.meta.save() } return `read ${tree.inventory.size} deps in ${timing.ms}` }) const Arborist = require('../') const printTree = require('./lib/print-tree.js') const log = require('./lib/logging.js') const Vuln = require('../lib/vuln.js') const printReport = report => { for (const vuln of report.values()) { log.info(printVuln(vuln)) } if (report.topVulns.size) { log.info('\n# top-level vulnerabilities') for (const vuln of report.topVulns.values()) { log.info(printVuln(vuln)) } } } const printVuln = vuln => { return { __proto__: { constructor: Vuln }, name: vuln.name, issues: [...vuln.advisories].map(a => printAdvisory(a)), range: vuln.simpleRange, nodes: [...vuln.nodes].map(node => `${node.name} ${node.location || '#ROOT'}`), ...(vuln.topNodes.size === 0 ? {} : { topNodes: [...vuln.topNodes].map(node => `${node.location || '#ROOT'}`), }), } } const printAdvisory = a => `${a.title}${a.url ? ' ' + a.url : ''}` module.exports = (options, time) => { const arb = new Arborist(options) return arb .audit(options) .then(time) .then(async ({ timing, result: tree }) => { if (options.fix) { printTree(tree) } printReport(arb.auditReport) if (tree.meta && options.save) { await tree.meta.save() } return options.fix ? `resolved ${tree.inventory.size} deps in ${timing.seconds}` : `done in ${timing.seconds}` }) } const Arborist = require('../') const log = require('./lib/logging.js') module.exports = (options, time) => { const query = options._.shift() const a = new Arborist(options) return a .loadVirtual() .then(tree => { // only load the actual tree if the virtual one doesn't have modern metadata if (!tree.meta || !(tree.meta.originalLockfileVersion >= 2)) { log.error('old metadata, load actual') throw 'load actual' } else { log.error('meta ok, return virtual tree') return tree } }) .catch(() => a.loadActual()) .then(time) .then(({ timing, result: tree }) => { if (!query) { for (const node of tree.inventory.values()) { if (node.package.funding) { log.info(node.name, node.location, node.package.funding) } } } else { for (const node of tree.inventory.query('name', query)) { if (node.package.funding) { log.info(node.name, node.location, node.package.funding) } } } return `read ${tree.inventory.size} deps in ${timing.ms}` }) } const Arborist = require('../') const printTree = require('./lib/print-tree.js') module.exports = (options, time) => new Arborist(options) .buildIdealTree(options) .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (tree.meta && options.save) { await tree.meta.save() } return `resolved ${tree.inventory.size} deps in ${timing.seconds}` }) #!/usr/bin/env node const fs = require('node:fs') const path = require('node:path') const { time } = require('proc-log') const { bin, arb: options } = require('./lib/options') const version = require('../package.json').version const usage = (message = '') => `Arborist - the npm tree doctor Version: ${version} ${message && '\n' + message + '\n'} # USAGE arborist [path] [options...] # COMMANDS * reify: reify ideal tree to node_modules (install, update, rm, ...) * prune: prune the ideal tree and reify (like npm prune) * ideal: generate and print the ideal tree * actual: read and print the actual tree in node_modules * virtual: read and print the virtual tree in the local shrinkwrap file * shrinkwrap: load a local shrinkwrap and print its data * audit: perform a security audit on project dependencies * funding: query funding information in the local package tree. A second positional argument after the path name can limit to a package name. * license: query license information in the local package tree. A second positional argument after the path name can limit to a license type. * help: print this text * version: print the version # OPTIONS Most npm options are supported, but in camelCase rather than css-case. For example, instead of '--dry-run', use '--dryRun'. Additionally: * --loglevel=warn|--quiet will supppress the printing of package trees * --logfile will output logs to a file * --timing will show timing information * Instead of 'npm install ', use 'arborist reify --add='. The '--add=' option can be specified multiple times. * Instead of 'npm rm ', use 'arborist reify --rm='. The '--rm=' option can be specified multiple times. * Instead of 'npm update', use 'arborist reify --update-all'. * 'npm audit fix' is 'arborist audit --fix' ` const commands = { version: () => console.log(version), help: () => console.log(usage()), exit: () => { process.exitCode = 1 console.error( usage(`Error: command '${bin.command}' does not exist.`) ) }, } const commandFiles = fs.readdirSync(__dirname).filter((f) => path.extname(f) === '.js' && f !== __filename) for (const file of commandFiles) { const command = require(`./${file}`) const name = path.basename(file, '.js') const totalTime = `bin:${name}:init` const scriptTime = `bin:${name}:script` commands[name] = () => { const timers = require('./lib/timers') const log = require('./lib/logging') log.info(name, options) const timeEnd = time.start(totalTime) const scriptEnd = time.start(scriptTime) return command(options, (result) => { scriptEnd() return { result, timing: { seconds: `${timers.get(scriptTime) / 1e9}s`, ms: `${timers.get(scriptTime) / 1e6}ms`, }, } }) .then((result) => { log.info(result) return result }) .catch((err) => { process.exitCode = 1 log.error(err) return err }) .then((r) => { timeEnd() if (bin.loglevel !== 'silent') { console[process.exitCode ? 'error' : 'log'](r) } return r }) } } if (commands[bin.command]) { commands[bin.command]() } else { commands.exit() } const { log } = require('proc-log') const fs = require('node:fs') const { dirname } = require('node:path') const os = require('node:os') const { inspect, format } = require('node:util') const { bin: options } = require('./options.js') // add a meta method to proc-log for passing optional // metadata through to log handlers const META = Symbol('meta') const parseArgs = (...args) => { const { [META]: isMeta } = args[args.length - 1] || {} return isMeta ? [args[args.length - 1], ...args.slice(0, args.length - 1)] : [{}, ...args] } log.meta = (meta = {}) => ({ [META]: true, ...meta }) const levels = new Map([ 'silly', 'verbose', 'info', 'http', 'notice', 'warn', 'error', 'silent', ].map((level, index) => [level, index])) const addLogListener = (write, { eol = os.EOL, loglevel = 'silly', colors = false } = {}) => { const levelIndex = levels.get(loglevel) const magenta = m => colors ? `\x1B[35m${m}\x1B[39m` : m const dim = m => colors ? `\x1B[2m${m}\x1B[22m` : m const red = m => colors ? `\x1B[31m${m}\x1B[39m` : m const formatter = (level, ...args) => { const depth = level === 'error' && args[0] && args[0].code === 'ERESOLVE' ? Infinity : 10 if (level === 'info' && args[0] === 'timeEnd') { args[1] = dim(args[1]) } else if (level === 'error' && args[0] === 'timeError') { args[1] = red(args[1]) } const messages = args.map(a => typeof a === 'string' ? a : inspect(a, { depth, colors })) const pref = `${process.pid} ${magenta(level)} ` return pref + format(...messages).trim().split('\n').join(`${eol}${pref}`) + eol } process.on('log', (...args) => { const [meta, level, ...logArgs] = parseArgs(...args) if (levelIndex <= levels.get(level) || meta.force) { write(formatter(level, ...logArgs)) } }) } if (options.loglevel !== 'silent') { addLogListener((v) => process.stderr.write(v), { eol: '\n', colors: options.colors, loglevel: options.loglevel, }) } if (options.logfile) { log.silly('logfile', options.logfile) fs.mkdirSync(dirname(options.logfile), { recursive: true }) const fd = fs.openSync(options.logfile, 'a') addLogListener((str) => fs.writeSync(fd, str)) } module.exports = log const nopt = require('nopt') const path = require('node:path') const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k) const cleanPath = (val) => { const k = Symbol('key') const data = {} nopt.typeDefs.path.validate(data, k, val) return data[k] } const parse = (...noptArgs) => { const binOnlyOpts = { command: String, loglevel: String, colors: Boolean, timing: ['always', Boolean], logfile: String, } const arbOpts = { add: Array, rm: Array, omit: Array, update: Array, workspaces: Array, global: Boolean, force: Boolean, 'global-style': Boolean, 'prefer-dedupe': Boolean, 'legacy-peer-deps': Boolean, 'update-all': Boolean, before: Date, path: path, cache: path, ...binOnlyOpts, } const short = { quiet: ['--loglevel', 'warn'], logs: ['--logfile', 'true'], w: '--workspaces', g: '--global', f: '--force', } const defaults = { // key order is important for command and path // since they shift positional args // command is 1st, path is 2nd command: (o) => o.argv.remain.shift(), path: (o) => cleanPath(o.argv.remain.shift() || '.'), colors: has(process.env, 'NO_COLOR') ? false : !!process.stderr.isTTY, loglevel: 'silly', timing: (o) => o.loglevel === 'silly', cache: `${process.env.HOME}/.npm/_cacache`, } const derived = [ // making update either `all` or an array of names but not both ({ updateAll: all, update: names, ...o }) => { if (all || names) { o.update = all != null ? { all } : { names } } return o }, ({ logfile, ...o }) => { // logfile is parsed as a string so if its true or set but empty // then set the default logfile if (logfile === 'true' || logfile === '') { logfile = `arb-log-${new Date().toISOString().replace(/[.:]/g, '_')}.log` } // then parse it the same as nopt parses other paths if (logfile) { o.logfile = cleanPath(logfile) } return o }, ] const transforms = [ // Camelcase all top level keys (o) => { const entries = Object.entries(o).map(([k, v]) => [ k.replace(/-./g, s => s[1].toUpperCase()), v, ]) return Object.fromEntries(entries) }, // Set defaults on unset keys (o) => { for (const [k, v] of Object.entries(defaults)) { if (!has(o, k)) { o[k] = typeof v === 'function' ? v(o) : v } } return o }, // Set/unset derived values ...derived.map((derive) => (o) => derive(o) || o), // Separate bin and arborist options ({ argv: { remain: _ }, ...o }) => { const bin = { _ } for (const k of Object.keys(binOnlyOpts)) { if (has(o, k)) { bin[k] = o[k] delete o[k] } } return { bin, arb: o } }, ] let options = nopt(arbOpts, short, ...noptArgs) for (const t of transforms) { options = t(options) } return options } module.exports = parse() const { inspect } = require('node:util') const log = require('./logging.js') module.exports = tree => log.info(inspect(tree.toJSON(), { depth: Infinity })) const { bin: options } = require('./options.js') const log = require('./logging.js') const timers = new Map() const finished = new Map() process.on('time', (level, name) => { if (level === 'start') { if (timers.has(name)) { throw new Error('conflicting timer! ' + name) } timers.set(name, process.hrtime.bigint()) } else if (level === 'end') { if (!timers.has(name)) { throw new Error('timer not started! ' + name) } const elapsed = Number(process.hrtime.bigint() - timers.get(name)) timers.delete(name) finished.set(name, elapsed) if (options.timing) { log.info('timeEnd', `${name} ${elapsed / 1e9}s`, log.meta({ force: options.timing === 'always' })) } } }) process.on('exit', () => { for (const name of timers.keys()) { log.error('timeError', 'Dangling timer:', name) process.exitCode = 1 } }) module.exports = finished const localeCompare = require('@isaacs/string-locale-compare')('en') const Arborist = require('../') const log = require('./lib/logging.js') module.exports = (options, time) => { const query = options._.shift() const a = new Arborist(options) return a .loadVirtual() .then(tree => { // only load the actual tree if the virtual one doesn't have modern metadata if (!tree.meta || !(tree.meta.originalLockfileVersion >= 2)) { throw 'load actual' } else { return tree } }).catch((er) => { log.error('loading actual tree', er) return a.loadActual() }) .then(time) .then(({ result: tree }) => { const output = [] if (!query) { const set = [] for (const license of tree.inventory.query('license')) { set.push([tree.inventory.query('license', license).size, license]) } for (const [count, license] of set.sort((a, b) => a[1] && b[1] ? b[0] - a[0] || localeCompare(a[1], b[1]) : a[1] ? -1 : b[1] ? 1 : 0)) { output.push(`${count} ${license}`) log.info(count, license) } } else { for (const node of tree.inventory.query('license', query === 'undefined' ? undefined : query)) { const msg = `${node.name} ${node.location} ${node.package.description || ''}` output.push(msg) log.info(msg) } } return output.join('\n') }) } const Arborist = require('../') const printTree = require('./lib/print-tree.js') const log = require('./lib/logging.js') const printDiff = diff => { const { depth } = require('treeverse') depth({ tree: diff, visit: d => { if (d.location === '') { return } switch (d.action) { case 'REMOVE': log.info('REMOVE', d.actual.location) break case 'ADD': log.info('ADD', d.ideal.location, d.ideal.resolved) break case 'CHANGE': log.info('CHANGE', d.actual.location, { from: d.actual.resolved, to: d.ideal.resolved, }) break } }, getChildren: d => d.children, }) } module.exports = (options, time) => { const arb = new Arborist(options) return arb .prune(options) .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (options.dryRun) { printDiff(arb.diff) } if (tree.meta && options.save) { await tree.meta.save() } return `resolved ${tree.inventory.size} deps in ${timing.seconds}` }) } const Arborist = require('../') const printTree = require('./lib/print-tree.js') const log = require('./lib/logging.js') const printDiff = diff => { const { depth } = require('treeverse') depth({ tree: diff, visit: d => { if (d.location === '') { return } switch (d.action) { case 'REMOVE': log.info('REMOVE', d.actual.location) break case 'ADD': log.info('ADD', d.ideal.location, d.ideal.resolved) break case 'CHANGE': log.info('CHANGE', d.actual.location, { from: d.actual.resolved, to: d.ideal.resolved, }) break } }, getChildren: d => d.children, }) } module.exports = (options, time) => { const arb = new Arborist(options) return arb .reify(options) .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (options.dryRun) { printDiff(arb.diff) } if (tree.meta && options.save) { await tree.meta.save() } return `resolved ${tree.inventory.size} deps in ${timing.seconds}` }) } const Shrinkwrap = require('../lib/shrinkwrap.js') module.exports = (options, time) => Shrinkwrap .load(options) .then((s) => s.commit()) .then(time) .then(({ result: s }) => JSON.stringify(s, 0, 2)) const Arborist = require('../') const printTree = require('./lib/print-tree.js') module.exports = (options, time) => new Arborist(options) .loadVirtual() .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (options.save) { await tree.meta.save() } return `read ${tree.inventory.size} deps in ${timing.ms}` }) // add and remove dependency specs to/from pkg manifest const { log } = require('proc-log') const localeCompare = require('@isaacs/string-locale-compare')('en') const add = ({ pkg, add, saveBundle, saveType }) => { for (const { name, rawSpec } of add) { let addSaveType = saveType // if the user does not give us a type, we infer which type(s) // to keep based on the same order of priority we do when // building the tree as defined in the _loadDeps method of // the node class. if (!addSaveType) { addSaveType = inferSaveType(pkg, name) } if (addSaveType === 'prod') { // a production dependency can only exist as production (rpj ensures it // doesn't coexist w/ optional) deleteSubKey(pkg, 'devDependencies', name, 'dependencies') deleteSubKey(pkg, 'peerDependencies', name, 'dependencies') } else if (addSaveType === 'dev') { // a dev dependency may co-exist as peer, or optional, but not production deleteSubKey(pkg, 'dependencies', name, 'devDependencies') } else if (addSaveType === 'optional') { // an optional dependency may co-exist as dev (rpj ensures it doesn't // coexist w/ prod) deleteSubKey(pkg, 'peerDependencies', name, 'optionalDependencies') } else { // peer or peerOptional is all that's left // a peer dependency may coexist as dev deleteSubKey(pkg, 'dependencies', name, 'peerDependencies') deleteSubKey(pkg, 'optionalDependencies', name, 'peerDependencies') } const depType = saveTypeMap.get(addSaveType) pkg[depType] = pkg[depType] || {} if (rawSpec !== '*' || pkg[depType][name] === undefined) { pkg[depType][name] = rawSpec } if (addSaveType === 'optional') { // Affordance for previous npm versions that require this behaviour pkg.dependencies = pkg.dependencies || {} pkg.dependencies[name] = pkg.optionalDependencies[name] } if (addSaveType === 'peer' || addSaveType === 'peerOptional') { const pdm = pkg.peerDependenciesMeta || {} if (addSaveType === 'peer' && pdm[name] && pdm[name].optional) { pdm[name].optional = false } else if (addSaveType === 'peerOptional') { pdm[name] = pdm[name] || {} pdm[name].optional = true pkg.peerDependenciesMeta = pdm } // peerDeps are often also a devDep, so that they can be tested when // using package managers that don't auto-install peer deps if (pkg.devDependencies && pkg.devDependencies[name] !== undefined) { pkg.devDependencies[name] = pkg.peerDependencies[name] } } if (saveBundle && addSaveType !== 'peer' && addSaveType !== 'peerOptional') { // keep it sorted, keep it unique const bd = new Set(pkg.bundleDependencies || []) bd.add(name) pkg.bundleDependencies = [...bd].sort(localeCompare) } } return pkg } // Canonical source of both the map between saveType and where it correlates to // in the package, and the names of all our dependencies attributes const saveTypeMap = new Map([ ['dev', 'devDependencies'], ['optional', 'optionalDependencies'], ['prod', 'dependencies'], ['peerOptional', 'peerDependencies'], ['peer', 'peerDependencies'], ]) // Finds where the package is already in the spec and infers saveType from that const inferSaveType = (pkg, name) => { for (const saveType of saveTypeMap.keys()) { if (hasSubKey(pkg, saveTypeMap.get(saveType), name)) { if ( saveType === 'peerOptional' && (!hasSubKey(pkg, 'peerDependenciesMeta', name) || !pkg.peerDependenciesMeta[name].optional) ) { return 'peer' } return saveType } } return 'prod' } const hasSubKey = (pkg, depType, name) => { return pkg[depType] && Object.prototype.hasOwnProperty.call(pkg[depType], name) } // Removes a subkey and warns about it if it's being replaced const deleteSubKey = (pkg, depType, name, replacedBy) => { if (hasSubKey(pkg, depType, name)) { if (replacedBy) { log.warn('idealTree', `Removing ${depType}.${name} in favor of ${replacedBy}.${name}`) } delete pkg[depType][name] // clean up peerDepsMeta if we are removing something from peerDependencies if (depType === 'peerDependencies' && pkg.peerDependenciesMeta) { delete pkg.peerDependenciesMeta[name] if (!Object.keys(pkg.peerDependenciesMeta).length) { delete pkg.peerDependenciesMeta } } if (!Object.keys(pkg[depType]).length) { delete pkg[depType] } } } const rm = (pkg, rm) => { for (const depType of new Set(saveTypeMap.values())) { for (const name of rm) { deleteSubKey(pkg, depType, name) } } if (pkg.bundleDependencies) { pkg.bundleDependencies = pkg.bundleDependencies .filter(name => !rm.includes(name)) if (!pkg.bundleDependencies.length) { delete pkg.bundleDependencies } } return pkg } module.exports = { add, rm, saveTypeMap, hasSubKey } // mixin implementing the buildIdealTree method const localeCompare = require('@isaacs/string-locale-compare')('en') const rpj = require('read-package-json-fast') const npa = require('npm-package-arg') const pacote = require('pacote') const cacache = require('cacache') const { callLimit: promiseCallLimit } = require('promise-call-limit') const realpath = require('../../lib/realpath.js') const { resolve, dirname } = require('node:path') const treeCheck = require('../tree-check.js') const { readdirScoped } = require('@npmcli/fs') const { lstat, readlink } = require('node:fs/promises') const { depth } = require('treeverse') const { log, time } = require('proc-log') const { redact } = require('@npmcli/redact') const { OK, REPLACE, CONFLICT, } = require('../can-place-dep.js') const PlaceDep = require('../place-dep.js') const debug = require('../debug.js') const fromPath = require('../from-path.js') const calcDepFlags = require('../calc-dep-flags.js') const Shrinkwrap = require('../shrinkwrap.js') const { defaultLockfileVersion } = Shrinkwrap const Node = require('../node.js') const Link = require('../link.js') const addRmPkgDeps = require('../add-rm-pkg-deps.js') const optionalSet = require('../optional-set.js') const { checkEngine, checkPlatform } = require('npm-install-checks') const relpath = require('../relpath.js') const resetDepFlags = require('../reset-dep-flags.js') // note: some of these symbols are shared so we can hit // them with unit tests and reuse them across mixins const _updateAll = Symbol.for('updateAll') const _flagsSuspect = Symbol.for('flagsSuspect') const _setWorkspaces = Symbol.for('setWorkspaces') const _updateNames = Symbol.for('updateNames') const _resolvedAdd = Symbol.for('resolvedAdd') const _usePackageLock = Symbol.for('usePackageLock') const _rpcache = Symbol.for('realpathCache') const _stcache = Symbol.for('statCache') // used by Reify mixin const _addNodeToTrashList = Symbol.for('addNodeToTrashList') // Push items in, pop them sorted by depth and then path // Sorts physically shallower deps up to the front of the queue, because // they'll affect things deeper in, then alphabetical for consistency between // installs class DepsQueue { #deps = [] #sorted = true get length () { return this.#deps.length } push (item) { if (!this.#deps.includes(item)) { this.#sorted = false this.#deps.push(item) } } pop () { if (!this.#sorted) { this.#deps.sort((a, b) => (a.depth - b.depth) || localeCompare(a.path, b.path)) this.#sorted = true } return this.#deps.shift() } } module.exports = cls => class IdealTreeBuilder extends cls { #complete #currentDep = null #depsQueue = new DepsQueue() #depsSeen = new Set() #explicitRequests = new Set() #follow #installStrategy #linkNodes = new Set() #loadFailures = new Set() #manifests = new Map() #mutateTree = false // a map of each module in a peer set to the thing that depended on // that set of peers in the first place. Use a WeakMap so that we // don't hold onto references for nodes that are garbage collected. #peerSetSource = new WeakMap() #preferDedupe = false #prune #strictPeerDeps #virtualRoots = new Map() constructor (options) { super(options) // normalize trailing slash const registry = options.registry || 'https://registry.npmjs.org' options.registry = this.registry = registry.replace(/\/+$/, '') + '/' const { follow = false, installStrategy = 'hoisted', idealTree = null, installLinks = false, legacyPeerDeps = false, packageLock = true, strictPeerDeps = false, workspaces, global, } = options this.#strictPeerDeps = !!strictPeerDeps this.idealTree = idealTree this.installLinks = installLinks this.legacyPeerDeps = legacyPeerDeps this[_usePackageLock] = packageLock this.#installStrategy = global ? 'shallow' : installStrategy this.#follow = !!follow if (workspaces?.length && global) { throw new Error('Cannot operate on workspaces in global mode') } this[_updateAll] = false this[_updateNames] = [] this[_resolvedAdd] = [] } get explicitRequests () { return new Set(this.#explicitRequests) } // public method async buildIdealTree (options = {}) { if (this.idealTree) { return this.idealTree } // allow the user to set reify options on the ctor as well. // XXX: deprecate separate reify() options object. options = { ...this.options, ...options } // an empty array or any falsey value is the same as null if (!options.add || options.add.length === 0) { options.add = null } if (!options.rm || options.rm.length === 0) { options.rm = null } const timeEnd = time.start('idealTree') if (!options.add && !options.rm && !options.update && this.options.global) { throw new Error('global requires add, rm, or update option') } // first get the virtual tree, if possible. If there's a lockfile, then // that defines the ideal tree, unless the root package.json is not // satisfied by what the ideal tree provides. // from there, we start adding nodes to it to satisfy the deps requested // by the package.json in the root. this.#parseSettings(options) // start tracker block this.addTracker('idealTree') try { await this.#initTree() await this.#inflateAncientLockfile() await this.#applyUserRequests(options) await this.#buildDeps() await this.#fixDepFlags() await this.#pruneFailedOptional() await this.#checkEngineAndPlatform() } finally { timeEnd() this.finishTracker('idealTree') } return treeCheck(this.idealTree) } async #checkEngineAndPlatform () { const { engineStrict, npmVersion, nodeVersion } = this.options for (const node of this.idealTree.inventory.values()) { if (!node.optional) { try { // if devEngines is present in the root node we ignore the engines check if (!(node.isRoot && node.package.devEngines)) { checkEngine(node.package, npmVersion, nodeVersion, this.options.force) } } catch (err) { if (engineStrict) { throw err } log.warn(err.code, err.message, { package: err.pkgid, required: err.required, current: err.current, }) } checkPlatform(node.package, this.options.force) } } } #parseSettings (options) { const update = options.update === true ? { all: true } : Array.isArray(options.update) ? { names: options.update } : options.update || {} if (update.all || !Array.isArray(update.names)) { update.names = [] } this.#complete = !!options.complete this.#preferDedupe = !!options.preferDedupe // validates list of update names, they must // be dep names only, no semver ranges are supported for (const name of update.names) { const spec = npa(name) const validationError = new TypeError(`Update arguments must only contain package names, eg: npm update ${spec.name}`) validationError.code = 'EUPDATEARGS' // If they gave us anything other than a bare package name if (spec.raw !== spec.name) { throw validationError } } this[_updateNames] = update.names this[_updateAll] = update.all // we prune by default unless explicitly set to boolean false this.#prune = options.prune !== false // set if we add anything, but also set here if we know we'll make // changes and thus have to maybe prune later. this.#mutateTree = !!( options.add || options.rm || update.all || update.names.length ) } // load the initial tree, either the virtualTree from a shrinkwrap, // or just the root node from a package.json async #initTree () { const timeEnd = time.start('idealTree:init') let root if (this.options.global) { root = await this.#globalRootNode() } else { try { const pkg = await rpj(this.path + '/package.json') root = await this.#rootNodeFromPackage(pkg) } catch (err) { if (err.code === 'EJSONPARSE') { throw err } root = await this.#rootNodeFromPackage({}) } } return this[_setWorkspaces](root) // ok to not have a virtual tree. probably initial install. // When updating all, we load the shrinkwrap, but don't bother // to build out the full virtual tree from it, since we'll be // reconstructing it anyway. .then(root => this.options.global ? root : !this[_usePackageLock] || this[_updateAll] ? Shrinkwrap.reset({ path: this.path, lockfileVersion: this.options.lockfileVersion, resolveOptions: this.options, }).then(meta => Object.assign(root, { meta })) : this.loadVirtual({ root })) // if we don't have a lockfile to go from, then start with the // actual tree, so we only make the minimum required changes. // don't do this for global installs or updates, because in those // cases we don't use a lockfile anyway. // Load on a new Arborist object, so the Nodes aren't the same, // or else it'll get super confusing when we change them! .then(async root => { if ((!this[_updateAll] && !this.options.global && !root.meta.loadedFromDisk) || (this.options.global && this[_updateNames].length)) { await new this.constructor(this.options).loadActual({ root }) const tree = root.target // even though we didn't load it from a package-lock.json FILE, // we still loaded it "from disk", meaning we have to reset // dep flags before assuming that any mutations were reflected. if (tree.children.size) { root.meta.loadedFromDisk = true // set these so that we don't try to ancient lockfile reload it root.meta.originalLockfileVersion = root.meta.lockfileVersion = this.options.lockfileVersion || defaultLockfileVersion } } root.meta.inferFormattingOptions(root.package) return root }) .then(tree => { // search the virtual tree for invalid edges, if any are found add their source to // the depsQueue so that we'll fix it later depth({ tree, getChildren: (node) => { const children = [] for (const edge of node.edgesOut.values()) { children.push(edge.to) } return children }, filter: node => node, visit: node => { for (const edge of node.edgesOut.values()) { if (!edge.valid) { this.#depsQueue.push(node) break // no need to continue the loop after the first hit } } }, }) // null the virtual tree, because we're about to hack away at it // if you want another one, load another copy. this.idealTree = tree this.virtualTree = null timeEnd() return tree }) } async #globalRootNode () { const root = await this.#rootNodeFromPackage({ dependencies: {} }) // this is a gross kludge to handle the fact that we don't save // metadata on the root node in global installs, because the "root" // node is something like /usr/local/lib. const meta = new Shrinkwrap({ path: this.path, lockfileVersion: this.options.lockfileVersion, resolveOptions: this.options, }) meta.reset() root.meta = meta return root } async #rootNodeFromPackage (pkg) { // if the path doesn't exist, then we explode at this point. Note that // this is not a problem for reify(), since it creates the root path // before ever loading trees. // TODO: make buildIdealTree() and loadActual handle a missing root path, // or a symlink to a missing target, and let reify() create it as needed. const real = await realpath(this.path, this[_rpcache], this[_stcache]) const Cls = real === this.path ? Node : Link const root = new Cls({ path: this.path, realpath: real, pkg, extraneous: false, dev: false, devOptional: false, peer: false, optional: false, global: this.options.global, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, loadOverrides: true, }) if (root.isLink) { root.target = new Node({ path: real, realpath: real, pkg, extraneous: false, dev: false, devOptional: false, peer: false, optional: false, global: this.options.global, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, root, }) } return root } // process the add/rm requests by modifying the root node, and the // update.names request by queueing nodes dependent on those named. async #applyUserRequests (options) { const timeEnd = time.start('idealTree:userRequests') const tree = this.idealTree.target if (!this.options.workspaces.length) { await this.#applyUserRequestsToNode(tree, options) } else { const nodes = this.workspaceNodes(tree, this.options.workspaces) if (this.options.includeWorkspaceRoot) { nodes.push(tree) } const appliedRequests = nodes.map( node => this.#applyUserRequestsToNode(node, options) ) await Promise.all(appliedRequests) } timeEnd() } async #applyUserRequestsToNode (tree, options) { // If we have a list of package names to update, and we know it's // going to update them wherever they are, add any paths into those // named nodes to the buildIdealTree queue. if (!this.options.global && this[_updateNames].length) { this.#queueNamedUpdates() } // global updates only update the globalTop nodes, but we need to know // that they're there, and not reinstall the world unnecessarily. const globalExplicitUpdateNames = [] if (this.options.global && (this[_updateAll] || this[_updateNames].length)) { const nm = resolve(this.path, 'node_modules') const paths = await readdirScoped(nm).catch(() => []) for (const p of paths) { const name = p.replace(/\\/g, '/') tree.package.dependencies = tree.package.dependencies || {} const updateName = this[_updateNames].includes(name) if (this[_updateAll] || updateName) { if (updateName) { globalExplicitUpdateNames.push(name) } const dir = resolve(nm, name) const st = await lstat(dir) .catch(/* istanbul ignore next */ () => null) if (st && st.isSymbolicLink()) { const target = await readlink(dir) const real = resolve(dirname(dir), target).replace(/#/g, '%23') tree.package.dependencies[name] = `file:${real}` } else { tree.package.dependencies[name] = '*' } } } } if (this.auditReport && this.auditReport.size > 0) { await this.#queueVulnDependents(options) } const { add, rm } = options if (rm && rm.length) { addRmPkgDeps.rm(tree.package, rm) for (const name of rm) { this.#explicitRequests.add({ from: tree, name, action: 'DELETE' }) } } if (add && add.length) { await this.#add(tree, options) } // triggers a refresh of all edgesOut. this has to be done BEFORE // adding the edges to explicitRequests, because the package setter // resets all edgesOut. if (add && add.length || rm && rm.length || this.options.global) { tree.package = tree.package } for (const spec of this[_resolvedAdd]) { if (spec.tree === tree) { this.#explicitRequests.add(tree.edgesOut.get(spec.name)) } } for (const name of globalExplicitUpdateNames) { this.#explicitRequests.add(tree.edgesOut.get(name)) } this.#depsQueue.push(tree) } // This returns a promise because we might not have the name yet, and need to // call pacote.manifest to find the name. async #add (tree, { add, saveType = null, saveBundle = false }) { // If we have a link it will need to be added relative to the target's path const path = tree.target.path // get the name for each of the specs in the list. // ie, doing `foo@bar` we just return foo but if it's a url or git, we // don't know the name until we fetch it and look in its manifest. await Promise.all(add.map(async rawSpec => { // We do NOT provide the path to npa here, because user-additions need to // be resolved relative to the tree being added to. let spec = npa(rawSpec) // if it's just @'' then we reload whatever's there, or get latest // if it's an explicit tag, we need to install that specific tag version const isTag = spec.rawSpec && spec.type === 'tag' // look up the names of file/directory/git specs if (!spec.name || isTag) { const mani = await pacote.manifest(spec, { ...this.options }) if (isTag) { // translate tag to a version spec = npa(`${mani.name}@${mani.version}`) } spec.name = mani.name } const { name } = spec if (spec.type === 'file') { spec = npa(`file:${relpath(path, spec.fetchSpec).replace(/#/g, '%23')}`, path) spec.name = name } else if (spec.type === 'directory') { try { const real = await realpath(spec.fetchSpec, this[_rpcache], this[_stcache]) spec = npa(`file:${relpath(path, real).replace(/#/g, '%23')}`, path) spec.name = name } catch { // TODO: create synthetic test case to simulate realpath failure } } spec.tree = tree this[_resolvedAdd].push(spec) })) // now this._resolvedAdd is a list of spec objects with names. // find a home for each of them! addRmPkgDeps.add({ pkg: tree.package, add: this[_resolvedAdd], saveBundle, saveType, }) } // TODO: provide a way to fix bundled deps by exposing metadata about // what's in the bundle at each published manifest. Without that, we // can't possibly fix bundled deps without breaking a ton of other stuff, // and leaving the user subject to getting it overwritten later anyway. async #queueVulnDependents (options) { for (const vuln of this.auditReport.values()) { for (const node of vuln.nodes) { const bundler = node.getBundler() // XXX this belongs in the audit report itself, not here. // We shouldn't even get these things here, and they shouldn't // be printed by npm-audit-report as if they can be fixed, because // they can't. if (bundler) { log.warn(`audit fix ${node.name}@${node.version}`, `${node.location}\nis a bundled dependency of\n${ bundler.name}@${bundler.version} at ${bundler.location}\n` + 'It cannot be fixed automatically.\n' + `Check for updates to the ${bundler.name} package.`) continue } for (const edge of node.edgesIn) { this.addTracker('idealTree', edge.from.name, edge.from.location) this.#depsQueue.push(edge.from) } } } // note any that can't be fixed at the root level without --force // if there's a fix, we use that. otherwise, the user has to remove it, // find a different thing, fix the upstream, etc. // // XXX: how to handle top nodes that aren't the root? Maybe the report // just tells the user to cd into that directory and fix it? if (this.options.force && this.auditReport && this.auditReport.topVulns.size) { options.add = options.add || [] options.rm = options.rm || [] const nodesTouched = new Set() for (const [name, topVuln] of this.auditReport.topVulns.entries()) { const { simpleRange, topNodes, fixAvailable, } = topVuln for (const node of topNodes) { if (!node.isProjectRoot && !node.isWorkspace) { // not something we're going to fix, sorry. have to cd into // that directory and fix it yourself. log.warn('audit', 'Manual fix required in linked project ' + `at ./${node.location} for ${name}@${simpleRange}.\n` + `'cd ./${node.location}' and run 'npm audit' for details.`) continue } if (!fixAvailable) { log.warn('audit', `No fix available for ${name}@${simpleRange}`) continue } // name may be different if parent fixes the dep // see Vuln fixAvailable setter const { isSemVerMajor, version, name: fixName } = fixAvailable const breakingMessage = isSemVerMajor ? 'a SemVer major change' : 'outside your stated dependency range' log.warn('audit', `Updating ${fixName} to ${version}, ` + `which is ${breakingMessage}.`) await this.#add(node, { add: [`${fixName}@${version}`] }) nodesTouched.add(node) } } for (const node of nodesTouched) { node.package = node.package } } } #avoidRange (name) { if (!this.auditReport) { return null } const vuln = this.auditReport.get(name) if (!vuln) { return null } return vuln.range } #queueNamedUpdates () { // ignore top nodes, since they are not loaded the same way, and // probably have their own project associated with them. // for every node with one of the names on the list, we add its // dependents to the queue to be evaluated. in buildDepStep, // anything on the update names list will get refreshed, even if // it isn't a problem. // XXX this could be faster by doing a series of inventory.query('name') // calls rather than walking over everything in the tree. for (const node of this.idealTree.inventory.values()) { // XXX add any invalid edgesOut to the queue if (this[_updateNames].includes(node.name) && !node.isTop && !node.inDepBundle && !node.inShrinkwrap) { for (const edge of node.edgesIn) { this.addTracker('idealTree', edge.from.name, edge.from.location) this.#depsQueue.push(edge.from) } } } } async #inflateAncientLockfile () { const { meta, inventory } = this.idealTree const ancient = meta.ancientLockfile const old = meta.loadedFromDisk && !(meta.originalLockfileVersion >= 2) if (inventory.size === 0 || !ancient && !old) { return } // if the lockfile is from node v5 or earlier, then we'll have to reload // all the manifests of everything we encounter. this is costly, but at // least it's just a one-time hit. const timeEnd = time.start('idealTree:inflate') // don't warn if we're not gonna actually write it back anyway. const heading = ancient ? 'ancient lockfile' : 'old lockfile' if (ancient || !this.options.lockfileVersion || this.options.lockfileVersion >= defaultLockfileVersion) { log.warn(heading, ` The ${meta.type} file was created with an old version of npm, so supplemental metadata must be fetched from the registry. This is a one-time fix-up, please be patient... `) } this.addTracker('idealTree:inflate') const queue = [] for (const node of inventory.values()) { if (node.isProjectRoot) { continue } // if the node's location isn't within node_modules then this is actually // a link target, so skip it. the link node itself will be queued later. if (!node.location.startsWith('node_modules')) { continue } queue.push(async () => { log.silly('inflate', node.location) const { resolved, version, path, name, location, integrity } = node // don't try to hit the registry for linked deps const useResolved = resolved && ( !version || resolved.startsWith('file:') ) const id = useResolved ? resolved : version const spec = npa.resolve(name, id, dirname(path)) const t = `idealTree:inflate:${location}` this.addTracker(t) try { const mani = await pacote.manifest(spec, { ...this.options, resolved: resolved, integrity: integrity, fullMetadata: false, }) node.package = { ...mani, _id: `${mani.name}@${mani.version}` } } catch (er) { const warning = `Could not fetch metadata for ${name}@${id}` log.warn(heading, warning, er) } this.finishTracker(t) }) } await promiseCallLimit(queue) // have to re-calc dep flags, because the nodes don't have edges // until their packages get assigned, so everything looks extraneous calcDepFlags(this.idealTree) // yes, yes, this isn't the "original" version, but now that it's been // upgraded, we need to make sure we don't do the work to upgrade it // again, since it's now as new as can be. if (!this.options.lockfileVersion && !meta.hiddenLockfile) { meta.originalLockfileVersion = defaultLockfileVersion } this.finishTracker('idealTree:inflate') timeEnd() } // at this point we have a virtual tree with the actual root node's // package deps, which may be partly or entirely incomplete, invalid // or extraneous. #buildDeps () { const timeEnd = time.start('idealTree:buildDeps') const tree = this.idealTree.target tree.assertRootOverrides() this.#depsQueue.push(tree) // XXX also push anything that depends on a node with a name // in the override list log.silly('idealTree', 'buildDeps') this.addTracker('idealTree', tree.name, '') return this.#buildDepStep().then(timeEnd) } async #buildDepStep () { // removes tracker of previous dependency in the queue if (this.#currentDep) { const { location, name } = this.#currentDep time.end(`idealTree:${location || '#root'}`) this.finishTracker('idealTree', name, location) this.#currentDep = null } if (!this.#depsQueue.length) { return this.#resolveLinks() } const node = this.#depsQueue.pop() const bd = node.package.bundleDependencies const hasBundle = bd && Array.isArray(bd) && bd.length const { hasShrinkwrap } = node // if the node was already visited, or has since been removed from the // tree, skip over it and process the rest of the queue. If a node has // a shrinkwrap, also skip it, because it's going to get its deps // satisfied by whatever's in that file anyway. if (this.#depsSeen.has(node) || node.root !== this.idealTree || hasShrinkwrap && !this.#complete) { return this.#buildDepStep() } this.#depsSeen.add(node) this.#currentDep = node time.start(`idealTree:${node.location || '#root'}`) // if we're loading a _complete_ ideal tree, for a --package-lock-only // installation for example, we have to crack open the tarball and // look inside if it has bundle deps or shrinkwraps. note that this is // not necessary during a reification, because we just update the // ideal tree by reading bundles/shrinkwraps in place. // Don't bother if the node is from the actual tree and hasn't // been resolved, because we can't fetch it anyway, could be anything! const crackOpen = this.#complete && node !== this.idealTree && node.resolved && (hasBundle || hasShrinkwrap) if (crackOpen) { const Arborist = this.constructor const opt = { ...this.options } await cacache.tmp.withTmp(this.cache, opt, async path => { await pacote.extract(node.resolved, path, { ...opt, Arborist, resolved: node.resolved, integrity: node.integrity, }) if (hasShrinkwrap) { await new Arborist({ ...this.options, path }) .loadVirtual({ root: node }) } if (hasBundle) { await new Arborist({ ...this.options, path }) .loadActual({ root: node, ignoreMissing: true }) } }) } // if any deps are missing or invalid, then we fetch the manifest for // the thing we want, and build a new dep node from that. // Then, find the ideal placement for that node. The ideal placement // searches from the node's deps (or parent deps in the case of non-root // peer deps), and walks up the tree until it finds the highest spot // where it doesn't cause any conflicts. // // A conflict can be: // - A node by that name already exists at that location. // - The parent has a peer dep on that name // - One of the node's peer deps conflicts at that location, unless the // peer dep is met by a node at that location, which is fine. // // If we create a new node, then build its ideal deps as well. // // Note: this is the same "maximally naive" deduping tree-building // algorithm that npm has used since v3. In a case like this: // // root -> (a@1, b@1||2) // a -> (b@1) // // You'll end up with a tree like this: // // root // +-- a@1 // | +-- b@1 // +-- b@2 // // rather than this, more deduped, but just as correct tree: // // root // +-- a@1 // +-- b@1 // // Another way to look at it is that this algorithm favors getting higher // version deps at higher levels in the tree, even if that reduces // potential deduplication. // // Set `preferDedupe: true` in the options to replace the shallower // dep if allowed. const tasks = [] const peerSource = this.#peerSetSource.get(node) || node for (const edge of this.#problemEdges(node)) { if (edge.peerConflicted) { continue } // peerSetSource is only relevant when we have a peerEntryEdge // otherwise we're setting regular non-peer deps as if they have // a virtual root of whatever brought in THIS node. // so we VR the node itself if the edge is not a peer const source = edge.peer ? peerSource : node const virtualRoot = this.#virtualRoot(source, true) // reuse virtual root if we already have one, but don't // try to do the override ahead of time, since we MAY be able // to create a more correct tree than the virtual root could. const vrEdge = virtualRoot && virtualRoot.edgesOut.get(edge.name) const vrDep = vrEdge && vrEdge.valid && vrEdge.to // only re-use the virtualRoot if it's a peer edge we're placing. // otherwise, we end up in situations where we override peer deps that // we could have otherwise found homes for. Eg: // xy -> (x, y) // x -> PEER(z@1) // y -> PEER(z@2) // If xy is a dependency, we can resolve this like: // project // +-- xy // | +-- y // | +-- z@2 // +-- x // +-- z@1 // But if x and y are loaded in the same virtual root, then they will // be forced to agree on a version of z. const required = new Set([edge.from]) const parent = edge.peer ? virtualRoot : null const dep = vrDep && vrDep.satisfies(edge) ? vrDep : await this.#nodeFromEdge(edge, parent, null, required) /* istanbul ignore next */ debug(() => { if (!dep) { throw new Error('no dep??') } }) tasks.push({ edge, dep }) } const placeDeps = tasks.sort((a, b) => localeCompare(a.edge.name, b.edge.name)) const promises = [] for (const { edge, dep } of placeDeps) { const pd = new PlaceDep({ edge, dep, auditReport: this.auditReport, explicitRequest: this.#explicitRequests.has(edge), force: this.options.force, installLinks: this.installLinks, installStrategy: this.#installStrategy, legacyPeerDeps: this.legacyPeerDeps, preferDedupe: this.#preferDedupe, strictPeerDeps: this.#strictPeerDeps, updateNames: this[_updateNames], }) // placing a dep is actually a tree of placing the dep itself // and all of its peer group that aren't already met by the tree depth({ tree: pd, getChildren: pd => pd.children, visit: pd => { const { placed, edge, canPlace: cpd } = pd // if we didn't place anything, nothing to do here if (!placed) { return } // we placed something, that means we changed the tree if (placed.errors.length) { this.#loadFailures.add(placed) } this.#mutateTree = true if (cpd.canPlaceSelf === OK) { for (const edgeIn of placed.edgesIn) { if (edgeIn === edge) { continue } const { from, valid, peerConflicted } = edgeIn if (!peerConflicted && !valid && !this.#depsSeen.has(from)) { this.addTracker('idealTree', from.name, from.location) this.#depsQueue.push(edgeIn.from) } } } else { /* istanbul ignore else - should be only OK or REPLACE here */ if (cpd.canPlaceSelf === REPLACE) { // this may also create some invalid edges, for example if we're // intentionally causing something to get nested which was // previously placed in this location. for (const edgeIn of placed.edgesIn) { if (edgeIn === edge) { continue } const { valid, peerConflicted } = edgeIn if (!valid && !peerConflicted) { // if it's already been visited, we have to re-visit // otherwise, just enqueue normally. this.#depsSeen.delete(edgeIn.from) this.#depsQueue.push(edgeIn.from) } } } } /* istanbul ignore if - should be impossible */ if (cpd.canPlaceSelf === CONFLICT) { debug(() => { const er = new Error('placed with canPlaceSelf=CONFLICT') throw Object.assign(er, { placeDep: pd }) }) return } // lastly, also check for the missing deps of the node we placed, // and any holes created by pruning out conflicted peer sets. this.#depsQueue.push(placed) for (const dep of pd.needEvaluation) { this.#depsSeen.delete(dep) this.#depsQueue.push(dep) } // pre-fetch any problem edges, since we'll need these soon // if it fails at this point, though, dont' worry because it // may well be an optional dep that has gone missing. it'll // fail later anyway. for (const e of this.#problemEdges(placed)) { // XXX This is somehow load bearing. This makes tests that print // the ideal tree of a tree with tarball dependencies fail. This // can't be changed or removed till we figure out why // The test is named "tarball deps with transitive tarball deps" promises.push(() => this.#fetchManifest(npa.resolve(e.name, e.spec, fromPath(placed, e))) .catch(() => null) ) } }, }) } for (const { to } of node.edgesOut.values()) { if (to && to.isLink && to.target) { this.#linkNodes.add(to) } } await promiseCallLimit(promises) return this.#buildDepStep() } // loads a node from an edge, and then loads its peer deps (and their // peer deps, on down the line) into a virtual root parent. async #nodeFromEdge (edge, parent_, secondEdge, required) { // create a virtual root node with the same deps as the node that // is requesting this one, so that we can get all the peer deps in // a context where they're likely to be resolvable. // Note that the virtual root will also have virtual copies of the // targets of any child Links, so that they resolve appropriately. const parent = parent_ || this.#virtualRoot(edge.from) const spec = npa.resolve(edge.name, edge.spec, edge.from.path) const first = await this.#nodeFromSpec(edge.name, spec, parent, edge) // we might have a case where the parent has a peer dependency on // `foo@*` which resolves to v2, but another dep in the set has a // peerDependency on `foo@1`. In that case, if we force it to be v2, // we're unnecessarily triggering an ERESOLVE. // If we have a second edge to worry about, and it's not satisfied // by the first node, try a second and see if that satisfies the // original edge here. const spec2 = secondEdge && npa.resolve( edge.name, secondEdge.spec, secondEdge.from.path ) const second = secondEdge && !secondEdge.valid ? await this.#nodeFromSpec(edge.name, spec2, parent, secondEdge) : null // pick the second one if they're both happy with that, otherwise first const node = second && edge.valid ? second : first // ensure the one we want is the one that's placed node.parent = parent if (required.has(edge.from) && edge.type !== 'peerOptional' || secondEdge && ( required.has(secondEdge.from) && secondEdge.type !== 'peerOptional')) { required.add(node) } // keep track of the thing that caused this node to be included. const src = parent.sourceReference this.#peerSetSource.set(node, src) // do not load the peers along with the set if this is a global top pkg // otherwise we'll be tempted to put peers as other top-level installed // things, potentially clobbering what's there already, which is not // what we want. the missing edges will be picked up on the next pass. if (this.options.global && edge.from.isProjectRoot) { return node } // otherwise, we have to make sure that our peers can go along with us. return this.#loadPeerSet(node, required) } #virtualRoot (node, reuse = false) { if (reuse && this.#virtualRoots.has(node)) { return this.#virtualRoots.get(node) } const vr = new Node({ path: node.realpath, sourceReference: node, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, overrides: node.overrides, }) // also need to set up any targets from any link deps, so that // they are properly reflected in the virtual environment for (const child of node.children.values()) { if (child.isLink) { new Node({ path: child.realpath, sourceReference: child.target, root: vr, }) } } this.#virtualRoots.set(node, vr) return vr } #problemEdges (node) { // skip over any bundled deps, they're not our problem. // Note that this WILL fetch bundled meta-deps which are also dependencies // but not listed as bundled deps. When reifying, we first unpack any // nodes that have bundleDependencies, then do a loadActual on them, move // the nodes into the ideal tree, and then prune. So, fetching those // possibly-bundled meta-deps at this point doesn't cause any worse // problems than a few unnecessary packument fetches. // also skip over any nodes in the tree that failed to load, since those // will crash the install later on anyway. const bd = node.isProjectRoot || node.isWorkspace ? null : node.package.bundleDependencies const bundled = new Set(bd || []) const problems = [] for (const edge of node.edgesOut.values()) { // If it's included in a bundle, we take whatever is specified. if (bundled.has(edge.name)) { continue } // If it's already been logged as a load failure, skip it. if (edge.to && this.#loadFailures.has(edge.to)) { continue } // If it's shrinkwrapped, we use what the shrinkwap wants. if (edge.to && edge.to.inShrinkwrap) { continue } // If the edge has no destination, that's a problem, unless // if it's peerOptional and not explicitly requested. if (!edge.to) { if (edge.type !== 'peerOptional' || this.#explicitRequests.has(edge)) { problems.push(edge) } continue } // If the edge has an error, there's a problem. if (!edge.valid) { problems.push(edge) continue } // If the edge is a workspace, and it's valid, leave it alone if (edge.to.isWorkspace) { continue } // user explicitly asked to update this package by name, problem if (this[_updateNames].includes(edge.name)) { problems.push(edge) continue } // fixing a security vulnerability with this package, problem if (this.auditReport && this.auditReport.isVulnerable(edge.to)) { problems.push(edge) continue } // user has explicitly asked to install this package, problem if (this.#explicitRequests.has(edge)) { problems.push(edge) continue } } return problems } async #fetchManifest (spec) { const options = { ...this.options, avoid: this.#avoidRange(spec.name), fullMetadata: true, } // get the intended spec and stored metadata from yarn.lock file, // if available and valid. spec = this.idealTree.meta.checkYarnLock(spec, options) if (this.#manifests.has(spec.raw)) { return this.#manifests.get(spec.raw) } else { log.silly('fetch manifest', spec.raw.replace(spec.rawSpec, redact(spec.rawSpec))) const mani = await pacote.manifest(spec, options) this.#manifests.set(spec.raw, mani) return mani } } #nodeFromSpec (name, spec, parent, edge) { // pacote will slap integrity on its options, so we have to clone // the object so it doesn't get mutated. // Don't bother to load the manifest for link deps, because the target // might be within another package that doesn't exist yet. const { installLinks, legacyPeerDeps } = this const isWorkspace = this.idealTree.workspaces && this.idealTree.workspaces.has(spec.name) // spec is a directory, link it unless installLinks is set or it's a workspace // TODO post arborist refactor, will need to check for installStrategy=linked if (spec.type === 'directory' && (isWorkspace || !installLinks)) { return this.#linkFromSpec(name, spec, parent, edge) } // if the spec matches a workspace name, then see if the workspace node will // satisfy the edge. if it does, we return the workspace node to make sure it // takes priority. if (isWorkspace) { const existingNode = this.idealTree.edgesOut.get(spec.name).to if (existingNode && existingNode.isWorkspace && existingNode.satisfies(edge)) { return existingNode } } // spec isn't a directory, and either isn't a workspace or the workspace we have // doesn't satisfy the edge. try to fetch a manifest and build a node from that. return this.#fetchManifest(spec) .then(pkg => new Node({ name, pkg, parent, installLinks, legacyPeerDeps }), error => { error.requiredBy = edge.from.location || '.' // failed to load the spec, either because of enotarget or // fetch failure of some other sort. save it so we can verify // later that it's optional, otherwise the error is fatal. const n = new Node({ name, parent, error, installLinks, legacyPeerDeps, }) this.#loadFailures.add(n) return n }) } #linkFromSpec (name, spec, parent) { const realpath = spec.fetchSpec const { installLinks, legacyPeerDeps } = this return rpj(realpath + '/package.json').catch(() => ({})).then(pkg => { const link = new Link({ name, parent, realpath, pkg, installLinks, legacyPeerDeps }) this.#linkNodes.add(link) return link }) } // load all peer deps and meta-peer deps into the node's parent // At the end of this, the node's peer-type outward edges are all // resolved, and so are all of theirs, but other dep types are not. // We prefer to get peer deps that meet the requiring node's dependency, // if possible, since that almost certainly works (since that package was // developed with this set of deps) and will typically be more restrictive. // Note that the peers in the set can conflict either with each other, // or with a direct dependency from the virtual root parent! In strict // mode, this is always an error. In force mode, it never is, and we // prefer the parent's non-peer dep over a peer dep, or the version that // gets placed first. In non-strict mode, we behave strictly if the // virtual root is based on the root project, and allow non-peer parent // deps to override, but throw if no preference can be determined. async #loadPeerSet (node, required) { const peerEdges = [...node.edgesOut.values()] // we typically only install non-optional peers, but we have to // factor them into the peerSet so that we can avoid conflicts .filter(e => e.peer && !(e.valid && e.to)) .sort(({ name: a }, { name: b }) => localeCompare(a, b)) for (const edge of peerEdges) { // already placed this one, and we're happy with it. if (edge.valid && edge.to) { continue } const parentEdge = node.parent.edgesOut.get(edge.name) const { isProjectRoot, isWorkspace } = node.parent.sourceReference const isMine = isProjectRoot || isWorkspace const conflictOK = this.options.force || !isMine && !this.#strictPeerDeps if (!edge.to) { if (!parentEdge) { // easy, just put the thing there await this.#nodeFromEdge(edge, node.parent, null, required) continue } else { // if the parent's edge is very broad like >=1, and the edge in // question is something like 1.x, then we want to get a 1.x, not // a 2.x. pass along the child edge as an advisory guideline. // if the parent edge doesn't satisfy the child edge, and the // child edge doesn't satisfy the parent edge, then we have // a conflict. this is always a problem in strict mode, never // in force mode, and a problem in non-strict mode if this isn't // on behalf of our project. in all such cases, we warn at least. const dep = await this.#nodeFromEdge( parentEdge, node.parent, edge, required ) // hooray! that worked! if (edge.valid) { continue } // allow it. either we're overriding, or it's not something // that will be installed by default anyway, and we'll fail when // we get to the point where we need to, if we need to. if (conflictOK || !required.has(dep)) { edge.peerConflicted = true continue } // problem this.#failPeerConflict(edge, parentEdge) } } // There is something present already, and we're not happy about it // See if the thing we WOULD be happy with is also going to satisfy // the other dependents on the current node. const current = edge.to const dep = await this.#nodeFromEdge(edge, null, null, required) if (dep.canReplace(current)) { await this.#nodeFromEdge(edge, node.parent, null, required) continue } // at this point we know that there is a dep there, and // we don't like it. always fail strictly, always allow forcibly or // in non-strict mode if it's not our fault. don't warn here, because // we are going to warn again when we place the deps, if we end up // overriding for something else. If the thing that has this dep // isn't also required, then there's a good chance we won't need it, // so allow it for now and let it conflict if it turns out to actually // be necessary for the installation. if (conflictOK || !required.has(edge.from)) { continue } // ok, it's the root, or we're in unforced strict mode, so this is bad this.#failPeerConflict(edge, parentEdge) } return node } #failPeerConflict (edge, currentEdge) { const expl = this.#explainPeerConflict(edge, currentEdge) throw Object.assign(new Error('unable to resolve dependency tree'), expl) } #explainPeerConflict (edge, currentEdge) { const node = edge.from const curNode = node.resolve(edge.name) const current = curNode.explain() return { code: 'ERESOLVE', current, // it SHOULD be impossible to get here without a current node in place, // but this at least gives us something report on when bugs creep into // the tree handling logic. currentEdge: currentEdge ? currentEdge.explain() : null, edge: edge.explain(), strictPeerDeps: this.#strictPeerDeps, force: this.options.force, } } // go through all the links in the this.#linkNodes set // for each one: // - if outside the root, ignore it, assume it's fine, it's not our problem // - if a node in the tree already, assign the target to that node. // - if a path under an existing node, then assign that as the fsParent, // and add it to the _depsQueue // // call buildDepStep if anything was added to the queue, otherwise we're done #resolveLinks () { for (const link of this.#linkNodes) { this.#linkNodes.delete(link) // link we never ended up placing, skip it if (link.root !== this.idealTree) { continue } const tree = this.idealTree.target const external = !link.target.isDescendantOf(tree) // outside the root, somebody else's problem, ignore it if (external && !this.#follow) { continue } // didn't find a parent for it or it has not been seen yet // so go ahead and process it. const unseenLink = (link.target.parent || link.target.fsParent) && !this.#depsSeen.has(link.target) if (this.#follow && !link.target.parent && !link.target.fsParent || unseenLink) { this.addTracker('idealTree', link.target.name, link.target.location) this.#depsQueue.push(link.target) } } if (this.#depsQueue.length) { return this.#buildDepStep() } } #fixDepFlags () { const timeEnd = time.start('idealTree:fixDepFlags') const metaFromDisk = this.idealTree.meta.loadedFromDisk const flagsSuspect = this[_flagsSuspect] const mutateTree = this.#mutateTree // if the options set prune:false, then we don't prune, but we still // mark the extraneous items in the tree if we modified it at all. // If we did no modifications, we just iterate over the extraneous nodes. // if we started with an empty tree, then the dep flags are already // all set to true, and there can be nothing extraneous, so there's // nothing to prune, because we built it from scratch. if we didn't // add or remove anything, then also nothing to do. if (metaFromDisk && mutateTree) { resetDepFlags(this.idealTree) } // update all the dev/optional/etc flags in the tree // either we started with a fresh tree, or we // reset all the flags to find the extraneous nodes. // // if we started from a blank slate, or changed something, then // the dep flags will be all set to true. if (!metaFromDisk || mutateTree) { calcDepFlags(this.idealTree) } else { // otherwise just unset all the flags on the root node // since they will sometimes have the default value this.idealTree.extraneous = false this.idealTree.dev = false this.idealTree.optional = false this.idealTree.devOptional = false this.idealTree.peer = false } // at this point, any node marked as extraneous should be pruned. // if we started from a shrinkwrap, and then added/removed something, // then the tree is suspect. Prune what is marked as extraneous. // otherwise, don't bother. const needPrune = metaFromDisk && (mutateTree || flagsSuspect) if (this.#prune && needPrune) { this.#idealTreePrune() for (const node of this.idealTree.inventory.values()) { if (node.extraneous) { node.parent = null } } } timeEnd() } #idealTreePrune () { for (const node of this.idealTree.inventory.values()) { if (node.extraneous) { node.parent = null } } } #pruneFailedOptional () { for (const node of this.#loadFailures) { if (!node.optional) { throw node.errors[0] } const set = optionalSet(node) for (const node of set) { node.parent = null } } } async prune (options = {}) { // allow the user to set options on the ctor as well. // XXX: deprecate separate method options objects. options = { ...this.options, ...options } await this.buildIdealTree(options) this.#idealTreePrune() if (!this.options.workspacesEnabled) { const excludeNodes = this.excludeWorkspacesDependencySet(this.idealTree) for (const node of this.idealTree.inventory.values()) { if ( node.parent !== null && !node.isProjectRoot && !excludeNodes.has(node) ) { this[_addNodeToTrashList](node) } } } return this.reify(options) } } // The arborist manages three trees: // - actual // - virtual // - ideal // // The actual tree is what's present on disk in the node_modules tree // and elsewhere that links may extend. // // The virtual tree is loaded from metadata (package.json and lock files). // // The ideal tree is what we WANT that actual tree to become. This starts // with the virtual tree, and then applies the options requesting // add/remove/update actions. // // To reify a tree, we calculate a diff between the ideal and actual trees, // and then turn the actual tree into the ideal tree by taking the actions // required. At the end of the reification process, the actualTree is // updated to reflect the changes. // // Each tree has an Inventory at the root. Shrinkwrap is tracked by Arborist // instance. It always refers to the actual tree, but is updated (and written // to disk) on reification. // Each of the mixin "classes" adds functionality, but are not dependent on // constructor call order. So, we just load them in an array, and build up // the base class, so that the overall voltron class is easier to test and // cover, and separation of concerns can be maintained. const { resolve } = require('node:path') const { homedir } = require('node:os') const { depth } = require('treeverse') const mapWorkspaces = require('@npmcli/map-workspaces') const { log, time } = require('proc-log') const { saveTypeMap } = require('../add-rm-pkg-deps.js') const AuditReport = require('../audit-report.js') const relpath = require('../relpath.js') const PackumentCache = require('../packument-cache.js') const mixins = [ require('../tracker.js'), require('./build-ideal-tree.js'), require('./load-actual.js'), require('./load-virtual.js'), require('./rebuild.js'), require('./reify.js'), require('./isolated-reifier.js'), ] const _setWorkspaces = Symbol.for('setWorkspaces') const Base = mixins.reduce((a, b) => b(a), require('node:events')) // if it's 1, 2, or 3, set it explicitly that. // if undefined or null, set it null // otherwise, throw. const lockfileVersion = lfv => { if (lfv === 1 || lfv === 2 || lfv === 3) { return lfv } if (lfv === undefined || lfv === null) { return null } throw new TypeError('Invalid lockfileVersion config: ' + lfv) } class Arborist extends Base { constructor (options = {}) { const timeEnd = time.start('arborist:ctor') super(options) this.options = { nodeVersion: process.version, ...options, Arborist: this.constructor, binLinks: 'binLinks' in options ? !!options.binLinks : true, cache: options.cache || `${homedir()}/.npm/_cacache`, dryRun: !!options.dryRun, formatPackageLock: 'formatPackageLock' in options ? !!options.formatPackageLock : true, force: !!options.force, global: !!options.global, ignoreScripts: !!options.ignoreScripts, installStrategy: options.global ? 'shallow' : (options.installStrategy ? options.installStrategy : 'hoisted'), lockfileVersion: lockfileVersion(options.lockfileVersion), packageLockOnly: !!options.packageLockOnly, packumentCache: options.packumentCache || new PackumentCache(), path: options.path || '.', rebuildBundle: 'rebuildBundle' in options ? !!options.rebuildBundle : true, replaceRegistryHost: options.replaceRegistryHost, savePrefix: 'savePrefix' in options ? options.savePrefix : '^', scriptShell: options.scriptShell, workspaces: options.workspaces || [], workspacesEnabled: options.workspacesEnabled !== false, } // TODO we only ever look at this.options.replaceRegistryHost, not // this.replaceRegistryHost. Defaulting needs to be written back to // this.options to work properly this.replaceRegistryHost = this.options.replaceRegistryHost = (!this.options.replaceRegistryHost || this.options.replaceRegistryHost === 'npmjs') ? 'registry.npmjs.org' : this.options.replaceRegistryHost if (options.saveType && !saveTypeMap.get(options.saveType)) { throw new Error(`Invalid saveType ${options.saveType}`) } this.cache = resolve(this.options.cache) this.diff = null this.path = resolve(this.options.path) timeEnd() } // TODO: We should change these to static functions instead // of methods for the next major version // Get the actual nodes corresponding to a root node's child workspaces, // given a list of workspace names. workspaceNodes (tree, workspaces) { const wsMap = tree.workspaces if (!wsMap) { log.warn('workspaces', 'filter set, but no workspaces present') return [] } const nodes = [] for (const name of workspaces) { const path = wsMap.get(name) if (!path) { log.warn('workspaces', `${name} in filter set, but not in workspaces`) continue } const loc = relpath(tree.realpath, path) const node = tree.inventory.get(loc) if (!node) { log.warn('workspaces', `${name} in filter set, but no workspace folder present`) continue } nodes.push(node) } return nodes } // returns a set of workspace nodes and all their deps // TODO why is includeWorkspaceRoot a param? // TODO why is workspaces a param? workspaceDependencySet (tree, workspaces, includeWorkspaceRoot) { const wsNodes = this.workspaceNodes(tree, workspaces) if (includeWorkspaceRoot) { for (const edge of tree.edgesOut.values()) { if (edge.type !== 'workspace' && edge.to) { wsNodes.push(edge.to) } } } const wsDepSet = new Set(wsNodes) const extraneous = new Set() for (const node of wsDepSet) { for (const edge of node.edgesOut.values()) { const dep = edge.to if (dep) { wsDepSet.add(dep) if (dep.isLink) { wsDepSet.add(dep.target) } } } for (const child of node.children.values()) { if (child.extraneous) { extraneous.add(child) } } } for (const extra of extraneous) { wsDepSet.add(extra) } return wsDepSet } // returns a set of root dependencies, excluding dependencies that are // exclusively workspace dependencies excludeWorkspacesDependencySet (tree) { const rootDepSet = new Set() depth({ tree, visit: node => { for (const { to } of node.edgesOut.values()) { if (!to || to.isWorkspace) { continue } for (const edgeIn of to.edgesIn.values()) { if (edgeIn.from.isRoot || rootDepSet.has(edgeIn.from)) { rootDepSet.add(to) } } } return node }, filter: node => node, getChildren: (node, tree) => [...tree.edgesOut.values()].map(edge => edge.to), }) return rootDepSet } async [_setWorkspaces] (node) { const workspaces = await mapWorkspaces({ cwd: node.path, pkg: node.package, }) if (node && workspaces.size) { node.workspaces = workspaces } return node } async audit (options = {}) { this.addTracker('audit') if (this.options.global) { throw Object.assign( new Error('`npm audit` does not support testing globals'), { code: 'EAUDITGLOBAL' } ) } // allow the user to set options on the ctor as well. // XXX: deprecate separate method options objects. options = { ...this.options, ...options } const timeEnd = time.start('audit') let tree if (options.packageLock === false) { // build ideal tree await this.loadActual(options) await this.buildIdealTree() tree = this.idealTree } else { tree = await this.loadVirtual() } if (this.options.workspaces.length) { options.filterSet = this.workspaceDependencySet( tree, this.options.workspaces, this.options.includeWorkspaceRoot ) } if (!options.workspacesEnabled) { options.filterSet = this.excludeWorkspacesDependencySet(tree) } this.auditReport = await AuditReport.load(tree, options) const ret = options.fix ? this.reify(options) : this.auditReport timeEnd() this.finishTracker('audit') return ret } async dedupe (options = {}) { // allow the user to set options on the ctor as well. // XXX: deprecate separate method options objects. options = { ...this.options, ...options } const tree = await this.loadVirtual().catch(() => this.loadActual()) const names = [] for (const name of tree.inventory.query('name')) { if (tree.inventory.query('name', name).size > 1) { names.push(name) } } return this.reify({ ...options, preferDedupe: true, update: { names }, }) } } module.exports = Arborist const _makeIdealGraph = Symbol('makeIdealGraph') const _createIsolatedTree = Symbol.for('createIsolatedTree') const _createBundledTree = Symbol('createBundledTree') const { mkdirSync } = require('node:fs') const pacote = require('pacote') const { join } = require('node:path') const { depth } = require('treeverse') const crypto = require('node:crypto') // cache complicated function results const memoize = (fn) => { const memo = new Map() return async function (arg) { const key = arg if (memo.has(key)) { return memo.get(key) } const result = {} memo.set(key, result) await fn(result, arg) return result } } module.exports = cls => class IsolatedReifier extends cls { /** * Create an ideal graph. * * An implementation of npm RFC-0042 * https://github.com/npm/rfcs/blob/main/accepted/0042-isolated-mode.md * * This entire file should be considered technical debt that will be resolved * with an Arborist refactor or rewrite. Embedded logic in Nodes and Links, * and the incremental state of building trees and reifying contains too many * assumptions to do a linked mode properly. * * Instead, this approach takes a tree built from build-ideal-tree, and * returns a new tree-like structure without the embedded logic of Node and * Link classes. * * Since the RFC requires leaving the package-lock in place, this approach * temporarily replaces the tree state for a couple of steps of reifying. * **/ async [_makeIdealGraph] (options) { /* Make sure that the ideal tree is build as the rest of * the algorithm depends on it. */ const bitOpt = { ...options, complete: false, } await this.buildIdealTree(bitOpt) const idealTree = this.idealTree this.rootNode = {} const root = this.rootNode this.counter = 0 // memoize to cache generating proxy Nodes this.externalProxyMemo = memoize(this.externalProxy.bind(this)) this.workspaceProxyMemo = memoize(this.workspaceProxy.bind(this)) root.external = [] root.isProjectRoot = true root.localLocation = idealTree.location root.localPath = idealTree.path root.workspaces = await Promise.all( Array.from(idealTree.fsChildren.values(), this.workspaceProxyMemo)) const processed = new Set() const queue = [idealTree, ...idealTree.fsChildren] while (queue.length !== 0) { const next = queue.pop() if (processed.has(next.location)) { continue } processed.add(next.location) next.edgesOut.forEach(e => { if (!e.to || (next.package.bundleDependencies || next.package.bundledDependencies || []).includes(e.to.name)) { return } queue.push(e.to) }) if (!next.isProjectRoot && !next.isWorkspace) { root.external.push(await this.externalProxyMemo(next)) } } await this.assignCommonProperties(idealTree, root) this.idealGraph = root } async workspaceProxy (result, node) { result.localLocation = node.location result.localPath = node.path result.isWorkspace = true result.resolved = node.resolved await this.assignCommonProperties(node, result) } async externalProxy (result, node) { await this.assignCommonProperties(node, result) if (node.hasShrinkwrap) { const dir = join( node.root.path, 'node_modules', '.store', `${node.name}@${node.version}` ) mkdirSync(dir, { recursive: true }) // TODO this approach feels wrong // and shouldn't be necessary for shrinkwraps await pacote.extract(node.resolved, dir, { ...this.options, resolved: node.resolved, integrity: node.integrity, }) const Arborist = this.constructor const arb = new Arborist({ ...this.options, path: dir }) await arb[_makeIdealGraph]({ dev: false }) this.rootNode.external.push(...arb.idealGraph.external) arb.idealGraph.external.forEach(e => { e.root = this.rootNode e.id = `${node.id}=>${e.id}` }) result.localDependencies = [] result.externalDependencies = arb.idealGraph.externalDependencies result.externalOptionalDependencies = arb.idealGraph.externalOptionalDependencies result.dependencies = [ ...result.externalDependencies, ...result.localDependencies, ...result.externalOptionalDependencies, ] } result.optional = node.optional result.resolved = node.resolved result.version = node.version } async assignCommonProperties (node, result) { function validEdgesOut (node) { return [...node.edgesOut.values()].filter(e => e.to && e.to.target && !(node.package.bundledDepenedencies || node.package.bundleDependencies || []).includes(e.to.name)) } const edges = validEdgesOut(node) const optionalDeps = edges.filter(e => e.optional).map(e => e.to.target) const nonOptionalDeps = edges.filter(e => !e.optional).map(e => e.to.target) result.localDependencies = await Promise.all(nonOptionalDeps.filter(n => n.isWorkspace).map(this.workspaceProxyMemo)) result.externalDependencies = await Promise.all(nonOptionalDeps.filter(n => !n.isWorkspace).map(this.externalProxyMemo)) result.externalOptionalDependencies = await Promise.all(optionalDeps.map(this.externalProxyMemo)) result.dependencies = [ ...result.externalDependencies, ...result.localDependencies, ...result.externalOptionalDependencies, ] result.root = this.rootNode result.id = this.counter++ result.name = node.name result.package = { ...node.package } result.package.bundleDependencies = undefined result.hasInstallScript = node.hasInstallScript } async [_createBundledTree] () { // TODO: make sure that idealTree object exists const idealTree = this.idealTree // TODO: test workspaces having bundled deps const queue = [] for (const [, edge] of idealTree.edgesOut) { if (edge.to && (idealTree.package.bundleDependencies || idealTree.package.bundledDependencies || []).includes(edge.to.name)) { queue.push({ from: idealTree, to: edge.to }) } } for (const child of idealTree.fsChildren) { for (const [, edge] of child.edgesOut) { if (edge.to && (child.package.bundleDependencies || child.package.bundledDependencies || []).includes(edge.to.name)) { queue.push({ from: child, to: edge.to }) } } } const processed = new Set() const nodes = new Map() const edges = [] while (queue.length !== 0) { const nextEdge = queue.pop() const key = `${nextEdge.from.location}=>${nextEdge.to.location}` // should be impossible, unless bundled is duped /* istanbul ignore next */ if (processed.has(key)) { continue } processed.add(key) const from = nextEdge.from if (!from.isRoot && !from.isWorkspace) { nodes.set(from.location, { location: from.location, resolved: from.resolved, name: from.name, optional: from.optional, pkg: { ...from.package, bundleDependencies: undefined } }) } const to = nextEdge.to nodes.set(to.location, { location: to.location, resolved: to.resolved, name: to.name, optional: to.optional, pkg: { ...to.package, bundleDependencies: undefined } }) edges.push({ from: from.isRoot ? 'root' : from.location, to: to.location }) to.edgesOut.forEach(e => { // an edge out should always have a to /* istanbul ignore else */ if (e.to) { queue.push({ from: e.from, to: e.to }) } }) } return { edges, nodes } } async [_createIsolatedTree] () { await this[_makeIdealGraph](this.options) const proxiedIdealTree = this.idealGraph const bundledTree = await this[_createBundledTree]() const treeHash = (startNode) => { // generate short hash based on the dependency tree // starting at this node const deps = [] const branch = [] depth({ tree: startNode, getChildren: node => node.dependencies, filter: node => node, visit: node => { branch.push(`${node.name}@${node.version}`) deps.push(`${branch.join('->')}::${node.resolved}`) }, leave: () => { branch.pop() }, }) deps.sort() return crypto.createHash('shake256', { outputLength: 16 }) .update(deps.join(',')) .digest('base64') // Node v14 doesn't support base64url .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/m, '') } const getKey = (idealTreeNode) => { return `${idealTreeNode.name}@${idealTreeNode.version}-${treeHash(idealTreeNode)}` } const root = { fsChildren: [], integrity: null, inventory: new Map(), isLink: false, isRoot: true, binPaths: [], edgesIn: new Set(), edgesOut: new Map(), hasShrinkwrap: false, parent: null, // TODO: we should probably not reference this.idealTree resolved: this.idealTree.resolved, isTop: true, path: proxiedIdealTree.root.localPath, realpath: proxiedIdealTree.root.localPath, package: proxiedIdealTree.root.package, meta: { loadedFromDisk: false }, global: false, isProjectRoot: true, children: [], } // root.inventory.set('', t) // root.meta = this.idealTree.meta // TODO We should mock better the inventory object because it is used by audit-report.js ... maybe root.inventory.query = () => { return [] } const processed = new Set() proxiedIdealTree.workspaces.forEach(c => { const workspace = { edgesIn: new Set(), edgesOut: new Map(), children: [], hasInstallScript: c.hasInstallScript, binPaths: [], package: c.package, location: c.localLocation, path: c.localPath, realpath: c.localPath, resolved: c.resolved, } root.fsChildren.push(workspace) root.inventory.set(workspace.location, workspace) }) const generateChild = (node, location, pkg, inStore) => { const newChild = { global: false, globalTop: false, isProjectRoot: false, isTop: false, location, name: node.name, optional: node.optional, top: { path: proxiedIdealTree.root.localPath }, children: [], edgesIn: new Set(), edgesOut: new Map(), binPaths: [], fsChildren: [], /* istanbul ignore next -- emulate Node */ getBundler () { return null }, hasShrinkwrap: false, inDepBundle: false, integrity: null, isLink: false, isRoot: false, isInStore: inStore, path: join(proxiedIdealTree.root.localPath, location), realpath: join(proxiedIdealTree.root.localPath, location), resolved: node.resolved, version: pkg.version, package: pkg, } newChild.target = newChild root.children.push(newChild) root.inventory.set(newChild.location, newChild) } proxiedIdealTree.external.forEach(c => { const key = getKey(c) if (processed.has(key)) { return } processed.add(key) const location = join('node_modules', '.store', key, 'node_modules', c.name) generateChild(c, location, c.package, true) }) bundledTree.nodes.forEach(node => { generateChild(node, node.location, node.pkg, false) }) bundledTree.edges.forEach(e => { const from = e.from === 'root' ? root : root.inventory.get(e.from) const to = root.inventory.get(e.to) // Maybe optional should be propagated from the original edge const edge = { optional: false, from, to } from.edgesOut.set(to.name, edge) to.edgesIn.add(edge) }) const memo = new Set() function processEdges (node, externalEdge) { externalEdge = !!externalEdge const key = getKey(node) if (memo.has(key)) { return } memo.add(key) let from, nmFolder if (externalEdge) { const fromLocation = join('node_modules', '.store', key, 'node_modules', node.name) from = root.children.find(c => c.location === fromLocation) nmFolder = join('node_modules', '.store', key, 'node_modules') } else { from = node.isProjectRoot ? root : root.fsChildren.find(c => c.location === node.localLocation) nmFolder = join(node.localLocation, 'node_modules') } const processDeps = (dep, optional, external) => { optional = !!optional external = !!external const location = join(nmFolder, dep.name) const binNames = dep.package.bin && Object.keys(dep.package.bin) || [] const toKey = getKey(dep) let target if (external) { const toLocation = join('node_modules', '.store', toKey, 'node_modules', dep.name) target = root.children.find(c => c.location === toLocation) } else { target = root.fsChildren.find(c => c.location === dep.localLocation) } // TODO: we should no-op is an edge has already been created with the same fromKey and toKey binNames.forEach(bn => { target.binPaths.push(join(from.realpath, 'node_modules', '.bin', bn)) }) const link = { global: false, globalTop: false, isProjectRoot: false, edgesIn: new Set(), edgesOut: new Map(), binPaths: [], isTop: false, optional, location: location, path: join(dep.root.localPath, nmFolder, dep.name), realpath: target.path, name: toKey, resolved: dep.resolved, top: { path: dep.root.localPath }, children: [], fsChildren: [], isLink: true, isStoreLink: true, isRoot: false, package: { _id: 'abc', bundleDependencies: undefined, deprecated: undefined, bin: target.package.bin, scripts: dep.package.scripts }, target, } const newEdge1 = { optional, from, to: link } from.edgesOut.set(dep.name, newEdge1) link.edgesIn.add(newEdge1) const newEdge2 = { optional: false, from: link, to: target } link.edgesOut.set(dep.name, newEdge2) target.edgesIn.add(newEdge2) root.children.push(link) } for (const dep of node.localDependencies) { processEdges(dep, false) // nonOptional, local processDeps(dep, false, false) } for (const dep of node.externalDependencies) { processEdges(dep, true) // nonOptional, external processDeps(dep, false, true) } for (const dep of node.externalOptionalDependencies) { processEdges(dep, true) // optional, external processDeps(dep, true, true) } } processEdges(proxiedIdealTree, false) for (const node of proxiedIdealTree.workspaces) { processEdges(node, false) } root.children.forEach(c => c.parent = root) root.children.forEach(c => c.root = root) root.root = root root.target = root return root } } // mix-in implementing the loadActual method const { relative, dirname, resolve, join, normalize } = require('node:path') const rpj = require('read-package-json-fast') const { readdirScoped } = require('@npmcli/fs') const { walkUp } = require('walk-up-path') const ancestorPath = require('common-ancestor-path') const treeCheck = require('../tree-check.js') const Shrinkwrap = require('../shrinkwrap.js') const calcDepFlags = require('../calc-dep-flags.js') const Node = require('../node.js') const Link = require('../link.js') const realpath = require('../realpath.js') // public symbols const _changePath = Symbol.for('_changePath') const _setWorkspaces = Symbol.for('setWorkspaces') const _rpcache = Symbol.for('realpathCache') const _stcache = Symbol.for('statCache') module.exports = cls => class ActualLoader extends cls { #actualTree // ensure when walking the tree that we don't call loadTree on the same // actual node more than one time. #actualTreeLoaded = new Set() #actualTreePromise // cache of nodes when loading the actualTree, so that we avoid loaded the // same node multiple times when symlinks attack. #cache = new Map() #filter // cache of link targets for setting fsParent links // We don't do fsParent as a magic getter/setter, because it'd be too costly // to keep up to date along the walk. // And, we know that it can ONLY be relevant when the node is a target of a // link, otherwise it'd be in a node_modules folder, so take advantage of // that to limit the scans later. #topNodes = new Set() #transplantFilter constructor (options) { super(options) // the tree of nodes on disk this.actualTree = options.actualTree // caches for cached realpath calls const cwd = process.cwd() // assume that the cwd is real enough for our purposes this[_rpcache] = new Map([[cwd, cwd]]) this[_stcache] = new Map() } // public method // TODO remove options param in next semver major async loadActual (options = {}) { // In the past this.actualTree was set as a promise that eventually // resolved, and overwrite this.actualTree with the resolved value. This // was a problem because virtually no other code expects this.actualTree to // be a promise. Instead we only set it once resolved, and also return it // from the promise so that it is what's returned from this function when // awaited. if (this.actualTree) { return this.actualTree } if (!this.#actualTreePromise) { // allow the user to set options on the ctor as well. // XXX: deprecate separate method options objects. options = { ...this.options, ...options } this.#actualTreePromise = this.#loadActual(options) .then(tree => { // reset all deps to extraneous prior to recalc if (!options.root) { for (const node of tree.inventory.values()) { node.extraneous = true } } // only reset root flags if we're not re-rooting, // otherwise leave as-is calcDepFlags(tree, !options.root) this.actualTree = treeCheck(tree) return this.actualTree }) } return this.#actualTreePromise } // return the promise so that we don't ever have more than one going at the // same time. This is so that buildIdealTree can default to the actualTree // if no shrinkwrap present, but reify() can still call buildIdealTree and // loadActual in parallel safely. async #loadActual (options) { // mostly realpath to throw if the root doesn't exist const { global, filter = () => true, root = null, transplantFilter = () => true, ignoreMissing = false, forceActual = false, } = options this.#filter = filter this.#transplantFilter = transplantFilter if (global) { const real = await realpath(this.path, this[_rpcache], this[_stcache]) const params = { path: this.path, realpath: real, pkg: {}, global, loadOverrides: true, } if (this.path === real) { this.#actualTree = this.#newNode(params) } else { this.#actualTree = await this.#newLink(params) } } else { // not in global mode, hidden lockfile is allowed, load root pkg too this.#actualTree = await this.#loadFSNode({ path: this.path, real: await realpath(this.path, this[_rpcache], this[_stcache]), loadOverrides: true, }) this.#actualTree.assertRootOverrides() // if forceActual is set, don't even try the hidden lockfile if (!forceActual) { // Note: hidden lockfile will be rejected if it's not the latest thing // in the folder, or if any of the entries in the hidden lockfile are // missing. const meta = await Shrinkwrap.load({ path: this.#actualTree.path, hiddenLockfile: true, resolveOptions: this.options, }) if (meta.loadedFromDisk) { this.#actualTree.meta = meta // have to load on a new Arborist object, so we don't assign // the virtualTree on this one! Also, the weird reference is because // we can't easily get a ref to Arborist in this module, without // creating a circular reference, since this class is a mixin used // to build up the Arborist class itself. await new this.constructor({ ...this.options }).loadVirtual({ root: this.#actualTree, }) await this[_setWorkspaces](this.#actualTree) this.#transplant(root) return this.#actualTree } } const meta = await Shrinkwrap.load({ path: this.#actualTree.path, lockfileVersion: this.options.lockfileVersion, resolveOptions: this.options, }) this.#actualTree.meta = meta } await this.#loadFSTree(this.#actualTree) await this[_setWorkspaces](this.#actualTree) // if there are workspace targets without Link nodes created, load // the targets, so that we know what they are. if (this.#actualTree.workspaces && this.#actualTree.workspaces.size) { const promises = [] for (const path of this.#actualTree.workspaces.values()) { if (!this.#cache.has(path)) { // workspace overrides use the root overrides const p = this.#loadFSNode({ path, root: this.#actualTree, useRootOverrides: true }) .then(node => this.#loadFSTree(node)) promises.push(p) } } await Promise.all(promises) } if (!ignoreMissing) { await this.#findMissingEdges() } // try to find a node that is the parent in a fs tree sense, but not a // node_modules tree sense, of any link targets. this allows us to // resolve deps that node will find, but a legacy npm view of the // world would not have noticed. for (const path of this.#topNodes) { const node = this.#cache.get(path) if (node && !node.parent && !node.fsParent) { for (const p of walkUp(dirname(path))) { if (this.#cache.has(p)) { node.fsParent = this.#cache.get(p) break } } } } this.#transplant(root) if (global) { // need to depend on the children, or else all of them // will end up being flagged as extraneous, since the // global root isn't a "real" project const tree = this.#actualTree const actualRoot = tree.isLink ? tree.target : tree const { dependencies = {} } = actualRoot.package for (const [name, kid] of actualRoot.children.entries()) { const def = kid.isLink ? `file:${kid.realpath.replace(/#/g, '%23')}` : '*' dependencies[name] = dependencies[name] || def } actualRoot.package = { ...actualRoot.package, dependencies } } return this.#actualTree } #transplant (root) { if (!root || root === this.#actualTree) { return } this.#actualTree[_changePath](root.path) for (const node of this.#actualTree.children.values()) { if (!this.#transplantFilter(node)) { node.root = null } } root.replace(this.#actualTree) for (const node of this.#actualTree.fsChildren) { node.root = this.#transplantFilter(node) ? root : null } this.#actualTree = root } async #loadFSNode ({ path, parent, real, root, loadOverrides, useRootOverrides }) { if (!real) { try { real = await realpath(path, this[_rpcache], this[_stcache]) } catch (error) { // if realpath fails, just provide a dummy error node return new Node({ error, path, realpath: path, parent, root, loadOverrides, }) } } const cached = this.#cache.get(path) let node // missing edges get a dummy node, assign the parent and return it if (cached && !cached.dummy) { cached.parent = parent return cached } else { const params = { installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, path, realpath: real, parent, root, loadOverrides, } try { const pkg = await rpj(join(real, 'package.json')) params.pkg = pkg if (useRootOverrides && root.overrides) { params.overrides = root.overrides.getNodeRule({ name: pkg.name, version: pkg.version }) } } catch (err) { params.error = err } // soldier on if read-package-json raises an error, passing it to the // Node which will attach it to its errors array (Link passes it along to // its target node) if (normalize(path) === real) { node = this.#newNode(params) } else { node = await this.#newLink(params) } } this.#cache.set(path, node) return node } #newNode (options) { // check it for an fsParent if it's a tree top. there's a decent chance // it'll get parented later, making the fsParent scan a no-op, but better // safe than sorry, since it's cheap. const { parent, realpath } = options if (!parent) { this.#topNodes.add(realpath) } return new Node(options) } async #newLink (options) { const { realpath } = options this.#topNodes.add(realpath) const target = this.#cache.get(realpath) const link = new Link({ ...options, target }) if (!target) { // Link set its target itself in this case this.#cache.set(realpath, link.target) // if a link target points at a node outside of the root tree's // node_modules hierarchy, then load that node as well. await this.#loadFSTree(link.target) } return link } async #loadFSTree (node) { const did = this.#actualTreeLoaded if (!node.isLink && !did.has(node.target.realpath)) { did.add(node.target.realpath) await this.#loadFSChildren(node.target) return Promise.all( [...node.target.children.entries()] .filter(([, kid]) => !did.has(kid.realpath)) .map(([, kid]) => this.#loadFSTree(kid)) ) } } // create child nodes for all the entries in node_modules // and attach them to the node as a parent async #loadFSChildren (node) { const nm = resolve(node.realpath, 'node_modules') try { const kids = await readdirScoped(nm).then(paths => paths.map(p => p.replace(/\\/g, '/'))) return Promise.all( // ignore . dirs and retired scoped package folders kids.filter(kid => !/^(@[^/]+\/)?\./.test(kid)) .filter(kid => this.#filter(node, kid)) .map(kid => this.#loadFSNode({ parent: node, path: resolve(nm, kid), }))) } catch { // error in the readdir is not fatal, just means no kids } } async #findMissingEdges () { // try to resolve any missing edges by walking up the directory tree, // checking for the package in each node_modules folder. stop at the // root directory. // The tricky move here is that we load a "dummy" node for the folder // containing the node_modules folder, so that it can be assigned as // the fsParent. It's a bad idea to *actually* load that full node, // because people sometimes develop in ~/projects/node_modules/... // so we'd end up loading a massive tree with lots of unrelated junk. const nmContents = new Map() const tree = this.#actualTree for (const node of tree.inventory.values()) { const ancestor = ancestorPath(node.realpath, this.path) const depPromises = [] for (const [name, edge] of node.edgesOut.entries()) { const notMissing = !edge.missing && !(edge.to && (edge.to.dummy || edge.to.parent !== node)) if (notMissing) { continue } // start the walk from the dirname, because we would have found // the dep in the loadFSTree step already if it was local. for (const p of walkUp(dirname(node.realpath))) { // only walk as far as the nearest ancestor // this keeps us from going into completely unrelated // places when a project is just missing something, but // allows for finding the transitive deps of link targets. // ie, if it has to go up and back out to get to the path // from the nearest common ancestor, we've gone too far. if (ancestor && /^\.\.(?:[\\/]|$)/.test(relative(ancestor, p))) { break } let entries if (!nmContents.has(p)) { entries = await readdirScoped(p + '/node_modules') .catch(() => []).then(paths => paths.map(p => p.replace(/\\/g, '/'))) nmContents.set(p, entries) } else { entries = nmContents.get(p) } if (!entries.includes(name)) { continue } let d if (!this.#cache.has(p)) { d = new Node({ path: p, root: node.root, dummy: true }) this.#cache.set(p, d) } else { d = this.#cache.get(p) } if (d.dummy) { // it's a placeholder, so likely would not have loaded this dep, // unless another dep in the tree also needs it. const depPath = normalize(`${p}/node_modules/${name}`) const cached = this.#cache.get(depPath) if (!cached || cached.dummy) { depPromises.push(this.#loadFSNode({ path: depPath, root: node.root, parent: d, }).then(node => this.#loadFSTree(node))) } } break } } await Promise.all(depPromises) } } } // mixin providing the loadVirtual method const mapWorkspaces = require('@npmcli/map-workspaces') const { resolve } = require('node:path') const nameFromFolder = require('@npmcli/name-from-folder') const consistentResolve = require('../consistent-resolve.js') const Shrinkwrap = require('../shrinkwrap.js') const Node = require('../node.js') const Link = require('../link.js') const relpath = require('../relpath.js') const calcDepFlags = require('../calc-dep-flags.js') const rpj = require('read-package-json-fast') const treeCheck = require('../tree-check.js') const flagsSuspect = Symbol.for('flagsSuspect') const setWorkspaces = Symbol.for('setWorkspaces') module.exports = cls => class VirtualLoader extends cls { #rootOptionProvided constructor (options) { super(options) // the virtual tree we load from a shrinkwrap this.virtualTree = options.virtualTree this[flagsSuspect] = false } // public method async loadVirtual (options = {}) { if (this.virtualTree) { return this.virtualTree } // allow the user to set reify options on the ctor as well. // XXX: deprecate separate reify() options object. options = { ...this.options, ...options } if (options.root && options.root.meta) { await this.#loadFromShrinkwrap(options.root.meta, options.root) return treeCheck(this.virtualTree) } const s = await Shrinkwrap.load({ path: this.path, lockfileVersion: this.options.lockfileVersion, resolveOptions: this.options, }) if (!s.loadedFromDisk && !options.root) { const er = new Error('loadVirtual requires existing shrinkwrap file') throw Object.assign(er, { code: 'ENOLOCK' }) } // when building the ideal tree, we pass in a root node to this function // otherwise, load it from the root package json or the lockfile const { root = await this.#loadRoot(s), } = options this.#rootOptionProvided = options.root await this.#loadFromShrinkwrap(s, root) root.assertRootOverrides() return treeCheck(this.virtualTree) } async #loadRoot (s) { const pj = this.path + '/package.json' const pkg = await rpj(pj).catch(() => s.data.packages['']) || {} return this[setWorkspaces](this.#loadNode('', pkg, true)) } async #loadFromShrinkwrap (s, root) { if (!this.#rootOptionProvided) { // root is never any of these things, but might be a brand new // baby Node object that never had its dep flags calculated. root.extraneous = false root.dev = false root.optional = false root.devOptional = false root.peer = false } else { this[flagsSuspect] = true } this.#checkRootEdges(s, root) root.meta = s this.virtualTree = root const { links, nodes } = this.#resolveNodes(s, root) await this.#resolveLinks(links, nodes) if (!(s.originalLockfileVersion >= 2)) { this.#assignBundles(nodes) } if (this[flagsSuspect]) { // reset all dep flags // can't use inventory here, because virtualTree might not be root for (const node of nodes.values()) { if (node.isRoot || node === this.#rootOptionProvided) { continue } node.extraneous = true node.dev = true node.optional = true node.devOptional = true node.peer = true } calcDepFlags(this.virtualTree, !this.#rootOptionProvided) } return root } // check the lockfile deps, and see if they match. if they do not // then we have to reset dep flags at the end. for example, if the // user manually edits their package.json file, then we need to know // that the idealTree is no longer entirely trustworthy. #checkRootEdges (s, root) { // loaded virtually from tree, no chance of being out of sync // ancient lockfiles are critically damaged by this process, // so we need to just hope for the best in those cases. if (!s.loadedFromDisk || s.ancientLockfile) { return } const lock = s.get('') const prod = lock.dependencies || {} const dev = lock.devDependencies || {} const optional = lock.optionalDependencies || {} const peer = lock.peerDependencies || {} const peerOptional = {} if (lock.peerDependenciesMeta) { for (const [name, meta] of Object.entries(lock.peerDependenciesMeta)) { if (meta.optional && peer[name] !== undefined) { peerOptional[name] = peer[name] delete peer[name] } } } for (const name of Object.keys(optional)) { delete prod[name] } const lockWS = {} const workspaces = mapWorkspaces.virtual({ cwd: this.path, lockfile: s.data, }) for (const [name, path] of workspaces.entries()) { lockWS[name] = `file:${path.replace(/#/g, '%23')}` } // Should rootNames exclude optional? const rootNames = new Set(root.edgesOut.keys()) const lockByType = ({ dev, optional, peer, peerOptional, prod, workspace: lockWS }) // Find anything in shrinkwrap deps that doesn't match root's type or spec for (const type in lockByType) { const deps = lockByType[type] for (const name in deps) { const edge = root.edgesOut.get(name) if (!edge || edge.type !== type || edge.spec !== deps[name]) { return this[flagsSuspect] = true } rootNames.delete(name) } } // Something was in root that's not accounted for in shrinkwrap if (rootNames.size) { return this[flagsSuspect] = true } } // separate out link metadatas, and create Node objects for nodes #resolveNodes (s, root) { const links = new Map() const nodes = new Map([['', root]]) for (const [location, meta] of Object.entries(s.data.packages)) { // skip the root because we already got it if (!location) { continue } if (meta.link) { links.set(location, meta) } else { nodes.set(location, this.#loadNode(location, meta)) } } return { links, nodes } } // links is the set of metadata, and nodes is the map of non-Link nodes // Set the targets to nodes in the set, if we have them (we might not) async #resolveLinks (links, nodes) { for (const [location, meta] of links.entries()) { const targetPath = resolve(this.path, meta.resolved) const targetLoc = relpath(this.path, targetPath) const target = nodes.get(targetLoc) const link = this.#loadLink(location, targetLoc, target, meta) nodes.set(location, link) nodes.set(targetLoc, link.target) // we always need to read the package.json for link targets // outside node_modules because they can be changed by the local user if (!link.target.parent) { const pj = link.realpath + '/package.json' const pkg = await rpj(pj).catch(() => null) if (pkg) { link.target.package = pkg } } } } #assignBundles (nodes) { for (const [location, node] of nodes) { // Skip assignment of parentage for the root package if (!location || node.isLink && !node.target.location) { continue } const { name, parent, package: { inBundle } } = node if (!parent) { continue } // read inBundle from package because 'package' here is // actually a v2 lockfile metadata entry. // If the *parent* is also bundled, though, or if the parent has // no dependency on it, then we assume that it's being pulled in // just by virtue of its parent or a transitive dep being bundled. const { package: ppkg } = parent const { inBundle: parentBundled } = ppkg if (inBundle && !parentBundled && parent.edgesOut.has(node.name)) { if (!ppkg.bundleDependencies) { ppkg.bundleDependencies = [name] } else { ppkg.bundleDependencies.push(name) } } } } #loadNode (location, sw, loadOverrides) { const p = this.virtualTree ? this.virtualTree.realpath : this.path const path = resolve(p, location) // shrinkwrap doesn't include package name unless necessary if (!sw.name) { sw.name = nameFromFolder(path) } const dev = sw.dev const optional = sw.optional const devOptional = dev || optional || sw.devOptional const peer = sw.peer const node = new Node({ installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, root: this.virtualTree, path, realpath: path, integrity: sw.integrity, resolved: consistentResolve(sw.resolved, this.path, path), pkg: sw, hasShrinkwrap: sw.hasShrinkwrap, dev, optional, devOptional, peer, loadOverrides, }) // cast to boolean because they're undefined in the lock file when false node.extraneous = !!sw.extraneous node.devOptional = !!(sw.devOptional || sw.dev || sw.optional) node.peer = !!sw.peer node.optional = !!sw.optional node.dev = !!sw.dev return node } #loadLink (location, targetLoc, target) { const path = resolve(this.path, location) const link = new Link({ installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, path, realpath: resolve(this.path, targetLoc), target, pkg: target && target.package, }) link.extraneous = target.extraneous link.devOptional = target.devOptional link.peer = target.peer link.optional = target.optional link.dev = target.dev return link } } // Arborist.rebuild({path = this.path}) will do all the binlinks and // bundle building needed. Called by reify, and by `npm rebuild`. const localeCompare = require('@isaacs/string-locale-compare')('en') const { depth: dfwalk } = require('treeverse') const promiseAllRejectLate = require('promise-all-reject-late') const rpj = require('read-package-json-fast') const binLinks = require('bin-links') const runScript = require('@npmcli/run-script') const { callLimit: promiseCallLimit } = require('promise-call-limit') const { resolve } = require('node:path') const { isNodeGypPackage, defaultGypInstallScript } = require('@npmcli/node-gyp') const { log, time } = require('proc-log') const boolEnv = b => b ? '1' : '' const sortNodes = (a, b) => (a.depth - b.depth) || localeCompare(a.path, b.path) const _checkBins = Symbol.for('checkBins') // defined by reify mixin const _handleOptionalFailure = Symbol.for('handleOptionalFailure') const _trashList = Symbol.for('trashList') module.exports = cls => class Builder extends cls { #doHandleOptionalFailure #oldMeta = null #queues constructor (options) { super(options) this.scriptsRun = new Set() this.#resetQueues() } async rebuild ({ nodes, handleOptionalFailure = false } = {}) { // nothing to do if we're not building anything! if (this.options.ignoreScripts && !this.options.binLinks) { return } // when building for the first time, as part of reify, we ignore // failures in optional nodes, and just delete them. however, when // running JUST a rebuild, we treat optional failures as real fails this.#doHandleOptionalFailure = handleOptionalFailure if (!nodes) { nodes = await this.#loadDefaultNodes() } // separates links nodes so that it can run // prepare scripts and link bins in the expected order const timeEnd = time.start('build') const { depNodes, linkNodes, } = this.#retrieveNodesByType(nodes) // build regular deps await this.#build(depNodes, {}) // build link deps if (linkNodes.size) { this.#resetQueues() await this.#build(linkNodes, { type: 'links' }) } timeEnd() } // if we don't have a set of nodes, then just rebuild // the actual tree on disk. async #loadDefaultNodes () { let nodes const tree = await this.loadActual() let filterSet if (!this.options.workspacesEnabled) { filterSet = this.excludeWorkspacesDependencySet(tree) nodes = tree.inventory.filter(node => filterSet.has(node) || node.isProjectRoot ) } else if (this.options.workspaces.length) { filterSet = this.workspaceDependencySet( tree, this.options.workspaces, this.options.includeWorkspaceRoot ) nodes = tree.inventory.filter(node => filterSet.has(node)) } else { nodes = tree.inventory.values() } return nodes } #retrieveNodesByType (nodes) { const depNodes = new Set() const linkNodes = new Set() const storeNodes = new Set() for (const node of nodes) { if (node.isStoreLink) { storeNodes.add(node) } else if (node.isLink) { linkNodes.add(node) } else { depNodes.add(node) } } // Make sure that store linked nodes are processed last. // We can't process store links separately or else lifecycle scripts on // standard nodes might not have bin links yet. for (const node of storeNodes) { depNodes.add(node) } // deduplicates link nodes and their targets, avoids // calling lifecycle scripts twice when running `npm rebuild` // ref: https://github.com/npm/cli/issues/2905 // // we avoid doing so if global=true since `bin-links` relies // on having the target nodes available in global mode. if (!this.options.global) { for (const node of linkNodes) { depNodes.delete(node.target) } } return { depNodes, linkNodes, } } #resetQueues () { this.#queues = { preinstall: [], install: [], postinstall: [], prepare: [], bin: [], } } async #build (nodes, { type = 'deps' }) { const timeEnd = time.start(`build:${type}`) await this.#buildQueues(nodes) if (!this.options.ignoreScripts) { await this.#runScripts('preinstall') } // links should run prepare scripts and only link bins after that if (type === 'links') { if (!this.options.ignoreScripts) { await this.#runScripts('prepare') } } if (this.options.binLinks) { await this.#linkAllBins() } if (!this.options.ignoreScripts) { await this.#runScripts('install') await this.#runScripts('postinstall') } timeEnd() } async #buildQueues (nodes) { const timeEnd = time.start('build:queue') const set = new Set() const promises = [] for (const node of nodes) { promises.push(this.#addToBuildSet(node, set)) // if it has bundle deps, add those too, if rebuildBundle if (this.options.rebuildBundle !== false) { const bd = node.package.bundleDependencies if (bd && bd.length) { dfwalk({ tree: node, leave: node => promises.push(this.#addToBuildSet(node, set)), getChildren: node => [...node.children.values()], filter: node => node.inBundle, }) } } } await promiseAllRejectLate(promises) // now sort into the queues for the 4 things we have to do // run in the same predictable order that buildIdealTree uses // there's no particular reason for doing it in this order rather // than another, but sorting *somehow* makes it consistent. const queue = [...set].sort(sortNodes) for (const node of queue) { const { package: { bin, scripts = {} } } = node.target const { preinstall, install, postinstall, prepare } = scripts const tests = { bin, preinstall, install, postinstall, prepare } for (const [key, has] of Object.entries(tests)) { if (has) { this.#queues[key].push(node) } } } timeEnd() } async [_checkBins] (node) { // if the node is a global top, and we're not in force mode, then // any existing bins need to either be missing, or a symlink into // the node path. Otherwise a package can have a preinstall script // that unlinks something, to allow them to silently overwrite system // binaries, which is unsafe and insecure. if (!node.globalTop || this.options.force) { return } const { path, package: pkg } = node await binLinks.checkBins({ pkg, path, top: true, global: true }) } async #addToBuildSet (node, set, refreshed = false) { if (set.has(node)) { return } if (this.#oldMeta === null) { const { root: { meta } } = node this.#oldMeta = meta && meta.loadedFromDisk && !(meta.originalLockfileVersion >= 2) } const { package: pkg, hasInstallScript } = node.target const { gypfile, bin, scripts = {} } = pkg const { preinstall, install, postinstall, prepare } = scripts const anyScript = preinstall || install || postinstall || prepare if (!refreshed && !anyScript && (hasInstallScript || this.#oldMeta)) { // we either have an old metadata (and thus might have scripts) // or we have an indication that there's install scripts (but // don't yet know what they are) so we have to load the package.json // from disk to see what the deal is. Failure here just means // no scripts to add, probably borked package.json. // add to the set then remove while we're reading the pj, so we // don't accidentally hit it multiple times. set.add(node) const pkg = await rpj(node.path + '/package.json').catch(() => ({})) set.delete(node) const { scripts = {} } = pkg node.package.scripts = scripts return this.#addToBuildSet(node, set, true) } // Rebuild node-gyp dependencies lacking an install or preinstall script // note that 'scripts' might be missing entirely, and the package may // set gypfile:false to avoid this automatic detection. const isGyp = gypfile !== false && !install && !preinstall && await isNodeGypPackage(node.path) if (bin || preinstall || install || postinstall || prepare || isGyp) { if (bin) { await this[_checkBins](node) } if (isGyp) { scripts.install = defaultGypInstallScript node.package.scripts = scripts } set.add(node) } } async #runScripts (event) { const queue = this.#queues[event] if (!queue.length) { return } const timeEnd = time.start(`build:run:${event}`) const stdio = this.options.foregroundScripts ? 'inherit' : 'pipe' const limit = this.options.foregroundScripts ? 1 : undefined await promiseCallLimit(queue.map(node => async () => { const { path, integrity, resolved, optional, peer, dev, devOptional, package: pkg, location, isStoreLink, } = node.target // skip any that we know we'll be deleting // or storeLinks if (this[_trashList].has(path) || isStoreLink) { return } const timeEndLocation = time.start(`build:run:${event}:${location}`) log.info('run', pkg._id, event, location, pkg.scripts[event]) const env = { npm_package_resolved: resolved, npm_package_integrity: integrity, npm_package_json: resolve(path, 'package.json'), npm_package_optional: boolEnv(optional), npm_package_dev: boolEnv(dev), npm_package_peer: boolEnv(peer), npm_package_dev_optional: boolEnv(devOptional && !dev && !optional), } const runOpts = { event, path, pkg, stdio, env, scriptShell: this.options.scriptShell, } const p = runScript(runOpts).catch(er => { const { code, signal } = er log.info('run', pkg._id, event, { code, signal }) throw er }).then(({ args, code, signal, stdout, stderr }) => { this.scriptsRun.add({ pkg, path, event, // I do not know why this needs to be on THIS line but refactoring // this function would be quite a process // eslint-disable-next-line promise/always-return cmd: args && args[args.length - 1], env, code, signal, stdout, stderr, }) log.info('run', pkg._id, event, { code, signal }) }) await (this.#doHandleOptionalFailure ? this[_handleOptionalFailure](node, p) : p) timeEndLocation() }), { limit }) timeEnd() } async #linkAllBins () { const queue = this.#queues.bin if (!queue.length) { return } const timeEnd = time.start('build:link') const promises = [] // sort the queue by node path, so that the module-local collision // detector in bin-links will always resolve the same way. for (const node of queue.sort(sortNodes)) { // TODO these run before they're awaited promises.push(this.#createBinLinks(node)) } await promiseAllRejectLate(promises) timeEnd() } async #createBinLinks (node) { if (this[_trashList].has(node.path)) { return } const timeEnd = time.start(`build:link:${node.location}`) const p = binLinks({ pkg: node.package, path: node.path, top: !!(node.isTop || node.globalTop), force: this.options.force, global: !!node.globalTop, }) await (this.#doHandleOptionalFailure ? this[_handleOptionalFailure](node, p) : p) timeEnd() } } // mixin implementing the reify method const onExit = require('../signal-handling.js') const pacote = require('pacote') const AuditReport = require('../audit-report.js') const { subset, intersects } = require('semver') const npa = require('npm-package-arg') const semver = require('semver') const debug = require('../debug.js') const { walkUp } = require('walk-up-path') const { log, time } = require('proc-log') const hgi = require('hosted-git-info') const rpj = require('read-package-json-fast') const { dirname, resolve, relative, join } = require('node:path') const { depth: dfwalk } = require('treeverse') const { lstat, mkdir, rm, symlink, } = require('node:fs/promises') const { moveFile } = require('@npmcli/fs') const PackageJson = require('@npmcli/package-json') const packageContents = require('@npmcli/installed-package-contents') const runScript = require('@npmcli/run-script') const { checkEngine, checkPlatform } = require('npm-install-checks') const treeCheck = require('../tree-check.js') const relpath = require('../relpath.js') const Diff = require('../diff.js') const retirePath = require('../retire-path.js') const promiseAllRejectLate = require('promise-all-reject-late') const { callLimit: promiseCallLimit } = require('promise-call-limit') const optionalSet = require('../optional-set.js') const calcDepFlags = require('../calc-dep-flags.js') const { saveTypeMap, hasSubKey } = require('../add-rm-pkg-deps.js') const Shrinkwrap = require('../shrinkwrap.js') const { defaultLockfileVersion } = Shrinkwrap // Part of steps (steps need refactoring before we can do anything about these) const _retireShallowNodes = Symbol.for('retireShallowNodes') const _loadBundlesAndUpdateTrees = Symbol.for('loadBundlesAndUpdateTrees') const _submitQuickAudit = Symbol('submitQuickAudit') const _addOmitsToTrashList = Symbol('addOmitsToTrashList') const _unpackNewModules = Symbol.for('unpackNewModules') const _build = Symbol.for('build') // shared by rebuild mixin const _trashList = Symbol.for('trashList') const _handleOptionalFailure = Symbol.for('handleOptionalFailure') const _loadTrees = Symbol.for('loadTrees') // defined by rebuild mixin const _checkBins = Symbol.for('checkBins') // shared symbols for swapping out when testing // TODO tests should not be this deep into internals const _diffTrees = Symbol.for('diffTrees') const _createSparseTree = Symbol.for('createSparseTree') const _loadShrinkwrapsAndUpdateTrees = Symbol.for('loadShrinkwrapsAndUpdateTrees') const _reifyNode = Symbol.for('reifyNode') const _updateAll = Symbol.for('updateAll') const _updateNames = Symbol.for('updateNames') const _moveContents = Symbol.for('moveContents') const _moveBackRetiredUnchanged = Symbol.for('moveBackRetiredUnchanged') const _removeTrash = Symbol.for('removeTrash') const _renamePath = Symbol.for('renamePath') const _rollbackRetireShallowNodes = Symbol.for('rollbackRetireShallowNodes') const _rollbackCreateSparseTree = Symbol.for('rollbackCreateSparseTree') const _rollbackMoveBackRetiredUnchanged = Symbol.for('rollbackMoveBackRetiredUnchanged') const _saveIdealTree = Symbol.for('saveIdealTree') const _reifyPackages = Symbol.for('reifyPackages') // defined by build-ideal-tree mixin const _resolvedAdd = Symbol.for('resolvedAdd') const _usePackageLock = Symbol.for('usePackageLock') // used by build-ideal-tree mixin const _addNodeToTrashList = Symbol.for('addNodeToTrashList') const _createIsolatedTree = Symbol.for('createIsolatedTree') module.exports = cls => class Reifier extends cls { #bundleMissing = new Set() // child nodes we'd EXPECT to be included in a bundle, but aren't #bundleUnpacked = new Set() // the nodes we unpack to read their bundles #dryRun #nmValidated = new Set() #omitDev #omitPeer #omitOptional #retiredPaths = {} #retiredUnchanged = {} #savePrefix #shrinkwrapInflated = new Set() #sparseTreeDirs = new Set() #sparseTreeRoots = new Set() constructor (options) { super(options) this[_trashList] = new Set() } // public method async reify (options = {}) { const linked = (options.installStrategy || this.options.installStrategy) === 'linked' if (this.options.packageLockOnly && this.options.global) { const er = new Error('cannot generate lockfile for global packages') er.code = 'ESHRINKWRAPGLOBAL' throw er } const omit = new Set(options.omit || []) this.#omitDev = omit.has('dev') this.#omitOptional = omit.has('optional') this.#omitPeer = omit.has('peer') // start tracker block this.addTracker('reify') const timeEnd = time.start('reify') // don't create missing dirs on dry runs if (!this.options.packageLockOnly && !this.options.dryRun) { // we do NOT want to set ownership on this folder, especially // recursively, because it can have other side effects to do that // in a project directory. We just want to make it if it's missing. await mkdir(resolve(this.path), { recursive: true }) // do not allow the top-level node_modules to be a symlink await this.#validateNodeModules(resolve(this.path, 'node_modules')) } await this[_loadTrees](options) const oldTree = this.idealTree if (linked) { // swap out the tree with the isolated tree // this is currently technical debt which will be resolved in a refactor // of Node/Link trees log.warn('reify', 'The "linked" install strategy is EXPERIMENTAL and may contain bugs.') this.idealTree = await this[_createIsolatedTree]() } await this[_diffTrees]() await this[_reifyPackages]() if (linked) { // swap back in the idealTree // so that the lockfile is preserved this.idealTree = oldTree } await this[_saveIdealTree](options) // clean up any trash that is still in the tree for (const path of this[_trashList]) { const loc = relpath(this.idealTree.realpath, path) const node = this.idealTree.inventory.get(loc) if (node && node.root === this.idealTree) { node.parent = null } } // if we filtered to only certain nodes, then anything ELSE needs // to be untouched in the resulting actual tree, even if it differs // in the idealTree. Copy over anything that was in the actual and // was not changed, delete anything in the ideal and not actual. // Then we move the entire idealTree over to this.actualTree, and // save the hidden lockfile. if (this.diff && this.diff.filterSet.size) { const reroot = new Set() const { filterSet } = this.diff const seen = new Set() for (const [loc, ideal] of this.idealTree.inventory.entries()) { seen.add(loc) // if it's an ideal node from the filter set, then skip it // because we already made whatever changes were necessary if (filterSet.has(ideal)) { continue } // otherwise, if it's not in the actualTree, then it's not a thing // that we actually added. And if it IS in the actualTree, then // it's something that we left untouched, so we need to record // that. const actual = this.actualTree.inventory.get(loc) if (!actual) { ideal.root = null } else { if ([...actual.linksIn].some(link => filterSet.has(link))) { seen.add(actual.location) continue } const { realpath, isLink } = actual if (isLink && ideal.isLink && ideal.realpath === realpath) { continue } else { reroot.add(actual) } } } // now find any actual nodes that may not be present in the ideal // tree, but were left behind by virtue of not being in the filter for (const [loc, actual] of this.actualTree.inventory.entries()) { if (seen.has(loc)) { continue } seen.add(loc) // we know that this is something that ISN'T in the idealTree, // or else we will have addressed it in the previous loop. // If it's in the filterSet, that means we intentionally removed // it, so nothing to do here. if (filterSet.has(actual)) { continue } reroot.add(actual) } // go through the rerooted actual nodes, and move them over. for (const actual of reroot) { actual.root = this.idealTree } // prune out any tops that lack a linkIn, they are no longer relevant. for (const top of this.idealTree.tops) { if (top.linksIn.size === 0) { top.root = null } } // need to calculate dep flags, since nodes may have been marked // as extraneous or otherwise incorrect during transit. calcDepFlags(this.idealTree) } // save the ideal's meta as a hidden lockfile after we actualize it this.idealTree.meta.filename = this.idealTree.realpath + '/node_modules/.package-lock.json' this.idealTree.meta.hiddenLockfile = true this.idealTree.meta.lockfileVersion = defaultLockfileVersion this.actualTree = this.idealTree this.idealTree = null if (!this.options.global) { await this.actualTree.meta.save() const ignoreScripts = !!this.options.ignoreScripts // if we aren't doing a dry run or ignoring scripts and we actually made changes to the dep // tree, then run the dependencies scripts if (!this.options.dryRun && !ignoreScripts && this.diff && this.diff.children.length) { const { path, package: pkg } = this.actualTree.target const stdio = this.options.foregroundScripts ? 'inherit' : 'pipe' const { scripts = {} } = pkg for (const event of ['predependencies', 'dependencies', 'postdependencies']) { if (Object.prototype.hasOwnProperty.call(scripts, event)) { log.info('run', pkg._id, event, scripts[event]) await time.start(`reify:run:${event}`, () => runScript({ event, path, pkg, stdio, scriptShell: this.options.scriptShell, })) } } } } // This is a very bad pattern and I can't wait to stop doing it this.auditReport = await this.auditReport this.finishTracker('reify') timeEnd() return treeCheck(this.actualTree) } async [_reifyPackages] () { // we don't submit the audit report or write to disk on dry runs if (this.options.dryRun) { return } if (this.options.packageLockOnly) { // we already have the complete tree, so just audit it now, // and that's all we have to do here. return this[_submitQuickAudit]() } // ok, we're about to start touching the fs. need to roll back // if we get an early termination. let reifyTerminated = null const removeHandler = onExit(({ signal }) => { // only call once. if signal hits twice, we just terminate removeHandler() reifyTerminated = Object.assign(new Error('process terminated'), { signal, }) return false }) // [rollbackfn, [...actions]] // after each step, if the process was terminated, execute the rollback // note that each rollback *also* calls the previous one when it's // finished, and then the first one throws the error, so we only need // a new rollback step when we have a new thing that must be done to // revert the install. const steps = [ [_rollbackRetireShallowNodes, [ _retireShallowNodes, ]], [_rollbackCreateSparseTree, [ _createSparseTree, _addOmitsToTrashList, _loadShrinkwrapsAndUpdateTrees, _loadBundlesAndUpdateTrees, _submitQuickAudit, _unpackNewModules, ]], [_rollbackMoveBackRetiredUnchanged, [ _moveBackRetiredUnchanged, _build, ]], ] for (const [rollback, actions] of steps) { for (const action of actions) { try { await this[action]() if (reifyTerminated) { throw reifyTerminated } } catch (er) { // TODO rollbacks shouldn't be relied on to throw err await this[rollback](er) /* istanbul ignore next - rollback throws, should never hit this */ throw er } } } // no rollback for this one, just exit with the error, since the // install completed and can't be safely recovered at this point. await this[_removeTrash]() if (reifyTerminated) { throw reifyTerminated } // done modifying the file system, no need to keep listening for sigs removeHandler() } // when doing a local install, we load everything and figure it all out. // when doing a global install, we *only* care about the explicit requests. [_loadTrees] (options) { const timeEnd = time.start('reify:loadTrees') const bitOpt = { ...options, complete: this.options.packageLockOnly || this.options.dryRun, } // if we're only writing a package lock, then it doesn't matter what's here if (this.options.packageLockOnly) { return this.buildIdealTree(bitOpt).then(timeEnd) } const actualOpt = this.options.global ? { ignoreMissing: true, global: true, filter: (node, kid) => { // if it's not the project root, and we have no explicit requests, // then we're already into a nested dep, so we keep it if (this.explicitRequests.size === 0 || !node.isProjectRoot) { return true } // if we added it as an edgeOut, then we want it if (this.idealTree.edgesOut.has(kid)) { return true } // if it's an explicit request, then we want it const hasExplicit = [...this.explicitRequests] .some(edge => edge.name === kid) if (hasExplicit) { return true } // ignore the rest of the global install folder return false }, } : { ignoreMissing: true } if (!this.options.global) { return Promise.all([ this.loadActual(actualOpt), this.buildIdealTree(bitOpt), ]).then(timeEnd) } // the global install space tends to have a lot of stuff in it. don't // load all of it, just what we care about. we won't be saving a // hidden lockfile in there anyway. Note that we have to load ideal // BEFORE loading actual, so that the actualOpt can use the // explicitRequests which is set during buildIdealTree return this.buildIdealTree(bitOpt) .then(() => this.loadActual(actualOpt)) .then(timeEnd) } [_diffTrees] () { if (this.options.packageLockOnly) { return } const timeEnd = time.start('reify:diffTrees') // XXX if we have an existing diff already, there should be a way // to just invalidate the parts that changed, but avoid walking the // whole tree again. const includeWorkspaces = this.options.workspacesEnabled const includeRootDeps = !includeWorkspaces || this.options.includeWorkspaceRoot && this.options.workspaces.length > 0 const filterNodes = [] if (this.options.global && this.explicitRequests.size) { const idealTree = this.idealTree.target const actualTree = this.actualTree.target // we ONLY are allowed to make changes in the global top-level // children where there's an explicit request. for (const { name } of this.explicitRequests) { const ideal = idealTree.children.get(name) if (ideal) { filterNodes.push(ideal) } const actual = actualTree.children.get(name) if (actual) { filterNodes.push(actual) } } } else { if (includeWorkspaces) { // add all ws nodes to filterNodes for (const ws of this.options.workspaces) { const ideal = this.idealTree.children.get(ws) if (ideal) { filterNodes.push(ideal) } const actual = this.actualTree.children.get(ws) if (actual) { filterNodes.push(actual) } } } if (includeRootDeps) { // add all non-workspace nodes to filterNodes for (const tree of [this.idealTree, this.actualTree]) { for (const { type, to } of tree.edgesOut.values()) { if (type !== 'workspace' && to) { filterNodes.push(to) } } } } } // find all the nodes that need to change between the actual // and ideal trees. this.diff = Diff.calculate({ shrinkwrapInflated: this.#shrinkwrapInflated, filterNodes, actual: this.actualTree, ideal: this.idealTree, }) // we don't have to add 'removed' folders to the trashlist, because // they'll be moved aside to a retirement folder, and then the retired // folder will be deleted at the end. This is important when we have // a folder like FOO being "removed" in favor of a folder like "foo", // because if we remove node_modules/FOO on case-insensitive systems, // it will remove the dep that we *want* at node_modules/foo. timeEnd() } // add the node and all its bins to the list of things to be // removed later on in the process. optionally, also mark them // as a retired paths, so that we move them out of the way and // replace them when rolling back on failure. [_addNodeToTrashList] (node, retire = false) { const paths = [node.path, ...node.binPaths] const moves = this.#retiredPaths log.silly('reify', 'mark', retire ? 'retired' : 'deleted', paths) for (const path of paths) { if (retire) { const retired = retirePath(path) moves[path] = retired this[_trashList].add(retired) } else { this[_trashList].add(path) } } } // move aside the shallowest nodes in the tree that have to be // changed or removed, so that we can rollback if necessary. [_retireShallowNodes] () { const timeEnd = time.start('reify:retireShallow') const moves = this.#retiredPaths = {} for (const diff of this.diff.children) { if (diff.action === 'CHANGE' || diff.action === 'REMOVE') { // we'll have to clean these up at the end, so add them to the list this[_addNodeToTrashList](diff.actual, true) } } log.silly('reify', 'moves', moves) const movePromises = Object.entries(moves) .map(([from, to]) => this[_renamePath](from, to)) return promiseAllRejectLate(movePromises).then(timeEnd) } [_renamePath] (from, to, didMkdirp = false) { return moveFile(from, to) .catch(er => { // Occasionally an expected bin file might not exist in the package, // or a shim/symlink might have been moved aside. If we've already // handled the most common cause of ENOENT (dir doesn't exist yet), // then just ignore any ENOENT. if (er.code === 'ENOENT') { return didMkdirp ? null : mkdir(dirname(to), { recursive: true }).then(() => this[_renamePath](from, to, true)) } else if (er.code === 'EEXIST') { return rm(to, { recursive: true, force: true }).then(() => moveFile(from, to)) } else { throw er } }) } [_rollbackRetireShallowNodes] (er) { const timeEnd = time.start('reify:rollback:retireShallow') const moves = this.#retiredPaths const movePromises = Object.entries(moves) .map(([from, to]) => this[_renamePath](to, from)) return promiseAllRejectLate(movePromises) // ignore subsequent rollback errors .catch(() => {}) .then(timeEnd) .then(() => { throw er }) } // adding to the trash list will skip reifying, and delete them // if they are currently in the tree and otherwise untouched. [_addOmitsToTrashList] () { if (!this.#omitDev && !this.#omitOptional && !this.#omitPeer) { return } const timeEnd = time.start('reify:trashOmits') for (const node of this.idealTree.inventory.values()) { const { top } = node // if the top is not the root or workspace then we do not want to omit it if (!top.isProjectRoot && !top.isWorkspace) { continue } // if a diff filter has been created, then we do not omit the node if the // top node is not in that set if (this.diff?.filterSet?.size && !this.diff.filterSet.has(top)) { continue } // omit node if the dep type matches any omit flags that were set if ( node.peer && this.#omitPeer || node.dev && this.#omitDev || node.optional && this.#omitOptional || node.devOptional && this.#omitOptional && this.#omitDev ) { this[_addNodeToTrashList](node) } } timeEnd() } [_createSparseTree] () { const timeEnd = time.start('reify:createSparse') // if we call this fn again, we look for the previous list // so that we can avoid making the same directory multiple times const leaves = this.diff.leaves .filter(diff => { return (diff.action === 'ADD' || diff.action === 'CHANGE') && !this.#sparseTreeDirs.has(diff.ideal.path) && !diff.ideal.isLink }) .map(diff => diff.ideal) // we check this in parallel, so guard against multiple attempts to // retire the same path at the same time. const dirsChecked = new Set() return promiseAllRejectLate(leaves.map(async node => { for (const d of walkUp(node.path)) { if (d === node.top.path) { break } if (dirsChecked.has(d)) { continue } dirsChecked.add(d) const st = await lstat(d).catch(() => null) // this can happen if we have a link to a package with a name // that the filesystem treats as if it is the same thing. // would be nice to have conditional istanbul ignores here... /* istanbul ignore next - defense in depth */ if (st && !st.isDirectory()) { const retired = retirePath(d) this.#retiredPaths[d] = retired this[_trashList].add(retired) await this[_renamePath](d, retired) } } this.#sparseTreeDirs.add(node.path) const made = await mkdir(node.path, { recursive: true }) // if the directory already exists, made will be undefined. if that's the case // we don't want to remove it because we aren't the ones who created it so we // omit it from the #sparseTreeRoots if (made) { this.#sparseTreeRoots.add(made) } })).then(timeEnd) } [_rollbackCreateSparseTree] (er) { const timeEnd = time.start('reify:rollback:createSparse') // cut the roots of the sparse tree that were created, not the leaves const roots = this.#sparseTreeRoots // also delete the moves that we retired, so that we can move them back const failures = [] const targets = [...roots, ...Object.keys(this.#retiredPaths)] const unlinks = targets .map(path => rm(path, { recursive: true, force: true }).catch(er => failures.push([path, er]))) return promiseAllRejectLate(unlinks).then(() => { // eslint-disable-next-line promise/always-return if (failures.length) { log.warn('cleanup', 'Failed to remove some directories', failures) } }) .then(timeEnd) .then(() => this[_rollbackRetireShallowNodes](er)) } // shrinkwrap nodes define their dependency branches with a file, so // we need to unpack them, read that shrinkwrap file, and then update // the tree by calling loadVirtual with the node as the root. [_loadShrinkwrapsAndUpdateTrees] () { const seen = this.#shrinkwrapInflated const shrinkwraps = this.diff.leaves .filter(d => (d.action === 'CHANGE' || d.action === 'ADD' || !d.action) && d.ideal.hasShrinkwrap && !seen.has(d.ideal) && !this[_trashList].has(d.ideal.path)) if (!shrinkwraps.length) { return } const timeEnd = time.start('reify:loadShrinkwraps') const Arborist = this.constructor return promiseAllRejectLate(shrinkwraps.map(diff => { const node = diff.ideal seen.add(node) return diff.action ? this[_reifyNode](node) : node })) .then(nodes => promiseAllRejectLate(nodes.map(node => new Arborist({ ...this.options, path: node.path, }).loadVirtual({ root: node })))) // reload the diff and sparse tree because the ideal tree changed .then(() => this[_diffTrees]()) .then(() => this[_createSparseTree]()) .then(() => this[_addOmitsToTrashList]()) .then(() => this[_loadShrinkwrapsAndUpdateTrees]()) .then(timeEnd) } // create a symlink for Links, extract for Nodes // return the node object, since we usually want that // handle optional dep failures here // If node is in trash list, skip it // If reifying fails, and the node is optional, add it and its optionalSet // to the trash list // Always return the node. [_reifyNode] (node) { if (this[_trashList].has(node.path)) { return node } const timeEnd = time.start(`reifyNode:${node.location}`) this.addTracker('reify', node.name, node.location) const { npmVersion, nodeVersion, cpu, os, libc } = this.options const p = Promise.resolve().then(async () => { // when we reify an optional node, check the engine and platform // first. be sure to ignore the --force and --engine-strict flags, // since we always want to skip any optional packages we can't install. // these checks throwing will result in a rollback and removal // of the mismatches // eslint-disable-next-line promise/always-return if (node.optional) { checkEngine(node.package, npmVersion, nodeVersion, false) checkPlatform(node.package, false, { cpu, os, libc }) } await this[_checkBins](node) await this.#extractOrLink(node) const { _id, deprecated } = node.package // The .catch is in _handleOptionalFailure. Not ideal, this should be cleaned up. // eslint-disable-next-line promise/always-return if (deprecated) { log.warn('deprecated', `${_id}: ${deprecated}`) } }) return this[_handleOptionalFailure](node, p) .then(() => { this.finishTracker('reify', node.name, node.location) timeEnd() return node }) } // do not allow node_modules to be a symlink async #validateNodeModules (nm) { if (this.options.force || this.#nmValidated.has(nm)) { return } const st = await lstat(nm).catch(() => null) if (!st || st.isDirectory()) { this.#nmValidated.add(nm) return } log.warn('reify', 'Removing non-directory', nm) await rm(nm, { recursive: true, force: true }) } async #extractOrLink (node) { const nm = resolve(node.parent.path, 'node_modules') await this.#validateNodeModules(nm) if (!node.isLink) { // in normal cases, node.resolved should *always* be set by now. // however, it is possible when a lockfile is damaged, or very old, // or in some other race condition bugs in npm v6, that a previously // bundled dependency will have just a version, but no resolved value, // and no 'bundled: true' setting. // Do the best with what we have, or else remove it from the tree // entirely, since we can't possibly reify it. let res = null if (node.resolved) { const registryResolved = this.#registryResolved(node.resolved) if (registryResolved) { res = `${node.name}@${registryResolved}` } } else if (node.package.name && node.version) { res = `${node.package.name}@${node.version}` } // no idea what this thing is. remove it from the tree. if (!res) { const warning = 'invalid or damaged lockfile detected\n' + 'please re-try this operation once it completes\n' + 'so that the damage can be corrected, or perform\n' + 'a fresh install with no lockfile if the problem persists.' log.warn('reify', warning) log.verbose('reify', 'unrecognized node in tree', node.path) node.parent = null node.fsParent = null this[_addNodeToTrashList](node) return } await debug(async () => { const st = await lstat(node.path).catch(() => null) if (st && !st.isDirectory()) { debug.log('unpacking into a non-directory', node) throw Object.assign(new Error('ENOTDIR: not a directory'), { code: 'ENOTDIR', path: node.path, }) } }) await pacote.extract(res, node.path, { ...this.options, resolved: node.resolved, integrity: node.integrity, }) // store nodes don't use Node class so node.package doesn't get updated if (node.isInStore) { const pkg = await rpj(join(node.path, 'package.json')) node.package.scripts = pkg.scripts } return } // node.isLink await rm(node.path, { recursive: true, force: true }) // symlink const dir = dirname(node.path) const target = node.realpath const rel = relative(dir, target) await mkdir(dir, { recursive: true }) return symlink(rel, node.path, 'junction') } // if the node is optional, then the failure of the promise is nonfatal // just add it and its optional set to the trash list. [_handleOptionalFailure] (node, p) { return (node.optional ? p.catch(() => { const set = optionalSet(node) for (node of set) { log.verbose('reify', 'failed optional dependency', node.path) this[_addNodeToTrashList](node) } }) : p).then(() => node) } #registryResolved (resolved) { // the default registry url is a magic value meaning "the currently // configured registry". // `resolved` must never be falsey. // // XXX: use a magic string that isn't also a valid value, like // ${REGISTRY} or something. This has to be threaded through the // Shrinkwrap and Node classes carefully, so for now, just treat // the default reg as the magical animal that it has been. const resolvedURL = hgi.parseUrl(resolved) if (!resolvedURL) { // if we could not parse the url at all then returning nothing // here means it will get removed from the tree in the next step return } if ((this.options.replaceRegistryHost === resolvedURL.hostname) || this.options.replaceRegistryHost === 'always') { // this.registry always has a trailing slash return `${this.registry.slice(0, -1)}${resolvedURL.pathname}${resolvedURL.searchParams}` } return resolved } // bundles are *sort of* like shrinkwraps, in that the branch is defined // by the contents of the package. however, in their case, rather than // shipping a virtual tree that must be reified, they ship an entire // reified actual tree that must be unpacked and not modified. [_loadBundlesAndUpdateTrees] (depth = 0, bundlesByDepth) { let maxBundleDepth if (!bundlesByDepth) { bundlesByDepth = new Map() maxBundleDepth = -1 dfwalk({ tree: this.diff, visit: diff => { const node = diff.ideal if (!node) { return } if (node.isProjectRoot) { return } const { bundleDependencies } = node.package if (bundleDependencies && bundleDependencies.length) { maxBundleDepth = Math.max(maxBundleDepth, node.depth) if (!bundlesByDepth.has(node.depth)) { bundlesByDepth.set(node.depth, [node]) } else { bundlesByDepth.get(node.depth).push(node) } } }, getChildren: diff => diff.children, }) bundlesByDepth.set('maxBundleDepth', maxBundleDepth) } else { maxBundleDepth = bundlesByDepth.get('maxBundleDepth') } if (depth === 0) { time.start('reify:loadBundles') } if (depth > maxBundleDepth) { // if we did something, then prune the tree and update the diffs if (maxBundleDepth !== -1) { this.#pruneBundledMetadeps(bundlesByDepth) this[_diffTrees]() } time.end('reify:loadBundles') return } // skip any that have since been removed from the tree, eg by a // shallower bundle overwriting them with a bundled meta-dep. const set = (bundlesByDepth.get(depth) || []) .filter(node => node.root === this.idealTree && node.target !== node.root && !this[_trashList].has(node.path)) if (!set.length) { return this[_loadBundlesAndUpdateTrees](depth + 1, bundlesByDepth) } // extract all the nodes with bundles return promiseCallLimit(set.map(node => { return () => { this.#bundleUnpacked.add(node) return this[_reifyNode](node) } }), { rejectLate: true }) // then load their unpacked children and move into the ideal tree .then(nodes => promiseAllRejectLate(nodes.map(async node => { const arb = new this.constructor({ ...this.options, path: node.path, }) const notTransplanted = new Set(node.children.keys()) await arb.loadActual({ root: node, // don't transplant any sparse folders we created // loadActual will set node.package to {} for empty directories // if by chance there are some empty folders in the node_modules // tree for some other reason, then ok, ignore those too. transplantFilter: node => { if (node.package._id) { // it's actually in the bundle if it gets transplanted notTransplanted.delete(node.name) return true } else { return false } }, }) for (const name of notTransplanted) { this.#bundleMissing.add(node.children.get(name)) } }))) // move onto the next level of bundled items .then(() => this[_loadBundlesAndUpdateTrees](depth + 1, bundlesByDepth)) } // https://github.com/npm/cli/issues/1597#issuecomment-667639545 #pruneBundledMetadeps (bundlesByDepth) { const bundleShadowed = new Set() // Example dep graph: // root -> (a, c) // a -> BUNDLE(b) // b -> c // c -> b // // package tree: // root // +-- a // | +-- b(1) // | +-- c(1) // +-- b(2) // +-- c(2) // 1. mark everything that's shadowed by anything in the bundle. This // marks b(2) and c(2). // 2. anything with edgesIn from outside the set, mark not-extraneous, // remove from set. This unmarks c(2). // 3. continue until no change // 4. remove everything in the set from the tree. b(2) is pruned // create the list of nodes shadowed by children of bundlers for (const bundles of bundlesByDepth.values()) { // skip the 'maxBundleDepth' item if (!Array.isArray(bundles)) { continue } for (const node of bundles) { for (const name of node.children.keys()) { const shadow = node.parent.resolve(name) if (!shadow) { continue } bundleShadowed.add(shadow) shadow.extraneous = true } } } // lib -> (a@1.x) BUNDLE(a@1.2.3 (b@1.2.3)) // a@1.2.3 -> (b@1.2.3) // a@1.3.0 -> (b@2) // b@1.2.3 -> () // b@2 -> (c@2) // // root // +-- lib // | +-- a@1.2.3 // | +-- b@1.2.3 // +-- b@2 <-- shadowed, now extraneous // +-- c@2 <-- also shadowed, because only dependent is shadowed for (const shadow of bundleShadowed) { for (const shadDep of shadow.edgesOut.values()) { /* istanbul ignore else - pretty unusual situation, just being * defensive here. Would mean that a bundled dep has a dependency * that is unmet. which, weird, but if you bundle it, we take * whatever you put there and assume the publisher knows best. */ if (shadDep.to) { bundleShadowed.add(shadDep.to) shadDep.to.extraneous = true } } } let changed do { changed = false for (const shadow of bundleShadowed) { for (const edge of shadow.edgesIn) { if (!bundleShadowed.has(edge.from)) { shadow.extraneous = false bundleShadowed.delete(shadow) changed = true break } } } } while (changed) for (const shadow of bundleShadowed) { this[_addNodeToTrashList](shadow) shadow.root = null } } async [_submitQuickAudit] () { if (this.options.audit === false) { this.auditReport = null return } // we submit the quick audit at this point in the process, as soon as // we have all the deps resolved, so that it can overlap with the other // actions as much as possible. Stash the promise, which we resolve // before finishing the reify() and returning the tree. Thus, we do // NOT return the promise, as the intent is for this to run in parallel // with the reification, and be resolved at a later time. const timeEnd = time.start('reify:audit') const options = { ...this.options } const tree = this.idealTree // if we're operating on a workspace, only audit the workspace deps if (this.options.workspaces.length) { options.filterSet = this.workspaceDependencySet( tree, this.options.workspaces, this.options.includeWorkspaceRoot ) } this.auditReport = AuditReport.load(tree, options).then(res => { timeEnd() return res }) } // ok! actually unpack stuff into their target locations! // The sparse tree has already been created, so we walk the diff // kicking off each unpack job. If any fail, we rm the sparse // tree entirely and try to put everything back where it was. [_unpackNewModules] () { const timeEnd = time.start('reify:unpack') const unpacks = [] dfwalk({ tree: this.diff, visit: diff => { // no unpacking if we don't want to change this thing if (diff.action !== 'CHANGE' && diff.action !== 'ADD') { return } const node = diff.ideal const bd = this.#bundleUnpacked.has(node) const sw = this.#shrinkwrapInflated.has(node) const bundleMissing = this.#bundleMissing.has(node) // check whether we still need to unpack this one. // test the inDepBundle last, since that's potentially a tree walk. const doUnpack = node && // can't unpack if removed! // root node already exists !node.isRoot && // already unpacked to read bundle !bd && // already unpacked to read sw !sw && // already unpacked by another dep's bundle (bundleMissing || !node.inDepBundle) if (doUnpack) { unpacks.push(this[_reifyNode](node)) } }, getChildren: diff => diff.children, }) return promiseAllRejectLate(unpacks).then(timeEnd) } // This is the part where we move back the unchanging nodes that were // the children of a node that did change. If this fails, the rollback // is a three-step process. First, we try to move the retired unchanged // nodes BACK to their retirement folders, then delete the sparse tree, // then move everything out of retirement. [_moveBackRetiredUnchanged] () { // get a list of all unchanging children of any shallow retired nodes // if they are not the ancestor of any node in the diff set, then the // directory won't already exist, so just rename it over. // This is sort of an inverse diff tree, of all the nodes where // the actualTree and idealTree _don't_ differ, starting from the // shallowest nodes that we moved aside in the first place. const timeEnd = time.start('reify:unretire') const moves = this.#retiredPaths this.#retiredUnchanged = {} return promiseAllRejectLate(this.diff.children.map(diff => { // skip if nothing was retired if (diff.action !== 'CHANGE' && diff.action !== 'REMOVE') { return } const { path: realFolder } = diff.actual const retireFolder = moves[realFolder] /* istanbul ignore next - should be impossible */ debug(() => { if (!retireFolder) { const er = new Error('trying to un-retire but not retired') throw Object.assign(er, { realFolder, retireFolder, actual: diff.actual, ideal: diff.ideal, action: diff.action, }) } }) this.#retiredUnchanged[retireFolder] = [] return promiseAllRejectLate(diff.unchanged.map(node => { // no need to roll back links, since we'll just delete them anyway if (node.isLink) { return mkdir(dirname(node.path), { recursive: true, force: true }) .then(() => this[_reifyNode](node)) } // will have been moved/unpacked along with bundler if (node.inDepBundle && !this.#bundleMissing.has(node)) { return } this.#retiredUnchanged[retireFolder].push(node) const rel = relative(realFolder, node.path) const fromPath = resolve(retireFolder, rel) // if it has bundleDependencies, then make node_modules. otherwise // skip it. const bd = node.package.bundleDependencies const dir = bd && bd.length ? node.path + '/node_modules' : node.path return mkdir(dir, { recursive: true }).then(() => this[_moveContents](node, fromPath)) })) })).then(timeEnd) } // move the contents from the fromPath to the node.path [_moveContents] (node, fromPath) { return packageContents({ path: fromPath, depth: 1, packageJsonCache: new Map([[fromPath + '/package.json', node.package]]), }).then(res => promiseAllRejectLate(res.map(path => { const rel = relative(fromPath, path) const to = resolve(node.path, rel) return this[_renamePath](path, to) }))) } [_rollbackMoveBackRetiredUnchanged] (er) { const moves = this.#retiredPaths // flip the mapping around to go back const realFolders = new Map(Object.entries(moves).map(([k, v]) => [v, k])) const promises = Object.entries(this.#retiredUnchanged) .map(([retireFolder, nodes]) => promiseAllRejectLate(nodes.map(node => { const realFolder = realFolders.get(retireFolder) const rel = relative(realFolder, node.path) const fromPath = resolve(retireFolder, rel) return this[_moveContents]({ ...node, path: fromPath }, node.path) }))) return promiseAllRejectLate(promises) .then(() => this[_rollbackCreateSparseTree](er)) } [_build] () { const timeEnd = time.start('reify:build') // for all the things being installed, run their appropriate scripts // run in tip->root order, so as to be more likely to build a node's // deps before attempting to build it itself const nodes = [] dfwalk({ tree: this.diff, leave: diff => { if (!diff.ideal.isProjectRoot) { nodes.push(diff.ideal) } }, // process adds before changes, ignore removals getChildren: diff => diff && diff.children, filter: diff => diff.action === 'ADD' || diff.action === 'CHANGE', }) // pick up link nodes from the unchanged list as we want to run their // scripts in every install despite of having a diff status change for (const node of this.diff.unchanged) { const tree = node.root.target // skip links that only live within node_modules as they are most // likely managed by packages we installed, we only want to rebuild // unchanged links we directly manage const linkedFromRoot = node.parent === tree || node.target.fsTop === tree if (node.isLink && linkedFromRoot) { nodes.push(node) } } return this.rebuild({ nodes, handleOptionalFailure: true }).then(timeEnd) } // the tree is pretty much built now, so it's cleanup time. // remove the retired folders, and any deleted nodes // If this fails, there isn't much we can do but tell the user about it. // Thankfully, it's pretty unlikely that it'll fail, since rm is a node builtin. async [_removeTrash] () { const timeEnd = time.start('reify:trash') const promises = [] const failures = [] const _rm = path => rm(path, { recursive: true, force: true }).catch(er => failures.push([path, er])) for (const path of this[_trashList]) { promises.push(_rm(path)) } await promiseAllRejectLate(promises) if (failures.length) { log.warn('cleanup', 'Failed to remove some directories', failures) } timeEnd() } // last but not least, we save the ideal tree metadata to the package-lock // or shrinkwrap file, and any additions or removals to package.json async [_saveIdealTree] (options) { // the ideal tree is actualized now, hooray! // it still contains all the references to optional nodes that were removed // for install failures. Those still end up in the shrinkwrap, so we // save it first, then prune out the optional trash, and then return it. const save = !(options.save === false) // we check for updates in order to make sure we run save ideal tree // even though save=false since we want `npm update` to be able to // write to package-lock files by default const hasUpdates = this[_updateAll] || this[_updateNames].length // we're going to completely skip save ideal tree in case of a global or // dry-run install and also if the save option is set to false, EXCEPT for // update since the expected behavior for npm7+ is for update to // NOT save to package.json, we make that exception since we still want // saveIdealTree to be able to write the lockfile by default. const saveIdealTree = !( (!save && !hasUpdates) || this.options.global || this.options.dryRun ) if (!saveIdealTree) { return false } const timeEnd = time.start('reify:save') const updatedTrees = new Set() const updateNodes = nodes => { for (const { name, tree: addTree } of nodes) { // addTree either the root, or a workspace const edge = addTree.edgesOut.get(name) const pkg = addTree.package const req = npa.resolve(name, edge.spec, addTree.realpath) const { rawSpec, subSpec } = req const spec = subSpec ? subSpec.rawSpec : rawSpec const child = edge.to // if we tried to install an optional dep, but it was a version // that we couldn't resolve, this MAY be missing. if we haven't // blown up by now, it's because it was not a problem, though, so // just move on. if (!child || !addTree.isTop) { continue } let newSpec // True if the dependency is getting installed from a local file path // In this case it is not possible to do the normal version comparisons // as the new version will be a file path const isLocalDep = req.type === 'directory' || req.type === 'file' if (req.registry) { const version = child.version const prefixRange = version ? this.options.savePrefix + version : '*' // if we installed a range, then we save the range specified // if it is not a subset of the ^x.y.z. eg, installing a range // of `1.x <1.2.3` will not be saved as `^1.2.0`, because that // would allow versions outside the requested range. Tags and // specific versions save with the save-prefix. const isRange = (subSpec || req).type === 'range' let range = spec if ( !isRange || spec === '*' || subset(prefixRange, spec, { loose: true }) ) { range = prefixRange } const pname = child.packageName const alias = name !== pname newSpec = alias ? `npm:${pname}@${range}` : range } else if (req.hosted) { // save the git+https url if it has auth, otherwise shortcut const h = req.hosted const opt = { noCommittish: false } if (h.https && h.auth) { newSpec = `git+${h.https(opt)}` } else { newSpec = h.shortcut(opt) } } else if (isLocalDep) { // when finding workspace nodes, make sure that // we save them using their version instead of // using their relative path if (edge.type === 'workspace') { const { version } = edge.to.target const prefixRange = version ? this.options.savePrefix + version : '*' newSpec = prefixRange } else { // save the relative path in package.json // Normally saveSpec is updated with the proper relative // path already, but it's possible to specify a full absolute // path initially, in which case we can end up with the wrong // thing, so just get the ultimate fetchSpec and relativize it. const p = req.fetchSpec.replace(/^file:/, '') const rel = relpath(addTree.realpath, p).replace(/#/g, '%23') newSpec = `file:${rel}` } } else { newSpec = req.saveSpec } if (options.saveType) { const depType = saveTypeMap.get(options.saveType) pkg[depType][name] = newSpec // rpj will have moved it here if it was in both // if it is empty it will be deleted later if (options.saveType === 'prod' && pkg.optionalDependencies) { delete pkg.optionalDependencies[name] } } else { if (hasSubKey(pkg, 'dependencies', name)) { pkg.dependencies[name] = newSpec } if (hasSubKey(pkg, 'devDependencies', name)) { pkg.devDependencies[name] = newSpec // don't update peer or optional if we don't have to if (hasSubKey(pkg, 'peerDependencies', name) && (isLocalDep || !intersects(newSpec, pkg.peerDependencies[name]))) { pkg.peerDependencies[name] = newSpec } if (hasSubKey(pkg, 'optionalDependencies', name) && (isLocalDep || !intersects(newSpec, pkg.optionalDependencies[name]))) { pkg.optionalDependencies[name] = newSpec } } else { if (hasSubKey(pkg, 'peerDependencies', name)) { pkg.peerDependencies[name] = newSpec } if (hasSubKey(pkg, 'optionalDependencies', name)) { pkg.optionalDependencies[name] = newSpec } } } updatedTrees.add(addTree) } } // Returns true if any of the edges from this node has a semver // range definition that is an exact match to the version installed // e.g: should return true if for a given an installed version 1.0.0, // range is either =1.0.0 or 1.0.0 const exactVersion = node => { for (const edge of node.edgesIn) { try { if (semver.subset(edge.spec, node.version)) { return false } } catch { // ignore errors } } return true } // helper that retrieves an array of nodes that were // potentially updated during the reify process, in order // to limit the number of nodes to check and update, only // select nodes from the inventory that are direct deps // of a given package.json (project root or a workspace) // and in ase of using a list of `names`, restrict nodes // to only names that are found in this list const retrieveUpdatedNodes = names => { const filterDirectDependencies = node => !node.isRoot && node.resolveParent && node.resolveParent.isRoot && (!names || names.includes(node.name)) && exactVersion(node) // skip update for exact ranges const directDeps = this.idealTree.inventory .filter(filterDirectDependencies) // traverses the list of direct dependencies and collect all nodes // to be updated, since any of them might have changed during reify const nodes = [] for (const node of directDeps) { for (const edgeIn of node.edgesIn) { nodes.push({ name: node.name, tree: edgeIn.from.target, }) } } return nodes } if (save) { // when using update all alongside with save, we'll make // sure to refresh every dependency of the root idealTree if (this[_updateAll]) { const nodes = retrieveUpdatedNodes() updateNodes(nodes) } else { // resolvedAdd is the list of user add requests, but with names added // to things like git repos and tarball file/urls. However, if the // user requested 'foo@', and we have a foo@file:../foo, then we should // end up saving the spec we actually used, not whatever they gave us. if (this[_resolvedAdd].length) { updateNodes(this[_resolvedAdd]) } // if updating given dependencies by name, restrict the list of // nodes to check to only those currently in _updateNames if (this[_updateNames].length) { const nodes = retrieveUpdatedNodes(this[_updateNames]) updateNodes(nodes) } // grab any from explicitRequests that had deps removed for (const { from: tree } of this.explicitRequests) { updatedTrees.add(tree) } } } if (save) { for (const tree of updatedTrees) { // refresh the edges so they have the correct specs tree.package = tree.package const pkgJson = await PackageJson.load(tree.path, { create: true }) const { dependencies = {}, devDependencies = {}, optionalDependencies = {}, peerDependencies = {}, // bundleDependencies is not required by PackageJson like the other // fields here PackageJson also doesn't omit an empty array for this // field so defaulting this to an empty array would add that field to // every package.json file. bundleDependencies, } = tree.package pkgJson.update({ dependencies, devDependencies, optionalDependencies, peerDependencies, bundleDependencies, }) await pkgJson.save() } } // before now edge specs could be changing, affecting the `requires` field // in the package lock, so we hold off saving to the very last action if (this[_usePackageLock]) { // preserve indentation, if possible let format = this.idealTree.package[Symbol.for('indent')] if (format === undefined) { format = ' ' } // TODO this ignores options.save await this.idealTree.meta.save({ format: (this.options.formatPackageLock && format) ? format : this.options.formatPackageLock, }) } timeEnd() return true } } // an object representing the set of vulnerabilities in a tree /* eslint camelcase: "off" */ const localeCompare = require('@isaacs/string-locale-compare')('en') const npa = require('npm-package-arg') const pickManifest = require('npm-pick-manifest') const Vuln = require('./vuln.js') const Calculator = require('@npmcli/metavuln-calculator') const _getReport = Symbol('getReport') const _fixAvailable = Symbol('fixAvailable') const _checkTopNode = Symbol('checkTopNode') const _init = Symbol('init') const _omit = Symbol('omit') const { log, time } = require('proc-log') const npmFetch = require('npm-registry-fetch') class AuditReport extends Map { static load (tree, opts) { return new AuditReport(tree, opts).run() } get auditReportVersion () { return 2 } toJSON () { const obj = { auditReportVersion: this.auditReportVersion, vulnerabilities: {}, metadata: { vulnerabilities: { info: 0, low: 0, moderate: 0, high: 0, critical: 0, total: this.size, }, dependencies: { prod: 0, dev: 0, optional: 0, peer: 0, peerOptional: 0, total: this.tree.inventory.size - 1, }, }, } for (const node of this.tree.inventory.values()) { const { dependencies } = obj.metadata let prod = true for (const type of [ 'dev', 'optional', 'peer', 'peerOptional', ]) { if (node[type]) { dependencies[type]++ prod = false } } if (prod) { dependencies.prod++ } } // if it doesn't have any topVulns, then it's fixable with audit fix // for each topVuln, figure out if it's fixable with audit fix --force, // or if we have to just delete the thing, and if the fix --force will // require a semver major update. const vulnerabilities = [] for (const [name, vuln] of this.entries()) { vulnerabilities.push([name, vuln.toJSON()]) obj.metadata.vulnerabilities[vuln.severity]++ } obj.vulnerabilities = vulnerabilities .sort(([a], [b]) => localeCompare(a, b)) .reduce((set, [name, vuln]) => { set[name] = vuln return set }, {}) return obj } constructor (tree, opts = {}) { super() const { omit } = opts this[_omit] = new Set(omit || []) this.topVulns = new Map() this.calculator = new Calculator(opts) this.error = null this.options = opts this.tree = tree this.filterSet = opts.filterSet } async run () { this.report = await this[_getReport]() log.silly('audit report', this.report) if (this.report) { await this[_init]() } return this } isVulnerable (node) { const vuln = this.get(node.packageName) return !!(vuln && vuln.isVulnerable(node)) } async [_init] () { const timeEnd = time.start('auditReport:init') const promises = [] for (const [name, advisories] of Object.entries(this.report)) { for (const advisory of advisories) { promises.push(this.calculator.calculate(name, advisory)) } } // now the advisories are calculated with a set of versions // and the packument. turn them into our style of vuln objects // which also have the affected nodes, and also create entries // for all the metavulns that we find from dependents. const advisories = new Set(await Promise.all(promises)) const seen = new Set() for (const advisory of advisories) { const { name, range } = advisory const k = `${name}@${range}` const vuln = this.get(name) || new Vuln({ name, advisory }) if (this.has(name)) { vuln.addAdvisory(advisory) } super.set(name, vuln) // don't flag the exact same name/range more than once // adding multiple advisories with the same range is fine, but no // need to search for nodes we already would have added. if (!seen.has(k)) { const p = [] for (const node of this.tree.inventory.query('packageName', name)) { if (!shouldAudit(node, this[_omit], this.filterSet)) { continue } // if not vulnerable by this advisory, keep searching if (!advisory.testVersion(node.version)) { continue } // we will have loaded the source already if this is a metavuln if (advisory.type === 'metavuln') { vuln.addVia(this.get(advisory.dependency)) } // already marked this one, no need to do it again if (vuln.nodes.has(node)) { continue } // haven't marked this one yet. get its dependents. vuln.nodes.add(node) for (const { from: dep, spec } of node.edgesIn) { if (dep.isTop && !vuln.topNodes.has(dep)) { this[_checkTopNode](dep, vuln, spec) } else { // calculate a metavuln, if necessary const calc = this.calculator.calculate(dep.packageName, advisory) // eslint-disable-next-line promise/always-return p.push(calc.then(meta => { // eslint-disable-next-line promise/always-return if (meta.testVersion(dep.version, spec)) { advisories.add(meta) } })) } } } await Promise.all(p) seen.add(k) } // make sure we actually got something. if not, remove it // this can happen if you are loading from a lockfile created by // npm v5, since it lists the current version of all deps, // rather than the range that is actually depended upon, // or if using --omit with the older audit endpoint. if (this.get(name).nodes.size === 0) { this.delete(name) continue } // if the vuln is valid, but THIS advisory doesn't apply to any of // the nodes it references, then remove it from the advisory list. // happens when using omit with old audit endpoint. for (const advisory of vuln.advisories) { const relevant = [...vuln.nodes] .some(n => advisory.testVersion(n.version)) if (!relevant) { vuln.deleteAdvisory(advisory) } } } timeEnd() } [_checkTopNode] (topNode, vuln, spec) { vuln.fixAvailable = this[_fixAvailable](topNode, vuln, spec) if (vuln.fixAvailable !== true) { // now we know the top node is vulnerable, and cannot be // upgraded out of the bad place without --force. But, there's // no need to add it to the actual vulns list, because nothing // depends on root. this.topVulns.set(vuln.name, vuln) vuln.topNodes.add(topNode) } } // check whether the top node is vulnerable. // check whether we can get out of the bad place with --force, and if // so, whether that update is SemVer Major [_fixAvailable] (topNode, vuln, spec) { // this will always be set to at least {name, versions:{}} const paku = vuln.packument if (!vuln.testSpec(spec)) { return true } // similarly, even if we HAVE a packument, but we're looking for it // somewhere other than the registry, and we got something vulnerable, // then we're stuck with it. const specObj = npa(spec) if (!specObj.registry) { return false } if (specObj.subSpec) { spec = specObj.subSpec.rawSpec } // We don't provide fixes for top nodes other than root, but we // still check to see if the node is fixable with a different version, // and if that is a semver major bump. try { const { _isSemVerMajor: isSemVerMajor, version, name, } = pickManifest(paku, spec, { ...this.options, before: null, avoid: vuln.range, avoidStrict: true, }) return { name, version, isSemVerMajor } } catch (er) { return false } } set () { throw new Error('do not call AuditReport.set() directly') } async [_getReport] () { // if we're not auditing, just return false if (this.options.audit === false || this.options.offline === true || this.tree.inventory.size === 1) { return null } const timeEnd = time.start('auditReport:getReport') try { const body = prepareBulkData(this.tree, this[_omit], this.filterSet) log.silly('audit', 'bulk request', body) // no sense asking if we don't have anything to audit, // we know it'll be empty if (!Object.keys(body).length) { return null } const res = await npmFetch('/-/npm/v1/security/advisories/bulk', { ...this.options, registry: this.options.auditRegistry || this.options.registry, method: 'POST', gzip: true, body, }) return await res.json() } catch (er) { log.verbose('audit error', er) log.silly('audit error', String(er.body)) this.error = er return null } finally { timeEnd() } } } // return true if we should audit this one const shouldAudit = (node, omit, filterSet) => !node.version ? false : node.isRoot ? false : filterSet && filterSet.size !== 0 && !filterSet.has(node) ? false : omit.size === 0 ? true : !( // otherwise, just ensure we're not omitting this one node.dev && omit.has('dev') || node.optional && omit.has('optional') || node.devOptional && omit.has('dev') && omit.has('optional') || node.peer && omit.has('peer') ) const prepareBulkData = (tree, omit, filterSet) => { const payload = {} for (const name of tree.inventory.query('packageName')) { const set = new Set() for (const node of tree.inventory.query('packageName', name)) { if (!shouldAudit(node, omit, filterSet)) { continue } set.add(node.version) } if (set.size) { payload[name] = [...set] } } return payload } module.exports = AuditReport const { depth } = require('treeverse') const calcDepFlags = (tree, resetRoot = true) => { if (resetRoot) { tree.dev = false tree.optional = false tree.devOptional = false tree.peer = false } const ret = depth({ tree, visit: node => calcDepFlagsStep(node), filter: node => node, getChildren: (node, tree) => [...tree.edgesOut.values()].map(edge => edge.to), }) return ret } const calcDepFlagsStep = (node) => { // This rewalk is necessary to handle cases where devDep and optional // or normal dependency graphs overlap deep in the dep graph. // Since we're only walking through deps that are not already flagged // as non-dev/non-optional, it's typically a very shallow traversal node.extraneous = false resetParents(node, 'extraneous') resetParents(node, 'dev') resetParents(node, 'peer') resetParents(node, 'devOptional') resetParents(node, 'optional') // for links, map their hierarchy appropriately if (node.isLink) { // node.target can be null, we check to ensure it's not null before proceeding if (node.target == null) { return node } node.target.dev = node.dev node.target.optional = node.optional node.target.devOptional = node.devOptional node.target.peer = node.peer return calcDepFlagsStep(node.target) } node.edgesOut.forEach(({ peer, optional, dev, to }) => { // if the dep is missing, then its flags are already maximally unset if (!to) { return } // everything with any kind of edge into it is not extraneous to.extraneous = false // devOptional is the *overlap* of the dev and optional tree. // however, for convenience and to save an extra rewalk, we leave // it set when we are in *either* tree, and then omit it from the // package-lock if either dev or optional are set. const unsetDevOpt = !node.devOptional && !node.dev && !node.optional && !dev && !optional // if we are not in the devOpt tree, then we're also not in // either the dev or opt trees const unsetDev = unsetDevOpt || !node.dev && !dev const unsetOpt = unsetDevOpt || !node.optional && !optional const unsetPeer = !node.peer && !peer if (unsetPeer) { unsetFlag(to, 'peer') } if (unsetDevOpt) { unsetFlag(to, 'devOptional') } if (unsetDev) { unsetFlag(to, 'dev') } if (unsetOpt) { unsetFlag(to, 'optional') } }) return node } const resetParents = (node, flag) => { if (node[flag]) { return } for (let p = node; p && (p === node || p[flag]); p = p.resolveParent) { p[flag] = false } } // typically a short walk, since it only traverses deps that have the flag set. const unsetFlag = (node, flag) => { if (node[flag]) { node[flag] = false depth({ tree: node, visit: node => { node.extraneous = node[flag] = false if (node.isLink && node.target) { node.target.extraneous = node.target[flag] = false } }, getChildren: node => { const children = [] const targetNode = node.isLink && node.target ? node.target : node for (const edge of targetNode.edgesOut.values()) { if ( edge.to && edge.to[flag] && ((flag !== 'peer' && edge.type === 'peer') || edge.type === 'prod') ) { children.push(edge.to) } } return children }, }) } } module.exports = calcDepFlags // Internal methods used by buildIdealTree. // Answer the question: "can I put this dep here?" // // IMPORTANT: *nothing* in this class should *ever* modify or mutate the tree // at all. The contract here is strictly limited to read operations. We call // this in the process of walking through the ideal tree checking many // different potential placement targets for a given node. If a change is made // to the tree along the way, that can cause serious problems! // // In order to enforce this restriction, in debug mode, canPlaceDep() will // snapshot the tree at the start of the process, and then at the end, will // verify that it still matches the snapshot, and throw an error if any changes // occurred. // // The algorithm is roughly like this: // - check the node itself: // - if there is no version present, and no conflicting edges from target, // OK, provided all peers can be placed at or above the target. // - if the current version matches, KEEP // - if there is an older version present, which can be replaced, then // - if satisfying and preferDedupe? KEEP // - else: REPLACE // - if there is a newer version present, and preferDedupe, REPLACE // - if the version present satisfies the edge, KEEP // - else: CONFLICT // - if the node is not in conflict, check each of its peers: // - if the peer can be placed in the target, continue // - else if the peer can be placed in a parent, and there is no other // conflicting version shadowing it, continue // - else CONFLICT // - If the peers are not in conflict, return the original node's value // // An exception to this logic is that if the target is the deepest location // that a node can be placed, and the conflicting node can be placed deeper, // then we will return REPLACE rather than CONFLICT, and Arborist will queue // the replaced node for resolution elsewhere. const localeCompare = require('@isaacs/string-locale-compare')('en') const semver = require('semver') const debug = require('./debug.js') const peerEntrySets = require('./peer-entry-sets.js') const deepestNestingTarget = require('./deepest-nesting-target.js') const CONFLICT = Symbol('CONFLICT') const OK = Symbol('OK') const REPLACE = Symbol('REPLACE') const KEEP = Symbol('KEEP') class CanPlaceDep { // dep is a dep that we're trying to place. it should already live in // a virtual tree where its peer set is loaded as children of the root. // target is the actual place where we're trying to place this dep // in a node_modules folder. // edge is the edge that we're trying to satisfy with this placement. // parent is the CanPlaceDep object of the entry node when placing a peer. constructor (options) { const { dep, target, edge, preferDedupe, parent = null, peerPath = [], explicitRequest = false, } = options debug(() => { if (!dep) { throw new Error('no dep provided to CanPlaceDep') } if (!target) { throw new Error('no target provided to CanPlaceDep') } if (!edge) { throw new Error('no edge provided to CanPlaceDep') } this._treeSnapshot = JSON.stringify([...target.root.inventory.entries()] .map(([loc, { packageName, version, resolved }]) => { return [loc, packageName, version, resolved] }).sort(([a], [b]) => localeCompare(a, b))) }) // the result of whether we can place it or not this.canPlace = null // if peers conflict, but this one doesn't, then that is useful info this.canPlaceSelf = null this.dep = dep this.target = target this.edge = edge this.explicitRequest = explicitRequest // preventing cycles when we check peer sets this.peerPath = peerPath // we always prefer to dedupe peers, because they are trying // a bit harder to be singletons. this.preferDedupe = !!preferDedupe || edge.peer this.parent = parent this.children = [] this.isSource = target === this.peerSetSource this.name = edge.name this.current = target.children.get(this.name) this.targetEdge = target.edgesOut.get(this.name) this.conflicts = new Map() // check if this dep was already subject to a peerDep override while // building the peerSet. this.edgeOverride = !dep.satisfies(edge) this.canPlace = this.checkCanPlace() if (!this.canPlaceSelf) { this.canPlaceSelf = this.canPlace } debug(() => { const treeSnapshot = JSON.stringify([...target.root.inventory.entries()] .map(([loc, { packageName, version, resolved }]) => { return [loc, packageName, version, resolved] }).sort(([a], [b]) => localeCompare(a, b))) /* istanbul ignore if */ if (this._treeSnapshot !== treeSnapshot) { throw Object.assign(new Error('tree changed in CanPlaceDep'), { expect: this._treeSnapshot, actual: treeSnapshot, }) } }) } checkCanPlace () { const { target, targetEdge, current, dep } = this // if the dep failed to load, we're going to fail the build or // prune it out anyway, so just move forward placing/replacing it. if (dep.errors.length) { return current ? REPLACE : OK } // cannot place peers inside their dependents, except for tops if (targetEdge && targetEdge.peer && !target.isTop) { return CONFLICT } // skip this test if there's a current node, because we might be able // to dedupe against it anyway if (!current && targetEdge && !dep.satisfies(targetEdge) && targetEdge !== this.edge) { return CONFLICT } return current ? this.checkCanPlaceCurrent() : this.checkCanPlaceNoCurrent() } // we know that the target has a dep by this name in its node_modules // already. Can return KEEP, REPLACE, or CONFLICT. checkCanPlaceCurrent () { const { preferDedupe, explicitRequest, current, target, edge, dep } = this if (dep.matches(current)) { if (current.satisfies(edge) || this.edgeOverride) { return explicitRequest ? REPLACE : KEEP } } const { version: curVer } = current const { version: newVer } = dep const tryReplace = curVer && newVer && semver.gte(newVer, curVer) if (tryReplace && dep.canReplace(current)) { // It's extremely rare that a replaceable node would be a conflict, if // the current one wasn't a conflict, but it is theoretically possible // if peer deps are pinned. In that case we treat it like any other // conflict, and keep trying. const cpp = this.canPlacePeers(REPLACE) if (cpp !== CONFLICT) { return cpp } } // ok, can't replace the current with new one, but maybe current is ok? if (current.satisfies(edge) && (!explicitRequest || preferDedupe)) { return KEEP } // if we prefer deduping, then try replacing newer with older if (preferDedupe && !tryReplace && dep.canReplace(current)) { const cpp = this.canPlacePeers(REPLACE) if (cpp !== CONFLICT) { return cpp } } // Check for interesting cases! // First, is this the deepest place that this thing can go, and NOT the // deepest place where the conflicting dep can go? If so, replace it, // and let it re-resolve deeper in the tree. const myDeepest = this.deepestNestingTarget // ok, i COULD be placed deeper, so leave the current one alone. if (target !== myDeepest) { return CONFLICT } // if we are not checking a peerDep, then we MUST place it here, in the // target that has a non-peer dep on it. if (!edge.peer && target === edge.from) { return this.canPlacePeers(REPLACE) } // if we aren't placing a peer in a set, then we're done here. // This is ignored because it SHOULD be redundant, as far as I can tell, // with the deepest target and target===edge.from tests. But until we // can prove that isn't possible, this condition is here for safety. /* istanbul ignore if - allegedly impossible */ if (!this.parent && !edge.peer) { return CONFLICT } // check the deps in the peer group for each edge into that peer group // if ALL of them can be pushed deeper, or if it's ok to replace its // members with the contents of the new peer group, then we're good. let canReplace = true for (const [entryEdge, currentPeers] of peerEntrySets(current)) { if (entryEdge === this.edge || entryEdge === this.peerEntryEdge) { continue } // First, see if it's ok to just replace the peerSet entirely. // we do this by walking out from the entryEdge, because in a case like // this: // // v -> PEER(a@1||2) // a@1 -> PEER(b@1) // a@2 -> PEER(b@2) // b@1 -> PEER(a@1) // b@2 -> PEER(a@2) // // root // +-- v // +-- a@2 // +-- b@2 // // Trying to place a peer group of (a@1, b@1) would fail to note that // they can be replaced, if we did it by looping 1 by 1. If we are // replacing something, we don't have to check its peer deps, because // the peerDeps in the placed peerSet will presumably satisfy. const entryNode = entryEdge.to const entryRep = dep.parent.children.get(entryNode.name) if (entryRep) { if (entryRep.canReplace(entryNode, dep.parent.children.keys())) { continue } } let canClobber = !entryRep if (!entryRep) { const peerReplacementWalk = new Set([entryNode]) OUTER: for (const currentPeer of peerReplacementWalk) { for (const edge of currentPeer.edgesOut.values()) { if (!edge.peer || !edge.valid) { continue } const rep = dep.parent.children.get(edge.name) if (!rep) { if (edge.to) { peerReplacementWalk.add(edge.to) } continue } if (!rep.satisfies(edge)) { canClobber = false break OUTER } } } } if (canClobber) { continue } // ok, we can't replace, but maybe we can nest the current set deeper? let canNestCurrent = true for (const currentPeer of currentPeers) { if (!canNestCurrent) { break } // still possible to nest this peerSet const curDeep = deepestNestingTarget(entryEdge.from, currentPeer.name) if (curDeep === target || target.isDescendantOf(curDeep)) { canNestCurrent = false canReplace = false } if (canNestCurrent) { continue } } } // if we can nest or replace all the current peer groups, we can replace. if (canReplace) { return this.canPlacePeers(REPLACE) } return CONFLICT } checkCanPlaceNoCurrent () { const { target, peerEntryEdge, dep, name } = this // check to see what that name resolves to here, and who may depend on // being able to reach it by crawling up past the parent. we know // that it's not the target's direct child node, and if it was a direct // dep of the target, we would have conflicted earlier. const current = target !== peerEntryEdge.from && target.resolve(name) if (current) { for (const edge of current.edgesIn.values()) { if (edge.from.isDescendantOf(target) && edge.valid) { if (!dep.satisfies(edge)) { return CONFLICT } } } } // no objections, so this is fine as long as peers are ok here. return this.canPlacePeers(OK) } get deepestNestingTarget () { const start = this.parent ? this.parent.deepestNestingTarget : this.edge.from return deepestNestingTarget(start, this.name) } get conflictChildren () { return this.allChildren.filter(c => c.canPlace === CONFLICT) } get allChildren () { const set = new Set(this.children) for (const child of set) { for (const grandchild of child.children) { set.add(grandchild) } } return [...set] } get top () { return this.parent ? this.parent.top : this } // check if peers can go here. returns state or CONFLICT canPlacePeers (state) { this.canPlaceSelf = state if (this._canPlacePeers) { return this._canPlacePeers } // TODO: represent peerPath in ERESOLVE error somehow? const peerPath = [...this.peerPath, this.dep] let sawConflict = false for (const peerEdge of this.dep.edgesOut.values()) { if (!peerEdge.peer || !peerEdge.to || peerPath.includes(peerEdge.to)) { continue } const peer = peerEdge.to // it may be the case that the *initial* dep can be nested, but a peer // of that dep needs to be placed shallower, because the target has // a peer dep on the peer as well. const target = deepestNestingTarget(this.target, peer.name) const cpp = new CanPlaceDep({ dep: peer, target, parent: this, edge: peerEdge, peerPath, // always place peers in preferDedupe mode preferDedupe: true, }) /* istanbul ignore next */ debug(() => { if (this.children.some(c => c.dep === cpp.dep)) { throw new Error('checking same dep repeatedly') } }) this.children.push(cpp) if (cpp.canPlace === CONFLICT) { sawConflict = true } } this._canPlacePeers = sawConflict ? CONFLICT : state return this._canPlacePeers } // what is the node that is causing this peerSet to be placed? get peerSetSource () { return this.parent ? this.parent.peerSetSource : this.edge.from } get peerEntryEdge () { return this.top.edge } static get CONFLICT () { return CONFLICT } static get OK () { return OK } static get REPLACE () { return REPLACE } static get KEEP () { return KEEP } get description () { const { canPlace } = this return canPlace && canPlace.description || /* istanbul ignore next - old node affordance */ canPlace } } module.exports = CanPlaceDep // package children are represented with a Map object, but many file systems // are case-insensitive and unicode-normalizing, so we need to treat // node.children.get('FOO') and node.children.get('foo') as the same thing. module.exports = class CIMap extends Map { #keys = new Map() constructor (items = []) { super() for (const [key, val] of items) { this.set(key, val) } } #normKey (key) { if (typeof key !== 'string') { return key } return key.normalize('NFKD').toLowerCase() } get (key) { const normKey = this.#normKey(key) return this.#keys.has(normKey) ? super.get(this.#keys.get(normKey)) : undefined } set (key, val) { const normKey = this.#normKey(key) if (this.#keys.has(normKey)) { super.delete(this.#keys.get(normKey)) } this.#keys.set(normKey, key) return super.set(key, val) } delete (key) { const normKey = this.#normKey(key) if (this.#keys.has(normKey)) { const prevKey = this.#keys.get(normKey) this.#keys.delete(normKey) return super.delete(prevKey) } } has (key) { const normKey = this.#normKey(key) return this.#keys.has(normKey) && super.has(this.#keys.get(normKey)) } } // take a path and a resolved value, and turn it into a resolution from // the given new path. This is used with converting a package.json's // relative file: path into one suitable for a lockfile, or between // lockfiles, and for converting hosted git repos to a consistent url type. const npa = require('npm-package-arg') const relpath = require('./relpath.js') const consistentResolve = (resolved, fromPath, toPath, relPaths = false) => { if (!resolved) { return null } try { const hostedOpt = { noCommittish: false } const { fetchSpec, saveSpec, type, hosted, rawSpec, raw, } = npa(resolved, fromPath) if (type === 'file' || type === 'directory') { const cleanFetchSpec = fetchSpec.replace(/#/g, '%23') if (relPaths && toPath) { return `file:${relpath(toPath, cleanFetchSpec)}` } return `file:${cleanFetchSpec}` } if (hosted) { return `git+${hosted.auth ? hosted.https(hostedOpt) : hosted.sshurl(hostedOpt)}` } if (type === 'git') { return saveSpec } if (rawSpec === '*') { return raw } return rawSpec } catch (_) { // whatever we passed in was not acceptable to npa. // leave it 100% untouched. return resolved } } module.exports = consistentResolve // certain assertions we should do only when testing arborist itself, because // they are too expensive or aggressive and would break user programs if we // miss a situation where they are actually valid. // // call like this: // // /* istanbul ignore next - debug check */ // debug(() => { // if (someExpensiveCheck) // throw new Error('expensive check should have returned false') // }) // run in debug mode if explicitly requested, running arborist tests, // or working in the arborist project directory. const debug = process.env.ARBORIST_DEBUG !== '0' && ( process.env.ARBORIST_DEBUG === '1' || /\barborist\b/.test(process.env.NODE_DEBUG || '') || process.env.npm_package_name === '@npmcli/arborist' && ['test', 'snap'].includes(process.env.npm_lifecycle_event) || process.cwd() === require('node:path').resolve(__dirname, '..') ) module.exports = debug ? fn => fn() : () => {} const red = process.stderr.isTTY ? msg => `\x1B[31m${msg}\x1B[39m` : m => m module.exports.log = (...msg) => module.exports(() => { const { format } = require('node:util') const prefix = `\n${process.pid} ${red(format(msg.shift()))} ` msg = (prefix + format(...msg).trim().split('\n').join(prefix)).trim() /* eslint-disable-next-line no-console */ console.error(msg) }) // given a starting node, what is the *deepest* target where name could go? // This is not on the Node class for the simple reason that we sometimes // need to check the deepest *potential* target for a Node that is not yet // added to the tree where we are checking. const deepestNestingTarget = (start, name) => { for (const target of start.ancestry()) { // note: this will skip past the first target if edge is peer if (target.isProjectRoot || !target.resolveParent || target.globalTop) { return target } const targetEdge = target.edgesOut.get(name) if (!targetEdge || !targetEdge.peer) { return target } } } module.exports = deepestNestingTarget // Do not rely on package._fields, so that we don't throw // false failures if a tree is generated by other clients. // Only relies on child.resolved, which MAY come from // client-specific package.json meta _fields, but most of // the time will be pulled out of a lockfile const semver = require('semver') const npa = require('npm-package-arg') const { relative } = require('node:path') const fromPath = require('./from-path.js') const depValid = (child, requested, requestor) => { // NB: we don't do much to verify 'tag' type requests. // Just verify that we got a remote resolution. Presumably, it // came from a registry and was tagged at some point. if (typeof requested === 'string') { try { // tarball/dir must have resolved to the same tgz on disk, but for // file: deps that depend on other files/dirs, we must resolve the // location based on the *requestor* file/dir, not where it ends up. // '' is equivalent to '*' requested = npa.resolve(child.name, requested || '*', fromPath(requestor, requestor.edgesOut.get(child.name))) } catch (er) { // Not invalid because the child doesn't match, but because // the spec itself is not supported. Nothing would match, // so the edge is definitely not valid and never can be. er.dependency = child.name er.requested = requested requestor.errors.push(er) return false } } // if the lockfile is super old, or hand-modified, // then it's possible to hit this state. if (!requested) { const er = new Error('Invalid dependency specifier') er.dependency = child.name er.requested = requested requestor.errors.push(er) return false } switch (requested.type) { case 'range': if (requested.fetchSpec === '*') { return true } // fallthrough case 'version': // if it's a version or a range other than '*', semver it return semver.satisfies(child.version, requested.fetchSpec, true) case 'directory': return linkValid(child, requested, requestor) case 'file': return tarballValid(child, requested, requestor) case 'alias': // check that the alias target is valid return depValid(child, requested.subSpec, requestor) case 'tag': // if it's a tag, we just verify that it has a tarball resolution // presumably, it came from the registry and was tagged at some point return child.resolved && npa(child.resolved).type === 'remote' case 'remote': // verify that we got it from the desired location return child.resolved === requested.fetchSpec case 'git': { // if it's a git type, verify that they're the same repo // // if it specifies a definite commit, then it must have the // same commit to be considered the same repo // // if it has a #semver: specifier, verify that the // version in the package is in the semver range const resRepo = npa(child.resolved || '') const resHost = resRepo.hosted const reqHost = requested.hosted const reqCommit = /^[a-fA-F0-9]{40}$/.test(requested.gitCommittish || '') const nc = { noCommittish: !reqCommit } if (!resHost) { if (resRepo.fetchSpec !== requested.fetchSpec) { return false } } else { if (reqHost?.ssh(nc) !== resHost.ssh(nc)) { return false } } if (!requested.gitRange) { return true } return semver.satisfies(child.package.version, requested.gitRange, { loose: true, }) } default: // unpossible, just being cautious break } const er = new Error('Unsupported dependency type') er.dependency = child.name er.requested = requested requestor.errors.push(er) return false } const linkValid = (child, requested, requestor) => { const isLink = !!child.isLink // if we're installing links and the node is a link, then it's invalid because we want // a real node to be there. Except for workspaces. They are always links. if (requestor.installLinks && !child.isWorkspace) { return !isLink } // directory must be a link to the specified folder return isLink && relative(child.realpath, requested.fetchSpec) === '' } const tarballValid = (child, requested) => { if (child.isLink) { return false } if (child.resolved) { return child.resolved.replace(/\\/g, '/') === `file:${requested.fetchSpec.replace(/\\/g, '/')}` } // if we have a legacy mutated package.json file. we can't be 100% // sure that it resolved to the same file, but if it was the same // request, that's a pretty good indicator of sameness. if (child.package._requested) { return child.package._requested.saveSpec === requested.saveSpec } // ok, we're probably dealing with some legacy cruft here, not much // we can do at this point unfortunately. return false } module.exports = (child, requested, accept, requestor) => depValid(child, requested, requestor) || (typeof accept === 'string' ? depValid(child, accept, requestor) : false) // a tree representing the difference between two trees // A Diff node's parent is not necessarily the parent of // the node location it refers to, but rather the highest level // node that needs to be either changed or removed. // Thus, the root Diff node is the shallowest change required // for a given branch of the tree being mutated. const { depth } = require('treeverse') const { existsSync } = require('node:fs') const ssri = require('ssri') class Diff { constructor ({ actual, ideal, filterSet, shrinkwrapInflated }) { this.filterSet = filterSet this.shrinkwrapInflated = shrinkwrapInflated this.children = [] this.actual = actual this.ideal = ideal if (this.ideal) { this.resolved = this.ideal.resolved this.integrity = this.ideal.integrity } this.action = getAction(this) this.parent = null // the set of leaf nodes that we rake up to the top level this.leaves = [] // the set of nodes that don't change in this branch of the tree this.unchanged = [] // the set of nodes that will be removed in this branch of the tree this.removed = [] } static calculate ({ actual, ideal, filterNodes = [], shrinkwrapInflated = new Set(), }) { // if there's a filterNode, then: // - get the path from the root to the filterNode. The root or // root.target should have an edge either to the filterNode or // a link to the filterNode. If not, abort. Add the path to the // filterSet. // - Add set of Nodes depended on by the filterNode to filterSet. // - Anything outside of that set should be ignored by getChildren const filterSet = new Set() const extraneous = new Set() for (const filterNode of filterNodes) { const { root } = filterNode if (root !== ideal && root !== actual) { throw new Error('invalid filterNode: outside idealTree/actualTree') } const rootTarget = root.target const edge = [...rootTarget.edgesOut.values()].filter(e => { return e.to && (e.to === filterNode || e.to.target === filterNode) })[0] filterSet.add(root) filterSet.add(rootTarget) filterSet.add(ideal) filterSet.add(actual) if (edge && edge.to) { filterSet.add(edge.to) filterSet.add(edge.to.target) } filterSet.add(filterNode) depth({ tree: filterNode, visit: node => filterSet.add(node), getChildren: node => { node = node.target const loc = node.location const idealNode = ideal.inventory.get(loc) const ideals = !idealNode ? [] : [...idealNode.edgesOut.values()].filter(e => e.to).map(e => e.to) const actualNode = actual.inventory.get(loc) const actuals = !actualNode ? [] : [...actualNode.edgesOut.values()].filter(e => e.to).map(e => e.to) if (actualNode) { for (const child of actualNode.children.values()) { if (child.extraneous) { extraneous.add(child) } } } return ideals.concat(actuals) }, }) } for (const extra of extraneous) { filterSet.add(extra) } return depth({ tree: new Diff({ actual, ideal, filterSet, shrinkwrapInflated }), getChildren, leave, }) } } const getAction = ({ actual, ideal }) => { if (!ideal) { return 'REMOVE' } // bundled meta-deps are copied over to the ideal tree when we visit it, // so they'll appear to be missing here. There's no need to handle them // in the diff, though, because they'll be replaced at reify time anyway // Otherwise, add the missing node. if (!actual) { return ideal.inDepBundle ? null : 'ADD' } // always ignore the root node if (ideal.isRoot && actual.isRoot) { return null } // if the versions don't match, it's a change no matter what if (ideal.version !== actual.version) { return 'CHANGE' } const binsExist = ideal.binPaths.every((path) => existsSync(path)) // top nodes, links, and git deps won't have integrity, but do have resolved // if neither node has integrity, the bins exist, and either (a) neither // node has a resolved value or (b) they both do and match, then we can // leave this one alone since we already know the versions match due to // the condition above. The "neither has resolved" case (a) cannot be // treated as a 'mark CHANGE and refetch', because shrinkwraps, bundles, // and link deps may lack this information, and we don't want to try to // go to the registry for something that isn't there. const noIntegrity = !ideal.integrity && !actual.integrity const noResolved = !ideal.resolved && !actual.resolved const resolvedMatch = ideal.resolved && ideal.resolved === actual.resolved if (noIntegrity && binsExist && (resolvedMatch || noResolved)) { return null } // otherwise, verify that it's the same bits // note that if ideal has integrity, and resolved doesn't, we treat // that as a 'change', so that it gets re-fetched and locked down. const integrityMismatch = !ideal.integrity || !actual.integrity || !ssri.parse(ideal.integrity).match(actual.integrity) if (integrityMismatch || !binsExist) { return 'CHANGE' } return null } const allChildren = node => { if (!node) { return new Map() } // if the node is root, and also a link, then what we really // want is to traverse the target's children if (node.isRoot && node.isLink) { return allChildren(node.target) } const kids = new Map() for (const n of [node, ...node.fsChildren]) { for (const kid of n.children.values()) { kids.set(kid.path, kid) } } return kids } // functions for the walk options when we traverse the trees // to create the diff tree const getChildren = diff => { const children = [] const { actual, ideal, unchanged, removed, filterSet, shrinkwrapInflated, } = diff // Note: we DON'T diff fsChildren themselves, because they are either // included in the package contents, or part of some other project, and // will never appear in legacy shrinkwraps anyway. but we _do_ include the // child nodes of fsChildren, because those are nodes that we are typically // responsible for installing. const actualKids = allChildren(actual) const idealKids = allChildren(ideal) if (ideal && ideal.hasShrinkwrap && !shrinkwrapInflated.has(ideal)) { // Guaranteed to get a diff.leaves here, because we always // be called with a proper Diff object when ideal has a shrinkwrap // that has not been inflated. diff.leaves.push(diff) return children } const paths = new Set([...actualKids.keys(), ...idealKids.keys()]) for (const path of paths) { const actual = actualKids.get(path) const ideal = idealKids.get(path) diffNode({ actual, ideal, children, unchanged, removed, filterSet, shrinkwrapInflated, }) } if (diff.leaves && !children.length) { diff.leaves.push(diff) } return children } const diffNode = ({ actual, ideal, children, unchanged, removed, filterSet, shrinkwrapInflated, }) => { if (filterSet.size && !(filterSet.has(ideal) || filterSet.has(actual))) { return } const action = getAction({ actual, ideal }) // if it's a match, then get its children // otherwise, this is the child diff node if (action || (!shrinkwrapInflated.has(ideal) && ideal.hasShrinkwrap)) { if (action === 'REMOVE') { removed.push(actual) } children.push(new Diff({ actual, ideal, filterSet, shrinkwrapInflated })) } else { unchanged.push(ideal) // !*! Weird dirty hack warning !*! // // Bundled deps aren't loaded in the ideal tree, because we don't know // what they are going to be without unpacking. Swap them over now if // the bundling node isn't changing, so we don't prune them later. // // It's a little bit dirty to be doing this here, since it means that // diffing trees can mutate them, but otherwise we have to walk over // all unchanging bundlers and correct the diff later, so it's more // efficient to just fix it while we're passing through already. // // Note that moving over a bundled dep will break the links to other // deps under this parent, which may have been transitively bundled. // Breaking those links means that we'll no longer see the transitive // dependency, meaning that it won't appear as bundled any longer! // In order to not end up dropping transitively bundled deps, we have // to get the list of nodes to move, then move them all at once, rather // than moving them one at a time in the first loop. const bd = ideal.package.bundleDependencies if (actual && bd && bd.length) { const bundledChildren = [] for (const node of actual.children.values()) { if (node.inBundle) { bundledChildren.push(node) } } for (const node of bundledChildren) { node.parent = ideal } } children.push(...getChildren({ actual, ideal, unchanged, removed, filterSet, shrinkwrapInflated, })) } } // set the parentage in the leave step so that we aren't attaching // child nodes only to remove them later. also bubble up the unchanged // nodes so that we can move them out of staging in the reification step. const leave = (diff, children) => { children.forEach(kid => { kid.parent = diff diff.leaves.push(...kid.leaves) diff.unchanged.push(...kid.unchanged) diff.removed.push(...kid.removed) }) diff.children = children return diff } module.exports = Diff // An edge in the dependency graph // Represents a dependency relationship of some kind const util = require('node:util') const npa = require('npm-package-arg') const depValid = require('./dep-valid.js') class ArboristEdge { constructor (edge) { this.name = edge.name this.spec = edge.spec this.type = edge.type const edgeFrom = edge.from?.location const edgeTo = edge.to?.location const override = edge.overrides?.value if (edgeFrom != null) { this.from = edgeFrom } if (edgeTo) { this.to = edgeTo } if (edge.error) { this.error = edge.error } if (edge.peerConflicted) { this.peerConflicted = true } if (override) { this.overridden = override } } } class Edge { #accept #error #explanation #from #name #spec #to #type static types = Object.freeze([ 'prod', 'dev', 'optional', 'peer', 'peerOptional', 'workspace', ]) // XXX where is this used? static errors = Object.freeze([ 'DETACHED', 'MISSING', 'PEER LOCAL', 'INVALID', ]) constructor (options) { const { type, name, spec, accept, from, overrides } = options // XXX are all of these error states even possible? if (typeof spec !== 'string') { throw new TypeError('must provide string spec') } if (!Edge.types.includes(type)) { throw new TypeError(`invalid type: ${type}\n(valid types are: ${Edge.types.join(', ')})`) } if (type === 'workspace' && npa(spec).type !== 'directory') { throw new TypeError('workspace edges must be a symlink') } if (typeof name !== 'string') { throw new TypeError('must provide dependency name') } if (!from) { throw new TypeError('must provide "from" node') } if (accept !== undefined) { if (typeof accept !== 'string') { throw new TypeError('accept field must be a string if provided') } this.#accept = accept || '*' } if (overrides !== undefined) { this.overrides = overrides } this.#name = name this.#type = type this.#spec = spec this.#explanation = null this.#from = from from.edgesOut.get(this.#name)?.detach() from.addEdgeOut(this) this.reload(true) this.peerConflicted = false } satisfiedBy (node) { if (node.name !== this.#name) { return false } // NOTE: this condition means we explicitly do not support overriding // bundled or shrinkwrapped dependencies if (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) { return depValid(node, this.rawSpec, this.#accept, this.#from) } return depValid(node, this.spec, this.#accept, this.#from) } // return the edge data, and an explanation of how that edge came to be here explain (seen = []) { if (!this.#explanation) { const explanation = { type: this.#type, name: this.#name, spec: this.spec, } if (this.rawSpec !== this.spec) { explanation.rawSpec = this.rawSpec explanation.overridden = true } if (this.bundled) { explanation.bundled = this.bundled } if (this.error) { explanation.error = this.error } if (this.#from) { explanation.from = this.#from.explain(null, seen) } this.#explanation = explanation } return this.#explanation } get bundled () { return !!this.#from?.package?.bundleDependencies?.includes(this.#name) } get workspace () { return this.#type === 'workspace' } get prod () { return this.#type === 'prod' } get dev () { return this.#type === 'dev' } get optional () { return this.#type === 'optional' || this.#type === 'peerOptional' } get peer () { return this.#type === 'peer' || this.#type === 'peerOptional' } get type () { return this.#type } get name () { return this.#name } get rawSpec () { return this.#spec } get spec () { if (this.overrides?.value && this.overrides.value !== '*' && this.overrides.name === this.#name) { if (this.overrides.value.startsWith('$')) { const ref = this.overrides.value.slice(1) // we may be a virtual root, if we are we want to resolve reference overrides // from the real root, not the virtual one const pkg = this.#from.sourceReference ? this.#from.sourceReference.root.package : this.#from.root.package if (pkg.devDependencies?.[ref]) { return pkg.devDependencies[ref] } if (pkg.optionalDependencies?.[ref]) { return pkg.optionalDependencies[ref] } if (pkg.dependencies?.[ref]) { return pkg.dependencies[ref] } if (pkg.peerDependencies?.[ref]) { return pkg.peerDependencies[ref] } throw new Error(`Unable to resolve reference ${this.overrides.value}`) } return this.overrides.value } return this.#spec } get accept () { return this.#accept } get valid () { return !this.error } get missing () { return this.error === 'MISSING' } get invalid () { return this.error === 'INVALID' } get peerLocal () { return this.error === 'PEER LOCAL' } get error () { if (!this.#error) { if (!this.#to) { if (this.optional) { this.#error = null } else { this.#error = 'MISSING' } } else if (this.peer && this.#from === this.#to.parent && !this.#from.isTop) { this.#error = 'PEER LOCAL' } else if (!this.satisfiedBy(this.#to)) { this.#error = 'INVALID' } else { this.#error = 'OK' } } if (this.#error === 'OK') { return null } return this.#error } reload (hard = false) { this.#explanation = null if (this.#from.overrides) { this.overrides = this.#from.overrides.getEdgeRule(this) } else { delete this.overrides } const newTo = this.#from.resolve(this.#name) if (newTo !== this.#to) { if (this.#to) { this.#to.edgesIn.delete(this) } this.#to = newTo this.#error = null if (this.#to) { this.#to.addEdgeIn(this) } } else if (hard) { this.#error = null } } detach () { this.#explanation = null if (this.#to) { this.#to.edgesIn.delete(this) } this.#from.edgesOut.delete(this.#name) this.#to = null this.#error = 'DETACHED' this.#from = null } get from () { return this.#from } get to () { return this.#to } toJSON () { return new ArboristEdge(this) } [util.inspect.custom] () { return this.toJSON() } } module.exports = Edge // file dependencies need their dependencies resolved based on the location // where the tarball was found, not the location where they end up getting // installed. directory (ie, symlink) deps also need to be resolved based on // their targets, but that's what realpath is const { dirname } = require('node:path') const npa = require('npm-package-arg') const fromPath = (node, edge) => { if (edge && edge.overrides && edge.overrides.name === edge.name && edge.overrides.value) { // fromPath could be called with a node that has a virtual root, if that // happens we want to make sure we get the real root node when overrides // are in use. this is to allow things like overriding a dependency with a // tarball file that's a relative path from the project root if (node.sourceReference) { return node.sourceReference.root.realpath } return node.root.realpath } if (node.resolved) { const spec = npa(node.resolved) if (spec?.type === 'file') { return dirname(spec.fetchSpec) } } return node.realpath } module.exports = fromPath // Given a set of nodes in a tree, and a filter function to test // incoming edges to the dep set that should be ignored otherwise. // // find the set of deps that are only depended upon by nodes in the set, or // their dependencies, or edges that are ignored. // // Used when figuring out what to prune when replacing a node with a newer // version, or when an optional dep fails to install. const gatherDepSet = (set, edgeFilter) => { const deps = new Set(set) // add the full set of dependencies. note that this loop will continue // as the deps set increases in size. for (const node of deps) { for (const edge of node.edgesOut.values()) { if (edge.to && edgeFilter(edge)) { deps.add(edge.to) } } } // now remove all nodes in the set that have a dependant outside the set // if any change is made, then re-check // continue until no changes made, or deps set evaporates fully. let changed = true while (changed === true && deps.size > 0) { changed = false for (const dep of deps) { for (const edge of dep.edgesIn) { if (!deps.has(edge.from) && edgeFilter(edge)) { changed = true deps.delete(dep) break } } } } return deps } module.exports = gatherDepSet module.exports = require('./arborist/index.js') module.exports.Arborist = module.exports module.exports.Node = require('./node.js') module.exports.Link = require('./link.js') module.exports.Edge = require('./edge.js') module.exports.Shrinkwrap = require('./shrinkwrap.js') // a class to manage an inventory and set of indexes of a set of objects based // on specific fields. const { hasOwnProperty } = Object.prototype const debug = require('./debug.js') const keys = ['name', 'license', 'funding', 'realpath', 'packageName'] class Inventory extends Map { #index constructor () { super() this.#index = new Map() for (const key of keys) { this.#index.set(key, new Map()) } } // XXX where is this used? get primaryKey () { return 'location' } // XXX where is this used? get indexes () { return [...keys] } * filter (fn) { for (const node of this.values()) { if (fn(node)) { yield node } } } add (node) { const root = super.get('') if (root && node.root !== root && node.root !== root.root) { debug(() => { throw Object.assign(new Error('adding external node to inventory'), { root: root.path, node: node.path, nodeRoot: node.root.path, }) }) return } const current = super.get(node.location) if (current) { if (current === node) { return } this.delete(current) } super.set(node.location, node) for (const [key, map] of this.#index.entries()) { let val if (hasOwnProperty.call(node, key)) { // if the node has the value, use it even if it's false val = node[key] } else if (key === 'license' && node.package) { // handling for the outdated "licenses" array, just pick the first one // also support the alternative spelling "licence" if (node.package.license) { val = node.package.license } else if (node.package.licence) { val = node.package.licence } else if (Array.isArray(node.package.licenses)) { val = node.package.licenses[0] } else if (Array.isArray(node.package.licences)) { val = node.package.licences[0] } } else if (node[key]) { val = node[key] } else { val = node.package?.[key] } if (val && typeof val === 'object') { // We currently only use license and funding /* istanbul ignore next - not used */ if (key === 'license') { val = val.type } else if (key === 'funding') { val = val.url } } if (!map.has(val)) { map.set(val, new Set()) } map.get(val).add(node) } } delete (node) { if (!this.has(node)) { return } super.delete(node.location) for (const [key, map] of this.#index.entries()) { let val if (node[key] !== undefined) { val = node[key] } else { val = node.package?.[key] } const set = map.get(val) if (set) { set.delete(node) if (set.size === 0) { map.delete(node[key]) } } } } query (key, val) { const map = this.#index.get(key) if (arguments.length === 2) { if (map.has(val)) { return map.get(val) } return new Set() } return map.keys() } has (node) { return super.get(node.location) === node } set () { throw new Error('direct set() not supported, use inventory.add(node)') } } module.exports = Inventory const relpath = require('./relpath.js') const Node = require('./node.js') const _loadDeps = Symbol.for('Arborist.Node._loadDeps') const _target = Symbol.for('_target') const { dirname } = require('node:path') // defined by Node class const _delistFromMeta = Symbol.for('_delistFromMeta') const _refreshLocation = Symbol.for('_refreshLocation') class Link extends Node { constructor (options) { const { root, realpath, target, parent, fsParent, isStoreLink } = options if (!realpath && !(target && target.path)) { throw new TypeError('must provide realpath for Link node') } super({ ...options, realpath: realpath || target.path, root: root || (parent ? parent.root : fsParent ? fsParent.root : target ? target.root : null), }) this.isStoreLink = isStoreLink || false if (target) { this.target = target } else if (this.realpath === this.root.path) { this.target = this.root } else { this.target = new Node({ ...options, path: realpath, parent: null, fsParent: null, root: this.root, }) } } get version () { return this.target ? this.target.version : this.package.version || '' } get target () { return this[_target] } set target (target) { const current = this[_target] if (target === current) { return } if (!target) { if (current && current.linksIn) { current.linksIn.delete(this) } if (this.path) { this[_delistFromMeta]() this[_target] = null this.package = {} this[_refreshLocation]() } else { this[_target] = null } return } if (!this.path) { // temp node pending assignment to a tree // we know it's not in the inventory yet, because no path. if (target.path) { this.realpath = target.path } else { target.path = target.realpath = this.realpath } target.root = this.root this[_target] = target target.linksIn.add(this) this.package = target.package return } // have to refresh metadata, because either realpath or package // is very likely changing. this[_delistFromMeta]() this.package = target.package this.realpath = target.path this[_refreshLocation]() target.root = this.root } // a link always resolves to the relative path to its target get resolved () { // the path/realpath guard is there for the benefit of setting // these things in the "wrong" order return this.path && this.realpath ? `file:${relpath(dirname(this.path), this.realpath).replace(/#/g, '%23')}` : null } set resolved (r) {} // deps are resolved on the target, not the Link // so this is a no-op [_loadDeps] () {} // links can't have children, only their targets can // fix it to an empty list so that we can still call // things that iterate over them, just as a no-op get children () { return new Map() } set children (c) {} get isLink () { return true } } module.exports = Link // inventory, path, realpath, root, and parent // // node.root is a reference to the root module in the tree (ie, typically the // cwd project folder) // // node.location is the /-delimited path from the root module to the node. In // the case of link targets that may be outside of the root's package tree, // this can include some number of /../ path segments. The location of the // root module is always '.'. node.location thus never contains drive letters // or absolute paths, and is portable within a given project, suitable for // inclusion in lockfiles and metadata. // // node.path is the path to the place where this node lives on disk. It is // system-specific and absolute. // // node.realpath is the path to where the module actually resides on disk. In // the case of non-link nodes, node.realpath is equivalent to node.path. In // the case of link nodes, it is equivalent to node.target.path. // // Setting node.parent will set the node's root to the parent's root, as well // as updating edgesIn and edgesOut to reload dependency resolutions as needed, // and setting node.path to parent.path/node_modules/name. // // node.inventory is a Map of name to a Set() of all the nodes under a given // root by that name. It's empty for non-root nodes, and changing the root // reference will remove it from the old root's inventory and add it to the new // one. This map is useful for cases like `npm update foo` or `npm ls foo` // where we need to quickly find all instances of a given package name within a // tree. const semver = require('semver') const nameFromFolder = require('@npmcli/name-from-folder') const Edge = require('./edge.js') const Inventory = require('./inventory.js') const OverrideSet = require('./override-set.js') const { normalize } = require('read-package-json-fast') const { getPaths: getBinPaths } = require('bin-links') const npa = require('npm-package-arg') const debug = require('./debug.js') const gatherDepSet = require('./gather-dep-set.js') const treeCheck = require('./tree-check.js') const { walkUp } = require('walk-up-path') const { resolve, relative, dirname, basename } = require('node:path') const util = require('node:util') const _package = Symbol('_package') const _parent = Symbol('_parent') const _target = Symbol.for('_target') const _fsParent = Symbol('_fsParent') const _reloadNamedEdges = Symbol('_reloadNamedEdges') // overridden by Link class const _loadDeps = Symbol.for('Arborist.Node._loadDeps') const _refreshLocation = Symbol.for('_refreshLocation') const _changePath = Symbol.for('_changePath') // used by Link class as well const _delistFromMeta = Symbol.for('_delistFromMeta') const _explain = Symbol('_explain') const _explanation = Symbol('_explanation') const relpath = require('./relpath.js') const consistentResolve = require('./consistent-resolve.js') const printableTree = require('./printable.js') const CaseInsensitiveMap = require('./case-insensitive-map.js') const querySelectorAll = require('./query-selector-all.js') class Node { #global #meta #root #workspaces constructor (options) { // NB: path can be null if it's a link target const { root, path, realpath, parent, error, meta, fsParent, resolved, integrity, // allow setting name explicitly when we haven't set a path yet name, children, fsChildren, installLinks = false, legacyPeerDeps = false, linksIn, isInStore = false, hasShrinkwrap, overrides, loadOverrides = false, extraneous = true, dev = true, optional = true, devOptional = true, peer = true, global = false, dummy = false, sourceReference = null, } = options // this object gives querySelectorAll somewhere to stash context about a node // while processing a query this.queryContext = {} // true if part of a global install this.#global = global this.#workspaces = null this.errors = error ? [error] : [] this.isInStore = isInStore // this will usually be null, except when modeling a // package's dependencies in a virtual root. this.sourceReference = sourceReference // TODO if this came from pacote.manifest we don't have to do this, // we can be told to skip this step const pkg = sourceReference ? sourceReference.package : normalize(options.pkg || {}) this.name = name || nameFromFolder(path || pkg.name || realpath) || pkg.name || null // should be equal if not a link this.path = path ? resolve(path) : null if (!this.name && (!this.path || this.path !== dirname(this.path))) { throw new TypeError('could not detect node name from path or package') } this.realpath = !this.isLink ? this.path : resolve(realpath) this.resolved = resolved || null if (!this.resolved) { // note: this *only* works for non-file: deps, so we avoid even // trying here. // file: deps are tracked in package.json will _resolved set to the // full path to the tarball or link target. However, if the package // is checked into git or moved to another location, that's 100% not // portable at all! The _where and _location don't provide much help, // since _location is just where the module ended up in the tree, // and _where can be different than the actual root if it's a // meta-dep deeper in the dependency graph. // // If we don't have the other oldest indicators of legacy npm, then it's // probably what we're getting from pacote, which IS trustworthy. // // Otherwise, hopefully a shrinkwrap will help us out. const resolved = consistentResolve(pkg._resolved) if (resolved && !(/^file:/.test(resolved) && pkg._where)) { this.resolved = resolved } } this.integrity = integrity || pkg._integrity || null this.hasShrinkwrap = hasShrinkwrap || pkg._hasShrinkwrap || false this.installLinks = installLinks this.legacyPeerDeps = legacyPeerDeps this.children = new CaseInsensitiveMap() this.fsChildren = new Set() this.inventory = new Inventory() this.tops = new Set() this.linksIn = new Set(linksIn || []) // these three are set by an Arborist taking a catalog // after the tree is built. We don't get this along the way, // because they have a tendency to change as new children are // added, especially when they're deduped. Eg, a dev dep may be // a 3-levels-deep dependency of a non-dev dep. If we calc the // flags along the way, then they'll tend to be invalid by the // time we need to look at them. if (!dummy) { this.dev = dev this.optional = optional this.devOptional = devOptional this.peer = peer this.extraneous = extraneous this.dummy = false } else { // true if this is a placeholder for the purpose of serving as a // fsParent to link targets that get their deps resolved outside // the root tree folder. this.dummy = true this.dev = false this.optional = false this.devOptional = false this.peer = false this.extraneous = false } this.edgesIn = new Set() this.edgesOut = new CaseInsensitiveMap() // have to set the internal package ref before assigning the parent, // because this.package is read when adding to inventory this[_package] = pkg && typeof pkg === 'object' ? pkg : {} if (overrides) { this.overrides = overrides } else if (loadOverrides) { const overrides = this[_package].overrides || {} if (Object.keys(overrides).length > 0) { this.overrides = new OverrideSet({ overrides: this[_package].overrides, }) } } // only relevant for the root and top nodes this.meta = meta // Note: this is _slightly_ less efficient for the initial tree // building than it could be, but in exchange, it's a much simpler // algorithm. // If this node has a bunch of children, and those children satisfy // its various deps, then we're going to _first_ create all the // edges, and _then_ assign the children into place, re-resolving // them all in _reloadNamedEdges. // A more efficient, but more complicated, approach would be to // flag this node as being a part of a tree build, so it could // hold off on resolving its deps until its children are in place. // call the parent setter // Must be set prior to calling _loadDeps, because top-ness is relevant // will also assign root if present on the parent this[_parent] = null this.parent = parent || null this[_fsParent] = null this.fsParent = fsParent || null // see parent/root setters below. // root is set to parent's root if we have a parent, otherwise if it's // null, then it's set to the node itself. if (!parent && !fsParent) { this.root = root || null } // mostly a convenience for testing, but also a way to create // trees in a more declarative way than setting parent on each if (children) { for (const c of children) { new Node({ ...c, parent: this }) } } if (fsChildren) { for (const c of fsChildren) { new Node({ ...c, fsParent: this }) } } // now load all the dep edges this[_loadDeps]() } get meta () { return this.#meta } set meta (meta) { this.#meta = meta if (meta) { meta.add(this) } } get global () { if (this.#root === this) { return this.#global } return this.#root.global } // true for packages installed directly in the global node_modules folder get globalTop () { return this.global && this.parent && this.parent.isProjectRoot } get workspaces () { return this.#workspaces } set workspaces (workspaces) { // deletes edges if they already exists if (this.#workspaces) { for (const name of this.#workspaces.keys()) { if (!workspaces.has(name)) { this.edgesOut.get(name).detach() } } } this.#workspaces = workspaces this.#loadWorkspaces() this[_loadDeps]() } get binPaths () { if (!this.parent) { return [] } return getBinPaths({ pkg: this[_package], path: this.path, global: this.global, top: this.globalTop, }) } get hasInstallScript () { const { hasInstallScript, scripts } = this.package const { install, preinstall, postinstall } = scripts || {} return !!(hasInstallScript || install || preinstall || postinstall) } get version () { return this[_package].version || '' } get packageName () { return this[_package].name || null } get pkgid () { const { name = '', version = '' } = this.package // root package will prefer package name over folder name, // and never be called an alias. const { isProjectRoot } = this const myname = isProjectRoot ? name || this.name : this.name const alias = !isProjectRoot && name && myname !== name ? `npm:${name}@` : '' return `${myname}@${alias}${version}` } get overridden () { return !!(this.overrides && this.overrides.value && this.overrides.name === this.name) } get package () { return this[_package] } set package (pkg) { // just detach them all. we could make this _slightly_ more efficient // by only detaching the ones that changed, but we'd still have to walk // them all, and the comparison logic gets a bit tricky. we generally // only do this more than once at the root level, so the resolve() calls // are only one level deep, and there's not much to be saved, anyway. // simpler to just toss them all out. for (const edge of this.edgesOut.values()) { edge.detach() } this[_explanation] = null /* istanbul ignore next - should be impossible */ if (!pkg || typeof pkg !== 'object') { debug(() => { throw new Error('setting Node.package to non-object') }) pkg = {} } this[_package] = pkg this.#loadWorkspaces() this[_loadDeps]() // do a hard reload, since the dependents may now be valid or invalid // as a result of the package change. this.edgesIn.forEach(edge => edge.reload(true)) } // node.explain(nodes seen already, edge we're trying to satisfy // if edge is not specified, it lists every edge into the node. explain (edge = null, seen = []) { if (this[_explanation]) { return this[_explanation] } return this[_explanation] = this[_explain](edge, seen) } [_explain] (edge, seen) { if (this.isProjectRoot && !this.sourceReference) { return { location: this.path, } } const why = { name: this.isProjectRoot || this.isTop ? this.packageName : this.name, version: this.package.version, } if (this.errors.length || !this.packageName || !this.package.version) { why.errors = this.errors.length ? this.errors : [ new Error('invalid package: lacks name and/or version'), ] why.package = this.package } if (this.root.sourceReference) { const { name, version } = this.root.package why.whileInstalling = { name, version, path: this.root.sourceReference.path, } } if (this.sourceReference) { return this.sourceReference.explain(edge, seen) } if (seen.includes(this)) { return why } why.location = this.location why.isWorkspace = this.isWorkspace // make a new list each time. we can revisit, but not loop. seen = seen.concat(this) why.dependents = [] if (edge) { why.dependents.push(edge.explain(seen)) } else { // ignore invalid edges, since those aren't satisfied by this thing, // and are not keeping it held in this spot anyway. const edges = [] for (const edge of this.edgesIn) { if (!edge.valid && !edge.from.isProjectRoot) { continue } edges.push(edge) } for (const edge of edges) { why.dependents.push(edge.explain(seen)) } } if (this.linksIn.size) { why.linksIn = [...this.linksIn].map(link => link[_explain](edge, seen)) } return why } isDescendantOf (node) { for (let p = this; p; p = p.resolveParent) { if (p === node) { return true } } return false } getBundler (path = []) { // made a cycle, definitely not bundled! if (path.includes(this)) { return null } path.push(this) const parent = this[_parent] if (!parent) { return null } const pBundler = parent.getBundler(path) if (pBundler) { return pBundler } const ppkg = parent.package const bd = ppkg && ppkg.bundleDependencies // explicit bundling if (Array.isArray(bd) && bd.includes(this.name)) { return parent } // deps that are deduped up to the bundling level are bundled. // however, if they get their dep met further up than that, // then they are not bundled. Ie, installing a package with // unmet bundled deps will not cause your deps to be bundled. for (const edge of this.edgesIn) { const eBundler = edge.from.getBundler(path) if (!eBundler) { continue } if (eBundler === parent) { return eBundler } } return null } get inBundle () { return !!this.getBundler() } // when reifying, if a package is technically in a bundleDependencies list, // but that list is the root project, we still have to install it. This // getter returns true if it's in a dependency's bundle list, not the root's. get inDepBundle () { const bundler = this.getBundler() return !!bundler && bundler !== this.root } get isWorkspace () { if (this.isProjectRoot) { return false } const { root } = this const { type, to } = root.edgesOut.get(this.packageName) || {} return type === 'workspace' && to && (to.target === this || to === this) } get isRoot () { return this === this.root } get isProjectRoot () { // only treat as project root if it's the actual link that is the root, // or the target of the root link, but NOT if it's another link to the // same root that happens to be somewhere else. return this === this.root || this === this.root.target } get isRegistryDependency () { if (this.edgesIn.size === 0) { return false } for (const edge of this.edgesIn) { if (!npa(edge.spec).registry) { return false } } return true } * ancestry () { for (let anc = this; anc; anc = anc.resolveParent) { yield anc } } set root (root) { // setting to null means this is the new root // should only ever be one step while (root && root.root !== root) { root = root.root } root = root || this // delete from current root inventory this[_delistFromMeta]() // can't set the root (yet) if there's no way to determine location // this allows us to do new Node({...}) and then set the root later. // just make the assignment so we don't lose it, and move on. if (!this.path || !root.realpath || !root.path) { this.#root = root return } // temporarily become a root node this.#root = this // break all linksIn, we're going to re-set them if needed later for (const link of this.linksIn) { link[_target] = null this.linksIn.delete(link) } // temporarily break this link as well, we'll re-set if possible later const { target } = this if (this.isLink) { if (target) { target.linksIn.delete(this) if (target.root === this) { target[_delistFromMeta]() } } this[_target] = null } // if this is part of a cascading root set, then don't do this bit // but if the parent/fsParent is in a different set, we have to break // that reference before proceeding if (this.parent && this.parent.root !== root) { this.parent.children.delete(this.name) this[_parent] = null } if (this.fsParent && this.fsParent.root !== root) { this.fsParent.fsChildren.delete(this) this[_fsParent] = null } if (root === this) { this[_refreshLocation]() } else { // setting to some different node. const loc = relpath(root.realpath, this.path) const current = root.inventory.get(loc) // clobber whatever is there now if (current) { current.root = null } this.#root = root // set this.location and add to inventory this[_refreshLocation]() // try to find our parent/fsParent in the new root inventory for (const p of walkUp(dirname(this.path))) { if (p === this.path) { continue } const ploc = relpath(root.realpath, p) const parent = root.inventory.get(ploc) if (parent) { /* istanbul ignore next - impossible */ if (parent.isLink) { debug(() => { throw Object.assign(new Error('assigning parentage to link'), { path: this.path, parent: parent.path, parentReal: parent.realpath, }) }) continue } const childLoc = `${ploc}${ploc ? '/' : ''}node_modules/${this.name}` const isParent = this.location === childLoc if (isParent) { const oldChild = parent.children.get(this.name) if (oldChild && oldChild !== this) { oldChild.root = null } if (this.parent) { this.parent.children.delete(this.name) this.parent[_reloadNamedEdges](this.name) } parent.children.set(this.name, this) this[_parent] = parent // don't do it for links, because they don't have a target yet // we'll hit them up a bit later on. if (!this.isLink) { parent[_reloadNamedEdges](this.name) } } else { /* istanbul ignore if - should be impossible, since we break * all fsParent/child relationships when moving? */ if (this.fsParent) { this.fsParent.fsChildren.delete(this) } parent.fsChildren.add(this) this[_fsParent] = parent } break } } // if it doesn't have a parent, it's a top node if (!this.parent) { root.tops.add(this) } else { root.tops.delete(this) } // assign parentage for any nodes that need to have this as a parent // this can happen when we have a node at nm/a/nm/b added *before* // the node at nm/a, which might have the root node as a fsParent. // we can't rely on the public setter here, because it calls into // this function to set up these references! // check dirname so that /foo isn't treated as the fsparent of /foo-bar const nmloc = `${this.location}${this.location ? '/' : ''}node_modules/` // only walk top nodes, since anything else already has a parent. for (const child of root.tops) { const isChild = child.location === nmloc + child.name const isFsChild = dirname(child.path).startsWith(this.path) && child !== this && !child.parent && ( !child.fsParent || child.fsParent === this || dirname(this.path).startsWith(child.fsParent.path) ) if (!isChild && !isFsChild) { continue } // set up the internal parentage links if (this.isLink) { child.root = null } else { // can't possibly have a parent, because it's in tops if (child.fsParent) { child.fsParent.fsChildren.delete(child) } child[_fsParent] = null if (isChild) { this.children.set(child.name, child) child[_parent] = this root.tops.delete(child) } else { this.fsChildren.add(child) child[_fsParent] = this } } } // look for any nodes with the same realpath. either they're links // to that realpath, or a thing at that realpath if we're adding a link // (if we're adding a regular node, we already deleted the old one) for (const node of root.inventory.query('realpath', this.realpath)) { if (node === this) { continue } /* istanbul ignore next - should be impossible */ debug(() => { if (node.root !== root) { throw new Error('inventory contains node from other root') } }) if (this.isLink) { const target = node.target this[_target] = target this[_package] = target.package target.linksIn.add(this) // reload edges here, because now we have a target if (this.parent) { this.parent[_reloadNamedEdges](this.name) } break } else { /* istanbul ignore else - should be impossible */ if (node.isLink) { node[_target] = this node[_package] = this.package this.linksIn.add(node) if (node.parent) { node.parent[_reloadNamedEdges](node.name) } } else { debug(() => { throw Object.assign(new Error('duplicate node in root setter'), { path: this.path, realpath: this.realpath, root: root.realpath, }) }) } } } } // reload all edgesIn where the root doesn't match, so we don't have // cross-tree dependency graphs for (const edge of this.edgesIn) { if (edge.from.root !== root) { edge.reload() } } // reload all edgesOut where root doens't match, or is missing, since // it might not be missing in the new tree for (const edge of this.edgesOut.values()) { if (!edge.to || edge.to.root !== root) { edge.reload() } } // now make sure our family comes along for the ride! const family = new Set([ ...this.fsChildren, ...this.children.values(), ...this.inventory.values(), ].filter(n => n !== this)) for (const child of family) { if (child.root !== root) { child[_delistFromMeta]() child[_parent] = null this.children.delete(child.name) child[_fsParent] = null this.fsChildren.delete(child) for (const l of child.linksIn) { l[_target] = null child.linksIn.delete(l) } } } for (const child of family) { if (child.root !== root) { child.root = root } } // if we had a target, and didn't find one in the new root, then bring // it over as well, but only if we're setting the link into a new root, // as we don't want to lose the target any time we remove a link. if (this.isLink && target && !this.target && root !== this) { target.root = root } if (!this.overrides && this.parent && this.parent.overrides) { this.overrides = this.parent.overrides.getNodeRule(this) } // tree should always be valid upon root setter completion. treeCheck(this) if (this !== root) { treeCheck(root) } } get root () { return this.#root || this } #loadWorkspaces () { if (!this.#workspaces) { return } for (const [name, path] of this.#workspaces.entries()) { new Edge({ from: this, name, spec: `file:${path.replace(/#/g, '%23')}`, type: 'workspace' }) } } [_loadDeps] () { // Caveat! Order is relevant! // Packages in optionalDependencies are optional. // Packages in both deps and devDeps are required. // Note the subtle breaking change from v6: it is no longer possible // to have a different spec for a devDep than production dep. // Linked targets that are disconnected from the tree are tops, // but don't have a 'path' field, only a 'realpath', because we // don't know their canonical location. We don't need their devDeps. const pd = this.package.peerDependencies const ad = this.package.acceptDependencies || {} if (pd && typeof pd === 'object' && !this.legacyPeerDeps) { const pm = this.package.peerDependenciesMeta || {} const peerDependencies = {} const peerOptional = {} for (const [name, dep] of Object.entries(pd)) { if (pm[name]?.optional) { peerOptional[name] = dep } else { peerDependencies[name] = dep } } this.#loadDepType(peerDependencies, 'peer', ad) this.#loadDepType(peerOptional, 'peerOptional', ad) } this.#loadDepType(this.package.dependencies, 'prod', ad) this.#loadDepType(this.package.optionalDependencies, 'optional', ad) const { globalTop, isTop, path, sourceReference } = this const { globalTop: srcGlobalTop, isTop: srcTop, path: srcPath, } = sourceReference || {} const thisDev = isTop && !globalTop && path const srcDev = !sourceReference || srcTop && !srcGlobalTop && srcPath if (thisDev && srcDev) { this.#loadDepType(this.package.devDependencies, 'dev', ad) } } #loadDepType (deps, type, ad) { // Because of the order in which _loadDeps runs, we always want to // prioritize a new edge over an existing one for (const [name, spec] of Object.entries(deps || {})) { const current = this.edgesOut.get(name) if (!current || current.type !== 'workspace') { new Edge({ from: this, name, spec, accept: ad[name], type }) } } } get fsParent () { // in debug setter prevents fsParent from being this return this[_fsParent] } set fsParent (fsParent) { if (!fsParent) { if (this[_fsParent]) { this.root = null } return } debug(() => { if (fsParent === this) { throw new Error('setting node to its own fsParent') } if (fsParent.realpath === this.realpath) { throw new Error('setting fsParent to same path') } // the initial set MUST be an actual walk-up from the realpath // subsequent sets will re-root on the new fsParent's path. if (!this[_fsParent] && this.realpath.indexOf(fsParent.realpath) !== 0) { throw Object.assign(new Error('setting fsParent improperly'), { path: this.path, realpath: this.realpath, fsParent: { path: fsParent.path, realpath: fsParent.realpath, }, }) } }) if (fsParent.isLink) { fsParent = fsParent.target } // setting a thing to its own fsParent is not normal, but no-op for safety if (this === fsParent || fsParent.realpath === this.realpath) { return } // nothing to do if (this[_fsParent] === fsParent) { return } const oldFsParent = this[_fsParent] const newPath = !oldFsParent ? this.path : resolve(fsParent.path, relative(oldFsParent.path, this.path)) const nmPath = resolve(fsParent.path, 'node_modules', this.name) // this is actually the parent, set that instead if (newPath === nmPath) { this.parent = fsParent return } const pathChange = newPath !== this.path // remove from old parent/fsParent const oldParent = this.parent const oldName = this.name if (this.parent) { this.parent.children.delete(this.name) this[_parent] = null } if (this.fsParent) { this.fsParent.fsChildren.delete(this) this[_fsParent] = null } // update this.path/realpath for this and all children/fsChildren if (pathChange) { this[_changePath](newPath) } if (oldParent) { oldParent[_reloadNamedEdges](oldName) } // clobbers anything at that path, resets all appropriate references this.root = fsParent.root } // is it safe to replace one node with another? check the edges to // make sure no one will get upset. Note that the node might end up // having its own unmet dependencies, if the new node has new deps. // Note that there are cases where Arborist will opt to insert a node // into the tree even though this function returns false! This is // necessary when a root dependency is added or updated, or when a // root dependency brings peer deps along with it. In that case, we // will go ahead and create the invalid state, and then try to resolve // it with more tree construction, because it's a user request. canReplaceWith (node, ignorePeers) { if (node.name !== this.name) { return false } if (node.packageName !== this.packageName) { return false } // XXX need to check for two root nodes? if (node.overrides !== this.overrides) { return false } ignorePeers = new Set(ignorePeers) // gather up all the deps of this node and that are only depended // upon by deps of this node. those ones don't count, since // they'll be replaced if this node is replaced anyway. const depSet = gatherDepSet([this], e => e.to !== this && e.valid) for (const edge of this.edgesIn) { // when replacing peer sets, we need to be able to replace the entire // peer group, which means we ignore incoming edges from other peers // within the replacement set. if (!this.isTop && edge.from.parent === this.parent && edge.peer && ignorePeers.has(edge.from.name)) { continue } // only care about edges that don't originate from this node if (!depSet.has(edge.from) && !edge.satisfiedBy(node)) { return false } } return true } canReplace (node, ignorePeers) { return node.canReplaceWith(this, ignorePeers) } // return true if it's safe to remove this node, because anything that // is depending on it would be fine with the thing that they would resolve // to if it was removed, or nothing is depending on it in the first place. canDedupe (preferDedupe = false) { // not allowed to mess with shrinkwraps or bundles if (this.inDepBundle || this.inShrinkwrap) { return false } // it's a top level pkg, or a dep of one if (!this.resolveParent || !this.resolveParent.resolveParent) { return false } // no one wants it, remove it if (this.edgesIn.size === 0) { return true } const other = this.resolveParent.resolveParent.resolve(this.name) // nothing else, need this one if (!other) { return false } // if it's the same thing, then always fine to remove if (other.matches(this)) { return true } // if the other thing can't replace this, then skip it if (!other.canReplace(this)) { return false } // if we prefer dedupe, or if the version is greater/equal, take the other if (preferDedupe || semver.gte(other.version, this.version)) { return true } return false } satisfies (requested) { if (requested instanceof Edge) { return this.name === requested.name && requested.satisfiedBy(this) } const parsed = npa(requested) const { name = this.name, rawSpec: spec } = parsed return this.name === name && this.satisfies(new Edge({ from: new Node({ path: this.root.realpath }), type: 'prod', name, spec, })) } matches (node) { // if the nodes are literally the same object, obviously a match. if (node === this) { return true } // if the names don't match, they're different things, even if // the package contents are identical. if (node.name !== this.name) { return false } // if they're links, they match if the targets match if (this.isLink) { return node.isLink && this.target.matches(node.target) } // if they're two project root nodes, they're different if the paths differ if (this.isProjectRoot && node.isProjectRoot) { return this.path === node.path } // if the integrity matches, then they're the same. if (this.integrity && node.integrity) { return this.integrity === node.integrity } // if no integrity, check resolved if (this.resolved && node.resolved) { return this.resolved === node.resolved } // if no resolved, check both package name and version // otherwise, conclude that they are different things return this.packageName && node.packageName && this.packageName === node.packageName && this.version && node.version && this.version === node.version } // replace this node with the supplied argument // Useful when mutating an ideal tree, so we can avoid having to call // the parent/root setters more than necessary. replaceWith (node) { node.replace(this) } replace (node) { this[_delistFromMeta]() // if the name matches, but is not identical, we are intending to clobber // something case-insensitively, so merely setting name and path won't // have the desired effect. just set the path so it'll collide in the // parent's children map, and leave it at that. if (node.parent?.children.get(this.name) === node) { this.path = resolve(node.parent.path, 'node_modules', this.name) } else { this.path = node.path this.name = node.name } if (!this.isLink) { this.realpath = this.path } this[_refreshLocation]() // keep children when a node replaces another if (!this.isLink) { for (const kid of node.children.values()) { kid.parent = this } if (node.isLink && node.target) { node.target.root = null } } if (!node.isRoot) { this.root = node.root } treeCheck(this) } get inShrinkwrap () { return this.parent && (this.parent.hasShrinkwrap || this.parent.inShrinkwrap) } get parent () { // setter prevents _parent from being this return this[_parent] } // This setter keeps everything in order when we move a node from // one point in a logical tree to another. Edges get reloaded, // metadata updated, etc. It's also called when we *replace* a node // with another by the same name (eg, to update or dedupe). // This does a couple of walks out on the node_modules tree, recursing // into child nodes. However, as setting the parent is typically done // with nodes that don't have have many children, and (deduped) package // trees tend to be broad rather than deep, it's not that bad. // The only walk that starts from the parent rather than this node is // limited by edge name. set parent (parent) { // when setting to null, just remove it from the tree entirely if (!parent) { // but only delete it if we actually had a parent in the first place // otherwise it's just setting to null when it's already null if (this[_parent]) { this.root = null } return } if (parent.isLink) { parent = parent.target } // setting a thing to its own parent is not normal, but no-op for safety if (this === parent) { return } const oldParent = this[_parent] // nothing to do if (oldParent === parent) { return } // ok now we know something is actually changing, and parent is not a link const newPath = resolve(parent.path, 'node_modules', this.name) const pathChange = newPath !== this.path // remove from old parent/fsParent if (oldParent) { oldParent.children.delete(this.name) this[_parent] = null } if (this.fsParent) { this.fsParent.fsChildren.delete(this) this[_fsParent] = null } // update this.path/realpath for this and all children/fsChildren if (pathChange) { this[_changePath](newPath) } if (parent.overrides) { this.overrides = parent.overrides.getNodeRule(this) } // clobbers anything at that path, resets all appropriate references this.root = parent.root } // Call this before changing path or updating the _root reference. // Removes the node from its root the metadata and inventory. [_delistFromMeta] () { const root = this.root if (!root.realpath || !this.path) { return } root.inventory.delete(this) root.tops.delete(this) if (root.meta) { root.meta.delete(this.path) } /* istanbul ignore next - should be impossible */ debug(() => { if ([...root.inventory.values()].includes(this)) { throw new Error('failed to delist') } }) } // update this.path/realpath and the paths of all children/fsChildren [_changePath] (newPath) { // have to de-list before changing paths this[_delistFromMeta]() const oldPath = this.path this.path = newPath const namePattern = /(?:^|\/|\\)node_modules[\\/](@[^/\\]+[\\/][^\\/]+|[^\\/]+)$/ const nameChange = newPath.match(namePattern) if (nameChange && this.name !== nameChange[1]) { this.name = nameChange[1].replace(/\\/g, '/') } // if we move a link target, update link realpaths if (!this.isLink) { this.realpath = newPath for (const link of this.linksIn) { link[_delistFromMeta]() link.realpath = newPath link[_refreshLocation]() } } // if we move /x to /y, then a module at /x/a/b becomes /y/a/b for (const child of this.fsChildren) { child[_changePath](resolve(newPath, relative(oldPath, child.path))) } for (const [name, child] of this.children.entries()) { child[_changePath](resolve(newPath, 'node_modules', name)) } this[_refreshLocation]() } // Called whenever the root/parent is changed. // NB: need to remove from former root's meta/inventory and then update // this.path BEFORE calling this method! [_refreshLocation] () { const root = this.root const loc = relpath(root.realpath, this.path) this.location = loc root.inventory.add(this) if (root.meta) { root.meta.add(this) } } assertRootOverrides () { if (!this.isProjectRoot || !this.overrides) { return } for (const edge of this.edgesOut.values()) { // if these differ an override has been applied, those are not allowed // for top level dependencies so throw an error if (edge.spec !== edge.rawSpec && !edge.spec.startsWith('$')) { throw Object.assign(new Error(`Override for ${edge.name}@${edge.rawSpec} conflicts with direct dependency`), { code: 'EOVERRIDE' }) } } } addEdgeOut (edge) { if (this.overrides) { edge.overrides = this.overrides.getEdgeRule(edge) } this.edgesOut.set(edge.name, edge) } addEdgeIn (edge) { if (edge.overrides) { this.overrides = edge.overrides } this.edgesIn.add(edge) // try to get metadata from the yarn.lock file if (this.root.meta) { this.root.meta.addEdge(edge) } } [_reloadNamedEdges] (name, rootLoc = this.location) { const edge = this.edgesOut.get(name) // if we don't have an edge, do nothing, but keep descending const rootLocResolved = edge && edge.to && edge.to.location === `${rootLoc}/node_modules/${edge.name}` const sameResolved = edge && this.resolve(name) === edge.to const recheck = rootLocResolved || !sameResolved if (edge && recheck) { edge.reload(true) } for (const c of this.children.values()) { c[_reloadNamedEdges](name, rootLoc) } for (const c of this.fsChildren) { c[_reloadNamedEdges](name, rootLoc) } } get isLink () { return false } get target () { return this } set target (n) { debug(() => { throw Object.assign(new Error('cannot set target on non-Link Nodes'), { path: this.path, }) }) } get depth () { if (this.isTop) { return 0 } return this.parent.depth + 1 } get isTop () { return !this.parent || this.globalTop } get top () { if (this.isTop) { return this } return this.parent.top } get isFsTop () { return !this.fsParent } get fsTop () { if (this.isFsTop) { return this } return this.fsParent.fsTop } get resolveParent () { return this.parent || this.fsParent } resolve (name) { /* istanbul ignore next - should be impossible, * but I keep doing this mistake in tests */ debug(() => { if (typeof name !== 'string' || !name) { throw new Error('non-string passed to Node.resolve') } }) const mine = this.children.get(name) if (mine) { return mine } const resolveParent = this.resolveParent if (resolveParent) { return resolveParent.resolve(name) } return null } inNodeModules () { const rp = this.realpath const name = this.name const scoped = name.charAt(0) === '@' const d = dirname(rp) const nm = scoped ? dirname(d) : d const dir = dirname(nm) const base = scoped ? `${basename(d)}/${basename(rp)}` : basename(rp) return base === name && basename(nm) === 'node_modules' ? dir : false } // maybe accept both string value or array of strings // seems to be what dom API does querySelectorAll (query, opts) { return querySelectorAll(this, query, opts) } toJSON () { return printableTree(this) } [util.inspect.custom] () { return this.toJSON() } } module.exports = Node // when an optional dep fails to install, we need to remove the branch of the // graph up to the first optionalDependencies, as well as any nodes that are // only required by other nodes in the set. // // This function finds the set of nodes that will need to be removed in that // case. // // Note that this is *only* going to work with trees where calcDepFlags // has been called, because we rely on the node.optional flag. const gatherDepSet = require('./gather-dep-set.js') const optionalSet = node => { if (!node.optional) { return new Set() } // start with the node, then walk up the dependency graph until we // get to the boundaries that define the optional set. since the // node is optional, we know that all paths INTO this area of the // graph are optional, but there may be non-optional dependencies // WITHIN the area. const set = new Set([node]) for (const node of set) { for (const edge of node.edgesIn) { if (!edge.optional) { set.add(edge.from) } } } // now that we've hit the boundary, gather the rest of the nodes in // the optional section. that's the set of dependencies that are only // depended upon by other nodes within the set, or optional dependencies // from outside the set. return gatherDepSet(set, edge => !edge.optional) } module.exports = optionalSet function overrideResolves (resolved, opts) { const { omitLockfileRegistryResolved = false } = opts if (omitLockfileRegistryResolved) { return undefined } return resolved } module.exports = { overrideResolves } const npa = require('npm-package-arg') const semver = require('semver') class OverrideSet { constructor ({ overrides, key, parent }) { this.parent = parent this.children = new Map() if (typeof overrides === 'string') { overrides = { '.': overrides } } // change a literal empty string to * so we can use truthiness checks on // the value property later if (overrides['.'] === '') { overrides['.'] = '*' } if (parent) { const spec = npa(key) if (!spec.name) { throw new Error(`Override without name: ${key}`) } this.name = spec.name spec.name = '' this.key = key this.keySpec = spec.toString() this.value = overrides['.'] || this.keySpec } for (const [key, childOverrides] of Object.entries(overrides)) { if (key === '.') { continue } const child = new OverrideSet({ parent: this, key, overrides: childOverrides, }) this.children.set(child.key, child) } } getEdgeRule (edge) { for (const rule of this.ruleset.values()) { if (rule.name !== edge.name) { continue } // if keySpec is * we found our override if (rule.keySpec === '*') { return rule } let spec = npa(`${edge.name}@${edge.spec}`) if (spec.type === 'alias') { spec = spec.subSpec } if (spec.type === 'git') { if (spec.gitRange && semver.intersects(spec.gitRange, rule.keySpec)) { return rule } continue } if (spec.type === 'range' || spec.type === 'version') { if (semver.intersects(spec.fetchSpec, rule.keySpec)) { return rule } continue } // if we got this far, the spec type is one of tag, directory or file // which means we have no real way to make version comparisons, so we // just accept the override return rule } return this } getNodeRule (node) { for (const rule of this.ruleset.values()) { if (rule.name !== node.name) { continue } if (semver.satisfies(node.version, rule.keySpec) || semver.satisfies(node.version, rule.value)) { return rule } } return this } getMatchingRule (node) { for (const rule of this.ruleset.values()) { if (rule.name !== node.name) { continue } if (semver.satisfies(node.version, rule.keySpec) || semver.satisfies(node.version, rule.value)) { return rule } } return null } * ancestry () { for (let ancestor = this; ancestor; ancestor = ancestor.parent) { yield ancestor } } get isRoot () { return !this.parent } get ruleset () { const ruleset = new Map() for (const override of this.ancestry()) { for (const kid of override.children.values()) { if (!ruleset.has(kid.key)) { ruleset.set(kid.key, kid) } } if (!override.isRoot && !ruleset.has(override.key)) { ruleset.set(override.key, override) } } return ruleset } } module.exports = OverrideSet const { LRUCache } = require('lru-cache') const { getHeapStatistics } = require('node:v8') const { log } = require('proc-log') // This is an in-memory cache that Pacote uses for packuments. // Packuments are usually cached on disk. This allows for rapid re-requests // of the same packument to bypass disk reads. The tradeoff here is memory // usage for disk reads. class PackumentCache extends LRUCache { static #heapLimit = Math.floor(getHeapStatistics().heap_size_limit) #sizeKey #disposed = new Set() #log (...args) { log.silly('packumentCache', ...args) } constructor ({ // How much of this.#heapLimit to take up heapFactor = 0.25, // How much of this.#maxSize we allow any one packument to take up // Anything over this is not cached maxEntryFactor = 0.5, sizeKey = '_contentLength', } = {}) { const maxSize = Math.floor(PackumentCache.#heapLimit * heapFactor) const maxEntrySize = Math.floor(maxSize * maxEntryFactor) super({ maxSize, maxEntrySize, sizeCalculation: (p) => { // Don't cache if we dont know the size // Some versions of pacote set this to `0`, newer versions set it to `null` if (!p[sizeKey]) { return maxEntrySize + 1 } if (p[sizeKey] < 10_000) { return p[sizeKey] * 2 } if (p[sizeKey] < 1_000_000) { return Math.floor(p[sizeKey] * 1.5) } // It is less beneficial to store a small amount of super large things // at the cost of all other packuments. return maxEntrySize + 1 }, dispose: (v, k) => { this.#disposed.add(k) this.#log(k, 'dispose') }, }) this.#sizeKey = sizeKey this.#log(`heap:${PackumentCache.#heapLimit} maxSize:${maxSize} maxEntrySize:${maxEntrySize}`) } set (k, v, ...args) { // we use disposed only for a logging signal if we are setting packuments that // have already been evicted from the cache previously. logging here could help // us tune this in the future. const disposed = this.#disposed.has(k) /* istanbul ignore next - this doesnt happen consistently so hard to test without resorting to unit tests */ if (disposed) { this.#disposed.delete(k) } this.#log(k, 'set', `size:${v[this.#sizeKey]} disposed:${disposed}`) return super.set(k, v, ...args) } has (k, ...args) { const has = super.has(k, ...args) this.#log(k, `cache-${has ? 'hit' : 'miss'}`) return has } } module.exports = PackumentCache // Given a node in a tree, return all of the peer dependency sets that // it is a part of, with the entry (top or non-peer) edges into the sets // identified. // // With this information, we can determine whether it is appropriate to // replace the entire peer set with another (and remove the old one), // push the set deeper into the tree, and so on. // // Returns a Map of { edge => Set(peerNodes) }, const peerEntrySets = node => { // this is the union of all peer groups that the node is a part of // later, we identify all of the entry edges, and create a set of // 1 or more overlapping sets that this node is a part of. const unionSet = new Set([node]) for (const node of unionSet) { for (const edge of node.edgesOut.values()) { if (edge.valid && edge.peer && edge.to) { unionSet.add(edge.to) } } for (const edge of node.edgesIn) { if (edge.valid && edge.peer) { unionSet.add(edge.from) } } } const entrySets = new Map() for (const peer of unionSet) { for (const edge of peer.edgesIn) { // if not valid, it doesn't matter anyway. either it's been previously // peerConflicted, or it's the thing we're interested in replacing. if (!edge.valid) { continue } // this is the entry point into the peer set if (!edge.peer || edge.from.isTop) { // get the subset of peer brought in by this peer entry edge const sub = new Set([peer]) for (const peer of sub) { for (const edge of peer.edgesOut.values()) { if (edge.valid && edge.peer && edge.to) { sub.add(edge.to) } } } // if this subset does not include the node we are focused on, // then it is not relevant for our purposes. Example: // // a -> (b, c, d) // b -> PEER(d) b -> d -> e -> f <-> g // c -> PEER(f, h) c -> (f <-> g, h -> g) // d -> PEER(e) d -> e -> f <-> g // e -> PEER(f) // f -> PEER(g) // g -> PEER(f) // h -> PEER(g) // // The unionSet(e) will include c, but we don't actually care about // it. We only expanded to the edge of the peer nodes in order to // find the entry edges that caused the inclusion of peer sets // including (e), so we want: // Map{ // Edge(a->b) => Set(b, d, e, f, g) // Edge(a->d) => Set(d, e, f, g) // } if (sub.has(node)) { entrySets.set(edge, sub) } } } } return entrySets } module.exports = peerEntrySets // Given a dep, a node that depends on it, and the edge representing that // dependency, place the dep somewhere in the node's tree, and all of its // peer dependencies. // // Handles all of the tree updating needed to place the dep, including // removing replaced nodes, pruning now-extraneous or invalidated nodes, // and saves a set of what was placed and what needs re-evaluation as // a result. const localeCompare = require('@isaacs/string-locale-compare')('en') const { log } = require('proc-log') const { redact } = require('@npmcli/redact') const deepestNestingTarget = require('./deepest-nesting-target.js') const CanPlaceDep = require('./can-place-dep.js') const { KEEP, CONFLICT, } = CanPlaceDep const debug = require('./debug.js') const Link = require('./link.js') const gatherDepSet = require('./gather-dep-set.js') const peerEntrySets = require('./peer-entry-sets.js') class PlaceDep { constructor (options) { this.auditReport = options.auditReport this.dep = options.dep this.edge = options.edge this.explicitRequest = options.explicitRequest this.force = options.force this.installLinks = options.installLinks this.installStrategy = options.installStrategy this.legacyPeerDeps = options.legacyPeerDeps this.parent = options.parent || null this.preferDedupe = options.preferDedupe this.strictPeerDeps = options.strictPeerDeps this.updateNames = options.updateNames this.canPlace = null this.canPlaceSelf = null // XXX this only appears to be used by tests this.checks = new Map() this.children = [] this.needEvaluation = new Set() this.peerConflict = null this.placed = null this.target = null this.current = this.edge.to this.name = this.edge.name this.top = this.parent?.top || this // nothing to do if the edge is fine as it is if (this.edge.to && !this.edge.error && !this.explicitRequest && !this.updateNames.includes(this.edge.name) && !this.auditReport?.isVulnerable(this.edge.to)) { return } // walk up the tree until we hit either a top/root node, or a place // where the dep is not a peer dep. const start = this.getStartNode() for (const target of start.ancestry()) { // if the current location has a peerDep on it, then we can't place here // this is pretty rare to hit, since we always prefer deduping peers, // and the getStartNode will start us out above any peers from the // thing that depends on it. but we could hit it with something like: // // a -> (b@1, c@1) // +-- c@1 // +-- b -> PEEROPTIONAL(v) (c@2) // +-- c@2 -> (v) // // So we check if we can place v under c@2, that's fine. // Then we check under b, and can't, because of the optional peer dep. // but we CAN place it under a, so the correct thing to do is keep // walking up the tree. const targetEdge = target.edgesOut.get(this.edge.name) if (!target.isTop && targetEdge && targetEdge.peer) { continue } const cpd = new CanPlaceDep({ dep: this.dep, edge: this.edge, // note: this sets the parent's canPlace as the parent of this // canPlace, but it does NOT add this canPlace to the parent's // children. This way, we can know that it's a peer dep, and // get the top edge easily, while still maintaining the // tree of checks that factored into the original decision. parent: this.parent && this.parent.canPlace, target, preferDedupe: this.preferDedupe, explicitRequest: this.explicitRequest, }) this.checks.set(target, cpd) // It's possible that a "conflict" is a conflict among the *peers* of // a given node we're trying to place, but there actually is no current // node. Eg, // root -> (a, b) // a -> PEER(c) // b -> PEER(d) // d -> PEER(c@2) // We place (a), and get a peer of (c) along with it. // then we try to place (b), and get CONFLICT in the check, because // of the conflicting peer from (b)->(d)->(c@2). In that case, we // should treat (b) and (d) as OK, and place them in the last place // where they did not themselves conflict, and skip c@2 if conflict // is ok by virtue of being forced or not ours and not strict. if (cpd.canPlaceSelf !== CONFLICT) { this.canPlaceSelf = cpd } // we found a place this can go, along with all its peer friends. // we break when we get the first conflict if (cpd.canPlace !== CONFLICT) { this.canPlace = cpd } else { break } // if it's a load failure, just plop it in the first place attempted, // since we're going to crash the build or prune it out anyway. // but, this will frequently NOT be a successful canPlace, because // it'll have no version or other information. if (this.dep.errors.length) { break } // nest packages like npm v1 and v2 // very disk-inefficient if (this.installStrategy === 'nested') { break } // when installing globally, or just in global style, we never place // deps above the first level. if (this.installStrategy === 'shallow') { const rp = target.resolveParent if (rp && rp.isProjectRoot) { break } } } // if we can't find a target, that means that the last place checked, // and all the places before it, had a conflict. if (!this.canPlace) { // if not forced, and it's our dep, or strictPeerDeps is set, then // this is an ERESOLVE error. if (!this.force && (this.isMine || this.strictPeerDeps)) { return this.failPeerConflict() } // ok! we're gonna allow the conflict, but we should still warn // if we have a current, then we treat CONFLICT as a KEEP. // otherwise, we just skip it. Only warn on the one that actually // could not be placed somewhere. if (!this.canPlaceSelf) { this.warnPeerConflict() return } this.canPlace = this.canPlaceSelf } // now we have a target, a tree of CanPlaceDep results for the peer group, // and we are ready to go /* istanbul ignore next */ if (!this.canPlace) { debug(() => { throw new Error('canPlace not set, but trying to place in tree') }) return } const { target } = this.canPlace log.silly( 'placeDep', target.location || 'ROOT', `${this.dep.name}@${this.dep.version}`, this.canPlace.description, `for: ${this.edge.from.package._id || this.edge.from.location}`, `want: ${redact(this.edge.spec || '*')}` ) const placementType = this.canPlace.canPlace === CONFLICT ? this.canPlace.canPlaceSelf : this.canPlace.canPlace // if we're placing in the tree with --force, we can get here even though // it's a conflict. Treat it as a KEEP, but warn and move on. if (placementType === KEEP) { // this was a peerConflicted peer dep if (this.edge.peer && !this.edge.valid) { this.warnPeerConflict() } // if we get a KEEP in a update scenario, then we MAY have something // already duplicating this unnecessarily! For example: // ``` // root (dep: y@1) // +-- x (dep: y@1.1) // | +-- y@1.1.0 (replacing with 1.1.2, got KEEP at the root) // +-- y@1.1.2 (updated already from 1.0.0) // ``` // Now say we do `reify({update:['y']})`, and the latest version is // 1.1.2, which we now have in the root. We'll try to place y@1.1.2 // first in x, then in the root, ending with KEEP, because we already // have it. In that case, we ought to REMOVE the nm/x/nm/y node, because // it is an unnecessary duplicate. this.pruneDedupable(target) return } // we were told to place it here in the target, so either it does not // already exist in the tree, OR it's shadowed. // handle otherwise unresolvable dependency nesting loops by // creating a symbolic link // a1 -> b1 -> a2 -> b2 -> a1 -> ... // instead of nesting forever, when the loop occurs, create // a symbolic link to the earlier instance for (let p = target; p; p = p.resolveParent) { if (p.matches(this.dep) && !p.isTop) { this.placed = new Link({ parent: target, target: p }) return } } // XXX if we are replacing SOME of a peer entry group, we will need to // remove any that are not being replaced and will now be invalid, and // re-evaluate them deeper into the tree. const virtualRoot = this.dep.parent this.placed = new this.dep.constructor({ name: this.dep.name, pkg: this.dep.package, resolved: this.dep.resolved, integrity: this.dep.integrity, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, error: this.dep.errors[0], ...(this.dep.overrides ? { overrides: this.dep.overrides } : {}), ...(this.dep.isLink ? { target: this.dep.target, realpath: this.dep.realpath } : {}), }) this.oldDep = target.children.get(this.name) if (this.oldDep) { this.replaceOldDep() } else { this.placed.parent = target } // if it's a peerConflicted peer dep, warn about it if (this.edge.peer && !this.placed.satisfies(this.edge)) { this.warnPeerConflict() } // If the edge is not an error, then we're updating something, and // MAY end up putting a better/identical node further up the tree in // a way that causes an unnecessary duplication. If so, remove the // now-unnecessary node. if (this.edge.valid && this.edge.to && this.edge.to !== this.placed) { this.pruneDedupable(this.edge.to, false) } // in case we just made some duplicates that can be removed, // prune anything deeper in the tree that can be replaced by this for (const node of target.root.inventory.query('name', this.name)) { if (node.isDescendantOf(target) && !node.isTop) { this.pruneDedupable(node, false) // only walk the direct children of the ones we kept if (node.root === target.root) { for (const kid of node.children.values()) { this.pruneDedupable(kid, false) } } } } // also place its unmet or invalid peer deps at this location // loop through any peer deps from the thing we just placed, and place // those ones as well. it's safe to do this with the virtual nodes, // because we're copying rather than moving them out of the virtual root, // otherwise they'd be gone and the peer set would change throughout // this loop. for (const peerEdge of this.placed.edgesOut.values()) { if (peerEdge.valid || !peerEdge.peer || peerEdge.peerConflicted) { continue } const peer = virtualRoot.children.get(peerEdge.name) // Note: if the virtualRoot *doesn't* have the peer, then that means // it's an optional peer dep. If it's not being properly met (ie, // peerEdge.valid is false), then this is likely heading for an // ERESOLVE error, unless it can walk further up the tree. if (!peer) { continue } // peerConflicted peerEdge, just accept what's there already if (!peer.satisfies(peerEdge)) { continue } this.children.push(new PlaceDep({ auditReport: this.auditReport, explicitRequest: this.explicitRequest, force: this.force, installLinks: this.installLinks, installStrategy: this.installStrategy, legacyPeerDeps: this.legaycPeerDeps, preferDedupe: this.preferDedupe, strictPeerDeps: this.strictPeerDeps, updateNames: this.updateName, parent: this, dep: peer, node: this.placed, edge: peerEdge, })) } } replaceOldDep () { const target = this.oldDep.parent // XXX handle replacing an entire peer group? // what about cases where we need to push some other peer groups deeper // into the tree? all the tree updating should be done here, and track // all the things that we add and remove, so that we can know what // to re-evaluate. // if we're replacing, we should also remove any nodes for edges that // are now invalid, and where this (or its deps) is the only dependent, // and also recurse on that pruning. Otherwise leaving that dep node // around can result in spurious conflicts pushing nodes deeper into // the tree than needed in the case of cycles that will be removed // later anyway. const oldDeps = [] for (const [name, edge] of this.oldDep.edgesOut.entries()) { if (!this.placed.edgesOut.has(name) && edge.to) { oldDeps.push(...gatherDepSet([edge.to], e => e.to !== edge.to)) } } // gather all peer edgesIn which are at this level, and will not be // satisfied by the new dependency. Those are the peer sets that need // to be either warned about (if they cannot go deeper), or removed and // re-placed (if they can). const prunePeerSets = [] for (const edge of this.oldDep.edgesIn) { if (this.placed.satisfies(edge) || !edge.peer || edge.from.parent !== target || edge.peerConflicted) { // not a peer dep, not invalid, or not from this level, so it's fine // to just let it re-evaluate as a problemEdge later, or let it be // satisfied by the new dep being placed. continue } for (const entryEdge of peerEntrySets(edge.from).keys()) { // either this one needs to be pruned and re-evaluated, or marked // as peerConflicted and warned about. If the entryEdge comes in from // the root or a workspace, then we have to leave it alone, and in that // case, it will have already warned or crashed by getting to this point const entryNode = entryEdge.to const deepestTarget = deepestNestingTarget(entryNode) if (deepestTarget !== target && !(entryEdge.from.isProjectRoot || entryEdge.from.isWorkspace)) { prunePeerSets.push(...gatherDepSet([entryNode], e => { return e.to !== entryNode && !e.peerConflicted })) } else { this.warnPeerConflict(edge, this.dep) } } } this.placed.replace(this.oldDep) this.pruneForReplacement(this.placed, oldDeps) for (const dep of prunePeerSets) { for (const edge of dep.edgesIn) { this.needEvaluation.add(edge.from) } dep.root = null } } pruneForReplacement (node, oldDeps) { // gather up all the now-invalid/extraneous edgesOut, as long as they are // only depended upon by the old node/deps const invalidDeps = new Set([...node.edgesOut.values()] .filter(e => e.to && !e.valid).map(e => e.to)) for (const dep of oldDeps) { const set = gatherDepSet([dep], e => e.to !== dep && e.valid) for (const dep of set) { invalidDeps.add(dep) } } // ignore dependency edges from the node being replaced, but // otherwise filter the set down to just the set with no // dependencies from outside the set, except the node in question. const deps = gatherDepSet(invalidDeps, edge => edge.from !== node && edge.to !== node && edge.valid) // now just delete whatever's left, because it's junk for (const dep of deps) { dep.root = null } } // prune all the nodes in a branch of the tree that can be safely removed // This is only the most basic duplication detection; it finds if there // is another satisfying node further up the tree, and if so, dedupes. // Even in installStategy is nested, we do this amount of deduplication. pruneDedupable (node, descend = true) { if (node.canDedupe(this.preferDedupe)) { // gather up all deps that have no valid edges in from outside // the dep set, except for this node we're deduping, so that we // also prune deps that would be made extraneous. const deps = gatherDepSet([node], e => e.to !== node && e.valid) for (const node of deps) { node.root = null } return } if (descend) { // sort these so that they're deterministically ordered // otherwise, resulting tree shape is dependent on the order // in which they happened to be resolved. const nodeSort = (a, b) => localeCompare(a.location, b.location) const children = [...node.children.values()].sort(nodeSort) for (const child of children) { this.pruneDedupable(child) } const fsChildren = [...node.fsChildren].sort(nodeSort) for (const topNode of fsChildren) { const children = [...topNode.children.values()].sort(nodeSort) for (const child of children) { this.pruneDedupable(child) } } } } get isMine () { const { edge } = this.top const { from: node } = edge if (node.isWorkspace || node.isProjectRoot) { return true } if (!edge.peer) { return false } // re-entry case. check if any non-peer edges come from the project, // or any entryEdges on peer groups are from the root. let hasPeerEdges = false for (const edge of node.edgesIn) { if (edge.peer) { hasPeerEdges = true continue } if (edge.from.isWorkspace || edge.from.isProjectRoot) { return true } } if (hasPeerEdges) { for (const edge of peerEntrySets(node).keys()) { if (edge.from.isWorkspace || edge.from.isProjectRoot) { return true } } } return false } warnPeerConflict (edge, dep) { edge = edge || this.edge dep = dep || this.dep edge.peerConflicted = true const expl = this.explainPeerConflict(edge, dep) log.warn('ERESOLVE', 'overriding peer dependency', expl) } failPeerConflict (edge, dep) { edge = edge || this.top.edge dep = dep || this.top.dep const expl = this.explainPeerConflict(edge, dep) throw Object.assign(new Error('could not resolve'), expl) } explainPeerConflict (edge, dep) { const { from: node } = edge const curNode = node.resolve(edge.name) // XXX decorate more with this.canPlace and this.canPlaceSelf, // this.checks, this.children, walk over conflicted peers, etc. const expl = { code: 'ERESOLVE', edge: edge.explain(), dep: dep.explain(edge), force: this.force, isMine: this.isMine, strictPeerDeps: this.strictPeerDeps, } if (this.parent) { // this is the conflicted peer expl.current = curNode && curNode.explain(edge) expl.peerConflict = this.current && this.current.explain(this.edge) } else { expl.current = curNode && curNode.explain() if (this.canPlaceSelf && this.canPlaceSelf.canPlaceSelf !== CONFLICT) { // failed while checking for a child dep const cps = this.canPlaceSelf for (const peer of cps.conflictChildren) { if (peer.current) { expl.peerConflict = { current: peer.current.explain(), peer: peer.dep.explain(peer.edge), } break } } } else { expl.peerConflict = { current: this.current && this.current.explain(), peer: this.dep.explain(this.edge), } } } return expl } getStartNode () { // if we are a peer, then we MUST be at least as shallow as the peer // dependent const from = this.parent?.getStartNode() || this.edge.from return deepestNestingTarget(from, this.name) } // XXX this only appears to be used by tests get allChildren () { const set = new Set(this.children) for (const child of set) { for (const grandchild of child.children) { set.add(grandchild) } } return [...set] } } module.exports = PlaceDep // helper function to output a clearer visualization // of the current node and its descendents const localeCompare = require('@isaacs/string-locale-compare')('en') const util = require('node:util') const relpath = require('./relpath.js') class ArboristNode { constructor (tree, path) { this.name = tree.name if (tree.packageName && tree.packageName !== this.name) { this.packageName = tree.packageName } if (tree.version) { this.version = tree.version } this.location = tree.location this.path = tree.path if (tree.realpath !== this.path) { this.realpath = tree.realpath } if (tree.resolved !== null) { this.resolved = tree.resolved } if (tree.extraneous) { this.extraneous = true } if (tree.dev) { this.dev = true } if (tree.optional) { this.optional = true } if (tree.devOptional && !tree.dev && !tree.optional) { this.devOptional = true } if (tree.peer) { this.peer = true } if (tree.inBundle) { this.bundled = true } if (tree.inDepBundle) { this.bundler = tree.getBundler().location } if (tree.isProjectRoot) { this.isProjectRoot = true } if (tree.isWorkspace) { this.isWorkspace = true } const bd = tree.package && tree.package.bundleDependencies if (bd && bd.length) { this.bundleDependencies = bd } if (tree.inShrinkwrap) { this.inShrinkwrap = true } else if (tree.hasShrinkwrap) { this.hasShrinkwrap = true } if (tree.error) { this.error = treeError(tree.error) } if (tree.errors && tree.errors.length) { this.errors = tree.errors.map(treeError) } if (tree.overrides) { this.overrides = new Map([...tree.overrides.ruleset.values()] .map((override) => [override.key, override.value])) } // edgesOut sorted by name if (tree.edgesOut.size) { this.edgesOut = new Map([...tree.edgesOut.entries()] .sort(([a], [b]) => localeCompare(a, b)) .map(([name, edge]) => [name, new EdgeOut(edge)])) } // edgesIn sorted by location if (tree.edgesIn.size) { this.edgesIn = new Set([...tree.edgesIn] .sort((a, b) => localeCompare(a.from.location, b.from.location)) .map(edge => new EdgeIn(edge))) } if (tree.workspaces && tree.workspaces.size) { this.workspaces = new Map([...tree.workspaces.entries()] .map(([name, path]) => [name, relpath(tree.root.realpath, path)])) } // fsChildren sorted by path if (tree.fsChildren.size) { this.fsChildren = new Set([...tree.fsChildren] .sort(({ path: a }, { path: b }) => localeCompare(a, b)) .map(tree => printableTree(tree, path))) } // children sorted by name if (tree.children.size) { this.children = new Map([...tree.children.entries()] .sort(([a], [b]) => localeCompare(a, b)) .map(([name, tree]) => [name, printableTree(tree, path)])) } } } class ArboristVirtualNode extends ArboristNode { constructor (tree, path) { super(tree, path) this.sourceReference = printableTree(tree.sourceReference, path) } } class ArboristLink extends ArboristNode { constructor (tree, path) { super(tree, path) this.target = printableTree(tree.target, path) } } const treeError = ({ code, path }) => ({ code, ...(path ? { path } : {}), }) // print out edges without dumping the full node all over again // this base class will toJSON as a plain old object, but the // util.inspect() output will be a bit cleaner class Edge { constructor (edge) { this.type = edge.type this.name = edge.name this.spec = edge.rawSpec || '*' if (edge.rawSpec !== edge.spec) { this.override = edge.spec } if (edge.error) { this.error = edge.error } if (edge.peerConflicted) { this.peerConflicted = edge.peerConflicted } } } // don't care about 'from' for edges out class EdgeOut extends Edge { constructor (edge) { super(edge) this.to = edge.to && edge.to.location } [util.inspect.custom] () { return `{ ${this.type} ${this.name}@${this.spec}${ this.override ? ` overridden:${this.override}` : '' }${ this.to ? ' -> ' + this.to : '' }${ this.error ? ' ' + this.error : '' }${ this.peerConflicted ? ' peerConflicted' : '' } }` } } // don't care about 'to' for edges in class EdgeIn extends Edge { constructor (edge) { super(edge) this.from = edge.from && edge.from.location } [util.inspect.custom] () { return `{ ${this.from || '""'} ${this.type} ${this.name}@${this.spec}${ this.error ? ' ' + this.error : '' }${ this.peerConflicted ? ' peerConflicted' : '' } }` } } const printableTree = (tree, path = []) => { if (!tree) { return tree } const Cls = tree.isLink ? ArboristLink : tree.sourceReference ? ArboristVirtualNode : ArboristNode if (path.includes(tree)) { const obj = Object.create(Cls.prototype) return Object.assign(obj, { location: tree.location }) } path.push(tree) return new Cls(tree, path) } module.exports = printableTree 'use strict' const { resolve } = require('node:path') const { parser, arrayDelimiter } = require('@npmcli/query') const localeCompare = require('@isaacs/string-locale-compare')('en') const { log } = require('proc-log') const { minimatch } = require('minimatch') const npa = require('npm-package-arg') const pacote = require('pacote') const semver = require('semver') const npmFetch = require('npm-registry-fetch') // handle results for parsed query asts, results are stored in a map that has a // key that points to each ast selector node and stores the resulting array of // arborist nodes as its value, that is essential to how we handle multiple // query selectors, e.g: `#a, #b, #c` <- 3 diff ast selector nodes class Results { #currentAstSelector #initialItems #inventory #outdatedCache = new Map() #vulnCache #pendingCombinator #results = new Map() #targetNode constructor (opts) { this.#currentAstSelector = opts.rootAstNode.nodes[0] this.#inventory = opts.inventory this.#initialItems = opts.initialItems this.#vulnCache = opts.vulnCache this.#targetNode = opts.targetNode this.currentResults = this.#initialItems // We get this when first called and need to pass it to pacote this.flatOptions = opts.flatOptions || {} // reset by rootAstNode walker this.currentAstNode = opts.rootAstNode } get currentResults () { return this.#results.get(this.#currentAstSelector) } set currentResults (value) { this.#results.set(this.#currentAstSelector, value) } // retrieves the initial items to which start the filtering / matching // for most of the different types of recognized ast nodes, e.g: class (aka // depType), id, *, etc in different contexts we need to start with the // current list of filtered results, for example a query for `.workspace` // actually means the same as `*.workspace` so we want to start with the full // inventory if that's the first ast node we're reading but if it appears in // the middle of a query it should respect the previous filtered results, // combinators are a special case in which we always want to have the // complete inventory list in order to use the left-hand side ast node as a // filter combined with the element on its right-hand side get initialItems () { const firstParsed = (this.currentAstNode.parent.nodes[0] === this.currentAstNode) && (this.currentAstNode.parent.parent.type === 'root') if (firstParsed) { return this.#initialItems } if (this.currentAstNode.prev().type === 'combinator') { return this.#inventory } return this.currentResults } // combinators need information about previously filtered items along // with info of the items parsed / retrieved from the selector right // past the combinator, for this reason combinators are stored and // only ran as the last part of each selector logic processPendingCombinator (nextResults) { if (this.#pendingCombinator) { const res = this.#pendingCombinator(this.currentResults, nextResults) this.#pendingCombinator = null this.currentResults = res } else { this.currentResults = nextResults } } // when collecting results to a root astNode, we traverse the list of child // selector nodes and collect all of their resulting arborist nodes into a // single/flat Set of items, this ensures we also deduplicate items collect (rootAstNode) { return new Set(rootAstNode.nodes.flatMap(n => this.#results.get(n))) } // selector types map to the '.type' property of the ast nodes via `${astNode.type}Type` // // attribute selector [name=value], etc attributeType () { const nextResults = this.initialItems.filter(node => attributeMatch(this.currentAstNode, node.package) ) this.processPendingCombinator(nextResults) } // dependency type selector (i.e. .prod, .dev, etc) // css calls this class, we interpret is as dependency type classType () { const depTypeFn = depTypes[String(this.currentAstNode)] if (!depTypeFn) { throw Object.assign( new Error(`\`${String(this.currentAstNode)}\` is not a supported dependency type.`), { code: 'EQUERYNODEPTYPE' } ) } const nextResults = depTypeFn(this.initialItems) this.processPendingCombinator(nextResults) } // combinators (i.e. '>', ' ', '~') combinatorType () { this.#pendingCombinator = combinators[String(this.currentAstNode)] } // name selectors (i.e. #foo) // css calls this id, we interpret it as name idType () { const name = this.currentAstNode.value const nextResults = this.initialItems.filter(node => (name === node.name) || (name === node.package.name) ) this.processPendingCombinator(nextResults) } // pseudo selectors (prefixed with :) async pseudoType () { const pseudoFn = `${this.currentAstNode.value.slice(1)}Pseudo` if (!this[pseudoFn]) { throw Object.assign( new Error(`\`${this.currentAstNode.value }\` is not a supported pseudo selector.`), { code: 'EQUERYNOPSEUDO' } ) } const nextResults = await this[pseudoFn]() this.processPendingCombinator(nextResults) } selectorType () { this.#currentAstSelector = this.currentAstNode // starts a new array in which resulting items // can be stored for each given ast selector if (!this.currentResults) { this.currentResults = [] } } universalType () { this.processPendingCombinator(this.initialItems) } // pseudo selectors map to the 'value' property of the pseudo selectors in the ast nodes // via selectors via `${value.slice(1)}Pseudo` attrPseudo () { const { lookupProperties, attributeMatcher } = this.currentAstNode return this.initialItems.filter(node => { let objs = [node.package] for (const prop of lookupProperties) { // if an isArray symbol is found that means we'll need to iterate // over the previous found array to basically make sure we traverse // all its indexes testing for possible objects that may eventually // hold more keys specified in a selector if (prop === arrayDelimiter) { objs = objs.flat() continue } // otherwise just maps all currently found objs // to the next prop from the lookup properties list, // filters out any empty key lookup objs = objs.flatMap(obj => obj[prop] || []) // in case there's no property found in the lookup // just filters that item out const noAttr = objs.every(obj => !obj) if (noAttr) { return false } } // if any of the potential object matches // that item should be in the final result return objs.some(obj => attributeMatch(attributeMatcher, obj)) }) } emptyPseudo () { return this.initialItems.filter(node => node.edgesOut.size === 0) } extraneousPseudo () { return this.initialItems.filter(node => node.extraneous) } async hasPseudo () { const found = [] for (const item of this.initialItems) { // This is the one time initialItems differs from inventory const res = await retrieveNodesFromParsedAst({ flatOptions: this.flatOptions, initialItems: [item], inventory: this.#inventory, rootAstNode: this.currentAstNode.nestedNode, targetNode: item, vulnCache: this.#vulnCache, }) if (res.size > 0) { found.push(item) } } return found } invalidPseudo () { const found = [] for (const node of this.initialItems) { for (const edge of node.edgesIn) { if (edge.invalid) { found.push(node) break } } } return found } async isPseudo () { const res = await retrieveNodesFromParsedAst({ flatOptions: this.flatOptions, initialItems: this.initialItems, inventory: this.#inventory, rootAstNode: this.currentAstNode.nestedNode, targetNode: this.currentAstNode, vulnCache: this.#vulnCache, }) return [...res] } linkPseudo () { return this.initialItems.filter(node => node.isLink || (node.isTop && !node.isRoot)) } missingPseudo () { return this.#inventory.reduce((res, node) => { for (const edge of node.edgesOut.values()) { if (edge.missing) { const pkg = { name: edge.name, version: edge.spec } const item = new this.#targetNode.constructor({ pkg }) item.queryContext = { missing: true, } item.edgesIn = new Set([edge]) res.push(item) } } return res }, []) } async notPseudo () { const res = await retrieveNodesFromParsedAst({ flatOptions: this.flatOptions, initialItems: this.initialItems, inventory: this.#inventory, rootAstNode: this.currentAstNode.nestedNode, targetNode: this.currentAstNode, vulnCache: this.#vulnCache, }) const internalSelector = new Set(res) return this.initialItems.filter(node => !internalSelector.has(node)) } overriddenPseudo () { return this.initialItems.filter(node => node.overridden) } pathPseudo () { return this.initialItems.filter(node => { if (!this.currentAstNode.pathValue) { return true } return minimatch( node.realpath.replace(/\\+/g, '/'), resolve(node.root.realpath, this.currentAstNode.pathValue).replace(/\\+/g, '/') ) }) } privatePseudo () { return this.initialItems.filter(node => node.package.private) } rootPseudo () { return this.initialItems.filter(node => node === this.#targetNode.root) } scopePseudo () { return this.initialItems.filter(node => node === this.#targetNode) } semverPseudo () { const { attributeMatcher, lookupProperties, semverFunc = 'infer', semverValue, } = this.currentAstNode const { qualifiedAttribute } = attributeMatcher if (!semverValue) { // DEPRECATED: remove this warning and throw an error as part of @npmcli/arborist@6 log.warn('query', 'usage of :semver() with no parameters is deprecated') return this.initialItems } if (!semver.valid(semverValue) && !semver.validRange(semverValue)) { throw Object.assign( new Error(`\`${semverValue}\` is not a valid semver version or range`), { code: 'EQUERYINVALIDSEMVER' }) } const valueIsVersion = !!semver.valid(semverValue) const nodeMatches = (node, obj) => { // if we already have an operator, the user provided some test as part of the selector // we evaluate that first because if it fails we don't want this node anyway if (attributeMatcher.operator) { if (!attributeMatch(attributeMatcher, obj)) { // if the initial operator doesn't match, we're done return false } } const attrValue = obj[qualifiedAttribute] // both valid and validRange return null for undefined, so this will skip both nodes that // do not have the attribute defined as well as those where the attribute value is invalid // and those where the value from the package.json is not a string if ((!semver.valid(attrValue) && !semver.validRange(attrValue)) || typeof attrValue !== 'string') { return false } const attrIsVersion = !!semver.valid(attrValue) let actualFunc = semverFunc // if we're asked to infer, we examine outputs to make a best guess if (actualFunc === 'infer') { if (valueIsVersion && attrIsVersion) { // two versions -> semver.eq actualFunc = 'eq' } else if (!valueIsVersion && !attrIsVersion) { // two ranges -> semver.intersects actualFunc = 'intersects' } else { // anything else -> semver.satisfies actualFunc = 'satisfies' } } if (['eq', 'neq', 'gt', 'gte', 'lt', 'lte'].includes(actualFunc)) { // both sides must be versions, but one is not if (!valueIsVersion || !attrIsVersion) { return false } return semver[actualFunc](attrValue, semverValue) } else if (['gtr', 'ltr', 'satisfies'].includes(actualFunc)) { // at least one side must be a version, but neither is if (!valueIsVersion && !attrIsVersion) { return false } return valueIsVersion ? semver[actualFunc](semverValue, attrValue) : semver[actualFunc](attrValue, semverValue) } else if (['intersects', 'subset'].includes(actualFunc)) { // these accept two ranges and since a version is also a range, anything goes return semver[actualFunc](attrValue, semverValue) } else { // user provided a function we don't know about, throw an error throw Object.assign(new Error(`\`semver.${actualFunc}\` is not a supported operator.`), { code: 'EQUERYINVALIDOPERATOR' }) } } return this.initialItems.filter((node) => { // no lookupProperties just means its a top level property, see if it matches if (!lookupProperties.length) { return nodeMatches(node, node.package) } // this code is mostly duplicated from attrPseudo to traverse into the package until we get // to our deepest requested object let objs = [node.package] for (const prop of lookupProperties) { if (prop === arrayDelimiter) { objs = objs.flat() continue } objs = objs.flatMap(obj => obj[prop] || []) const noAttr = objs.every(obj => !obj) if (noAttr) { return false } return objs.some(obj => nodeMatches(node, obj)) } }) } typePseudo () { if (!this.currentAstNode.typeValue) { return this.initialItems } return this.initialItems .flatMap(node => { const found = [] for (const edge of node.edgesIn) { if (npa(`${edge.name}@${edge.spec}`).type === this.currentAstNode.typeValue) { found.push(edge.to) } } return found }) } dedupedPseudo () { return this.initialItems.filter(node => node.target.edgesIn.size > 1) } async vulnPseudo () { if (!this.initialItems.length) { return this.initialItems } if (!this.#vulnCache) { const packages = {} // We have to map the items twice, once to get the request, and a second time to filter out the results of that request this.initialItems.map((node) => { if (node.isProjectRoot || node.package.private) { return } if (!packages[node.name]) { packages[node.name] = [] } if (!packages[node.name].includes(node.version)) { packages[node.name].push(node.version) } }) const res = await npmFetch('/-/npm/v1/security/advisories/bulk', { ...this.flatOptions, registry: this.flatOptions.auditRegistry || this.flatOptions.registry, method: 'POST', gzip: true, body: packages, }) this.#vulnCache = await res.json() } const advisories = this.#vulnCache const { vulns } = this.currentAstNode return this.initialItems.filter(item => { const vulnerable = advisories[item.name]?.filter(advisory => { // This could be for another version of this package elsewhere in the tree if (!semver.intersects(advisory.vulnerable_versions, item.version)) { return false } if (!vulns) { return true } // vulns are OR with each other, if any one matches we're done for (const vuln of vulns) { if (vuln.severity && !vuln.severity.includes('*')) { if (!vuln.severity.includes(advisory.severity)) { continue } } if (vuln?.cwe) { // * is special, it means "has a cwe" if (vuln.cwe.includes('*')) { if (!advisory.cwe.length) { continue } } else if (!vuln.cwe.every(cwe => advisory.cwe.includes(`CWE-${cwe}`))) { continue } } return true } }) if (vulnerable?.length) { item.queryContext = { advisories: vulnerable, } return true } return false }) } async outdatedPseudo () { const { outdatedKind = 'any' } = this.currentAstNode // filter the initialItems // NOTE: this uses a Promise.all around a map without in-line concurrency handling // since the only async action taken is retrieving the packument, which is limited // based on the max-sockets config in make-fetch-happen const initialResults = await Promise.all(this.initialItems.map(async (node) => { // the root can't be outdated, skip it if (node.isProjectRoot) { return false } // private packages can't be published, skip them if (node.package.private) { return false } // we cache the promise representing the full versions list, this helps reduce the // number of requests we send by keeping population of the cache in a single tick // making it less likely that multiple requests for the same package will be inflight if (!this.#outdatedCache.has(node.name)) { this.#outdatedCache.set(node.name, getPackageVersions(node.name, this.flatOptions)) } const availableVersions = await this.#outdatedCache.get(node.name) // we attach _all_ versions to the queryContext to allow consumers to do their own // filtering and comparisons node.queryContext.versions = availableVersions // next we further reduce the set to versions that are greater than the current one const greaterVersions = availableVersions.filter((available) => { return semver.gt(available, node.version) }) // no newer versions than the current one, drop this node from the result set if (!greaterVersions.length) { return false } // if we got here, we know that newer versions exist, if the kind is 'any' we're done if (outdatedKind === 'any') { return node } // look for newer versions that differ from current by a specific part of the semver version if (['major', 'minor', 'patch'].includes(outdatedKind)) { // filter the versions greater than our current one based on semver.diff const filteredVersions = greaterVersions.filter((version) => { return semver.diff(node.version, version) === outdatedKind }) // no available versions are of the correct diff type if (!filteredVersions.length) { return false } return node } // look for newer versions that satisfy at least one edgeIn to this node if (outdatedKind === 'in-range') { const inRangeContext = [] for (const edge of node.edgesIn) { const inRangeVersions = greaterVersions.filter((version) => { return semver.satisfies(version, edge.spec) }) // this edge has no in-range candidates, just move on if (!inRangeVersions.length) { continue } inRangeContext.push({ from: edge.from.location, versions: inRangeVersions, }) } // if we didn't find at least one match, drop this node if (!inRangeContext.length) { return false } // now add to the context each version that is in-range for each edgeIn node.queryContext.outdated = { ...node.queryContext.outdated, inRange: inRangeContext, } return node } // look for newer versions that _do not_ satisfy at least one edgeIn if (outdatedKind === 'out-of-range') { const outOfRangeContext = [] for (const edge of node.edgesIn) { const outOfRangeVersions = greaterVersions.filter((version) => { return !semver.satisfies(version, edge.spec) }) // this edge has no out-of-range candidates, skip it if (!outOfRangeVersions.length) { continue } outOfRangeContext.push({ from: edge.from.location, versions: outOfRangeVersions, }) } // if we didn't add at least one thing to the context, this node is not a match if (!outOfRangeContext.length) { return false } // attach the out-of-range context to the node node.queryContext.outdated = { ...node.queryContext.outdated, outOfRange: outOfRangeContext, } return node } // any other outdatedKind is unknown and will never match return false })) // return an array with the holes for non-matching nodes removed return initialResults.filter(Boolean) } } // operators for attribute selectors const attributeOperators = { // attribute value is equivalent '=' ({ attr, value }) { return attr === value }, // attribute value contains word '~=' ({ attr, value }) { return (attr.match(/\w+/g) || []).includes(value) }, // attribute value contains string '*=' ({ attr, value }) { return attr.includes(value) }, // attribute value is equal or starts with '|=' ({ attr, value }) { return attr.startsWith(`${value}-`) }, // attribute value starts with '^=' ({ attr, value }) { return attr.startsWith(value) }, // attribute value ends with '$=' ({ attr, value }) { return attr.endsWith(value) }, } const attributeOperator = ({ attr, value, insensitive, operator }) => { if (typeof attr === 'number') { attr = String(attr) } if (typeof attr !== 'string') { // It's an object or an array, bail return false } if (insensitive) { attr = attr.toLowerCase() } return attributeOperators[operator]({ attr, insensitive, value, }) } const attributeMatch = (matcher, obj) => { const insensitive = !!matcher.insensitive const operator = matcher.operator || '' const attribute = matcher.qualifiedAttribute let value = matcher.value || '' // return early if checking existence if (operator === '') { return Boolean(obj[attribute]) } if (insensitive) { value = value.toLowerCase() } // in case the current object is an array // then we try to match every item in the array if (Array.isArray(obj[attribute])) { return obj[attribute].find((i, index) => { const attr = obj[attribute][index] || '' return attributeOperator({ attr, value, insensitive, operator }) }) } else { const attr = obj[attribute] || '' return attributeOperator({ attr, value, insensitive, operator }) } } const edgeIsType = (node, type, seen = new Set()) => { for (const edgeIn of node.edgesIn) { // TODO Need a test with an infinite loop if (seen.has(edgeIn)) { continue } seen.add(edgeIn) if (edgeIn.type === type || edgeIn.from[type] || edgeIsType(edgeIn.from, type, seen)) { return true } } return false } const filterByType = (nodes, type) => { const found = [] for (const node of nodes) { if (node[type] || edgeIsType(node, type)) { found.push(node) } } return found } const depTypes = { // dependency '.prod' (prevResults) { const found = [] for (const node of prevResults) { if (!node.dev) { found.push(node) } } return found }, // devDependency '.dev' (prevResults) { return filterByType(prevResults, 'dev') }, // optionalDependency '.optional' (prevResults) { return filterByType(prevResults, 'optional') }, // peerDependency '.peer' (prevResults) { return filterByType(prevResults, 'peer') }, // workspace '.workspace' (prevResults) { return prevResults.filter(node => node.isWorkspace) }, // bundledDependency '.bundled' (prevResults) { return prevResults.filter(node => node.inBundle) }, } // checks if a given node has a direct parent in any of the nodes provided in // the compare nodes array const hasParent = (node, compareNodes) => { // All it takes is one so we loop and return on the first hit for (let compareNode of compareNodes) { if (compareNode.isLink) { compareNode = compareNode.target } // follows logical parent for link anscestors if (node.isTop && (node.resolveParent === compareNode)) { return true } // follows edges-in to check if they match a possible parent for (const edge of node.edgesIn) { if (edge && edge.from === compareNode) { return true } } } return false } // checks if a given node is a descendant of any of the nodes provided in the // compareNodes array const hasAscendant = (node, compareNodes, seen = new Set()) => { // TODO (future) loop over ancestry property if (hasParent(node, compareNodes)) { return true } if (node.isTop && node.resolveParent) { /* istanbul ignore if - investigate if linksIn check obviates need for this */ if (hasAscendant(node.resolveParent, compareNodes)) { return true } } for (const edge of node.edgesIn) { // TODO Need a test with an infinite loop if (seen.has(edge)) { continue } seen.add(edge) if (edge && edge.from && hasAscendant(edge.from, compareNodes, seen)) { return true } } for (const linkNode of node.linksIn) { if (hasAscendant(linkNode, compareNodes, seen)) { return true } } return false } const combinators = { // direct descendant '>' (prevResults, nextResults) { return nextResults.filter(node => hasParent(node, prevResults)) }, // any descendant ' ' (prevResults, nextResults) { return nextResults.filter(node => hasAscendant(node, prevResults)) }, // sibling '~' (prevResults, nextResults) { // Return any node in nextResults that is a sibling of (aka shares a // parent with) a node in prevResults const parentNodes = new Set() // Parents of everything in prevResults for (const node of prevResults) { for (const edge of node.edgesIn) { // edge.from always exists cause it's from another node's edgesIn parentNodes.add(edge.from) } } return nextResults.filter(node => !prevResults.includes(node) && hasParent(node, [...parentNodes]) ) }, } // get a list of available versions of a package filtered to respect --before // NOTE: this runs over each node and should not throw const getPackageVersions = async (name, opts) => { let packument try { packument = await pacote.packument(name, { ...opts, fullMetadata: false, // we only need the corgi }) } catch (err) { // if the fetch fails, log a warning and pretend there are no versions log.warn('query', `could not retrieve packument for ${name}: ${err.message}`) return [] } // start with a sorted list of all versions (lowest first) let candidates = Object.keys(packument.versions).sort(semver.compare) // if the packument has a time property, and the user passed a before flag, then // we filter this list down to only those versions that existed before the specified date if (packument.time && opts.before) { candidates = candidates.filter((version) => { // this version isn't found in the times at all, drop it if (!packument.time[version]) { return false } return Date.parse(packument.time[version]) <= opts.before }) } return candidates } const retrieveNodesFromParsedAst = async (opts) => { // when we first call this it's the parsed query. all other times it's // results.currentNode.nestedNode const rootAstNode = opts.rootAstNode if (!rootAstNode.nodes) { return new Set() } const results = new Results(opts) const astNodeQueue = new Set() // walk is sync, so we have to build up our async functions and then await them later rootAstNode.walk((nextAstNode) => { astNodeQueue.add(nextAstNode) }) for (const nextAstNode of astNodeQueue) { // This is the only place we reset currentAstNode results.currentAstNode = nextAstNode const updateFn = `${results.currentAstNode.type}Type` if (typeof results[updateFn] !== 'function') { throw Object.assign( new Error(`\`${results.currentAstNode.type}\` is not a supported selector.`), { code: 'EQUERYNOSELECTOR' } ) } await results[updateFn]() } return results.collect(rootAstNode) } const querySelectorAll = async (targetNode, query, flatOptions) => { // This never changes ever we just pass it around. But we can't scope it to // this whole file if we ever want to support concurrent calls to this // function. const inventory = [...targetNode.root.inventory.values()] // res is a Set of items returned for each parsed css ast selector const res = await retrieveNodesFromParsedAst({ initialItems: inventory, inventory, flatOptions, rootAstNode: parser(query), targetNode, }) // returns nodes ordered by realpath return [...res].sort((a, b) => localeCompare(a.location, b.location)) } module.exports = querySelectorAll // look up the realpath, but cache stats to minimize overhead // If the parent folder is in the realpath cache, then we just // lstat the child, since there's no need to do a full realpath // This is not a separate module, and is much simpler than Node's // built-in fs.realpath, because we only care about symbolic links, // so we can handle many fewer edge cases. const { lstat, readlink } = require('node:fs/promises') const { resolve, basename, dirname } = require('node:path') const realpathCached = (path, rpcache, stcache, depth) => { // just a safety against extremely deep eloops /* istanbul ignore next */ if (depth > 2000) { throw eloop(path) } path = resolve(path) if (rpcache.has(path)) { return Promise.resolve(rpcache.get(path)) } const dir = dirname(path) const base = basename(path) if (base && rpcache.has(dir)) { return realpathChild(dir, base, rpcache, stcache, depth) } // if it's the root, then we know it's real if (!base) { rpcache.set(dir, dir) return Promise.resolve(dir) } // the parent, what is that? // find out, and then come back. return realpathCached(dir, rpcache, stcache, depth + 1).then(() => realpathCached(path, rpcache, stcache, depth + 1)) } const lstatCached = (path, stcache) => { if (stcache.has(path)) { return Promise.resolve(stcache.get(path)) } const p = lstat(path).then(st => { stcache.set(path, st) return st }) stcache.set(path, p) return p } // This is a slight fib, as it doesn't actually occur during a stat syscall. // But file systems are giant piles of lies, so whatever. const eloop = path => Object.assign(new Error( `ELOOP: too many symbolic links encountered, stat '${path}'`), { errno: -62, syscall: 'stat', code: 'ELOOP', path: path, }) const realpathChild = (dir, base, rpcache, stcache, depth) => { const realdir = rpcache.get(dir) // that unpossible /* istanbul ignore next */ if (typeof realdir === 'undefined') { throw new Error('in realpathChild without parent being in realpath cache') } const realish = resolve(realdir, base) return lstatCached(realish, stcache).then(st => { if (!st.isSymbolicLink()) { rpcache.set(resolve(dir, base), realish) return realish } return readlink(realish).then(target => { const resolved = resolve(realdir, target) if (realish === resolved) { throw eloop(realish) } return realpathCached(resolved, rpcache, stcache, depth + 1) }).then(real => { rpcache.set(resolve(dir, base), real) return real }) }) } module.exports = realpathCached const { relative } = require('node:path') const relpath = (from, to) => relative(from, to).replace(/\\/g, '/') module.exports = relpath // Sometimes we need to actually do a walk from the root, because you can // have a cycle of deps that all depend on each other, but no path from root. // Also, since the ideal tree is loaded from the shrinkwrap, it had extraneous // flags set false that might now be actually extraneous, and dev/optional // flags that are also now incorrect. This method sets all flags to true, so // we can find the set that is actually extraneous. module.exports = tree => { for (const node of tree.inventory.values()) { node.extraneous = true node.dev = true node.devOptional = true node.peer = true node.optional = true } } const crypto = require('node:crypto') const { dirname, basename, resolve } = require('node:path') // use sha1 because it's faster, and collisions extremely unlikely anyway const pathSafeHash = s => crypto.createHash('sha1') .update(s) .digest('base64') .replace(/[^a-zA-Z0-9]+/g, '') .slice(0, 8) const retirePath = from => { const d = dirname(from) const b = basename(from) const hash = pathSafeHash(from) return resolve(d, `.${b}-${hash}`) } module.exports = retirePath // a module that manages a shrinkwrap file (npm-shrinkwrap.json or // package-lock.json). // Increment whenever the lockfile version updates // v1 - npm <=6 // v2 - arborist v1, npm v7, backwards compatible with v1, add 'packages' // v3 will drop the 'dependencies' field, backwards comp with v2, not v1 // // We cannot bump to v3 until npm v6 is out of common usage, and // definitely not before npm v8. const localeCompare = require('@isaacs/string-locale-compare')('en') const defaultLockfileVersion = 3 // for comparing nodes to yarn.lock entries const mismatch = (a, b) => a && b && a !== b // this.tree => the root node for the tree (ie, same path as this) // - Set the first time we do `this.add(node)` for a path matching this.path // // this.add(node) => // - decorate the node with the metadata we have, if we have it, and it matches // - add to the map of nodes needing to be committed, so that subsequent // changes are captured when we commit that location's metadata. // // this.commit() => // - commit all nodes awaiting update to their metadata entries // - re-generate this.data and this.yarnLock based on this.tree // // Note that between this.add() and this.commit(), `this.data` will be out of // date! Always call `commit()` before relying on it. // // After calling this.commit(), any nodes not present in the tree will have // been removed from the shrinkwrap data as well. const { log } = require('proc-log') const YarnLock = require('./yarn-lock.js') const { readFile, readdir, readlink, rm, stat, writeFile, } = require('node:fs/promises') const { resolve, basename, relative } = require('node:path') const specFromLock = require('./spec-from-lock.js') const versionFromTgz = require('./version-from-tgz.js') const npa = require('npm-package-arg') const pkgJson = require('@npmcli/package-json') const parseJSON = require('parse-conflict-json') const nameFromFolder = require('@npmcli/name-from-folder') const stringify = require('json-stringify-nice') const swKeyOrder = [ 'name', 'version', 'lockfileVersion', 'resolved', 'integrity', 'requires', 'packages', 'dependencies', ] // used to rewrite from yarn registry to npm registry const yarnRegRe = /^https?:\/\/registry\.yarnpkg\.com\// const npmRegRe = /^https?:\/\/registry\.npmjs\.org\// // sometimes resolved: is weird or broken, or something npa can't handle const specFromResolved = resolved => { try { return npa(resolved) } catch (er) { return {} } } const relpath = require('./relpath.js') const consistentResolve = require('./consistent-resolve.js') const { overrideResolves } = require('./override-resolves.js') const pkgMetaKeys = [ // note: name is included if necessary, for alias packages 'version', 'dependencies', 'peerDependencies', 'peerDependenciesMeta', 'optionalDependencies', 'bundleDependencies', 'acceptDependencies', 'funding', 'engines', 'os', 'cpu', '_integrity', 'license', '_hasShrinkwrap', 'hasInstallScript', 'bin', 'deprecated', 'workspaces', ] const nodeMetaKeys = [ 'integrity', 'inBundle', 'hasShrinkwrap', 'hasInstallScript', ] const metaFieldFromPkg = (pkg, key) => { const val = pkg[key] if (val) { // get only the license type, not the full object if (key === 'license' && typeof val === 'object' && val.type) { return val.type } // skip empty objects and falsey values if (typeof val !== 'object' || Object.keys(val).length) { return val } } return null } // check to make sure that there are no packages newer than or missing from the hidden lockfile const assertNoNewer = async (path, data, lockTime, dir, seen) => { const base = basename(dir) const isNM = dir !== path && base === 'node_modules' const isScope = dir !== path && base.startsWith('@') const isParent = (dir === path) || isNM || isScope const parent = isParent ? dir : resolve(dir, 'node_modules') const rel = relpath(path, dir) seen.add(rel) let entries if (dir === path) { entries = [{ name: 'node_modules', isDirectory: () => true }] } else { const { mtime: dirTime } = await stat(dir) if (dirTime > lockTime) { throw new Error(`out of date, updated: ${rel}`) } if (!isScope && !isNM && !data.packages[rel]) { throw new Error(`missing from lockfile: ${rel}`) } entries = await readdir(parent, { withFileTypes: true }).catch(() => []) } // TODO limit concurrency here, this is recursive await Promise.all(entries.map(async dirent => { const child = resolve(parent, dirent.name) if (dirent.isDirectory() && !dirent.name.startsWith('.')) { await assertNoNewer(path, data, lockTime, child, seen) } else if (dirent.isSymbolicLink()) { const target = resolve(parent, await readlink(child)) const tstat = await stat(target).catch( /* istanbul ignore next - windows */ () => null) seen.add(relpath(path, child)) /* istanbul ignore next - windows cannot do this */ if (tstat?.isDirectory() && !seen.has(relpath(path, target))) { await assertNoNewer(path, data, lockTime, target, seen) } } })) if (dir !== path) { return } // assert that all the entries in the lockfile were seen for (const loc in data.packages) { if (!seen.has(loc)) { throw new Error(`missing from node_modules: ${loc}`) } } } class Shrinkwrap { static get defaultLockfileVersion () { return defaultLockfileVersion } static load (options) { return new Shrinkwrap(options).load() } static get keyOrder () { return swKeyOrder } static async reset (options) { // still need to know if it was loaded from the disk, but don't // bother reading it if we're gonna just throw it away. const s = new Shrinkwrap(options) s.reset() const [sw, lock] = await s.resetFiles // XXX this is duplicated in this.load(), but using loadFiles instead of resetFiles if (s.hiddenLockfile) { s.filename = resolve(s.path, 'node_modules/.package-lock.json') } else if (s.shrinkwrapOnly || sw) { s.filename = resolve(s.path, 'npm-shrinkwrap.json') } else { s.filename = resolve(s.path, 'package-lock.json') } s.loadedFromDisk = !!(sw || lock) // TODO what uses this? s.type = basename(s.filename) return s } static metaFromNode (node, path, options = {}) { if (node.isLink) { return { resolved: relpath(path, node.realpath), link: true, } } const meta = {} for (const key of pkgMetaKeys) { const val = metaFieldFromPkg(node.package, key) if (val) { meta[key.replace(/^_/, '')] = val } } // we only include name if different from the node path name, and for the // root to help prevent churn based on the name of the directory the // project is in const pname = node.packageName // when Target package name and Target node share the same name, we include the name, target node should have name as per realpath. if (pname && (node === node.root || pname !== node.name || nameFromFolder(node.realpath) !== pname)) { meta.name = pname } if (node.isTop && node.package.devDependencies) { meta.devDependencies = node.package.devDependencies } for (const key of nodeMetaKeys) { if (node[key]) { meta[key] = node[key] } } const resolved = consistentResolve(node.resolved, node.path, path, true) // hide resolved from registry dependencies. if (!resolved) { // no-op } else if (node.isRegistryDependency) { meta.resolved = overrideResolves(resolved, options) } else { meta.resolved = resolved } if (node.extraneous) { meta.extraneous = true } else { if (node.peer) { meta.peer = true } if (node.dev) { meta.dev = true } if (node.optional) { meta.optional = true } if (node.devOptional && !node.dev && !node.optional) { meta.devOptional = true } } return meta } #awaitingUpdate = new Map() constructor (options = {}) { const { path, indent = 2, newline = '\n', shrinkwrapOnly = false, hiddenLockfile = false, lockfileVersion, resolveOptions = {}, } = options if (hiddenLockfile) { this.lockfileVersion = 3 } else if (lockfileVersion) { this.lockfileVersion = parseInt(lockfileVersion, 10) } else { this.lockfileVersion = null } this.tree = null this.path = resolve(path || '.') this.filename = null this.data = null this.indent = indent this.newline = newline this.loadedFromDisk = false this.type = null this.yarnLock = null this.hiddenLockfile = hiddenLockfile this.loadingError = null this.resolveOptions = resolveOptions // only load npm-shrinkwrap.json in dep trees, not package-lock this.shrinkwrapOnly = shrinkwrapOnly } // check to see if a spec is present in the yarn.lock file, and if so, // if we should use it, and what it should resolve to. This is only // done when we did not load a shrinkwrap from disk. Also, decorate // the options object if provided with the resolved and integrity that // we expect. checkYarnLock (spec, options = {}) { spec = npa(spec) const { yarnLock, loadedFromDisk } = this const useYarnLock = yarnLock && !loadedFromDisk const fromYarn = useYarnLock && yarnLock.entries.get(spec.raw) if (fromYarn && fromYarn.version) { // if it's the yarn or npm default registry, use the version as // our effective spec. if it's any other kind of thing, use that. const { resolved, version, integrity } = fromYarn const isYarnReg = spec.registry && yarnRegRe.test(resolved) const isnpmReg = spec.registry && !isYarnReg && npmRegRe.test(resolved) const isReg = isnpmReg || isYarnReg // don't use the simple version if the "registry" url is // something else entirely! const tgz = isReg && versionFromTgz(spec.name, resolved) || {} let yspec = resolved if (tgz.name === spec.name && tgz.version === version) { yspec = version } else if (isReg && tgz.name && tgz.version) { yspec = `npm:${tgz.name}@${tgz.version}` } if (yspec) { options.resolved = resolved.replace(yarnRegRe, 'https://registry.npmjs.org/') options.integrity = integrity return npa(`${spec.name}@${yspec}`) } } return spec } // throw away the shrinkwrap data so we can start fresh // still worth doing a load() first so we know which files to write. reset () { this.tree = null this.#awaitingUpdate = new Map() const lockfileVersion = this.lockfileVersion || defaultLockfileVersion this.originalLockfileVersion = lockfileVersion this.data = { lockfileVersion, requires: true, packages: {}, dependencies: {}, } } // files to potentially read from and write to, in order of priority get #filenameSet () { if (this.shrinkwrapOnly) { return [`${this.path}/npm-shrinkwrap.json`] } if (this.hiddenLockfile) { return [`${this.path}/node_modules/.package-lock.json`] } return [ `${this.path}/npm-shrinkwrap.json`, `${this.path}/package-lock.json`, `${this.path}/yarn.lock`, ] } get loadFiles () { return Promise.all( this.#filenameSet.map(file => file && readFile(file, 'utf8').then(d => d, er => { /* istanbul ignore else - can't test without breaking module itself */ if (er.code === 'ENOENT') { return '' } else { throw er } })) ) } get resetFiles () { // slice out yarn, we only care about lock or shrinkwrap when checking // this way, since we're not actually loading the full lock metadata return Promise.all(this.#filenameSet.slice(0, 2) .map(file => file && stat(file).then(st => st.isFile(), er => { /* istanbul ignore else - can't test without breaking module itself */ if (er.code === 'ENOENT') { return null } else { throw er } }) ) ) } inferFormattingOptions (packageJSONData) { const { [Symbol.for('indent')]: indent, [Symbol.for('newline')]: newline, } = packageJSONData if (indent !== undefined) { this.indent = indent } if (newline !== undefined) { this.newline = newline } } async load () { // we don't need to load package-lock.json except for top of tree nodes, // only npm-shrinkwrap.json. let data try { const [sw, lock, yarn] = await this.loadFiles data = sw || lock || '{}' // use shrinkwrap only for deps, otherwise prefer package-lock // and ignore npm-shrinkwrap if both are present. // TODO: emit a warning here or something if both are present. if (this.hiddenLockfile) { this.filename = resolve(this.path, 'node_modules/.package-lock.json') } else if (this.shrinkwrapOnly || sw) { this.filename = resolve(this.path, 'npm-shrinkwrap.json') } else { this.filename = resolve(this.path, 'package-lock.json') } this.type = basename(this.filename) this.loadedFromDisk = Boolean(sw || lock) if (yarn) { this.yarnLock = new YarnLock() // ignore invalid yarn data. we'll likely clobber it later anyway. try { this.yarnLock.parse(yarn) } catch { // ignore errors } } data = parseJSON(data) this.inferFormattingOptions(data) if (this.hiddenLockfile && data.packages) { // add a few ms just to account for jitter const lockTime = +(await stat(this.filename)).mtime + 10 await assertNoNewer(this.path, data, lockTime, this.path, new Set()) } // all good! hidden lockfile is the newest thing in here. } catch (er) { /* istanbul ignore else */ if (typeof this.filename === 'string') { const rel = relpath(this.path, this.filename) log.verbose('shrinkwrap', `failed to load ${rel}`, er.message) } else { log.verbose('shrinkwrap', `failed to load ${this.path}`, er.message) } this.loadingError = er this.loadedFromDisk = false this.ancientLockfile = false data = {} } // auto convert v1 lockfiles to v3 // leave v2 in place unless configured // v3 by default let lockfileVersion = defaultLockfileVersion if (this.lockfileVersion) { lockfileVersion = this.lockfileVersion } else if (data.lockfileVersion && data.lockfileVersion !== 1) { lockfileVersion = data.lockfileVersion } this.data = { ...data, lockfileVersion, requires: true, packages: data.packages || {}, dependencies: data.dependencies || {}, } this.originalLockfileVersion = data.lockfileVersion // use default if it wasn't explicitly set, and the current file is // less than our default. otherwise, keep whatever is in the file, // unless we had an explicit setting already. if (!this.lockfileVersion) { this.lockfileVersion = this.data.lockfileVersion = lockfileVersion } this.ancientLockfile = this.loadedFromDisk && !(data.lockfileVersion >= 2) && !data.requires // load old lockfile deps into the packages listing if (data.dependencies && !data.packages) { let pkg try { pkg = await pkgJson.normalize(this.path) pkg = pkg.content } catch { pkg = {} } this.#loadAll('', null, this.data) this.#fixDependencies(pkg) } return this } #loadAll (location, name, lock) { // migrate a v1 package lock to the new format. const meta = this.#metaFromLock(location, name, lock) // dependencies nested under a link are actually under the link target if (meta.link) { location = meta.resolved } if (lock.dependencies) { for (const name in lock.dependencies) { const loc = location + (location ? '/' : '') + 'node_modules/' + name this.#loadAll(loc, name, lock.dependencies[name]) } } } // v1 lockfiles track the optional/dev flags, but they don't tell us // which thing had what kind of dep on what other thing, so we need // to correct that now, or every link will be considered prod #fixDependencies (pkg) { // we need the root package.json because legacy shrinkwraps just // have requires:true at the root level, which is even less useful // than merging all dep types into one object. const root = this.data.packages[''] for (const key of pkgMetaKeys) { const val = metaFieldFromPkg(pkg, key) if (val) { root[key.replace(/^_/, '')] = val } } for (const loc in this.data.packages) { const meta = this.data.packages[loc] if (!meta.requires || !loc) { continue } // resolve each require to a meta entry // if this node isn't optional, but the dep is, then it's an optionalDep // likewise for dev deps. // This isn't perfect, but it's a pretty good approximation, and at // least gets us out of having all 'prod' edges, which throws off the // buildIdealTree process for (const name in meta.requires) { const dep = this.#resolveMetaNode(loc, name) // this overwrites the false value set above // default to dependencies if the dep just isn't in the tree, which // maybe should be an error, since it means that the shrinkwrap is // invalid, but we can't do much better without any info. let depType = 'dependencies' /* istanbul ignore else - dev deps are only for the root level */ if (dep?.optional && !meta.optional) { depType = 'optionalDependencies' } else if (dep?.dev && !meta.dev) { // XXX is this even reachable? depType = 'devDependencies' } if (!meta[depType]) { meta[depType] = {} } meta[depType][name] = meta.requires[name] } delete meta.requires } } #resolveMetaNode (loc, name) { for (let path = loc; true; path = path.replace(/(^|\/)[^/]*$/, '')) { const check = `${path}${path ? '/' : ''}node_modules/${name}` if (this.data.packages[check]) { return this.data.packages[check] } if (!path) { break } } return null } #lockFromLoc (lock, path, i = 0) { if (!lock) { return null } if (path[i] === '') { i++ } if (i >= path.length) { return lock } if (!lock.dependencies) { return null } return this.#lockFromLoc(lock.dependencies[path[i]], path, i + 1) } // pass in a path relative to the root path, or an absolute path, // get back a /-normalized location based on root path. #pathToLoc (path) { return relpath(this.path, resolve(this.path, path)) } delete (nodePath) { if (!this.data) { throw new Error('run load() before getting or setting data') } const location = this.#pathToLoc(nodePath) this.#awaitingUpdate.delete(location) delete this.data.packages[location] const path = location.split(/(?:^|\/)node_modules\//) const name = path.pop() const pLock = this.#lockFromLoc(this.data, path) if (pLock && pLock.dependencies) { delete pLock.dependencies[name] } } get (nodePath) { if (!this.data) { throw new Error('run load() before getting or setting data') } const location = this.#pathToLoc(nodePath) if (this.#awaitingUpdate.has(location)) { this.#updateWaitingNode(location) } // first try to get from the newer spot, which we know has // all the things we need. if (this.data.packages[location]) { return this.data.packages[location] } // otherwise, fall back to the legacy metadata, and hope for the best // get the node in the shrinkwrap corresponding to this spot const path = location.split(/(?:^|\/)node_modules\//) const name = path[path.length - 1] const lock = this.#lockFromLoc(this.data, path) return this.#metaFromLock(location, name, lock) } #metaFromLock (location, name, lock) { // This function tries as hard as it can to figure out the metadata // from a lockfile which may be outdated or incomplete. Since v1 // lockfiles used the "version" field to contain a variety of // different possible types of data, this gets a little complicated. if (!lock) { return {} } // try to figure out a npm-package-arg spec from the lockfile entry // This will return null if we could not get anything valid out of it. const spec = specFromLock(name, lock, this.path) if (spec.type === 'directory') { // the "version" was a file: url to a non-tarball path // this is a symlink dep. We don't store much metadata // about symlinks, just the target. const target = relpath(this.path, spec.fetchSpec) this.data.packages[location] = { link: true, resolved: target, } // also save the link target, omitting version since we don't know // what it is, but we know it isn't a link to itself! if (!this.data.packages[target]) { this.#metaFromLock(target, name, { ...lock, version: null }) } return this.data.packages[location] } const meta = {} // when calling loadAll we'll change these into proper dep objects if (lock.requires && typeof lock.requires === 'object') { meta.requires = lock.requires } if (lock.optional) { meta.optional = true } if (lock.dev) { meta.dev = true } // the root will typically have a name from the root project's // package.json file. if (location === '') { meta.name = lock.name } // if we have integrity, save it now. if (lock.integrity) { meta.integrity = lock.integrity } if (lock.version && !lock.integrity) { // this is usually going to be a git url or symlink, but it could // also be a registry dependency that did not have integrity at // the time it was saved. // Symlinks were already handled above, so that leaves git. // // For git, always save the full SSH url. we'll actually fetch the // tgz most of the time, since it's faster, but it won't work for // private repos, and we can't get back to the ssh from the tgz, // so we store the ssh instead. // For unknown git hosts, just resolve to the raw spec in lock.version if (spec.type === 'git') { meta.resolved = consistentResolve(spec, this.path, this.path) // return early because there is nothing else we can do with this return this.data.packages[location] = meta } else if (spec.registry) { // registry dep that didn't save integrity. grab the version, and // fall through to pick up the resolved and potentially name. meta.version = lock.version } // only other possible case is a tarball without integrity. // fall through to do what we can with the filename later. } // at this point, we know that the spec is either a registry dep // (ie, version, because locking, which means a resolved url), // or a remote dep, or file: url. Remote deps and file urls // have a fetchSpec equal to the fully resolved thing. // Registry deps, we take what's in the lockfile. if (lock.resolved || (spec.type && !spec.registry)) { if (spec.registry) { meta.resolved = lock.resolved } else if (spec.type === 'file') { meta.resolved = consistentResolve(spec, this.path, this.path, true) } else if (spec.fetchSpec) { meta.resolved = spec.fetchSpec } } // at this point, if still we don't have a version, do our best to // infer it from the tarball url/file. This works a surprising // amount of the time, even though it's not guaranteed. if (!meta.version) { if (spec.type === 'file' || spec.type === 'remote') { const fromTgz = versionFromTgz(spec.name, spec.fetchSpec) || versionFromTgz(spec.name, meta.resolved) if (fromTgz) { meta.version = fromTgz.version if (fromTgz.name !== name) { meta.name = fromTgz.name } } } else if (spec.type === 'alias') { meta.name = spec.subSpec.name meta.version = spec.subSpec.fetchSpec } else if (spec.type === 'version') { meta.version = spec.fetchSpec } // ok, I did my best! good luck! } if (lock.bundled) { meta.inBundle = true } // save it for next time return this.data.packages[location] = meta } add (node) { if (!this.data) { throw new Error('run load() before getting or setting data') } // will be actually updated on read const loc = relpath(this.path, node.path) if (node.path === this.path) { this.tree = node } // if we have metadata about this node, and it's a match, then // try to decorate it. if (node.resolved === null || node.integrity === null) { const { resolved, integrity, hasShrinkwrap, version, } = this.get(node.path) let pathFixed = null if (resolved) { if (!/^file:/.test(resolved)) { pathFixed = resolved } else { pathFixed = `file:${resolve(this.path, resolved.slice(5)).replace(/#/g, '%23')}` } } // if we have one, only set the other if it matches // otherwise it could be for a completely different thing. const resolvedOk = !resolved || !node.resolved || node.resolved === pathFixed const integrityOk = !integrity || !node.integrity || node.integrity === integrity const versionOk = !version || !node.version || version === node.version const allOk = (resolved || integrity || version) && resolvedOk && integrityOk && versionOk if (allOk) { node.resolved = node.resolved || pathFixed || null node.integrity = node.integrity || integrity || null node.hasShrinkwrap = node.hasShrinkwrap || hasShrinkwrap || false } else { // try to read off the package or node itself const { resolved, integrity, hasShrinkwrap, } = Shrinkwrap.metaFromNode(node, this.path, this.resolveOptions) node.resolved = node.resolved || resolved || null node.integrity = node.integrity || integrity || null node.hasShrinkwrap = node.hasShrinkwrap || hasShrinkwrap || false } } this.#awaitingUpdate.set(loc, node) } addEdge (edge) { if (!this.yarnLock || !edge.valid) { return } const { to: node } = edge // if it's already set up, nothing to do if (node.resolved !== null && node.integrity !== null) { return } // if the yarn lock is empty, nothing to do if (!this.yarnLock.entries || !this.yarnLock.entries.size) { return } // we relativize the path here because that's how it shows up in the lock // XXX why is this different from pathFixed in this.add?? let pathFixed = null if (node.resolved) { if (!/file:/.test(node.resolved)) { pathFixed = node.resolved } else { pathFixed = consistentResolve(node.resolved, node.path, this.path, true) } } const spec = npa(`${node.name}@${edge.spec}`) const entry = this.yarnLock.entries.get(`${node.name}@${edge.spec}`) if (!entry || mismatch(node.version, entry.version) || mismatch(node.integrity, entry.integrity) || mismatch(pathFixed, entry.resolved)) { return } if (entry.resolved && yarnRegRe.test(entry.resolved) && spec.registry) { entry.resolved = entry.resolved.replace(yarnRegRe, 'https://registry.npmjs.org/') } node.integrity = node.integrity || entry.integrity || null node.resolved = node.resolved || consistentResolve(entry.resolved, this.path, node.path) || null this.#awaitingUpdate.set(relpath(this.path, node.path), node) } #updateWaitingNode (loc) { const node = this.#awaitingUpdate.get(loc) this.#awaitingUpdate.delete(loc) this.data.packages[loc] = Shrinkwrap.metaFromNode( node, this.path, this.resolveOptions) } commit () { if (this.tree) { if (this.yarnLock) { this.yarnLock.fromTree(this.tree) } const root = Shrinkwrap.metaFromNode( this.tree.target, this.path, this.resolveOptions) this.data.packages = {} if (Object.keys(root).length) { this.data.packages[''] = root } for (const node of this.tree.root.inventory.values()) { // only way this.tree is not root is if the root is a link to it if (node === this.tree || node.isRoot || node.location === '') { continue } const loc = relpath(this.path, node.path) this.data.packages[loc] = Shrinkwrap.metaFromNode( node, this.path, this.resolveOptions) } } else if (this.#awaitingUpdate.size > 0) { for (const loc of this.#awaitingUpdate.keys()) { this.#updateWaitingNode(loc) } } // if we haven't set it by now, use the default if (!this.lockfileVersion) { this.lockfileVersion = defaultLockfileVersion } this.data.lockfileVersion = this.lockfileVersion // hidden lockfiles don't include legacy metadata or a root entry if (this.hiddenLockfile) { delete this.data.packages[''] delete this.data.dependencies } else if (this.tree && this.lockfileVersion <= 3) { this.#buildLegacyLockfile(this.tree, this.data) } // lf version 1 = dependencies only // lf version 2 = dependencies and packages // lf version 3 = packages only if (this.lockfileVersion >= 3) { const { dependencies, ...data } = this.data return data } else if (this.lockfileVersion < 2) { const { packages, ...data } = this.data return data } else { return { ...this.data } } } #buildLegacyLockfile (node, lock, path = []) { if (node === this.tree) { // the root node lock.name = node.packageName || node.name if (node.version) { lock.version = node.version } } // npm v6 and before tracked 'from', meaning "the request that led // to this package being installed". However, that's inherently // racey and non-deterministic in a world where deps are deduped // ahead of fetch time. In order to maintain backwards compatibility // with v6 in the lockfile, we do this trick where we pick a valid // dep link out of the edgesIn set. Choose the edge with the fewest // number of `node_modules` sections in the requestor path, and then // lexically sort afterwards. const edge = [...node.edgesIn].filter(e => e.valid).sort((a, b) => { const aloc = a.from.location.split('node_modules') const bloc = b.from.location.split('node_modules') /* istanbul ignore next - sort calling order is indeterminate */ if (aloc.length > bloc.length) { return 1 } if (bloc.length > aloc.length) { return -1 } return localeCompare(aloc[aloc.length - 1], bloc[bloc.length - 1]) })[0] const res = consistentResolve(node.resolved, this.path, this.path, true) const rSpec = specFromResolved(res) // if we don't have anything (ie, it's extraneous) then use the resolved // value as if that was where we got it from, since at least it's true. // if we don't have either, just an empty object so nothing matches below. // This will effectively just save the version and resolved, as if it's // a standard version/range dep, which is a reasonable default. let spec = rSpec if (edge) { spec = npa.resolve(node.name, edge.spec, edge.from.realpath) } if (node.isLink) { lock.version = `file:${relpath(this.path, node.realpath).replace(/#/g, '%23')}` } else if (spec && (spec.type === 'file' || spec.type === 'remote')) { lock.version = spec.saveSpec } else if (spec && spec.type === 'git' || rSpec.type === 'git') { lock.version = node.resolved /* istanbul ignore else - don't think there are any cases where a git * spec (or indeed, ANY npa spec) doesn't have a .raw member */ if (spec.raw) { lock.from = spec.raw } } else if (!node.isRoot && node.package && node.packageName && node.packageName !== node.name) { lock.version = `npm:${node.packageName}@${node.version}` } else if (node.package && node.version) { lock.version = node.version } if (node.inDepBundle) { lock.bundled = true } // when we didn't resolve to git, file, or dir, and didn't request // git, file, dir, or remote, then the resolved value is necessary. if (node.resolved && !node.isLink && rSpec.type !== 'git' && rSpec.type !== 'file' && rSpec.type !== 'directory' && spec.type !== 'directory' && spec.type !== 'git' && spec.type !== 'file' && spec.type !== 'remote') { lock.resolved = overrideResolves(node.resolved, this.resolveOptions) } if (node.integrity) { lock.integrity = node.integrity } if (node.extraneous) { lock.extraneous = true } else if (!node.isLink) { if (node.peer) { lock.peer = true } if (node.devOptional && !node.dev && !node.optional) { lock.devOptional = true } if (node.dev) { lock.dev = true } if (node.optional) { lock.optional = true } } const depender = node.target if (depender.edgesOut.size > 0) { if (node !== this.tree) { const entries = [...depender.edgesOut.entries()] lock.requires = entries.reduce((set, [k, v]) => { // omit peer deps from legacy lockfile requires field, because // npm v6 doesn't handle peer deps, and this triggers some bad // behavior if the dep can't be found in the dependencies list. const { spec, peer } = v if (peer) { return set } if (spec.startsWith('file:')) { // turn absolute file: paths into relative paths from the node // this especially shows up with workspace edges when the root // node is also a workspace in the set. const p = resolve(node.realpath, spec.slice('file:'.length)) set[k] = `file:${relpath(node.realpath, p).replace(/#/g, '%23')}` } else { set[k] = spec } return set }, {}) } else { lock.requires = true } } // now we walk the children, putting them in the 'dependencies' object const { children } = node.target if (!children.size) { delete lock.dependencies } else { const kidPath = [...path, node.realpath] const dependencies = {} // skip any that are already in the descent path, so cyclical link // dependencies don't blow up with ELOOP. let found = false for (const [name, kid] of children.entries()) { if (path.includes(kid.realpath)) { continue } dependencies[name] = this.#buildLegacyLockfile(kid, {}, kidPath) found = true } if (found) { lock.dependencies = dependencies } } return lock } toJSON () { if (!this.data) { throw new Error('run load() before getting or setting data') } return this.commit() } toString (options = {}) { const data = this.toJSON() const { format = true } = options const defaultIndent = this.indent || 2 const indent = format === true ? defaultIndent : format || 0 const eol = format ? this.newline || '\n' : '' return stringify(data, swKeyOrder, indent).replace(/\n/g, eol) } save (options = {}) { if (!this.data) { throw new Error('run load() before saving data') } // This must be called before the lockfile conversion check below since it sets properties as part of `commit()` const json = this.toString(options) if ( !this.hiddenLockfile && this.originalLockfileVersion !== undefined && this.originalLockfileVersion !== this.lockfileVersion ) { log.warn( 'shrinkwrap', `Converting lock file (${relative(process.cwd(), this.filename)}) from v${this.originalLockfileVersion} -> v${this.lockfileVersion}` ) } return Promise.all([ writeFile(this.filename, json).catch(er => { if (this.hiddenLockfile) { // well, we did our best. // if we reify, and there's nothing there, then it might be lacking // a node_modules folder, but then the lockfile is not important. // Remove the file, so that in case there WERE deps, but we just // failed to update the file for some reason, it's not out of sync. return rm(this.filename, { recursive: true, force: true }) } throw er }), this.yarnLock && this.yarnLock.entries.size && writeFile(this.path + '/yarn.lock', this.yarnLock.toString()), ]) } } module.exports = Shrinkwrap const signals = require('./signals.js') // for testing, expose the process being used module.exports = Object.assign(fn => setup(fn), { process }) // do all of this in a setup function so that we can call it // multiple times for multiple reifies that might be going on. // Otherwise, Arborist.reify() is a global action, which is a // new constraint we'd be adding with this behavior. const setup = fn => { const { process } = module.exports const sigListeners = { loaded: false } const unload = () => { if (!sigListeners.loaded) { return } for (const sig of signals) { try { process.removeListener(sig, sigListeners[sig]) } catch { // ignore errors } } process.removeListener('beforeExit', onBeforeExit) sigListeners.loaded = false } const onBeforeExit = () => { // this trick ensures that we exit with the same signal we caught // Ie, if you press ^C and npm gets a SIGINT, we'll do the rollback // and then exit with a SIGINT signal once we've removed the handler. // The timeout is there because signals are asynchronous, so we need // the process to NOT exit on its own, which means we have to have // something keeping the event loop looping. Hence this hack. unload() process.kill(process.pid, signalReceived) setTimeout(() => {}, 500) } let signalReceived = null const listener = (sig, fn) => () => { signalReceived = sig // if we exit normally, but caught a signal which would have been fatal, // then re-send it once we're done with whatever cleanup we have to do. unload() if (process.listeners(sig).length < 1) { process.once('beforeExit', onBeforeExit) } fn({ signal: sig }) } // do the actual loading here for (const sig of signals) { sigListeners[sig] = listener(sig, fn) const max = process.getMaxListeners() try { // if we call this a bunch of times, avoid triggering the warning const { length } = process.listeners(sig) if (length >= max) { process.setMaxListeners(length + 1) } process.on(sig, sigListeners[sig]) } catch { // ignore errors } } sigListeners.loaded = true return unload } // copied from signal-exit // This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't bother with SIGKILL. It's uncatchable, which // means that we can't fire any callbacks anyway. // // If a user does happen to register a handler on a non- // fatal signal like SIGWINCH or something, and then // exit, it'll end up firing `process.emit('exit')`, so // the handler will be fired anyway. // // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised // artificially, inherently leave the process in a // state from which it is not safe to try and enter JS // listeners. const platform = global.__ARBORIST_FAKE_PLATFORM__ || process.platform module.exports = [ 'SIGABRT', 'SIGALRM', 'SIGHUP', 'SIGINT', 'SIGTERM', ] if (platform !== 'win32') { module.exports.push( 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ) } if (platform === 'linux') { module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ) } const npa = require('npm-package-arg') // extracted from npm v6 lib/install/realize-shrinkwrap-specifier.js const specFromLock = (name, lock, where) => { try { if (lock.version) { const spec = npa.resolve(name, lock.version, where) if (lock.integrity || spec.type === 'git') { return spec } } if (lock.from) { // legacy metadata includes "from", but not integrity const spec = npa.resolve(name, lock.from, where) if (spec.registry && lock.version) { return npa.resolve(name, lock.version, where) } else if (!lock.resolved) { return spec } } if (lock.resolved) { return npa.resolve(name, lock.resolved, where) } } catch { // ignore errors } try { return npa.resolve(name, lock.version, where) } catch { return {} } } module.exports = specFromLock const proggy = require('proggy') module.exports = cls => class Tracker extends cls { #progress = new Map() #createTracker (key, name) { const tracker = new proggy.Tracker(name ?? key) tracker.on('done', () => this.#progress.delete(key)) this.#progress.set(key, tracker) } addTracker (section, subsection = null, key = null) { if (section === null || section === undefined) { this.#onError(`Tracker can't be null or undefined`) } if (key === null) { key = subsection } const hasTracker = this.#progress.has(section) const hasSubtracker = this.#progress.has(`${section}:${key}`) if (hasTracker && subsection === null) { // 0. existing tracker, no subsection this.#onError(`Tracker "${section}" already exists`) } else if (!hasTracker && subsection === null) { // 1. no existing tracker, no subsection // Create a new progress tracker this.#createTracker(section) } else if (!hasTracker && subsection !== null) { // 2. no parent tracker and subsection this.#onError(`Parent tracker "${section}" does not exist`) } else if (!hasTracker || !hasSubtracker) { // 3. existing parent tracker, no subsection tracker // Create a new subtracker and update parents const parentTracker = this.#progress.get(section) parentTracker.update(parentTracker.value, parentTracker.total + 1) this.#createTracker(`${section}:${key}`, `${section}:${subsection}`) } // 4. existing parent tracker, existing subsection tracker // skip it } finishTracker (section, subsection = null, key = null) { if (section === null || section === undefined) { this.#onError(`Tracker can't be null or undefined`) } if (key === null) { key = subsection } const hasTracker = this.#progress.has(section) const hasSubtracker = this.#progress.has(`${section}:${key}`) // 0. parent tracker exists, no subsection // Finish parent tracker and remove from this.#progress if (hasTracker && subsection === null) { // check if parent tracker does // not have any remaining children const keys = this.#progress.keys() for (const key of keys) { if (key.match(new RegExp(section + ':'))) { this.finishTracker(section, key) } } // remove parent tracker this.#progress.get(section).finish() } else if (!hasTracker && subsection === null) { // 1. no existing parent tracker, no subsection this.#onError(`Tracker "${section}" does not exist`) } else if (!hasTracker || hasSubtracker) { // 2. subtracker exists // Finish subtracker and remove from this.#progress const parentTracker = this.#progress.get(section) parentTracker.update(parentTracker.value + 1) this.#progress.get(`${section}:${key}`).finish() } // 3. existing parent tracker, no subsection } #onError (msg) { throw new Error(msg) } } const debug = require('./debug.js') const checkTree = (tree, checkUnreachable = true) => { const log = [['START TREE CHECK', tree.path]] // this can only happen in tests where we have a "tree" object // that isn't actually a tree. if (!tree.root || !tree.root.inventory) { return tree } const { inventory } = tree.root const seen = new Set() const check = (node, via = tree, viaType = 'self') => { log.push([ 'CHECK', node && node.location, via && via.location, viaType, 'seen=' + seen.has(node), 'promise=' + !!(node && node.then), 'root=' + !!(node && node.isRoot), ]) if (!node || seen.has(node) || node.then) { return } seen.add(node) if (node.isRoot && node !== tree.root) { throw Object.assign(new Error('double root'), { node: node.path, realpath: node.realpath, tree: tree.path, root: tree.root.path, via: via.path, viaType, log, }) } if (node.root !== tree.root) { throw Object.assign(new Error('node from other root in tree'), { node: node.path, realpath: node.realpath, tree: tree.path, root: tree.root.path, via: via.path, viaType, otherRoot: node.root && node.root.path, log, }) } if (!node.isRoot && node.inventory.size !== 0) { throw Object.assign(new Error('non-root has non-zero inventory'), { node: node.path, tree: tree.path, root: tree.root.path, via: via.path, viaType, inventory: [...node.inventory.values()].map(node => [node.path, node.location]), log, }) } if (!node.isRoot && !inventory.has(node) && !node.dummy) { throw Object.assign(new Error('not in inventory'), { node: node.path, tree: tree.path, root: tree.root.path, via: via.path, viaType, log, }) } const devEdges = [...node.edgesOut.values()].filter(e => e.dev) if (!node.isTop && devEdges.length) { throw Object.assign(new Error('dev edges on non-top node'), { node: node.path, tree: tree.path, root: tree.root.path, via: via.path, viaType, devEdges: devEdges.map(e => [e.type, e.name, e.spec, e.error]), log, }) } if (node.path === tree.root.path && node !== tree.root && !tree.root.isLink) { throw Object.assign(new Error('node with same path as root'), { node: node.path, tree: tree.path, root: tree.root.path, via: via.path, viaType, log, }) } if (!node.isLink && node.path !== node.realpath) { throw Object.assign(new Error('non-link with mismatched path/realpath'), { node: node.path, tree: tree.path, realpath: node.realpath, root: tree.root.path, via: via.path, viaType, log, }) } const { parent, fsParent, target } = node check(parent, node, 'parent') check(fsParent, node, 'fsParent') check(target, node, 'target') log.push(['CHILDREN', node.location, ...node.children.keys()]) for (const kid of node.children.values()) { check(kid, node, 'children') } for (const kid of node.fsChildren) { check(kid, node, 'fsChildren') } for (const link of node.linksIn) { check(link, node, 'linksIn') } for (const top of node.tops) { check(top, node, 'tops') } log.push(['DONE', node.location]) } check(tree) if (checkUnreachable) { for (const node of inventory.values()) { if (!seen.has(node) && node !== tree.root) { throw Object.assign(new Error('unreachable in inventory'), { node: node.path, realpath: node.realpath, location: node.location, root: tree.root.path, tree: tree.path, log, }) } } } return tree } // should only ever run this check in debug mode module.exports = tree => tree debug(() => module.exports = checkTree) const semver = require('semver') const { basename } = require('node:path') const { URL } = require('node:url') module.exports = (name, tgz) => { const base = basename(tgz) if (!base.endsWith('.tgz')) { return null } if (tgz.startsWith('http:/') || tgz.startsWith('https:/')) { const u = new URL(tgz) // registry url? check for most likely pattern. // either /@foo/bar/-/bar-1.2.3.tgz or // /foo/-/foo-1.2.3.tgz, and fall through to // basename checking. Note that registries can // be mounted below the root url, so /a/b/-/x/y/foo/-/foo-1.2.3.tgz // is a potential option. const tfsplit = u.pathname.slice(1).split('/-/') if (tfsplit.length > 1) { const afterTF = tfsplit.pop() if (afterTF === base) { const pre = tfsplit.pop() const preSplit = pre.split(/\/|%2f/i) const project = preSplit.pop() const scope = preSplit.pop() return versionFromBaseScopeName(base, scope, project) } } } const split = name.split(/\/|%2f/i) const project = split.pop() const scope = split.pop() return versionFromBaseScopeName(base, scope, project) } const versionFromBaseScopeName = (base, scope, name) => { if (!base.startsWith(name + '-')) { return null } const parsed = semver.parse(base.substring(name.length + 1, base.length - 4)) return parsed ? { name: scope && scope.charAt(0) === '@' ? `${scope}/${name}` : name, version: parsed.version, } : null } // An object representing a vulnerability either as the result of an // advisory or due to the package in question depending exclusively on // vulnerable versions of a dep. // // - name: package name // - range: Set of vulnerable versions // - nodes: Set of nodes affected // - effects: Set of vulns triggered by this one // - advisories: Set of advisories (including metavulns) causing this vuln. // All of the entries in via are vulnerability objects returned by // @npmcli/metavuln-calculator // - via: dependency vulns which cause this one const { satisfies, simplifyRange } = require('semver') const semverOpt = { loose: true, includePrerelease: true } const localeCompare = require('@isaacs/string-locale-compare')('en') const npa = require('npm-package-arg') const severities = new Map([ ['info', 0], [0, 'info'], ['low', 1], [1, 'low'], ['moderate', 2], [2, 'moderate'], ['high', 3], [3, 'high'], ['critical', 4], [4, 'critical'], [null, -1], [-1, null], ]) class Vuln { #range = null #simpleRange = null // assume a fix is available unless it hits a top node // that locks it in place, setting this false or {isSemVerMajor, version}. #fixAvailable = true constructor ({ name, advisory }) { this.name = name this.via = new Set() this.advisories = new Set() this.severity = null this.effects = new Set() this.topNodes = new Set() this.nodes = new Set() this.addAdvisory(advisory) this.packument = advisory.packument this.versions = advisory.versions } get fixAvailable () { return this.#fixAvailable } set fixAvailable (f) { this.#fixAvailable = f // if there's a fix available for this at the top level, it means that // it will also fix the vulns that led to it being there. to get there, // we set the vias to the most "strict" of fix availables. // - false: no fix is available // - {name, version, isSemVerMajor} fix requires -f, is semver major // - {name, version} fix requires -f, not semver major // - true: fix does not require -f // TODO: duped entries may require different fixes but the current // structure does not support this, so the case were a top level fix // corrects a duped entry may mean you have to run fix more than once for (const v of this.via) { // don't blow up on loops if (v.fixAvailable === f) { continue } if (f === false) { v.fixAvailable = f } else if (v.fixAvailable === true) { v.fixAvailable = f } else if (typeof f === 'object' && ( typeof v.fixAvailable !== 'object' || !v.fixAvailable.isSemVerMajor)) { v.fixAvailable = f } } } get isDirect () { for (const node of this.nodes.values()) { for (const edge of node.edgesIn) { if (edge.from.isProjectRoot || edge.from.isWorkspace) { return true } } } return false } testSpec (spec) { const specObj = npa(spec) if (!specObj.registry) { return true } if (specObj.subSpec) { spec = specObj.subSpec.rawSpec } for (const v of this.versions) { if (satisfies(v, spec) && !satisfies(v, this.range, semverOpt)) { return false } } return true } toJSON () { return { name: this.name, severity: this.severity, isDirect: this.isDirect, // just loop over the advisories, since via is only Vuln objects, // and calculated advisories have all the info we need via: [...this.advisories].map(v => v.type === 'metavuln' ? v.dependency : { ...v, versions: undefined, vulnerableVersions: undefined, id: undefined, }).sort((a, b) => localeCompare(String(a.source || a), String(b.source || b))), effects: [...this.effects].map(v => v.name).sort(localeCompare), range: this.simpleRange, nodes: [...this.nodes].map(n => n.location).sort(localeCompare), fixAvailable: this.#fixAvailable, } } addVia (v) { this.via.add(v) v.effects.add(this) // call the setter since we might add vias _after_ setting fixAvailable this.fixAvailable = this.fixAvailable } deleteVia (v) { this.via.delete(v) v.effects.delete(this) } deleteAdvisory (advisory) { this.advisories.delete(advisory) // make sure we have the max severity of all the vulns causing this one this.severity = null this.#range = null this.#simpleRange = null // refresh severity for (const advisory of this.advisories) { this.addAdvisory(advisory) } // remove any effects that are no longer relevant const vias = new Set([...this.advisories].map(a => a.dependency)) for (const via of this.via) { if (!vias.has(via.name)) { this.deleteVia(via) } } } addAdvisory (advisory) { this.advisories.add(advisory) const sev = severities.get(advisory.severity) this.#range = null this.#simpleRange = null if (sev > severities.get(this.severity)) { this.severity = advisory.severity } } get range () { if (!this.#range) { this.#range = [...this.advisories].map(v => v.range).join(' || ') } return this.#range } get simpleRange () { if (this.#simpleRange && this.#simpleRange === this.#range) { return this.#simpleRange } const versions = [...this.advisories][0].versions const range = this.range this.#simpleRange = simplifyRange(versions, range, semverOpt) this.#range = this.#simpleRange return this.#simpleRange } isVulnerable (node) { if (this.nodes.has(node)) { return true } const { version } = node.package if (!version) { return false } for (const v of this.advisories) { if (v.testVersion(version)) { this.nodes.add(node) return true } } return false } } module.exports = Vuln // parse a yarn lock file // basic format // // [, ...]: // // : // // // Assume that any key or value might be quoted, though that's only done // in practice if certain chars are in the string. When writing back, we follow // Yarn's rules for quoting, to cause minimal friction. // // The data format would support nested objects, but at this time, it // appears that yarn does not use that for anything, so in the interest // of a simpler parser algorithm, this implementation only supports a // single layer of sub objects. // // This doesn't deterministically define the shape of the tree, and so // cannot be used (on its own) for Arborist.loadVirtual. // But it can give us resolved, integrity, and version, which is useful // for Arborist.loadActual and for building the ideal tree. // // At the very least, when a yarn.lock file is present, we update it // along the way, and save it back in Shrinkwrap.save() // // NIHing this rather than using @yarnpkg/lockfile because that module // is an impenetrable 10kloc of webpack flow output, which is overkill // for something relatively simple and tailored to Arborist's use case. const localeCompare = require('@isaacs/string-locale-compare')('en') const consistentResolve = require('./consistent-resolve.js') const { dirname } = require('node:path') const { breadth } = require('treeverse') // Sort Yarn entries respecting the yarn.lock sort order const yarnEntryPriorities = { name: 1, version: 2, uid: 3, resolved: 4, integrity: 5, registry: 6, dependencies: 7, } const priorityThenLocaleCompare = (a, b) => { if (!yarnEntryPriorities[a] && !yarnEntryPriorities[b]) { return localeCompare(a, b) } /* istanbul ignore next */ return (yarnEntryPriorities[a] || 100) > (yarnEntryPriorities[b] || 100) ? 1 : -1 } const quoteIfNeeded = val => { if ( typeof val === 'boolean' || typeof val === 'number' || val.startsWith('true') || val.startsWith('false') || /[:\s\n\\",[\]]/g.test(val) || !/^[a-zA-Z]/g.test(val) ) { return JSON.stringify(val) } return val } // sort a key/value object into a string of JSON stringified keys and vals const sortKV = obj => Object.keys(obj) .sort(localeCompare) .map(k => ` ${quoteIfNeeded(k)} ${quoteIfNeeded(obj[k])}`) .join('\n') // for checking against previous entries const match = (p, n) => p.integrity && n.integrity ? p.integrity === n.integrity : p.resolved && n.resolved ? p.resolved === n.resolved : p.version && n.version ? p.version === n.version : true const prefix = `# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 ` const nullSymbol = Symbol('null') class YarnLock { static parse (data) { return new YarnLock().parse(data) } static fromTree (tree) { return new YarnLock().fromTree(tree) } constructor () { this.entries = null this.endCurrent() } endCurrent () { this.current = null this.subkey = nullSymbol } parse (data) { const ENTRY_START = /^[^\s].*:$/ const SUBKEY = /^ {2}[^\s]+:$/ const SUBVAL = /^ {4}[^\s]+ .+$/ const METADATA = /^ {2}[^\s]+ .+$/ this.entries = new Map() this.current = null const linere = /([^\r\n]*)\r?\n/gm let match let lineNum = 0 if (!/\n$/.test(data)) { data += '\n' } while (match = linere.exec(data)) { const line = match[1] lineNum++ if (line.charAt(0) === '#') { continue } if (line === '') { this.endCurrent() continue } if (ENTRY_START.test(line)) { this.endCurrent() const specs = this.splitQuoted(line.slice(0, -1), /, */) this.current = new YarnLockEntry(specs) specs.forEach(spec => this.entries.set(spec, this.current)) continue } if (SUBKEY.test(line)) { this.subkey = line.slice(2, -1) this.current[this.subkey] = {} continue } if (SUBVAL.test(line) && this.current && this.current[this.subkey]) { const subval = this.splitQuoted(line.trimLeft(), ' ') if (subval.length === 2) { this.current[this.subkey][subval[0]] = subval[1] continue } } // any other metadata if (METADATA.test(line) && this.current) { const metadata = this.splitQuoted(line.trimLeft(), ' ') if (metadata.length === 2) { // strip off the legacy shasum hashes if (metadata[0] === 'resolved') { metadata[1] = metadata[1].replace(/#.*/, '') } this.current[metadata[0]] = metadata[1] continue } } throw Object.assign(new Error('invalid or corrupted yarn.lock file'), { position: match.index, content: match[0], line: lineNum, }) } this.endCurrent() return this } splitQuoted (str, delim) { // a,"b,c",d"e,f => ['a','"b','c"','d"e','f'] => ['a','b,c','d"e','f'] const split = str.split(delim) const out = [] let o = 0 for (let i = 0; i < split.length; i++) { const chunk = split[i] if (/^".*"$/.test(chunk)) { out[o++] = chunk.trim().slice(1, -1) } else if (/^"/.test(chunk)) { let collect = chunk.trimLeft().slice(1) while (++i < split.length) { const n = split[i] // something that is not a slash, followed by an even number // of slashes then a " then end => ending on an unescaped " if (/[^\\](\\\\)*"$/.test(n)) { collect += n.trimRight().slice(0, -1) break } else { collect += n } } out[o++] = collect } else { out[o++] = chunk.trim() } } return out } toString () { return prefix + [...new Set([...this.entries.values()])] .map(e => e.toString()) .sort((a, b) => localeCompare(a.replace(/"/g, ''), b.replace(/"/g, ''))).join('\n\n') + '\n' } fromTree (tree) { this.entries = new Map() // walk the tree in a deterministic order, breadth-first, alphabetical breadth({ tree, visit: node => this.addEntryFromNode(node), getChildren: node => [...node.children.values(), ...node.fsChildren] .sort((a, b) => a.depth - b.depth || localeCompare(a.name, b.name)), }) return this } addEntryFromNode (node) { const specs = [...node.edgesIn] .map(e => `${node.name}@${e.spec}`) .sort(localeCompare) // Note: // yarn will do excessive duplication in a case like this: // root -> (x@1.x, y@1.x, z@1.x) // y@1.x -> (x@1.1, z@2.x) // z@1.x -> () // z@2.x -> (x@1.x) // // where x@1.2 exists, because the "x@1.x" spec will *always* resolve // to x@1.2, which doesn't work for y's dep on x@1.1, so you'll get this: // // root // +-- x@1.2.0 // +-- y // | +-- x@1.1.0 // | +-- z@2 // | +-- x@1.2.0 // +-- z@1 // // instead of this more deduped tree that arborist builds by default: // // root // +-- x@1.2.0 (dep is x@1.x, from root) // +-- y // | +-- x@1.1.0 // | +-- z@2 (dep on x@1.x deduped to x@1.1.0 under y) // +-- z@1 // // In order to not create an invalid yarn.lock file with conflicting // entries, AND not tell yarn to create an invalid tree, we need to // ignore the x@1.x spec coming from z, since it's already in the entries. // // So, if the integrity and resolved don't match a previous entry, skip it. // We call this method on shallower nodes first, so this is fine. const n = this.entryDataFromNode(node) let priorEntry = null const newSpecs = [] for (const s of specs) { const prev = this.entries.get(s) // no previous entry for this spec at all, so it's new if (!prev) { // if we saw a match already, then assign this spec to it as well if (priorEntry) { priorEntry.addSpec(s) } else { newSpecs.push(s) } continue } const m = match(prev, n) // there was a prior entry, but a different thing. skip this one if (!m) { continue } // previous matches, but first time seeing it, so already has this spec. // go ahead and add all the previously unseen specs, though if (!priorEntry) { priorEntry = prev for (const s of newSpecs) { priorEntry.addSpec(s) this.entries.set(s, priorEntry) } newSpecs.length = 0 continue } // have a prior entry matching n, and matching the prev we just saw // add the spec to it priorEntry.addSpec(s) this.entries.set(s, priorEntry) } // if we never found a matching prior, then this is a whole new thing if (!priorEntry) { const entry = Object.assign(new YarnLockEntry(newSpecs), n) for (const s of newSpecs) { this.entries.set(s, entry) } } else { // pick up any new info that we got for this node, so that we can // decorate with integrity/resolved/etc. Object.assign(priorEntry, n) } } entryDataFromNode (node) { const n = {} if (node.package.dependencies) { n.dependencies = node.package.dependencies } if (node.package.optionalDependencies) { n.optionalDependencies = node.package.optionalDependencies } if (node.version) { n.version = node.version } if (node.resolved) { n.resolved = consistentResolve( node.resolved, node.isLink ? dirname(node.path) : node.path, node.root.path, true ) } if (node.integrity) { n.integrity = node.integrity } return n } static get Entry () { return YarnLockEntry } } class YarnLockEntry { #specs constructor (specs) { this.#specs = new Set(specs) this.resolved = null this.version = null this.integrity = null this.dependencies = null this.optionalDependencies = null } toString () { // sort objects to the bottom, then alphabetical return ([...this.#specs] .sort(localeCompare) .map(quoteIfNeeded).join(', ') + ':\n' + Object.getOwnPropertyNames(this) .filter(prop => this[prop] !== null) .sort(priorityThenLocaleCompare) .map(prop => typeof this[prop] !== 'object' ? ` ${prop} ${prop === 'integrity' ? this[prop] : JSON.stringify(this[prop])}\n` : Object.keys(this[prop]).length === 0 ? '' : ` ${prop}:\n` + sortKV(this[prop]) + '\n') .join('')).trim() } addSpec (spec) { this.#specs.add(spec) } } module.exports = YarnLock { "name": "@npmcli/arborist", "version": "9.0.0", "description": "Manage node_modules trees", "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/fs": "^4.0.0", "@npmcli/installed-package-contents": "^3.0.0", "@npmcli/map-workspaces": "^4.0.1", "@npmcli/metavuln-calculator": "^9.0.0", "@npmcli/name-from-folder": "^3.0.0", "@npmcli/node-gyp": "^4.0.0", "@npmcli/package-json": "^6.0.1", "@npmcli/query": "^4.0.0", "@npmcli/redact": "^3.0.0", "@npmcli/run-script": "^9.0.1", "bin-links": "^5.0.0", "cacache": "^19.0.1", "common-ancestor-path": "^1.0.1", "hosted-git-info": "^8.0.0", "json-stringify-nice": "^1.1.4", "lru-cache": "^10.2.2", "minimatch": "^9.0.4", "nopt": "^8.0.0", "npm-install-checks": "^7.1.0", "npm-package-arg": "^12.0.0", "npm-pick-manifest": "^10.0.0", "npm-registry-fetch": "^18.0.1", "pacote": "^21.0.0", "parse-conflict-json": "^4.0.0", "proc-log": "^5.0.0", "proggy": "^3.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", "read-package-json-fast": "^4.0.0", "semver": "^7.3.7", "ssri": "^12.0.0", "treeverse": "^3.0.0", "walk-up-path": "^4.0.0" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", "@npmcli/template-oss": "4.23.6", "benchmark": "^2.1.4", "minify-registry-metadata": "^4.0.0", "nock": "^13.3.3", "tap": "^16.3.8", "tar-stream": "^3.0.0", "tcompare": "^5.0.6" }, "scripts": { "test": "tap", "posttest": "npm run lint", "snap": "tap", "test-proxy": "ARBORIST_TEST_PROXY=1 tap --snapshot", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "benchmark": "node scripts/benchmark.js", "benchclean": "rm -rf scripts/benchmark/*/", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/arborist" }, "author": "GitHub Inc.", "license": "ISC", "files": [ "bin/", "lib/" ], "main": "lib/index.js", "bin": { "arborist": "bin/index.js" }, "tap": { "after": "test/fixtures/cleanup.js", "test-env": [ "LC_ALL=sk" ], "timeout": "720", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" } } The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # `@npmcli/config` Configuration management for the npm cli. This module is the spiritual descendant of [`npmconf`](http://npm.im/npmconf), and the code that once lived in npm's `lib/config/` folder. It does the management of configuration files that npm uses, but importantly, does _not_ define all the configuration defaults or types, as those parts make more sense to live within the npm CLI itself. The only exceptions: - The `prefix` config value has some special semantics, setting the local prefix if specified on the CLI options and not in global mode, or the global prefix otherwise. - The `project` config file is loaded based on the local prefix (which can only be set by the CLI config options, and otherwise defaults to a walk up the folder tree to the first parent containing a `node_modules` folder, `package.json` file, or `package-lock.json` file.) - The `userconfig` value, as set by the environment and CLI (defaulting to `~/.npmrc`, is used to load user configs. - The `globalconfig` value, as set by the environment, CLI, and `userconfig` file (defaulting to `$PREFIX/etc/npmrc`) is used to load global configs. - A `builtin` config, read from a `npmrc` file in the root of the npm project itself, overrides all defaults. The resulting hierarchy of configs: - CLI switches. eg `--some-key=some-value` on the command line. These are parsed by [`nopt`](http://npm.im/nopt), which is not a great choice, but it's the one that npm has used forever, and changing it will be difficult. - Environment variables. eg `npm_config_some_key=some_value` in the environment. There is no way at this time to modify this prefix. - INI-formatted project configs. eg `some-key = some-value` in the `localPrefix` folder (ie, the `cwd`, or its nearest parent that contains either a `node_modules` folder or `package.json` file.) - INI-formatted userconfig file. eg `some-key = some-value` in `~/.npmrc`. The `userconfig` config value can be overridden by the `cli`, `env`, or `project` configs to change this value. - INI-formatted globalconfig file. eg `some-key = some-value` in the `globalPrefix` folder, which is inferred by looking at the location of the node executable, or the `prefix` setting in the `cli`, `env`, `project`, or `userconfig`. The `globalconfig` value at any of those levels can override this. - INI-formatted builtin config file. eg `some-key = some-value` in `/usr/local/lib/node_modules/npm/npmrc`. This is not configurable, and is determined by looking in the `npmPath` folder. - Default values (passed in by npm when it loads this module). ## USAGE ```js const Config = require('@npmcli/config') const { shorthands, definitions, flatten } = require('@npmcli/config/lib/definitions') const conf = new Config({ // path to the npm module being run npmPath: resolve(__dirname, '..'), definitions, shorthands, flatten, // optional, defaults to process.argv // argv: [] <- if you are using this package in your own cli // and dont want to have colliding argv argv: process.argv, // optional, defaults to process.env env: process.env, // optional, defaults to process.execPath execPath: process.execPath, // optional, defaults to process.platform platform: process.platform, // optional, defaults to process.cwd() cwd: process.cwd(), }) // emits log events on the process object // see `proc-log` for more info process.on('log', (level, ...args) => { console.log(level, ...args) }) // returns a promise that fails if config loading fails, and // resolves when the config object is ready for action conf.load().then(() => { conf.validate() console.log('loaded ok! some-key = ' + conf.get('some-key')) }).catch(er => { console.error('error loading configs!', er) }) ``` ## API The `Config` class is the sole export. ```js const Config = require('@npmcli/config') ``` ### static `Config.typeDefs` The type definitions passed to `nopt` for CLI option parsing and known configuration validation. ### constructor `new Config(options)` Options: - `types` Types of all known config values. Note that some are effectively given semantic value in the config loading process itself. - `shorthands` An object mapping a shorthand value to an array of CLI arguments that replace it. - `defaults` Default values for each of the known configuration keys. These should be defined for all configs given a type, and must be valid. - `npmPath` The path to the `npm` module, for loading the `builtin` config file. - `cwd` Optional, defaults to `process.cwd()`, used for inferring the `localPrefix` and loading the `project` config. - `platform` Optional, defaults to `process.platform`. Used when inferring the `globalPrefix` from the `execPath`, since this is done diferently on Windows. - `execPath` Optional, defaults to `process.execPath`. Used to infer the `globalPrefix`. - `env` Optional, defaults to `process.env`. Source of the environment variables for configuration. - `argv` Optional, defaults to `process.argv`. Source of the CLI options used for configuration. Returns a `config` object, which is not yet loaded. Fields: - `config.globalPrefix` The prefix for `global` operations. Set by the `prefix` config value, or defaults based on the location of the `execPath` option. - `config.localPrefix` The prefix for `local` operations. Set by the `prefix` config value on the CLI only, or defaults to either the `cwd` or its nearest ancestor containing a `node_modules` folder or `package.json` file. - `config.sources` A read-only `Map` of the file (or a comment, if no file found, or relevant) to the config level loaded from that source. - `config.data` A `Map` of config level to `ConfigData` objects. These objects should not be modified directly under any circumstances. - `source` The source where this data was loaded from. - `raw` The raw data used to generate this config data, as it was parsed initially from the environment, config file, or CLI options. - `data` The data object reflecting the inheritance of configs up to this point in the chain. - `loadError` Any errors encountered that prevented the loading of this config data. - `config.list` A list sorted in priority of all the config data objects in the prototype chain. `config.list[0]` is the `cli` level, `config.list[1]` is the `env` level, and so on. - `cwd` The `cwd` param - `env` The `env` param - `argv` The `argv` param - `execPath` The `execPath` param - `platform` The `platform` param - `defaults` The `defaults` param - `shorthands` The `shorthands` param - `types` The `types` param - `npmPath` The `npmPath` param - `globalPrefix` The effective `globalPrefix` - `localPrefix` The effective `localPrefix` - `prefix` If `config.get('global')` is true, then `globalPrefix`, otherwise `localPrefix` - `home` The user's home directory, found by looking at `env.HOME` or calling `os.homedir()`. - `loaded` A boolean indicating whether or not configs are loaded - `valid` A getter that returns `true` if all the config objects are valid. Any data objects that have been modified with `config.set(...)` will be re-evaluated when `config.valid` is read. ### `config.load()` Load configuration from the various sources of information. Returns a `Promise` that resolves when configuration is loaded, and fails if a fatal error is encountered. ### `config.find(key)` Find the effective place in the configuration levels a given key is set. Returns one of: `cli`, `env`, `project`, `user`, `global`, `builtin`, or `default`. Returns `null` if the key is not set. ### `config.get(key, where = 'cli')` Load the given key from the config stack. ### `config.set(key, value, where = 'cli')` Set the key to the specified value, at the specified level in the config stack. ### `config.delete(key, where = 'cli')` Delete the configuration key from the specified level in the config stack. ### `config.validate(where)` Verify that all known configuration options are set to valid values, and log a warning if they are invalid. Invalid auth options will cause this method to throw an error with a `code` property of `ERR_INVALID_AUTH`, and a `problems` property listing the specific concerns with the current configuration. If `where` is not set, then all config objects are validated. Returns `true` if all configs are valid. Note that it's usually enough (and more efficient) to just check `config.valid`, since each data object is marked for re-evaluation on every `config.set()` operation. ### `config.repair(problems)` Accept an optional array of problems (as thrown by `config.validate()`) and perform the necessary steps to resolve them. If no problems are provided, this method will call `config.validate()` internally to retrieve them. Note that you must `await config.save('user')` in order to persist the changes. ### `config.isDefault(key)` Returns `true` if the value is coming directly from the default definitions, if the current value for the key config is coming from any other source, returns `false`. This method can be used for avoiding or tweaking default values, e.g: > Given a global default definition of foo='foo' it's possible to read that > value such as: > > ```js > const save = config.get('foo') > ``` > > Now in a different place of your app it's possible to avoid using the `foo` > default value, by checking to see if the current config value is currently > one that was defined by the default definitions: > > ```js > const save = config.isDefault('foo') ? 'bar' : config.get('foo') > ``` ### `config.save(where)` Save the config file specified by the `where` param. Must be one of `project`, `user`, `global`, `builtin`. // class that describes a config key we know about // this keeps us from defining a config key and not // providing a default, description, etc. // // TODO: some kind of categorization system, so we can // say "these are for registry access", "these are for // version resolution" etc. const required = ['type', 'description', 'default', 'key'] const allowed = [ 'default', 'defaultDescription', 'deprecated', 'description', 'exclusive', 'flatten', 'hint', 'key', 'short', 'type', 'typeDescription', 'usage', 'envExport', ] const { semver: { type: semver }, Umask: { type: Umask }, url: { type: url }, path: { type: path }, } = require('../type-defs.js') class Definition { constructor (key, def) { this.key = key // if it's set falsey, don't export it, otherwise we do by default this.envExport = true Object.assign(this, def) this.validate() if (!this.defaultDescription) { this.defaultDescription = describeValue(this.default) } if (!this.typeDescription) { this.typeDescription = describeType(this.type) } // hint is only used for non-boolean values if (!this.hint) { if (this.type === Number) { this.hint = '' } else { this.hint = `<${this.key}>` } } if (!this.usage) { this.usage = describeUsage(this) } } validate () { for (const req of required) { if (!Object.prototype.hasOwnProperty.call(this, req)) { throw new Error(`config lacks ${req}: ${this.key}`) } } if (!this.key) { throw new Error(`config lacks key: ${this.key}`) } for (const field of Object.keys(this)) { if (!allowed.includes(field)) { throw new Error(`config defines unknown field ${field}: ${this.key}`) } } } // a textual description of this config, suitable for help output describe () { const description = unindent(this.description) const noEnvExport = this.envExport ? '' : ` This value is not exported to the environment for child processes. ` const deprecated = !this.deprecated ? '' : `* DEPRECATED: ${unindent(this.deprecated)}\n` /* eslint-disable-next-line max-len */ const exclusive = !this.exclusive ? '' : `\nThis config can not be used with: \`${this.exclusive.join('`, `')}\`` return wrapAll(`#### \`${this.key}\` * Default: ${unindent(this.defaultDescription)} * Type: ${unindent(this.typeDescription)} ${deprecated} ${description} ${exclusive} ${noEnvExport}`) } } const describeUsage = def => { let key = '' // Single type if (!Array.isArray(def.type)) { if (def.short) { key = `-${def.short}|` } if (def.type === Boolean && def.default !== false) { key = `${key}--no-${def.key}` } else { key = `${key}--${def.key}` } if (def.type !== Boolean) { key = `${key} ${def.hint}` } return key } key = `--${def.key}` if (def.short) { key = `-${def.short}|--${def.key}` } // Multiple types let types = def.type const multiple = types.includes(Array) const bool = types.includes(Boolean) // null type means optional and doesn't currently affect usage output since // all non-optional params have defaults so we render everything as optional types = types.filter(t => t !== null && t !== Array && t !== Boolean) if (!types.length) { return key } let description if (!types.some(t => typeof t !== 'string')) { // Specific values, use specifics given description = `<${types.filter(d => d).join('|')}>` } else { // Generic values, use hint description = def.hint } if (bool) { // Currently none of our multi-type configs with boolean values default to // false so all their hints should show `--no-`, if we ever add ones that // default to false we can branch the logic here key = `--no-${def.key}|${key}` } const usage = `${key} ${description}` if (multiple) { return `${usage} [${usage} ...]` } else { return usage } } const describeType = type => { if (Array.isArray(type)) { const descriptions = type.filter(t => t !== Array).map(t => describeType(t)) // [a] => "a" // [a, b] => "a or b" // [a, b, c] => "a, b, or c" // [a, Array] => "a (can be set multiple times)" // [a, Array, b] => "a or b (can be set multiple times)" const last = descriptions.length > 1 ? [descriptions.pop()] : [] const oxford = descriptions.length > 1 ? ', or ' : ' or ' const words = [descriptions.join(', ')].concat(last).join(oxford) const multiple = type.includes(Array) ? ' (can be set multiple times)' : '' return `${words}${multiple}` } // Note: these are not quite the same as the description printed // when validation fails. In that case, we want to give the user // a bit more information to help them figure out what's wrong. switch (type) { case String: return 'String' case Number: return 'Number' case Umask: return 'Octal numeric string in range 0000..0777 (0..511)' case Boolean: return 'Boolean' case Date: return 'Date' case path: return 'Path' case semver: return 'SemVer string' case url: return 'URL' default: return describeValue(type) } } // if it's a string, quote it. otherwise, just cast to string. const describeValue = val => (typeof val === 'string' ? JSON.stringify(val) : String(val)) const unindent = s => { // get the first \n followed by a bunch of spaces, and pluck off // that many spaces from the start of every line. const match = s.match(/\n +/) return !match ? s.trim() : s.split(match[0]).join('\n').trim() } const wrap = s => { const cols = Math.min(Math.max(20, process.stdout.columns) || 80, 80) - 5 return unindent(s) .split(/[ \n]+/) .reduce((left, right) => { const last = left.split('\n').pop() const join = last.length && last.length + right.length > cols ? '\n' : ' ' return left + join + right }) } const wrapAll = s => { let inCodeBlock = false return s .split('\n\n') .map(block => { if (inCodeBlock || block.startsWith('```')) { inCodeBlock = !block.endsWith('```') return block } if (block.charAt(0) === '*') { return ( '* ' + block .slice(1) .trim() .split('\n* ') .map(li => { return wrap(li).replace(/\n/g, '\n ') }) .join('\n* ') ) } else { return wrap(block) } }) .join('\n\n') } module.exports = Definition const Definition = require('./definition.js') const ciInfo = require('ci-info') const querystring = require('node:querystring') const { join } = require('node:path') const isWindows = process.platform === 'win32' // used by cafile flattening to flatOptions.ca const { readFileSync } = require('node:fs') const maybeReadFile = file => { try { return readFileSync(file, 'utf8') } catch (er) { if (er.code !== 'ENOENT') { throw er } return null } } const buildOmitList = obj => { const include = obj.include || [] const omit = obj.omit || [] const only = obj.only if (/^prod(uction)?$/.test(only) || obj.production) { omit.push('dev') } else if (obj.production === false) { include.push('dev') } if (/^dev/.test(obj.also)) { include.push('dev') } if (obj.dev) { include.push('dev') } if (obj.optional === false) { omit.push('optional') } else if (obj.optional === true) { include.push('optional') } obj.omit = [...new Set(omit)].filter(type => !include.includes(type)) obj.include = [...new Set(include)] if (obj.omit.includes('dev')) { process.env.NODE_ENV = 'production' } return obj.omit } const editor = process.env.EDITOR || process.env.VISUAL || (isWindows ? `${process.env.SYSTEMROOT}\\notepad.exe` : 'vi') const shell = isWindows ? process.env.ComSpec || 'cmd' : process.env.SHELL || 'sh' const { networkInterfaces } = require('node:os') const getLocalAddresses = () => { try { return Object.values(networkInterfaces()).map( int => int.map(({ address }) => address) ).reduce((set, addrs) => set.concat(addrs), [null]) } catch (e) { return [null] } } const unicode = /UTF-?8$/i.test( process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG ) // use LOCALAPPDATA on Windows, if set // https://github.com/npm/cli/pull/899 const cacheRoot = (isWindows && process.env.LOCALAPPDATA) || '~' const cacheExtra = isWindows ? 'npm-cache' : '.npm' const cache = `${cacheRoot}/${cacheExtra}` // TODO: refactor these type definitions so that they are less // weird to pull out of the config module. // TODO: use better type definition/validation API, nopt's is so weird. const { semver: { type: Semver }, Umask: { type: Umask }, url: { type: url }, path: { type: path }, } = require('../type-defs.js') // basic flattening function, just copy it over camelCase const flatten = (key, obj, flatOptions) => { const camel = key.replace(/-([a-z])/g, (_0, _1) => _1.toUpperCase()) flatOptions[camel] = obj[key] } // TODO: // Instead of having each definition provide a flatten method, // provide the (?list of?) flat option field(s?) that it impacts. // When that config is set, we mark the relevant flatOption fields // dirty. Then, a getter for that field defines how we actually // set it. // // So, `save-dev`, `save-optional`, `save-prod`, et al would indicate // that they affect the `saveType` flat option. Then the config.flat // object has a `get saveType () { ... }` that looks at the "real" // config settings from files etc and returns the appropriate value. // // Getters will also (maybe?) give us a hook to audit flat option // usage, so we can document and group these more appropriately. // // This will be a problem with cases where we currently do: // const opts = { ...npm.flatOptions, foo: 'bar' }, but we can maybe // instead do `npm.config.set('foo', 'bar')` prior to passing the // config object down where it needs to go. // // This way, when we go hunting for "where does saveType come from anyway!?" // while fixing some Arborist bug, we won't have to hunt through too // many places. // XXX: We should really deprecate all these `--save-blah` switches // in favor of a single `--save-type` option. The unfortunate shortcut // we took for `--save-peer --save-optional` being `--save-type=peerOptional` // makes this tricky, and likely a breaking change. // Define all config keys we know about. They are indexed by their own key for // ease of lookup later. This duplication is an optimization so that we don't // have to do an extra function call just to "reuse" the key in both places. const definitions = { _auth: new Definition('_auth', { default: null, type: [null, String], description: ` A basic-auth string to use when authenticating against the npm registry. This will ONLY be used to authenticate against the npm registry. For other registries you will need to scope it like "//other-registry.tld/:_auth" Warning: This should generally not be set via a command-line option. It is safer to use a registry-provided authentication bearer token stored in the ~/.npmrc file by running \`npm login\`. `, flatten, }), access: new Definition('access', { default: null, defaultDescription: ` 'public' for new packages, existing packages it will not change the current level `, type: [null, 'restricted', 'public'], description: ` If you do not want your scoped package to be publicly viewable (and installable) set \`--access=restricted\`. Unscoped packages can not be set to \`restricted\`. Note: This defaults to not changing the current access level for existing packages. Specifying a value of \`restricted\` or \`public\` during publish will change the access for an existing package the same way that \`npm access set status\` would. `, flatten, }), all: new Definition('all', { default: false, type: Boolean, short: 'a', description: ` When running \`npm outdated\` and \`npm ls\`, setting \`--all\` will show all outdated or installed packages, rather than only those directly depended upon by the current project. `, flatten, }), 'allow-same-version': new Definition('allow-same-version', { default: false, type: Boolean, description: ` Prevents throwing an error when \`npm version\` is used to set the new version to the same value as the current version. `, flatten, }), also: new Definition('also', { default: null, type: [null, 'dev', 'development'], description: ` When set to \`dev\` or \`development\`, this is an alias for \`--include=dev\`. `, deprecated: 'Please use --include=dev instead.', flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), audit: new Definition('audit', { default: true, type: Boolean, description: ` When "true" submit audit reports alongside the current npm command to the default registry and all registries configured for scopes. See the documentation for [\`npm audit\`](/commands/npm-audit) for details on what is submitted. `, flatten, }), 'audit-level': new Definition('audit-level', { default: null, type: [null, 'info', 'low', 'moderate', 'high', 'critical', 'none'], description: ` The minimum level of vulnerability for \`npm audit\` to exit with a non-zero exit code. `, flatten, }), 'auth-type': new Definition('auth-type', { default: 'web', type: ['legacy', 'web'], description: ` What authentication strategy to use with \`login\`. Note that if an \`otp\` config is given, this value will always be set to \`legacy\`. `, flatten, }), before: new Definition('before', { default: null, type: [null, Date], description: ` If passed to \`npm install\`, will rebuild the npm tree such that only versions that were available **on or before** the \`--before\` time get installed. If there's no versions available for the current set of direct dependencies, the command will error. If the requested version is a \`dist-tag\` and the given tag does not pass the \`--before\` filter, the most recent version less than or equal to that tag will be used. For example, \`foo@latest\` might install \`foo@1.2\` even though \`latest\` is \`2.0\`. `, flatten, }), 'bin-links': new Definition('bin-links', { default: true, type: Boolean, description: ` Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package executables. Set to false to have it not do this. This can be used to work around the fact that some file systems don't support symlinks, even on ostensibly Unix systems. `, flatten, }), browser: new Definition('browser', { default: null, defaultDescription: ` OS X: \`"open"\`, Windows: \`"start"\`, Others: \`"xdg-open"\` `, type: [null, Boolean, String], description: ` The browser that is called by npm commands to open websites. Set to \`false\` to suppress browser behavior and instead print urls to terminal. Set to \`true\` to use default system URL opener. `, flatten, }), ca: new Definition('ca', { default: null, type: [null, String, Array], description: ` The Certificate Authority signing certificate that is trusted for SSL connections to the registry. Values should be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the string "\\n". For example: \`\`\`ini ca="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----" \`\`\` Set to \`null\` to only allow "known" registrars, or to a specific CA cert to trust only that specific signing authority. Multiple CAs can be trusted by specifying an array of certificates: \`\`\`ini ca[]="..." ca[]="..." \`\`\` See also the \`strict-ssl\` config. `, flatten, }), cache: new Definition('cache', { default: cache, defaultDescription: ` Windows: \`%LocalAppData%\\npm-cache\`, Posix: \`~/.npm\` `, type: path, description: ` The location of npm's cache directory. `, flatten (key, obj, flatOptions) { flatOptions.cache = join(obj.cache, '_cacache') flatOptions.npxCache = join(obj.cache, '_npx') flatOptions.tufCache = join(obj.cache, '_tuf') }, }), 'cache-max': new Definition('cache-max', { default: Infinity, type: Number, description: ` \`--cache-max=0\` is an alias for \`--prefer-online\` `, deprecated: ` This option has been deprecated in favor of \`--prefer-online\` `, flatten (key, obj, flatOptions) { if (obj[key] <= 0) { flatOptions.preferOnline = true } }, }), 'cache-min': new Definition('cache-min', { default: 0, type: Number, description: ` \`--cache-min=9999 (or bigger)\` is an alias for \`--prefer-offline\`. `, deprecated: ` This option has been deprecated in favor of \`--prefer-offline\`. `, flatten (key, obj, flatOptions) { if (obj[key] >= 9999) { flatOptions.preferOffline = true } }, }), cafile: new Definition('cafile', { default: null, type: path, description: ` A path to a file containing one or multiple Certificate Authority signing certificates. Similar to the \`ca\` setting, but allows for multiple CA's, as well as for the CA information to be stored in a file on disk. `, flatten (key, obj, flatOptions) { // always set to null in defaults if (!obj.cafile) { return } const raw = maybeReadFile(obj.cafile) if (!raw) { return } const delim = '-----END CERTIFICATE-----' flatOptions.ca = raw.replace(/\r\n/g, '\n').split(delim) .filter(section => section.trim()) .map(section => section.trimLeft() + delim) }, }), call: new Definition('call', { default: '', type: String, short: 'c', description: ` Optional companion option for \`npm exec\`, \`npx\` that allows for specifying a custom command to be run along with the installed packages. \`\`\`bash npm exec --package yo --package generator-node --call "yo node" \`\`\` `, flatten, }), cert: new Definition('cert', { default: null, type: [null, String], description: ` A client certificate to pass when accessing the registry. Values should be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the string "\\n". For example: \`\`\`ini cert="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----" \`\`\` It is _not_ the path to a certificate file, though you can set a registry-scoped "cafile" path like "//other-registry.tld/:cafile=/path/to/cert.pem". `, deprecated: ` \`key\` and \`cert\` are no longer used for most registry operations. Use registry scoped \`keyfile\` and \`cafile\` instead. Example: //other-registry.tld/:keyfile=/path/to/key.pem //other-registry.tld/:cafile=/path/to/cert.crt `, flatten, }), cidr: new Definition('cidr', { default: null, type: [null, String, Array], description: ` This is a list of CIDR address to be used when configuring limited access tokens with the \`npm token create\` command. `, flatten, }), // This should never be directly used, the flattened value is the derived value // and is sent to other modules, and is also exposed as `npm.color` for use // inside npm itself. color: new Definition('color', { default: !process.env.NO_COLOR || process.env.NO_COLOR === '0', usage: '--color|--no-color|--color always', defaultDescription: ` true unless the NO_COLOR environ is set to something other than '0' `, type: ['always', Boolean], description: ` If false, never shows colors. If \`"always"\` then always shows colors. If true, then only prints color codes for tty file descriptors. `, flatten (key, obj, flatOptions) { flatOptions.color = !obj.color ? false : obj.color === 'always' ? true : !!process.stdout.isTTY flatOptions.logColor = !obj.color ? false : obj.color === 'always' ? true : !!process.stderr.isTTY }, }), 'commit-hooks': new Definition('commit-hooks', { default: true, type: Boolean, description: ` Run git commit hooks when using the \`npm version\` command. `, flatten, }), cpu: new Definition('cpu', { default: null, type: [null, String], description: ` Override CPU architecture of native modules to install. Acceptable values are same as \`cpu\` field of package.json, which comes from \`process.arch\`. `, flatten, }), depth: new Definition('depth', { default: null, defaultDescription: ` \`Infinity\` if \`--all\` is set, otherwise \`0\` `, type: [null, Number], description: ` The depth to go when recursing packages for \`npm ls\`. If not set, \`npm ls\` will show only the immediate dependencies of the root project. If \`--all\` is set, then npm will show all dependencies by default. `, flatten, }), description: new Definition('description', { default: true, type: Boolean, usage: '--no-description', description: ` Show the description in \`npm search\` `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || { limit: 20 } flatOptions.search[key] = obj[key] }, }), dev: new Definition('dev', { default: false, type: Boolean, description: ` Alias for \`--include=dev\`. `, deprecated: 'Please use --include=dev instead.', flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), diff: new Definition('diff', { default: [], hint: '', type: [String, Array], description: ` Define arguments to compare in \`npm diff\`. `, flatten, }), 'diff-ignore-all-space': new Definition('diff-ignore-all-space', { default: false, type: Boolean, description: ` Ignore whitespace when comparing lines in \`npm diff\`. `, flatten, }), 'diff-name-only': new Definition('diff-name-only', { default: false, type: Boolean, description: ` Prints only filenames when using \`npm diff\`. `, flatten, }), 'diff-no-prefix': new Definition('diff-no-prefix', { default: false, type: Boolean, description: ` Do not show any source or destination prefix in \`npm diff\` output. Note: this causes \`npm diff\` to ignore the \`--diff-src-prefix\` and \`--diff-dst-prefix\` configs. `, flatten, }), 'diff-dst-prefix': new Definition('diff-dst-prefix', { default: 'b/', hint: '', type: String, description: ` Destination prefix to be used in \`npm diff\` output. `, flatten, }), 'diff-src-prefix': new Definition('diff-src-prefix', { default: 'a/', hint: '', type: String, description: ` Source prefix to be used in \`npm diff\` output. `, flatten, }), 'diff-text': new Definition('diff-text', { default: false, type: Boolean, description: ` Treat all files as text in \`npm diff\`. `, flatten, }), 'diff-unified': new Definition('diff-unified', { default: 3, type: Number, description: ` The number of lines of context to print in \`npm diff\`. `, flatten, }), 'dry-run': new Definition('dry-run', { default: false, type: Boolean, description: ` Indicates that you don't want npm to make any changes and that it should only report what it would have done. This can be passed into any of the commands that modify your local installation, eg, \`install\`, \`update\`, \`dedupe\`, \`uninstall\`, as well as \`pack\` and \`publish\`. Note: This is NOT honored by other network related commands, eg \`dist-tags\`, \`owner\`, etc. `, flatten, }), editor: new Definition('editor', { default: editor, defaultDescription: ` The EDITOR or VISUAL environment variables, or '%SYSTEMROOT%\\notepad.exe' on Windows, or 'vi' on Unix systems `, type: String, description: ` The command to run for \`npm edit\` and \`npm config edit\`. `, flatten, }), 'engine-strict': new Definition('engine-strict', { default: false, type: Boolean, description: ` If set to true, then npm will stubbornly refuse to install (or even consider installing) any package that claims to not be compatible with the current Node.js version. This can be overridden by setting the \`--force\` flag. `, flatten, }), 'expect-result-count': new Definition('expect-result-count', { default: null, type: [null, Number], hint: '', exclusive: ['expect-results'], description: ` Tells to expect a specific number of results from the command. `, }), 'expect-results': new Definition('expect-results', { default: null, type: [null, Boolean], exclusive: ['expect-result-count'], description: ` Tells npm whether or not to expect results from the command. Can be either true (expect some results) or false (expect no results). `, }), 'fetch-retries': new Definition('fetch-retries', { default: 2, type: Number, description: ` The "retries" config for the \`retry\` module to use when fetching packages from the registry. npm will retry idempotent read requests to the registry in the case of network failures or 5xx HTTP errors. `, flatten (key, obj, flatOptions) { flatOptions.retry = flatOptions.retry || {} flatOptions.retry.retries = obj[key] }, }), 'fetch-retry-factor': new Definition('fetch-retry-factor', { default: 10, type: Number, description: ` The "factor" config for the \`retry\` module to use when fetching packages. `, flatten (key, obj, flatOptions) { flatOptions.retry = flatOptions.retry || {} flatOptions.retry.factor = obj[key] }, }), 'fetch-retry-maxtimeout': new Definition('fetch-retry-maxtimeout', { default: 60000, defaultDescription: '60000 (1 minute)', type: Number, description: ` The "maxTimeout" config for the \`retry\` module to use when fetching packages. `, flatten (key, obj, flatOptions) { flatOptions.retry = flatOptions.retry || {} flatOptions.retry.maxTimeout = obj[key] }, }), 'fetch-retry-mintimeout': new Definition('fetch-retry-mintimeout', { default: 10000, defaultDescription: '10000 (10 seconds)', type: Number, description: ` The "minTimeout" config for the \`retry\` module to use when fetching packages. `, flatten (key, obj, flatOptions) { flatOptions.retry = flatOptions.retry || {} flatOptions.retry.minTimeout = obj[key] }, }), 'fetch-timeout': new Definition('fetch-timeout', { default: 5 * 60 * 1000, defaultDescription: `${5 * 60 * 1000} (5 minutes)`, type: Number, description: ` The maximum amount of time to wait for HTTP requests to complete. `, flatten (key, obj, flatOptions) { flatOptions.timeout = obj[key] }, }), force: new Definition('force', { default: false, type: Boolean, short: 'f', description: ` Removes various protections against unfortunate side effects, common mistakes, unnecessary performance degradation, and malicious input. * Allow clobbering non-npm files in global installs. * Allow the \`npm version\` command to work on an unclean git repository. * Allow deleting the cache folder with \`npm cache clean\`. * Allow installing packages that have an \`engines\` declaration requiring a different version of npm. * Allow installing packages that have an \`engines\` declaration requiring a different version of \`node\`, even if \`--engine-strict\` is enabled. * Allow \`npm audit fix\` to install modules outside your stated dependency range (including SemVer-major changes). * Allow unpublishing all versions of a published package. * Allow conflicting peerDependencies to be installed in the root project. * Implicitly set \`--yes\` during \`npm init\`. * Allow clobbering existing values in \`npm pkg\` * Allow unpublishing of entire packages (not just a single version). If you don't have a clear idea of what you want to do, it is strongly recommended that you do not use this option! `, flatten, }), 'foreground-scripts': new Definition('foreground-scripts', { default: false, defaultDescription: `\`false\` unless when using \`npm pack\` or \`npm publish\` where it defaults to \`true\``, type: Boolean, description: ` Run all build scripts (ie, \`preinstall\`, \`install\`, and \`postinstall\`) scripts for installed packages in the foreground process, sharing standard input, output, and error with the main npm process. Note that this will generally make installs run slower, and be much noisier, but can be useful for debugging. `, flatten, }), 'format-package-lock': new Definition('format-package-lock', { default: true, type: Boolean, description: ` Format \`package-lock.json\` or \`npm-shrinkwrap.json\` as a human readable file. `, flatten, }), fund: new Definition('fund', { default: true, type: Boolean, description: ` When "true" displays the message at the end of each \`npm install\` acknowledging the number of dependencies looking for funding. See [\`npm fund\`](/commands/npm-fund) for details. `, flatten, }), git: new Definition('git', { default: 'git', type: String, description: ` The command to use for git commands. If git is installed on the computer, but is not in the \`PATH\`, then set this to the full path to the git binary. `, flatten, }), 'git-tag-version': new Definition('git-tag-version', { default: true, type: Boolean, description: ` Tag the commit when using the \`npm version\` command. Setting this to false results in no commit being made at all. `, flatten, }), global: new Definition('global', { default: false, type: Boolean, short: 'g', description: ` Operates in "global" mode, so that packages are installed into the \`prefix\` folder instead of the current working directory. See [folders](/configuring-npm/folders) for more on the differences in behavior. * packages are installed into the \`{prefix}/lib/node_modules\` folder, instead of the current working directory. * bin files are linked to \`{prefix}/bin\` * man pages are linked to \`{prefix}/share/man\` `, flatten: (key, obj, flatOptions) => { flatten(key, obj, flatOptions) if (flatOptions.global) { flatOptions.location = 'global' } }, }), // the globalconfig has its default defined outside of this module globalconfig: new Definition('globalconfig', { type: path, default: '', defaultDescription: ` The global --prefix setting plus 'etc/npmrc'. For example, '/usr/local/etc/npmrc' `, description: ` The config file to read for global config options. `, flatten, }), 'global-style': new Definition('global-style', { default: false, type: Boolean, description: ` Only install direct dependencies in the top level \`node_modules\`, but hoist on deeper dependencies. Sets \`--install-strategy=shallow\`. `, deprecated: ` This option has been deprecated in favor of \`--install-strategy=shallow\` `, flatten (key, obj, flatOptions) { if (obj[key]) { obj['install-strategy'] = 'shallow' flatOptions.installStrategy = 'shallow' } }, }), heading: new Definition('heading', { default: 'npm', type: String, description: ` The string that starts all the debugging log output. `, flatten, }), 'https-proxy': new Definition('https-proxy', { default: null, type: [null, url], description: ` A proxy to use for outgoing https requests. If the \`HTTPS_PROXY\` or \`https_proxy\` or \`HTTP_PROXY\` or \`http_proxy\` environment variables are set, proxy settings will be honored by the underlying \`make-fetch-happen\` library. `, flatten, }), 'if-present': new Definition('if-present', { default: false, type: Boolean, envExport: false, description: ` If true, npm will not exit with an error code when \`run-script\` is invoked for a script that isn't defined in the \`scripts\` section of \`package.json\`. This option can be used when it's desirable to optionally run a script when it's present and fail if the script fails. This is useful, for example, when running scripts that may only apply for some builds in an otherwise generic CI setup. `, flatten, }), 'ignore-scripts': new Definition('ignore-scripts', { default: false, type: Boolean, description: ` If true, npm does not run scripts specified in package.json files. Note that commands explicitly intended to run a particular script, such as \`npm start\`, \`npm stop\`, \`npm restart\`, \`npm test\`, and \`npm run-script\` will still run their intended script if \`ignore-scripts\` is set, but they will *not* run any pre- or post-scripts. `, flatten, }), include: new Definition('include', { default: [], type: [Array, 'prod', 'dev', 'optional', 'peer'], description: ` Option that allows for defining which types of dependencies to install. This is the inverse of \`--omit=\`. Dependency types specified in \`--include\` will not be omitted, regardless of the order in which omit/include are specified on the command-line. `, flatten (key, obj, flatOptions) { // just call the omit flattener, it reads from obj.include definitions.omit.flatten('omit', obj, flatOptions) }, }), 'include-staged': new Definition('include-staged', { default: false, type: Boolean, description: ` Allow installing "staged" published packages, as defined by [npm RFC PR #92](https://github.com/npm/rfcs/pull/92). This is experimental, and not implemented by the npm public registry. `, flatten, }), 'include-workspace-root': new Definition('include-workspace-root', { default: false, type: Boolean, envExport: false, description: ` Include the workspace root when workspaces are enabled for a command. When false, specifying individual workspaces via the \`workspace\` config, or all workspaces via the \`workspaces\` flag, will cause npm to operate only on the specified workspaces, and not on the root project. `, flatten, }), 'init-author-email': new Definition('init-author-email', { default: '', hint: '', type: String, description: ` The value \`npm init\` should use by default for the package author's email. `, }), 'init-author-name': new Definition('init-author-name', { default: '', hint: '', type: String, description: ` The value \`npm init\` should use by default for the package author's name. `, }), 'init-author-url': new Definition('init-author-url', { default: '', type: ['', url], hint: '', description: ` The value \`npm init\` should use by default for the package author's homepage. `, }), 'init-license': new Definition('init-license', { default: 'ISC', hint: '', type: String, description: ` The value \`npm init\` should use by default for the package license. `, }), 'init-module': new Definition('init-module', { default: '~/.npm-init.js', type: path, hint: '', description: ` A module that will be loaded by the \`npm init\` command. See the documentation for the [init-package-json](https://github.com/npm/init-package-json) module for more information, or [npm init](/commands/npm-init). `, }), 'init-version': new Definition('init-version', { default: '1.0.0', type: Semver, hint: '', description: ` The value that \`npm init\` should use by default for the package version number, if not already set in package.json. `, }), // these "aliases" are historically supported in .npmrc files, unfortunately // They should be removed in a future npm version. 'init.author.email': new Definition('init.author.email', { default: '', type: String, deprecated: ` Use \`--init-author-email\` instead.`, description: ` Alias for \`--init-author-email\` `, }), 'init.author.name': new Definition('init.author.name', { default: '', type: String, deprecated: ` Use \`--init-author-name\` instead. `, description: ` Alias for \`--init-author-name\` `, }), 'init.author.url': new Definition('init.author.url', { default: '', type: ['', url], deprecated: ` Use \`--init-author-url\` instead. `, description: ` Alias for \`--init-author-url\` `, }), 'init.license': new Definition('init.license', { default: 'ISC', type: String, deprecated: ` Use \`--init-license\` instead. `, description: ` Alias for \`--init-license\` `, }), 'init.module': new Definition('init.module', { default: '~/.npm-init.js', type: path, deprecated: ` Use \`--init-module\` instead. `, description: ` Alias for \`--init-module\` `, }), 'init.version': new Definition('init.version', { default: '1.0.0', type: Semver, deprecated: ` Use \`--init-version\` instead. `, description: ` Alias for \`--init-version\` `, }), 'install-links': new Definition('install-links', { default: false, type: Boolean, description: ` When set file: protocol dependencies will be packed and installed as regular dependencies instead of creating a symlink. This option has no effect on workspaces. `, flatten, }), 'install-strategy': new Definition('install-strategy', { default: 'hoisted', type: ['hoisted', 'nested', 'shallow', 'linked'], description: ` Sets the strategy for installing packages in node_modules. hoisted (default): Install non-duplicated in top-level, and duplicated as necessary within directory structure. nested: (formerly --legacy-bundling) install in place, no hoisting. shallow (formerly --global-style) only install direct deps at top-level. linked: (experimental) install in node_modules/.store, link in place, unhoisted. `, flatten, }), json: new Definition('json', { default: false, type: Boolean, description: ` Whether or not to output JSON data, rather than the normal output. * In \`npm pkg set\` it enables parsing set values with JSON.parse() before saving them to your \`package.json\`. Not supported by all npm commands. `, flatten, }), key: new Definition('key', { default: null, type: [null, String], description: ` A client key to pass when accessing the registry. Values should be in PEM format with newlines replaced by the string "\\n". For example: \`\`\`ini key="-----BEGIN PRIVATE KEY-----\\nXXXX\\nXXXX\\n-----END PRIVATE KEY-----" \`\`\` It is _not_ the path to a key file, though you can set a registry-scoped "keyfile" path like "//other-registry.tld/:keyfile=/path/to/key.pem". `, deprecated: ` \`key\` and \`cert\` are no longer used for most registry operations. Use registry scoped \`keyfile\` and \`cafile\` instead. Example: //other-registry.tld/:keyfile=/path/to/key.pem //other-registry.tld/:cafile=/path/to/cert.crt `, flatten, }), 'legacy-bundling': new Definition('legacy-bundling', { default: false, type: Boolean, description: ` Instead of hoisting package installs in \`node_modules\`, install packages in the same manner that they are depended on. This may cause very deep directory structures and duplicate package installs as there is no de-duplicating. Sets \`--install-strategy=nested\`. `, deprecated: ` This option has been deprecated in favor of \`--install-strategy=nested\` `, flatten (key, obj, flatOptions) { if (obj[key]) { obj['install-strategy'] = 'nested' flatOptions.installStrategy = 'nested' } }, }), 'legacy-peer-deps': new Definition('legacy-peer-deps', { default: false, type: Boolean, description: ` Causes npm to completely ignore \`peerDependencies\` when building a package tree, as in npm versions 3 through 6. If a package cannot be installed because of overly strict \`peerDependencies\` that collide, it provides a way to move forward resolving the situation. This differs from \`--omit=peer\`, in that \`--omit=peer\` will avoid unpacking \`peerDependencies\` on disk, but will still design a tree such that \`peerDependencies\` _could_ be unpacked in a correct place. Use of \`legacy-peer-deps\` is not recommended, as it will not enforce the \`peerDependencies\` contract that meta-dependencies may rely on. `, flatten, }), libc: new Definition('libc', { default: null, type: [null, String], description: ` Override libc of native modules to install. Acceptable values are same as \`libc\` field of package.json `, flatten, }), link: new Definition('link', { default: false, type: Boolean, description: ` Used with \`npm ls\`, limiting output to only those packages that are linked. `, }), 'local-address': new Definition('local-address', { default: null, type: getLocalAddresses(), typeDescription: 'IP Address', description: ` The IP address of the local interface to use when making connections to the npm registry. Must be IPv4 in versions of Node prior to 0.12. `, flatten, }), location: new Definition('location', { default: 'user', short: 'L', type: [ 'global', 'user', 'project', ], defaultDescription: ` "user" unless \`--global\` is passed, which will also set this value to "global" `, description: ` When passed to \`npm config\` this refers to which config file to use. When set to "global" mode, packages are installed into the \`prefix\` folder instead of the current working directory. See [folders](/configuring-npm/folders) for more on the differences in behavior. * packages are installed into the \`{prefix}/lib/node_modules\` folder, instead of the current working directory. * bin files are linked to \`{prefix}/bin\` * man pages are linked to \`{prefix}/share/man\` `, flatten: (key, obj, flatOptions) => { flatten(key, obj, flatOptions) if (flatOptions.global) { flatOptions.location = 'global' } if (obj.location === 'global') { flatOptions.global = true } }, }), 'lockfile-version': new Definition('lockfile-version', { default: null, type: [null, 1, 2, 3, '1', '2', '3'], defaultDescription: ` Version 3 if no lockfile, auto-converting v1 lockfiles to v3, otherwise maintain current lockfile version.`, description: ` Set the lockfile format version to be used in package-lock.json and npm-shrinkwrap-json files. Possible options are: 1: The lockfile version used by npm versions 5 and 6. Lacks some data that is used during the install, resulting in slower and possibly less deterministic installs. Prevents lockfile churn when interoperating with older npm versions. 2: The default lockfile version used by npm version 7 and 8. Includes both the version 1 lockfile data and version 3 lockfile data, for maximum determinism and interoperability, at the expense of more bytes on disk. 3: Only the new lockfile information introduced in npm version 7. Smaller on disk than lockfile version 2, but not interoperable with older npm versions. Ideal if all users are on npm version 7 and higher. `, flatten: (key, obj, flatOptions) => { flatOptions.lockfileVersion = obj[key] && parseInt(obj[key], 10) }, }), loglevel: new Definition('loglevel', { default: 'notice', type: [ 'silent', 'error', 'warn', 'notice', 'http', 'info', 'verbose', 'silly', ], description: ` What level of logs to report. All logs are written to a debug log, with the path to that file printed if the execution of a command fails. Any logs of a higher level than the setting are shown. The default is "notice". See also the \`foreground-scripts\` config. `, flatten (key, obj, flatOptions) { flatOptions.silent = obj[key] === 'silent' }, }), 'logs-dir': new Definition('logs-dir', { default: null, type: [null, path], defaultDescription: ` A directory named \`_logs\` inside the cache `, description: ` The location of npm's log directory. See [\`npm logging\`](/using-npm/logging) for more information. `, }), 'logs-max': new Definition('logs-max', { default: 10, type: Number, description: ` The maximum number of log files to store. If set to 0, no log files will be written for the current run. `, }), long: new Definition('long', { default: false, type: Boolean, short: 'l', description: ` Show extended information in \`ls\`, \`search\`, and \`help-search\`. `, }), maxsockets: new Definition('maxsockets', { default: 15, type: Number, description: ` The maximum number of connections to use per origin (protocol/host/port combination). `, flatten (key, obj, flatOptions) { flatOptions.maxSockets = obj[key] }, }), message: new Definition('message', { default: '%s', type: String, short: 'm', description: ` Commit message which is used by \`npm version\` when creating version commit. Any "%s" in the message will be replaced with the version number. `, flatten, }), 'node-options': new Definition('node-options', { default: null, type: [null, String], description: ` Options to pass through to Node.js via the \`NODE_OPTIONS\` environment variable. This does not impact how npm itself is executed but it does impact how lifecycle scripts are called. `, }), noproxy: new Definition('noproxy', { default: '', defaultDescription: ` The value of the NO_PROXY environment variable `, type: [String, Array], description: ` Domain extensions that should bypass any proxies. Also accepts a comma-delimited string. `, flatten (key, obj, flatOptions) { if (Array.isArray(obj[key])) { flatOptions.noProxy = obj[key].join(',') } else { flatOptions.noProxy = obj[key] } }, }), offline: new Definition('offline', { default: false, type: Boolean, description: ` Force offline mode: no network requests will be done during install. To allow the CLI to fill in missing cache data, see \`--prefer-offline\`. `, flatten, }), omit: new Definition('omit', { default: process.env.NODE_ENV === 'production' ? ['dev'] : [], defaultDescription: ` 'dev' if the \`NODE_ENV\` environment variable is set to 'production', otherwise empty. `, type: [Array, 'dev', 'optional', 'peer'], description: ` Dependency types to omit from the installation tree on disk. Note that these dependencies _are_ still resolved and added to the \`package-lock.json\` or \`npm-shrinkwrap.json\` file. They are just not physically installed on disk. If a package type appears in both the \`--include\` and \`--omit\` lists, then it will be included. If the resulting omit list includes \`'dev'\`, then the \`NODE_ENV\` environment variable will be set to \`'production'\` for all lifecycle scripts. `, flatten (key, obj, flatOptions) { flatOptions.omit = buildOmitList(obj) }, }), 'omit-lockfile-registry-resolved': new Definition('omit-lockfile-registry-resolved', { default: false, type: Boolean, description: ` This option causes npm to create lock files without a \`resolved\` key for registry dependencies. Subsequent installs will need to resolve tarball endpoints with the configured registry, likely resulting in a longer install time. `, flatten, }), only: new Definition('only', { default: null, type: [null, 'prod', 'production'], deprecated: ` Use \`--omit=dev\` to omit dev dependencies from the install. `, description: ` When set to \`prod\` or \`production\`, this is an alias for \`--omit=dev\`. `, flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), optional: new Definition('optional', { default: null, type: [null, Boolean], deprecated: ` Use \`--omit=optional\` to exclude optional dependencies, or \`--include=optional\` to include them. Default value does install optional deps unless otherwise omitted. `, description: ` Alias for --include=optional or --omit=optional `, flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), os: new Definition('os', { default: null, type: [null, String], description: ` Override OS of native modules to install. Acceptable values are same as \`os\` field of package.json, which comes from \`process.platform\`. `, flatten, }), otp: new Definition('otp', { default: null, type: [null, String], description: ` This is a one-time password from a two-factor authenticator. It's needed when publishing or changing package permissions with \`npm access\`. If not set, and a registry response fails with a challenge for a one-time password, npm will prompt on the command line for one. `, flatten (key, obj, flatOptions) { flatten(key, obj, flatOptions) if (obj.otp) { obj['auth-type'] = 'legacy' flatten('auth-type', obj, flatOptions) } }, }), package: new Definition('package', { default: [], hint: '', type: [String, Array], description: ` The package or packages to install for [\`npm exec\`](/commands/npm-exec) `, flatten, }), 'package-lock': new Definition('package-lock', { default: true, type: Boolean, description: ` If set to false, then ignore \`package-lock.json\` files when installing. This will also prevent _writing_ \`package-lock.json\` if \`save\` is true. `, flatten: (key, obj, flatOptions) => { flatten(key, obj, flatOptions) if (flatOptions.packageLockOnly) { flatOptions.packageLock = true } }, }), 'package-lock-only': new Definition('package-lock-only', { default: false, type: Boolean, description: ` If set to true, the current operation will only use the \`package-lock.json\`, ignoring \`node_modules\`. For \`update\` this means only the \`package-lock.json\` will be updated, instead of checking \`node_modules\` and downloading dependencies. For \`list\` this means the output will be based on the tree described by the \`package-lock.json\`, rather than the contents of \`node_modules\`. `, flatten: (key, obj, flatOptions) => { flatten(key, obj, flatOptions) if (flatOptions.packageLockOnly) { flatOptions.packageLock = true } }, }), 'pack-destination': new Definition('pack-destination', { default: '.', type: String, description: ` Directory in which \`npm pack\` will save tarballs. `, flatten, }), parseable: new Definition('parseable', { default: false, type: Boolean, short: 'p', description: ` Output parseable results from commands that write to standard output. For \`npm search\`, this will be tab-separated table format. `, flatten, }), 'prefer-dedupe': new Definition('prefer-dedupe', { default: false, type: Boolean, description: ` Prefer to deduplicate packages if possible, rather than choosing a newer version of a dependency. `, flatten, }), 'prefer-offline': new Definition('prefer-offline', { default: false, type: Boolean, description: ` If true, staleness checks for cached data will be bypassed, but missing data will be requested from the server. To force full offline mode, use \`--offline\`. `, flatten, }), 'prefer-online': new Definition('prefer-online', { default: false, type: Boolean, description: ` If true, staleness checks for cached data will be forced, making the CLI look for updates immediately even for fresh package data. `, flatten, }), // `prefix` has its default defined outside of this module prefix: new Definition('prefix', { type: path, short: 'C', default: '', defaultDescription: ` In global mode, the folder where the node executable is installed. Otherwise, the nearest parent folder containing either a package.json file or a node_modules folder. `, description: ` The location to install global items. If set on the command line, then it forces non-global commands to run in the specified folder. `, }), preid: new Definition('preid', { default: '', hint: 'prerelease-id', type: String, description: ` The "prerelease identifier" to use as a prefix for the "prerelease" part of a semver. Like the \`rc\` in \`1.2.0-rc.8\`. `, flatten, }), production: new Definition('production', { default: null, type: [null, Boolean], deprecated: 'Use `--omit=dev` instead.', description: 'Alias for `--omit=dev`', flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), progress: new Definition('progress', { default: !ciInfo.isCI, defaultDescription: ` \`true\` unless running in a known CI system `, type: Boolean, description: ` When set to \`true\`, npm will display a progress bar during time intensive operations, if \`process.stderr\` and \`process.stdout\` are a TTY. Set to \`false\` to suppress the progress bar. `, flatten (key, obj, flatOptions) { flatOptions.progress = !obj.progress ? false // progress is only written to stderr but we disable it unless stdout is a tty // also. This prevents the progress from appearing when piping output to another // command which doesn't break anything, but does look very odd to users. : !!process.stderr.isTTY && !!process.stdout.isTTY && process.env.TERM !== 'dumb' }, }), provenance: new Definition('provenance', { default: false, type: Boolean, exclusive: ['provenance-file'], description: ` When publishing from a supported cloud CI/CD system, the package will be publicly linked to where it was built and published from. `, flatten, }), 'provenance-file': new Definition('provenance-file', { default: null, type: path, hint: '', exclusive: ['provenance'], description: ` When publishing, the provenance bundle at the given path will be used. `, flatten, }), proxy: new Definition('proxy', { default: null, type: [null, false, url], // allow proxy to be disabled explicitly description: ` A proxy to use for outgoing http requests. If the \`HTTP_PROXY\` or \`http_proxy\` environment variables are set, proxy settings will be honored by the underlying \`request\` library. `, flatten, }), 'read-only': new Definition('read-only', { default: false, type: Boolean, description: ` This is used to mark a token as unable to publish when configuring limited access tokens with the \`npm token create\` command. `, flatten, }), 'rebuild-bundle': new Definition('rebuild-bundle', { default: true, type: Boolean, description: ` Rebuild bundled dependencies after installation. `, flatten, }), registry: new Definition('registry', { default: 'https://registry.npmjs.org/', type: url, description: ` The base URL of the npm registry. `, flatten, }), 'replace-registry-host': new Definition('replace-registry-host', { default: 'npmjs', hint: ' | hostname', type: ['npmjs', 'never', 'always', String], description: ` Defines behavior for replacing the registry host in a lockfile with the configured registry. The default behavior is to replace package dist URLs from the default registry (https://registry.npmjs.org) to the configured registry. If set to "never", then use the registry value. If set to "always", then replace the registry host with the configured host every time. You may also specify a bare hostname (e.g., "registry.npmjs.org"). `, flatten, }), save: new Definition('save', { default: true, defaultDescription: `\`true\` unless when using \`npm update\` where it defaults to \`false\``, usage: '-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle', type: Boolean, short: 'S', description: ` Save installed packages to a \`package.json\` file as dependencies. When used with the \`npm rm\` command, removes the dependency from \`package.json\`. Will also prevent writing to \`package-lock.json\` if set to \`false\`. `, flatten, }), 'save-bundle': new Definition('save-bundle', { default: false, type: Boolean, short: 'B', description: ` If a package would be saved at install time by the use of \`--save\`, \`--save-dev\`, or \`--save-optional\`, then also put it in the \`bundleDependencies\` list. Ignored if \`--save-peer\` is set, since peerDependencies cannot be bundled. `, flatten (key, obj, flatOptions) { // XXX update arborist to just ignore it if resulting saveType is peer // otherwise this won't have the expected effect: // // npm config set save-peer true // npm i foo --save-bundle --save-prod <-- should bundle flatOptions.saveBundle = obj['save-bundle'] && !obj['save-peer'] }, }), 'save-dev': new Definition('save-dev', { default: false, type: Boolean, short: 'D', description: ` Save installed packages to a package.json file as \`devDependencies\`. `, flatten (key, obj, flatOptions) { if (!obj[key]) { if (flatOptions.saveType === 'dev') { delete flatOptions.saveType } return } flatOptions.saveType = 'dev' }, }), 'save-exact': new Definition('save-exact', { default: false, type: Boolean, short: 'E', description: ` Dependencies saved to package.json will be configured with an exact version rather than using npm's default semver range operator. `, flatten (key, obj, flatOptions) { // just call the save-prefix flattener, it reads from obj['save-exact'] definitions['save-prefix'].flatten('save-prefix', obj, flatOptions) }, }), 'save-optional': new Definition('save-optional', { default: false, type: Boolean, short: 'O', description: ` Save installed packages to a package.json file as \`optionalDependencies\`. `, flatten (key, obj, flatOptions) { if (!obj[key]) { if (flatOptions.saveType === 'optional') { delete flatOptions.saveType } else if (flatOptions.saveType === 'peerOptional') { flatOptions.saveType = 'peer' } return } if (flatOptions.saveType === 'peerOptional') { return } if (flatOptions.saveType === 'peer') { flatOptions.saveType = 'peerOptional' } else { flatOptions.saveType = 'optional' } }, }), 'save-peer': new Definition('save-peer', { default: false, type: Boolean, description: ` Save installed packages to a package.json file as \`peerDependencies\` `, flatten (key, obj, flatOptions) { if (!obj[key]) { if (flatOptions.saveType === 'peer') { delete flatOptions.saveType } else if (flatOptions.saveType === 'peerOptional') { flatOptions.saveType = 'optional' } return } if (flatOptions.saveType === 'peerOptional') { return } if (flatOptions.saveType === 'optional') { flatOptions.saveType = 'peerOptional' } else { flatOptions.saveType = 'peer' } }, }), 'save-prefix': new Definition('save-prefix', { default: '^', type: String, description: ` Configure how versions of packages installed to a package.json file via \`--save\` or \`--save-dev\` get prefixed. For example if a package has version \`1.2.3\`, by default its version is set to \`^1.2.3\` which allows minor upgrades for that package, but after \`npm config set save-prefix='~'\` it would be set to \`~1.2.3\` which only allows patch upgrades. `, flatten (key, obj, flatOptions) { flatOptions.savePrefix = obj['save-exact'] ? '' : obj['save-prefix'] obj['save-prefix'] = flatOptions.savePrefix }, }), 'save-prod': new Definition('save-prod', { default: false, type: Boolean, short: 'P', description: ` Save installed packages into \`dependencies\` specifically. This is useful if a package already exists in \`devDependencies\` or \`optionalDependencies\`, but you want to move it to be a non-optional production dependency. This is the default behavior if \`--save\` is true, and neither \`--save-dev\` or \`--save-optional\` are true. `, flatten (key, obj, flatOptions) { if (!obj[key]) { if (flatOptions.saveType === 'prod') { delete flatOptions.saveType } return } flatOptions.saveType = 'prod' }, }), 'sbom-format': new Definition('sbom-format', { default: null, type: [ 'cyclonedx', 'spdx', ], description: ` SBOM format to use when generating SBOMs. `, flatten, }), 'sbom-type': new Definition('sbom-type', { default: 'library', type: [ 'library', 'application', 'framework', ], description: ` The type of package described by the generated SBOM. For SPDX, this is the value for the \`primaryPackagePurpose\` field. For CycloneDX, this is the value for the \`type\` field. `, flatten, }), scope: new Definition('scope', { default: '', defaultDescription: ` the scope of the current project, if any, or "" `, type: String, hint: '<@scope>', description: ` Associate an operation with a scope for a scoped registry. Useful when logging in to or out of a private registry: \`\`\` # log in, linking the scope to the custom registry npm login --scope=@mycorp --registry=https://registry.mycorp.com # log out, removing the link and the auth token npm logout --scope=@mycorp \`\`\` This will cause \`@mycorp\` to be mapped to the registry for future installation of packages specified according to the pattern \`@mycorp/package\`. This will also cause \`npm init\` to create a scoped package. \`\`\` # accept all defaults, and create a package named "@foo/whatever", # instead of just named "whatever" npm init --scope=@foo --yes \`\`\` `, flatten (key, obj, flatOptions) { const value = obj[key] const scope = value && !/^@/.test(value) ? `@${value}` : value flatOptions.scope = scope // projectScope is kept for compatibility with npm-registry-fetch flatOptions.projectScope = scope }, }), 'script-shell': new Definition('script-shell', { default: null, defaultDescription: ` '/bin/sh' on POSIX systems, 'cmd.exe' on Windows `, type: [null, String], description: ` The shell to use for scripts run with the \`npm exec\`, \`npm run\` and \`npm init \` commands. `, flatten (key, obj, flatOptions) { flatOptions.scriptShell = obj[key] || undefined }, }), searchexclude: new Definition('searchexclude', { default: '', type: String, description: ` Space-separated options that limit the results from search. `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || { limit: 20 } flatOptions.search.exclude = obj[key].toLowerCase() }, }), searchlimit: new Definition('searchlimit', { default: 20, type: Number, description: ` Number of items to limit search results to. Will not apply at all to legacy searches. `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || {} flatOptions.search.limit = obj[key] }, }), searchopts: new Definition('searchopts', { default: '', type: String, description: ` Space-separated options that are always passed to search. `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || { limit: 20 } flatOptions.search.opts = querystring.parse(obj[key]) }, }), searchstaleness: new Definition('searchstaleness', { default: 15 * 60, type: Number, description: ` The age of the cache, in seconds, before another registry request is made if using legacy search endpoint. `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || { limit: 20 } flatOptions.search.staleness = obj[key] }, }), shell: new Definition('shell', { default: shell, defaultDescription: ` SHELL environment variable, or "bash" on Posix, or "cmd.exe" on Windows `, type: String, description: ` The shell to run for the \`npm explore\` command. `, flatten, }), shrinkwrap: new Definition('shrinkwrap', { default: true, type: Boolean, deprecated: ` Use the --package-lock setting instead. `, description: ` Alias for --package-lock `, flatten (key, obj, flatOptions) { obj['package-lock'] = obj.shrinkwrap definitions['package-lock'].flatten('package-lock', obj, flatOptions) }, }), 'sign-git-commit': new Definition('sign-git-commit', { default: false, type: Boolean, description: ` If set to true, then the \`npm version\` command will commit the new package version using \`-S\` to add a signature. Note that git requires you to have set up GPG keys in your git configs for this to work properly. `, flatten, }), 'sign-git-tag': new Definition('sign-git-tag', { default: false, type: Boolean, description: ` If set to true, then the \`npm version\` command will tag the version using \`-s\` to add a signature. Note that git requires you to have set up GPG keys in your git configs for this to work properly. `, flatten, }), 'strict-peer-deps': new Definition('strict-peer-deps', { default: false, type: Boolean, description: ` If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ conflicting \`peerDependencies\` will be treated as an install failure, even if npm could reasonably guess the appropriate resolution based on non-peer dependency relationships. By default, conflicting \`peerDependencies\` deep in the dependency graph will be resolved using the nearest non-peer dependency specification, even if doing so will result in some packages receiving a peer dependency outside the range set in their package's \`peerDependencies\` object. When such an override is performed, a warning is printed, explaining the conflict and the packages involved. If \`--strict-peer-deps\` is set, then this warning is treated as a failure. `, flatten, }), 'strict-ssl': new Definition('strict-ssl', { default: true, type: Boolean, description: ` Whether or not to do SSL key validation when making requests to the registry via https. See also the \`ca\` config. `, flatten (key, obj, flatOptions) { flatOptions.strictSSL = obj[key] }, }), tag: new Definition('tag', { default: 'latest', type: String, description: ` If you ask npm to install a package and don't tell it a specific version, then it will install the specified tag. It is the tag added to the package@version specified in the \`npm dist-tag add\` command, if no explicit tag is given. When used by the \`npm diff\` command, this is the tag used to fetch the tarball that will be compared with the local files by default. If used in the \`npm publish\` command, this is the tag that will be added to the package submitted to the registry. `, flatten (key, obj, flatOptions) { flatOptions.defaultTag = obj[key] }, }), 'tag-version-prefix': new Definition('tag-version-prefix', { default: 'v', type: String, description: ` If set, alters the prefix used when tagging a new version when performing a version increment using \`npm version\`. To remove the prefix altogether, set it to the empty string: \`""\`. Because other tools may rely on the convention that npm version tags look like \`v1.0.0\`, _only use this property if it is absolutely necessary_. In particular, use care when overriding this setting for public packages. `, flatten, }), timing: new Definition('timing', { default: false, type: Boolean, description: ` If true, writes timing information to a process specific json file in the cache or \`logs-dir\`. The file name ends with \`-timing.json\`. You can quickly view it with this [json](https://npm.im/json) command line: \`cat ~/.npm/_logs/*-timing.json | npm exec -- json -g\`. Timing information will also be reported in the terminal. To suppress this while still writing the timing file, use \`--silent\`. `, }), umask: new Definition('umask', { default: 0, type: Umask, description: ` The "umask" value to use when setting the file creation mode on files and folders. Folders and executables are given a mode which is \`0o777\` masked against this value. Other files are given a mode which is \`0o666\` masked against this value. Note that the underlying system will _also_ apply its own umask value to files and folders that are created, and npm does not circumvent this, but rather adds the \`--umask\` config to it. Thus, the effective default umask value on most POSIX systems is 0o22, meaning that folders and executables are created with a mode of 0o755 and other files are created with a mode of 0o644. `, flatten, }), unicode: new Definition('unicode', { default: unicode, defaultDescription: ` false on windows, true on mac/unix systems with a unicode locale, as defined by the \`LC_ALL\`, \`LC_CTYPE\`, or \`LANG\` environment variables. `, type: Boolean, description: ` When set to true, npm uses unicode characters in the tree output. When false, it uses ascii characters instead of unicode glyphs. `, flatten, }), 'update-notifier': new Definition('update-notifier', { default: true, type: Boolean, description: ` Set to false to suppress the update notification when using an older version of npm than the latest. `, }), usage: new Definition('usage', { default: false, type: Boolean, short: ['?', 'H', 'h'], description: ` Show short usage output about the command specified. `, }), 'user-agent': new Definition('user-agent', { default: 'npm/{npm-version} ' + 'node/{node-version} ' + '{platform} ' + '{arch} ' + 'workspaces/{workspaces} ' + '{ci}', type: String, description: ` Sets the User-Agent request header. The following fields are replaced with their actual counterparts: * \`{npm-version}\` - The npm version in use * \`{node-version}\` - The Node.js version in use * \`{platform}\` - The value of \`process.platform\` * \`{arch}\` - The value of \`process.arch\` * \`{workspaces}\` - Set to \`true\` if the \`workspaces\` or \`workspace\` options are set. * \`{ci}\` - The value of the \`ci-name\` config, if set, prefixed with \`ci/\`, or an empty string if \`ci-name\` is empty. `, flatten (key, obj, flatOptions) { const value = obj[key] const ciName = ciInfo.name?.toLowerCase().split(' ').join('-') || null let inWorkspaces = false if (obj.workspaces || obj.workspace && obj.workspace.length) { inWorkspaces = true } flatOptions.userAgent = value.replace(/\{node-version\}/gi, process.version) .replace(/\{npm-version\}/gi, obj['npm-version']) .replace(/\{platform\}/gi, process.platform) .replace(/\{arch\}/gi, process.arch) .replace(/\{workspaces\}/gi, inWorkspaces) .replace(/\{ci\}/gi, ciName ? `ci/${ciName}` : '') .trim() // We can't clobber the original or else subsequent flattening will fail // (i.e. when we change the underlying config values) // obj[key] = flatOptions.userAgent // user-agent is a unique kind of config item that gets set from a template // and ends up translated. Because of this, the normal "should we set this // to process.env also doesn't work process.env.npm_config_user_agent = flatOptions.userAgent }, }), userconfig: new Definition('userconfig', { default: '~/.npmrc', type: path, description: ` The location of user-level configuration settings. This may be overridden by the \`npm_config_userconfig\` environment variable or the \`--userconfig\` command line option, but may _not_ be overridden by settings in the \`globalconfig\` file. `, }), version: new Definition('version', { default: false, type: Boolean, short: 'v', description: ` If true, output the npm version and exit successfully. Only relevant when specified explicitly on the command line. `, }), versions: new Definition('versions', { default: false, type: Boolean, description: ` If true, output the npm version as well as node's \`process.versions\` map and the version in the current working directory's \`package.json\` file if one exists, and exit successfully. Only relevant when specified explicitly on the command line. `, }), viewer: new Definition('viewer', { default: isWindows ? 'browser' : 'man', defaultDescription: ` "man" on Posix, "browser" on Windows `, type: String, description: ` The program to use to view help content. Set to \`"browser"\` to view html help content in the default web browser. `, }), which: new Definition('which', { default: null, hint: '', type: [null, Number], description: ` If there are multiple funding sources, which 1-indexed source URL to open. `, }), workspace: new Definition('workspace', { default: [], type: [String, Array], hint: '', short: 'w', envExport: false, description: ` Enable running a command in the context of the configured workspaces of the current project while filtering by running only the workspaces defined by this configuration option. Valid values for the \`workspace\` config are either: * Workspace names * Path to a workspace directory * Path to a parent workspace directory (will result in selecting all workspaces within that folder) When set for the \`npm init\` command, this may be set to the folder of a workspace which does not yet exist, to create the folder and set it up as a brand new workspace within the project. `, flatten: (key, obj, flatOptions) => { definitions['user-agent'].flatten('user-agent', obj, flatOptions) }, }), workspaces: new Definition('workspaces', { default: null, type: [null, Boolean], short: 'ws', envExport: false, description: ` Set to true to run the command in the context of **all** configured workspaces. Explicitly setting this to false will cause commands like \`install\` to ignore workspaces altogether. When not set explicitly: - Commands that operate on the \`node_modules\` tree (install, update, etc.) will link workspaces into the \`node_modules\` folder. - Commands that do other things (test, exec, publish, etc.) will operate on the root project, _unless_ one or more workspaces are specified in the \`workspace\` config. `, flatten: (key, obj, flatOptions) => { definitions['user-agent'].flatten('user-agent', obj, flatOptions) // TODO: this is a derived value, and should be reworked when we have a // pattern for derived value // workspacesEnabled is true whether workspaces is null or true // commands contextually work with workspaces or not regardless of // configuration, so we need an option specifically to disable workspaces flatOptions.workspacesEnabled = obj[key] !== false }, }), 'workspaces-update': new Definition('workspaces-update', { default: true, type: Boolean, description: ` If set to true, the npm cli will run an update after operations that may possibly change the workspaces installed to the \`node_modules\` folder. `, flatten, }), yes: new Definition('yes', { default: null, type: [null, Boolean], short: 'y', description: ` Automatically answer "yes" to any prompts that npm might print on the command line. `, }), } module.exports = definitions const definitions = require('./definitions.js') // use the defined flattening function, and copy over any scoped // registries and registry-specific "nerfdart" configs verbatim // // TODO: make these getters so that we only have to make dirty // the thing that changed, and then flatten the fields that // could have changed when a config.set is called. // // TODO: move nerfdart auth stuff into a nested object that // is only passed along to paths that end up calling npm-registry-fetch. const flatten = (obj, flat = {}) => { for (const [key, val] of Object.entries(obj)) { const def = definitions[key] if (def && def.flatten) { def.flatten(key, obj, flat) } else if (/@.*:registry$/i.test(key) || /^\/\//.test(key)) { flat[key] = val } } return flat } const definitionProps = Object.entries(definitions) .reduce((acc, [key, { short = [], default: d }]) => { // can be either an array or string for (const s of [].concat(short)) { acc.shorthands[s] = [`--${key}`] } acc.defaults[key] = d return acc }, { shorthands: {}, defaults: {} }) // aliases where they get expanded into a completely different thing // these are NOT supported in the environment or npmrc files, only // expanded on the CLI. // TODO: when we switch off of nopt, use an arg parser that supports // more reasonable aliasing and short opts right in the definitions set. const shorthands = { 'enjoy-by': ['--before'], d: ['--loglevel', 'info'], dd: ['--loglevel', 'verbose'], ddd: ['--loglevel', 'silly'], quiet: ['--loglevel', 'warn'], q: ['--loglevel', 'warn'], s: ['--loglevel', 'silent'], silent: ['--loglevel', 'silent'], verbose: ['--loglevel', 'verbose'], desc: ['--description'], help: ['--usage'], local: ['--no-global'], n: ['--no-yes'], no: ['--no-yes'], porcelain: ['--parseable'], readonly: ['--read-only'], reg: ['--registry'], iwr: ['--include-workspace-root'], ...definitionProps.shorthands, } module.exports = { defaults: definitionProps.defaults, definitions, flatten, shorthands, } // replace any ${ENV} values with the appropriate environ. const envExpr = /(? f.replace(envExpr, (orig, esc, name) => { const val = env[name] !== undefined ? env[name] : `$\{${name}}` // consume the escape chars that are relevant. if (esc.length % 2) { return orig.slice((esc.length + 1) / 2) } return (esc.slice(esc.length / 2)) + val }) 'use strict' class ErrInvalidAuth extends Error { constructor (problems) { let message = 'Invalid auth configuration found: ' message += problems.map((problem) => { // istanbul ignore else if (problem.action === 'delete') { return `\`${problem.key}\` is not allowed in ${problem.where} config` } else if (problem.action === 'rename') { return `\`${problem.from}\` must be renamed to \`${problem.to}\` in ${problem.where} config` } }).join(', ') message += '\nPlease run `npm config fix` to repair your configuration.`' super(message) this.code = 'ERR_INVALID_AUTH' this.problems = problems } } module.exports = { ErrInvalidAuth, } // TODO: set the scope config from package.json or explicit cli config const { walkUp } = require('walk-up-path') const ini = require('ini') const nopt = require('nopt') const { log, time } = require('proc-log') const { resolve, dirname, join } = require('node:path') const { homedir } = require('node:os') const { readFile, writeFile, chmod, unlink, stat, mkdir, } = require('node:fs/promises') const fileExists = (...p) => stat(resolve(...p)) .then((st) => st.isFile()) .catch(() => false) const dirExists = (...p) => stat(resolve(...p)) .then((st) => st.isDirectory()) .catch(() => false) const hasOwnProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key) const typeDefs = require('./type-defs.js') const nerfDart = require('./nerf-dart.js') const envReplace = require('./env-replace.js') const parseField = require('./parse-field.js') const setEnvs = require('./set-envs.js') // types that can be saved back to const confFileTypes = new Set([ 'global', 'user', 'project', ]) const confTypes = new Set([ 'default', 'builtin', ...confFileTypes, 'env', 'cli', ]) class Config { #loaded = false #flatten // populated the first time we flatten the object #flatOptions = null static get typeDefs () { return typeDefs } constructor ({ definitions, shorthands, flatten, npmPath, // options just to override in tests, mostly env = process.env, argv = process.argv, platform = process.platform, execPath = process.execPath, cwd = process.cwd(), excludeNpmCwd = false, }) { // turn the definitions into nopt's weirdo syntax this.definitions = definitions const types = {} const defaults = {} this.deprecated = {} for (const [key, def] of Object.entries(definitions)) { defaults[key] = def.default types[key] = def.type if (def.deprecated) { this.deprecated[key] = def.deprecated.trim().replace(/\n +/, '\n') } } this.#flatten = flatten this.types = types this.shorthands = shorthands this.defaults = defaults this.npmPath = npmPath this.npmBin = join(this.npmPath, 'bin/npm-cli.js') this.argv = argv this.env = env this.execPath = execPath this.platform = platform this.cwd = cwd this.excludeNpmCwd = excludeNpmCwd // set when we load configs this.globalPrefix = null this.localPrefix = null this.localPackage = null // defaults to env.HOME, but will always be *something* this.home = null // set up the prototype chain of config objects const wheres = [...confTypes] this.data = new Map() let parent = null for (const where of wheres) { this.data.set(where, parent = new ConfigData(parent)) } this.data.set = () => { throw new Error('cannot change internal config data structure') } this.data.delete = () => { throw new Error('cannot change internal config data structure') } this.sources = new Map([]) this.list = [] for (const { data } of this.data.values()) { this.list.unshift(data) } Object.freeze(this.list) this.#loaded = false } get loaded () { return this.#loaded } get prefix () { return this.#get('global') ? this.globalPrefix : this.localPrefix } // return the location where key is found. find (key) { if (!this.loaded) { throw new Error('call config.load() before reading values') } // have to look in reverse order const entries = [...this.data.entries()] for (let i = entries.length - 1; i > -1; i--) { const [where, { data }] = entries[i] if (hasOwnProperty(data, key)) { return where } } return null } get (key, where) { if (!this.loaded) { throw new Error('call config.load() before reading values') } return this.#get(key, where) } // we need to get values sometimes, so use this internal one to do so // while in the process of loading. #get (key, where = null) { if (where !== null && !confTypes.has(where)) { throw new Error('invalid config location param: ' + where) } const { data } = this.data.get(where || 'cli') return where === null || hasOwnProperty(data, key) ? data[key] : undefined } set (key, val, where = 'cli') { if (!this.loaded) { throw new Error('call config.load() before setting values') } if (!confTypes.has(where)) { throw new Error('invalid config location param: ' + where) } this.#checkDeprecated(key) const { data, raw } = this.data.get(where) data[key] = val if (['global', 'user', 'project'].includes(where)) { raw[key] = val } // this is now dirty, the next call to this.valid will have to check it this.data.get(where)[_valid] = null // the flat options are invalidated, regenerate next time they're needed this.#flatOptions = null } get flat () { if (this.#flatOptions) { return this.#flatOptions } // create the object for flat options passed to deps const timeEnd = time.start('config:load:flatten') this.#flatOptions = {} // walk from least priority to highest for (const { data } of this.data.values()) { this.#flatten(data, this.#flatOptions) } this.#flatOptions.nodeBin = this.execPath this.#flatOptions.npmBin = this.npmBin timeEnd() return this.#flatOptions } delete (key, where = 'cli') { if (!this.loaded) { throw new Error('call config.load() before deleting values') } if (!confTypes.has(where)) { throw new Error('invalid config location param: ' + where) } const { data, raw } = this.data.get(where) delete data[key] if (['global', 'user', 'project'].includes(where)) { delete raw[key] } } async load () { if (this.loaded) { throw new Error('attempting to load npm config multiple times') } // first load the defaults, which sets the global prefix this.loadDefaults() // next load the builtin config, as this sets new effective defaults await this.loadBuiltinConfig() // cli and env are not async, and can set the prefix, relevant to project this.loadCLI() this.loadEnv() // next project config, which can affect userconfig location await this.loadProjectConfig() // then user config, which can affect globalconfig location await this.loadUserConfig() // last but not least, global config file await this.loadGlobalConfig() // set this before calling setEnvs, so that we don't have to share // private attributes, as that module also does a bunch of get operations this.#loaded = true // set proper globalPrefix now that everything is loaded this.globalPrefix = this.get('prefix') this.setEnvs() } loadDefaults () { this.loadGlobalPrefix() this.loadHome() const defaultsObject = { ...this.defaults, prefix: this.globalPrefix, } try { defaultsObject['npm-version'] = require(join(this.npmPath, 'package.json')).version } catch { // in some weird state where the passed in npmPath does not have a package.json // this will never happen in npm, but is guarded here in case this is consumed // in other ways + tests } this.#loadObject(defaultsObject, 'default', 'default values') const { data } = this.data.get('default') // if the prefix is set on cli, env, or userconfig, then we need to // default the globalconfig file to that location, instead of the default // global prefix. It's weird that `npm get globalconfig --prefix=/foo` // returns `/foo/etc/npmrc`, but better to not change it at this point. // define a custom getter, but turn into a normal prop // if we set it. otherwise it can't be set on child objects Object.defineProperty(data, 'globalconfig', { get: () => resolve(this.#get('prefix'), 'etc/npmrc'), set (value) { Object.defineProperty(data, 'globalconfig', { value, configurable: true, writable: true, enumerable: true, }) }, configurable: true, enumerable: true, }) } loadHome () { this.home = this.env.HOME || homedir() } loadGlobalPrefix () { if (this.globalPrefix) { throw new Error('cannot load default global prefix more than once') } if (this.env.PREFIX) { this.globalPrefix = this.env.PREFIX } else if (this.platform === 'win32') { // c:\node\node.exe --> prefix=c:\node\ this.globalPrefix = dirname(this.execPath) } else { // /usr/local/bin/node --> prefix=/usr/local this.globalPrefix = dirname(dirname(this.execPath)) // destdir only is respected on Unix if (this.env.DESTDIR) { this.globalPrefix = join(this.env.DESTDIR, this.globalPrefix) } } } loadEnv () { const conf = Object.create(null) for (const [envKey, envVal] of Object.entries(this.env)) { if (!/^npm_config_/i.test(envKey) || envVal === '') { continue } let key = envKey.slice('npm_config_'.length) if (!key.startsWith('//')) { // don't normalize nerf-darted keys key = key.replace(/(?!^)_/g, '-') // don't replace _ at the start of the key .toLowerCase() } conf[key] = envVal } this.#loadObject(conf, 'env', 'environment') } loadCLI () { nopt.invalidHandler = (k, val, type) => this.invalidHandler(k, val, type, 'command line options', 'cli') const conf = nopt(this.types, this.shorthands, this.argv) nopt.invalidHandler = null this.parsedArgv = conf.argv delete conf.argv this.#loadObject(conf, 'cli', 'command line options') } get valid () { for (const [where, { valid }] of this.data.entries()) { if (valid === false || valid === null && !this.validate(where)) { return false } } return true } validate (where) { if (!where) { let valid = true const authProblems = [] for (const entryWhere of this.data.keys()) { // no need to validate our defaults, we know they're fine // cli was already validated when parsed the first time if (entryWhere === 'default' || entryWhere === 'builtin' || entryWhere === 'cli') { continue } const ret = this.validate(entryWhere) valid = valid && ret if (['global', 'user', 'project'].includes(entryWhere)) { // after validating everything else, we look for old auth configs we no longer support // if these keys are found, we build up a list of them and the appropriate action and // attach it as context on the thrown error // first, keys that should be removed for (const key of ['_authtoken', '-authtoken']) { if (this.get(key, entryWhere)) { authProblems.push({ action: 'delete', key, where: entryWhere }) } } // NOTE we pull registry without restricting to the current 'where' because we want to // suggest scoping things to the registry they would be applied to, which is the default // regardless of where it was defined const nerfedReg = nerfDart(this.get('registry')) // keys that should be nerfed but currently are not for (const key of ['_auth', '_authToken', 'username', '_password']) { if (this.get(key, entryWhere)) { // username and _password must both exist in the same file to be recognized correctly if (key === 'username' && !this.get('_password', entryWhere)) { authProblems.push({ action: 'delete', key, where: entryWhere }) } else if (key === '_password' && !this.get('username', entryWhere)) { authProblems.push({ action: 'delete', key, where: entryWhere }) } else { authProblems.push({ action: 'rename', from: key, to: `${nerfedReg}:${key}`, where: entryWhere, }) } } } } } if (authProblems.length) { const { ErrInvalidAuth } = require('./errors.js') throw new ErrInvalidAuth(authProblems) } return valid } else { const obj = this.data.get(where) obj[_valid] = true nopt.invalidHandler = (k, val, type) => this.invalidHandler(k, val, type, obj.source, where) nopt.clean(obj.data, this.types, typeDefs) nopt.invalidHandler = null return obj[_valid] } } // fixes problems identified by validate(), accepts the 'problems' property from a thrown // ErrInvalidAuth to avoid having to check everything again repair (problems) { if (!problems) { try { this.validate() } catch (err) { // coverage skipped here because we don't need to test re-throwing an error // istanbul ignore next if (err.code !== 'ERR_INVALID_AUTH') { throw err } problems = err.problems } finally { if (!problems) { problems = [] } } } for (const problem of problems) { // coverage disabled for else branch because it doesn't do anything and shouldn't // istanbul ignore else if (problem.action === 'delete') { this.delete(problem.key, problem.where) } else if (problem.action === 'rename') { const raw = this.data.get(problem.where).raw?.[problem.from] const calculated = this.get(problem.from, problem.where) this.set(problem.to, raw || calculated, problem.where) this.delete(problem.from, problem.where) } } } // Returns true if the value is coming directly from the source defined // in default definitions, if the current value for the key config is // coming from any other different source, returns false isDefault (key) { const [defaultType, ...types] = [...confTypes] const defaultData = this.data.get(defaultType).data return hasOwnProperty(defaultData, key) && types.every(type => { const typeData = this.data.get(type).data return !hasOwnProperty(typeData, key) }) } invalidHandler (k, val, type, source, where) { const typeDescription = require('./type-description.js') log.warn( 'invalid config', k + '=' + JSON.stringify(val), `set in ${source}` ) this.data.get(where)[_valid] = false if (Array.isArray(type)) { if (type.includes(typeDefs.url.type)) { type = typeDefs.url.type } else { /* istanbul ignore if - no actual configs matching this, but * path types SHOULD be handled this way, like URLs, for the * same reason */ if (type.includes(typeDefs.path.type)) { type = typeDefs.path.type } } } const typeDesc = typeDescription(type) const mustBe = typeDesc .filter(m => m !== undefined && m !== Array) const msg = 'Must be' + this.#getOneOfKeywords(mustBe, typeDesc) const desc = mustBe.length === 1 ? mustBe[0] : [...new Set(mustBe.map(n => typeof n === 'string' ? n : JSON.stringify(n)))].join(', ') log.warn('invalid config', msg, desc) } #getOneOfKeywords (mustBe, typeDesc) { let keyword if (mustBe.length === 1 && typeDesc.includes(Array)) { keyword = ' one or more' } else if (mustBe.length > 1 && typeDesc.includes(Array)) { keyword = ' one or more of:' } else if (mustBe.length > 1) { keyword = ' one of:' } else { keyword = '' } return keyword } #loadObject (obj, where, source, er = null) { // obj is the raw data read from the file const conf = this.data.get(where) if (conf.source) { const m = `double-loading "${where}" configs from ${source}, ` + `previously loaded from ${conf.source}` throw new Error(m) } if (this.sources.has(source)) { const m = `double-loading config "${source}" as "${where}", ` + `previously loaded as "${this.sources.get(source)}"` throw new Error(m) } conf.source = source this.sources.set(source, where) if (er) { conf.loadError = er if (er.code !== 'ENOENT') { log.verbose('config', `error loading ${where} config`, er) } } else { conf.raw = obj for (const [key, value] of Object.entries(obj)) { const k = envReplace(key, this.env) const v = this.parseField(value, k) if (where !== 'default') { this.#checkDeprecated(k) if (this.definitions[key]?.exclusive) { for (const exclusive of this.definitions[key].exclusive) { if (!this.isDefault(exclusive)) { throw new TypeError(`--${key} can not be provided when using --${exclusive}`) } } } } conf.data[k] = v } } } #checkDeprecated (key) { // XXX(npm9+) make this throw an error if (this.deprecated[key]) { log.warn('config', key, this.deprecated[key]) } } // Parse a field, coercing it to the best type available. parseField (f, key, listElement = false) { return parseField(f, key, this, listElement) } async #loadFile (file, type) { // only catch the error from readFile, not from the loadObject call log.silly('config', `load:file:${file}`) await readFile(file, 'utf8').then( data => { const parsedConfig = ini.parse(data) if (type === 'project' && parsedConfig.prefix) { // Log error if prefix is mentioned in project .npmrc /* eslint-disable-next-line max-len */ log.error('config', `prefix cannot be changed from project config: ${file}.`) } return this.#loadObject(parsedConfig, type, file) }, er => this.#loadObject(null, type, file, er) ) } loadBuiltinConfig () { return this.#loadFile(resolve(this.npmPath, 'npmrc'), 'builtin') } async loadProjectConfig () { // the localPrefix can be set by the CLI config, but otherwise is // found by walking up the folder tree. either way, we load it before // we return to make sure localPrefix is set await this.loadLocalPrefix() // if we have not detected a local package json yet, try now that we // have a local prefix if (this.localPackage == null) { this.localPackage = await fileExists(this.localPrefix, 'package.json') } if (this.#get('global') === true || this.#get('location') === 'global') { this.data.get('project').source = '(global mode enabled, ignored)' this.sources.set(this.data.get('project').source, 'project') return } const projectFile = resolve(this.localPrefix, '.npmrc') // if we're in the ~ directory, and there happens to be a node_modules // folder (which is not TOO uncommon, it turns out), then we can end // up loading the "project" config where the "userconfig" will be, // which causes some calamaties. So, we only load project config if // it doesn't match what the userconfig will be. if (projectFile !== this.#get('userconfig')) { return this.#loadFile(projectFile, 'project') } else { this.data.get('project').source = '(same as "user" config, ignored)' this.sources.set(this.data.get('project').source, 'project') } } async loadLocalPrefix () { const cliPrefix = this.#get('prefix', 'cli') if (cliPrefix) { this.localPrefix = cliPrefix return } const cliWorkspaces = this.#get('workspaces', 'cli') const isGlobal = this.#get('global') || this.#get('location') === 'global' for (const p of walkUp(this.cwd)) { // HACK: this is an option set in tests to stop the local prefix from being set // on tests that are created inside the npm repo if (this.excludeNpmCwd && p === this.npmPath) { break } const hasPackageJson = await fileExists(p, 'package.json') if (!this.localPrefix && (hasPackageJson || await dirExists(p, 'node_modules'))) { this.localPrefix = p this.localPackage = hasPackageJson // if workspaces are disabled, or we're in global mode, return now if (cliWorkspaces === false || isGlobal) { return } // otherwise, continue the loop continue } if (this.localPrefix && hasPackageJson) { const pkgJson = require('@npmcli/package-json') // if we already set localPrefix but this dir has a package.json // then we need to see if `p` is a workspace root by reading its package.json // however, if reading it fails then we should just move on const { content: pkg } = await pkgJson.normalize(p).catch(() => ({ content: {} })) if (!pkg?.workspaces) { continue } const mapWorkspaces = require('@npmcli/map-workspaces') const workspaces = await mapWorkspaces({ cwd: p, pkg }) for (const w of workspaces.values()) { if (w === this.localPrefix) { // see if there's a .npmrc file in the workspace, if so log a warning if (await fileExists(this.localPrefix, '.npmrc')) { log.warn('config', `ignoring workspace config at ${this.localPrefix}/.npmrc`) } // set the workspace in the default layer, which allows it to be overridden easily const { data } = this.data.get('default') data.workspace = [this.localPrefix] this.localPrefix = p this.localPackage = hasPackageJson log.info('config', `found workspace root at ${this.localPrefix}`) // we found a root, so we return now return } } } } if (!this.localPrefix) { this.localPrefix = this.cwd } } loadUserConfig () { return this.#loadFile(this.#get('userconfig'), 'user') } loadGlobalConfig () { return this.#loadFile(this.#get('globalconfig'), 'global') } async save (where) { if (!this.loaded) { throw new Error('call config.load() before saving') } if (!confFileTypes.has(where)) { throw new Error('invalid config location param: ' + where) } const conf = this.data.get(where) conf[_loadError] = null if (where === 'user') { // if email is nerfed, then we want to de-nerf it const nerfed = nerfDart(this.get('registry')) const email = this.get(`${nerfed}:email`, 'user') if (email) { this.delete(`${nerfed}:email`, 'user') this.set('email', email, 'user') } } // We need the actual raw data before we called parseField so that we are // saving the same content back to the file const iniData = ini.stringify(conf.raw).trim() + '\n' if (!iniData.trim()) { // ignore the unlink error (eg, if file doesn't exist) await unlink(conf.source).catch(() => {}) return } const dir = dirname(conf.source) await mkdir(dir, { recursive: true }) await writeFile(conf.source, iniData, 'utf8') const mode = where === 'user' ? 0o600 : 0o666 await chmod(conf.source, mode) } clearCredentialsByURI (uri, level = 'user') { const nerfed = nerfDart(uri) const def = nerfDart(this.get('registry')) if (def === nerfed) { this.delete(`-authtoken`, level) this.delete(`_authToken`, level) this.delete(`_authtoken`, level) this.delete(`_auth`, level) this.delete(`_password`, level) this.delete(`username`, level) // de-nerf email if it's nerfed to the default registry const email = this.get(`${nerfed}:email`, level) if (email) { this.set('email', email, level) } } this.delete(`${nerfed}:_authToken`, level) this.delete(`${nerfed}:_auth`, level) this.delete(`${nerfed}:_password`, level) this.delete(`${nerfed}:username`, level) this.delete(`${nerfed}:email`, level) this.delete(`${nerfed}:certfile`, level) this.delete(`${nerfed}:keyfile`, level) } setCredentialsByURI (uri, { token, username, password, certfile, keyfile }) { const nerfed = nerfDart(uri) // field that hasn't been used as documented for a LONG time, // and as of npm 7.10.0, isn't used at all. We just always // send auth if we have it, only to the URIs under the nerf dart. this.delete(`${nerfed}:always-auth`, 'user') this.delete(`${nerfed}:email`, 'user') if (certfile && keyfile) { this.set(`${nerfed}:certfile`, certfile, 'user') this.set(`${nerfed}:keyfile`, keyfile, 'user') // cert/key may be used in conjunction with other credentials, thus no `else` } if (token) { this.set(`${nerfed}:_authToken`, token, 'user') this.delete(`${nerfed}:_password`, 'user') this.delete(`${nerfed}:username`, 'user') } else if (username || password) { if (!username) { throw new Error('must include username') } if (!password) { throw new Error('must include password') } this.delete(`${nerfed}:_authToken`, 'user') this.set(`${nerfed}:username`, username, 'user') // note: not encrypted, no idea why we bothered to do this, but oh well // protects against shoulder-hacks if password is memorable, I guess? const encoded = Buffer.from(password, 'utf8').toString('base64') this.set(`${nerfed}:_password`, encoded, 'user') } else if (!certfile || !keyfile) { throw new Error('No credentials to set.') } } // this has to be a bit more complicated to support legacy data of all forms getCredentialsByURI (uri) { const nerfed = nerfDart(uri) const def = nerfDart(this.get('registry')) const creds = {} // email is handled differently, it used to always be nerfed and now it never should be // if it's set nerfed to the default registry, then we copy it to the unnerfed key // TODO: evaluate removing 'email' from the credentials object returned here const email = this.get(`${nerfed}:email`) || this.get('email') if (email) { if (nerfed === def) { this.set('email', email, 'user') } creds.email = email } const certfileReg = this.get(`${nerfed}:certfile`) const keyfileReg = this.get(`${nerfed}:keyfile`) if (certfileReg && keyfileReg) { creds.certfile = certfileReg creds.keyfile = keyfileReg // cert/key may be used in conjunction with other credentials, thus no `return` } const tokenReg = this.get(`${nerfed}:_authToken`) if (tokenReg) { creds.token = tokenReg return creds } const userReg = this.get(`${nerfed}:username`) const passReg = this.get(`${nerfed}:_password`) if (userReg && passReg) { creds.username = userReg creds.password = Buffer.from(passReg, 'base64').toString('utf8') const auth = `${creds.username}:${creds.password}` creds.auth = Buffer.from(auth, 'utf8').toString('base64') return creds } const authReg = this.get(`${nerfed}:_auth`) if (authReg) { const authDecode = Buffer.from(authReg, 'base64').toString('utf8') const authSplit = authDecode.split(':') creds.username = authSplit.shift() creds.password = authSplit.join(':') creds.auth = authReg return creds } // at this point, nothing else is usable so just return what we do have return creds } // set up the environment object we have with npm_config_* environs // for all configs that are different from their default values, and // set EDITOR and HOME. setEnvs () { setEnvs(this) } } const _loadError = Symbol('loadError') const _valid = Symbol('valid') class ConfigData { #data #source = null #raw = null constructor (parent) { this.#data = Object.create(parent && parent.data) this.#raw = {} this[_valid] = true } get data () { return this.#data } get valid () { return this[_valid] } set source (s) { if (this.#source) { throw new Error('cannot set ConfigData source more than once') } this.#source = s } get source () { return this.#source } set loadError (e) { if (this[_loadError] || (Object.keys(this.#raw).length)) { throw new Error('cannot set ConfigData loadError after load') } this[_loadError] = e } get loadError () { return this[_loadError] } set raw (r) { if (Object.keys(this.#raw).length || this[_loadError]) { throw new Error('cannot set ConfigData raw after load') } this.#raw = r } get raw () { return this.#raw } } module.exports = Config const { URL } = require('node:url') /** * Maps a URL to an identifier. * * Name courtesy schiffertronix media LLC, a New Jersey corporation * * @param {String} uri The URL to be nerfed. * * @returns {String} A nerfed URL. */ module.exports = (url) => { const parsed = new URL(url) const from = `${parsed.protocol}//${parsed.host}${parsed.pathname}` const rel = new URL('.', from) const res = `//${rel.host}${rel.pathname}` return res } // Parse a field, coercing it to the best type available. const typeDefs = require('./type-defs.js') const envReplace = require('./env-replace.js') const { resolve } = require('node:path') const { parse: umaskParse } = require('./umask.js') const parseField = (f, key, opts, listElement = false) => { if (typeof f !== 'string' && !Array.isArray(f)) { return f } const { platform, types, home, env } = opts // type can be array or a single thing. coerce to array. const typeList = new Set([].concat(types[key])) const isPath = typeList.has(typeDefs.path.type) const isBool = typeList.has(typeDefs.Boolean.type) const isString = isPath || typeList.has(typeDefs.String.type) const isUmask = typeList.has(typeDefs.Umask.type) const isNumber = typeList.has(typeDefs.Number.type) const isList = !listElement && typeList.has(Array) const isDate = typeList.has(typeDefs.Date.type) if (Array.isArray(f)) { return !isList ? f : f.map(field => parseField(field, key, opts, true)) } // now we know it's a string f = f.trim() // list types get put in the environment separated by double-\n // usually a single \n would suffice, but ca/cert configs can contain // line breaks and multiple entries. if (isList) { return parseField(f.split('\n\n'), key, opts) } // --foo is like --foo=true for boolean types if (isBool && !isString && f === '') { return true } // string types can be the string 'true', 'false', etc. // otherwise, parse these values out if (!isString && !isPath && !isNumber) { switch (f) { case 'true': return true case 'false': return false case 'null': return null case 'undefined': return undefined } } f = envReplace(f, env) if (isDate) { return new Date(f) } if (isPath) { const homePattern = platform === 'win32' ? /^~(\/|\\)/ : /^~\// if (homePattern.test(f) && home) { f = resolve(home, f.slice(2)) } else { f = resolve(f) } } if (isUmask) { try { return umaskParse(f) } catch (er) { // let it warn later when we validate return f } } if (isNumber && !isNaN(f)) { f = +f } return f } module.exports = parseField // Set environment variables for any non-default configs, // so that they're already there when we run lifecycle scripts. // // See https://github.com/npm/rfcs/pull/90 // Return the env key if this is a thing that belongs in the env. // Ie, if the key isn't a @scope, //nerf.dart, or _private, // and the value is a string or array. Otherwise return false. const envKey = (key, val) => { return !/^[/@_]/.test(key) && (typeof envVal(val) === 'string') && `npm_config_${key.replace(/-/g, '_').toLowerCase()}` } const envVal = val => Array.isArray(val) ? val.map(v => envVal(v)).join('\n\n') : val === null || val === undefined || val === false ? '' : typeof val === 'object' ? null : String(val) const sameConfigValue = (def, val) => !Array.isArray(val) || !Array.isArray(def) ? def === val : sameArrayValue(def, val) const sameArrayValue = (def, val) => { if (def.length !== val.length) { return false } for (let i = 0; i < def.length; i++) { /* istanbul ignore next - there are no array configs where the default * is not an empty array, so this loop is a no-op, but it's the correct * thing to do if we ever DO add a config like that. */ if (def[i] !== val[i]) { return false } } return true } const setEnv = (env, rawKey, rawVal) => { const val = envVal(rawVal) const key = envKey(rawKey, val) if (key && val !== null) { env[key] = val } } const setEnvs = (config) => { // This ensures that all npm config values that are not the defaults are // shared appropriately with child processes, without false positives. const { env, defaults, definitions, list: [cliConf, envConf], } = config env.INIT_CWD = process.cwd() // if the key is deprecated, skip it always. // if the key is the default value, // if the environ is NOT the default value, // set the environ // else skip it, it's fine // if the key is NOT the default value, // if the env is setting it, then leave it (already set) // otherwise, set the env const cliSet = new Set(Object.keys(cliConf)) const envSet = new Set(Object.keys(envConf)) for (const key in cliConf) { const { deprecated, envExport = true } = definitions[key] || {} if (deprecated || envExport === false) { continue } if (sameConfigValue(defaults[key], cliConf[key])) { // config is the default, if the env thought different, then we // have to set it BACK to the default in the environment. if (!sameConfigValue(envConf[key], cliConf[key])) { setEnv(env, key, cliConf[key]) } } else { // config is not the default. if the env wasn't the one to set // it that way, then we have to put it in the env if (!(envSet.has(key) && !cliSet.has(key))) { setEnv(env, key, cliConf[key]) } } } // also set some other common nice envs that we want to rely on env.HOME = config.home env.npm_config_global_prefix = config.globalPrefix env.npm_config_local_prefix = config.localPrefix if (cliConf.editor) { env.EDITOR = cliConf.editor } // note: this doesn't afect the *current* node process, of course, since // it's already started, but it does affect the options passed to scripts. if (cliConf['node-options']) { env.NODE_OPTIONS = cliConf['node-options'] } env.npm_execpath = config.npmBin env.NODE = env.npm_node_execpath = config.execPath } module.exports = setEnvs const nopt = require('nopt') const { validate: validateUmask } = require('./umask.js') class Umask {} class Semver {} const semverValid = require('semver/functions/valid') const validateSemver = (data, k, val) => { const valid = semverValid(val) if (!valid) { return false } data[k] = valid } const noptValidatePath = nopt.typeDefs.path.validate const validatePath = (data, k, val) => { if (typeof val !== 'string') { return false } return noptValidatePath(data, k, val) } // add descriptions so we can validate more usefully module.exports = { ...nopt.typeDefs, semver: { type: Semver, validate: validateSemver, description: 'full valid SemVer string', }, Umask: { type: Umask, validate: validateUmask, description: 'octal number in range 0o000..0o777 (0..511)', }, url: { ...nopt.typeDefs.url, description: 'full url with "http://"', }, path: { ...nopt.typeDefs.path, validate: validatePath, description: 'valid filesystem path', }, Number: { ...nopt.typeDefs.Number, description: 'numeric value', }, Boolean: { ...nopt.typeDefs.Boolean, description: 'boolean value (true or false)', }, Date: { ...nopt.typeDefs.Date, description: 'valid Date string', }, } // TODO: make nopt less of a global beast so this kludge isn't necessary nopt.typeDefs = module.exports // return the description of the valid values of a field // returns a string for one thing, or an array of descriptions const typeDefs = require('./type-defs.js') const typeDescription = t => { if (!t || typeof t !== 'function' && typeof t !== 'object') { return t } if (Array.isArray(t)) { return t.map(t => typeDescription(t)) } for (const { type, description } of Object.values(typeDefs)) { if (type === t) { return description || type } } return t } module.exports = t => [].concat(typeDescription(t)).filter(t => t !== undefined) const parse = val => { // this is run via nopt and parse field where everything is // converted to a string first, ignoring coverage for now // instead of figuring out what is happening under the hood in nopt // istanbul ignore else if (typeof val === 'string') { if (/^0o?[0-7]+$/.test(val)) { return parseInt(val.replace(/^0o?/, ''), 8) } else if (/^[1-9][0-9]*$/.test(val)) { return parseInt(val, 10) } else { throw new Error(`invalid umask value: ${val}`) } } else { if (typeof val !== 'number') { throw new Error(`invalid umask value: ${val}`) } val = Math.floor(val) if (val < 0 || val > 511) { throw new Error(`invalid umask value: ${val}`) } return val } } const validate = (data, k, val) => { try { data[k] = parse(val) return true } catch (er) { return false } } module.exports = { parse, validate } { "name": "@npmcli/config", "version": "10.0.1", "files": [ "bin/", "lib/" ], "main": "lib/index.js", "description": "Configuration management for the npm cli", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/config" }, "author": "GitHub Inc.", "license": "ISC", "scripts": { "test": "tap", "snap": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-globals": "^1.0.0", "@npmcli/template-oss": "4.23.6", "tap": "^16.3.8" }, "dependencies": { "@npmcli/map-workspaces": "^4.0.1", "@npmcli/package-json": "^6.0.1", "ci-info": "^4.0.0", "ini": "^5.0.0", "nopt": "^8.0.0", "proc-log": "^5.0.0", "semver": "^7.3.5", "walk-up-path": "^4.0.0" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" } } ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // given an input that may or may not be an object, return an object that has // a copy of every defined property listed in 'copy'. if the input is not an // object, assign it to the property named by 'wrap' const getOptions = (input, { copy, wrap }) => { const result = {} if (input && typeof input === 'object') { for (const prop of copy) { if (input[prop] !== undefined) { result[prop] = input[prop] } } } else { result[wrap] = input } return result } module.exports = getOptions const semver = require('semver') const satisfies = (range) => { return semver.satisfies(process.version, range, { includePrerelease: true }) } module.exports = { satisfies, } (The MIT License) Copyright (c) 2011-2017 JP Richardson 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. 'use strict' const { inspect } = require('util') // adapted from node's internal/errors // https://github.com/nodejs/node/blob/c8a04049/lib/internal/errors.js // close copy of node's internal SystemError class. class SystemError { constructor (code, prefix, context) { // XXX context.code is undefined in all constructors used in cp/polyfill // that may be a bug copied from node, maybe the constructor should use // `code` not `errno`? nodejs/node#41104 let message = `${prefix}: ${context.syscall} returned ` + `${context.code} (${context.message})` if (context.path !== undefined) { message += ` ${context.path}` } if (context.dest !== undefined) { message += ` => ${context.dest}` } this.code = code Object.defineProperties(this, { name: { value: 'SystemError', enumerable: false, writable: true, configurable: true, }, message: { value: message, enumerable: false, writable: true, configurable: true, }, info: { value: context, enumerable: true, configurable: true, writable: false, }, errno: { get () { return context.errno }, set (value) { context.errno = value }, enumerable: true, configurable: true, }, syscall: { get () { return context.syscall }, set (value) { context.syscall = value }, enumerable: true, configurable: true, }, }) if (context.path !== undefined) { Object.defineProperty(this, 'path', { get () { return context.path }, set (value) { context.path = value }, enumerable: true, configurable: true, }) } if (context.dest !== undefined) { Object.defineProperty(this, 'dest', { get () { return context.dest }, set (value) { context.dest = value }, enumerable: true, configurable: true, }) } } toString () { return `${this.name} [${this.code}]: ${this.message}` } [Symbol.for('nodejs.util.inspect.custom')] (_recurseTimes, ctx) { return inspect(this, { ...ctx, getters: true, customInspect: false, }) } } function E (code, message) { module.exports[code] = class NodeError extends SystemError { constructor (ctx) { super(code, message, ctx) } } } E('ERR_FS_CP_DIR_TO_NON_DIR', 'Cannot overwrite directory with non-directory') E('ERR_FS_CP_EEXIST', 'Target already exists') E('ERR_FS_CP_EINVAL', 'Invalid src or dest') E('ERR_FS_CP_FIFO_PIPE', 'Cannot copy a FIFO pipe') E('ERR_FS_CP_NON_DIR_TO_DIR', 'Cannot overwrite non-directory with directory') E('ERR_FS_CP_SOCKET', 'Cannot copy a socket file') E('ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY', 'Cannot overwrite symlink in subdirectory of self') E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type') E('ERR_FS_EISDIR', 'Path is a directory') module.exports.ERR_INVALID_ARG_TYPE = class ERR_INVALID_ARG_TYPE extends Error { constructor (name, expected, actual) { super() this.code = 'ERR_INVALID_ARG_TYPE' this.message = `The ${name} argument must be ${expected}. Received ${typeof actual}` } } const fs = require('fs/promises') const getOptions = require('../common/get-options.js') const node = require('../common/node.js') const polyfill = require('./polyfill.js') // node 16.7.0 added fs.cp const useNative = node.satisfies('>=16.7.0') const cp = async (src, dest, opts) => { const options = getOptions(opts, { copy: ['dereference', 'errorOnExist', 'filter', 'force', 'preserveTimestamps', 'recursive'], }) // the polyfill is tested separately from this module, no need to hack // process.version to try to trigger it just for coverage // istanbul ignore next return useNative ? fs.cp(src, dest, options) : polyfill(src, dest, options) } module.exports = cp // this file is a modified version of the code in node 17.2.0 // which is, in turn, a modified version of the fs-extra module on npm // node core changes: // - Use of the assert module has been replaced with core's error system. // - All code related to the glob dependency has been removed. // - Bring your own custom fs module is not currently supported. // - Some basic code cleanup. // changes here: // - remove all callback related code // - drop sync support // - change assertions back to non-internal methods (see options.js) // - throws ENOTDIR when rmdir gets an ENOENT for a path that exists in Windows 'use strict' const { ERR_FS_CP_DIR_TO_NON_DIR, ERR_FS_CP_EEXIST, ERR_FS_CP_EINVAL, ERR_FS_CP_FIFO_PIPE, ERR_FS_CP_NON_DIR_TO_DIR, ERR_FS_CP_SOCKET, ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY, ERR_FS_CP_UNKNOWN, ERR_FS_EISDIR, ERR_INVALID_ARG_TYPE, } = require('./errors.js') const { constants: { errno: { EEXIST, EISDIR, EINVAL, ENOTDIR, }, }, } = require('os') const { chmod, copyFile, lstat, mkdir, readdir, readlink, stat, symlink, unlink, utimes, } = require('fs/promises') const { dirname, isAbsolute, join, parse, resolve, sep, toNamespacedPath, } = require('path') const { fileURLToPath } = require('url') const defaultOptions = { dereference: false, errorOnExist: false, filter: undefined, force: true, preserveTimestamps: false, recursive: false, } async function cp (src, dest, opts) { if (opts != null && typeof opts !== 'object') { throw new ERR_INVALID_ARG_TYPE('options', ['Object'], opts) } return cpFn( toNamespacedPath(getValidatedPath(src)), toNamespacedPath(getValidatedPath(dest)), { ...defaultOptions, ...opts }) } function getValidatedPath (fileURLOrPath) { const path = fileURLOrPath != null && fileURLOrPath.href && fileURLOrPath.origin ? fileURLToPath(fileURLOrPath) : fileURLOrPath return path } async function cpFn (src, dest, opts) { // Warn about using preserveTimestamps on 32-bit node // istanbul ignore next if (opts.preserveTimestamps && process.arch === 'ia32') { const warning = 'Using the preserveTimestamps option in 32-bit ' + 'node is not recommended' process.emitWarning(warning, 'TimestampPrecisionWarning') } const stats = await checkPaths(src, dest, opts) const { srcStat, destStat } = stats await checkParentPaths(src, srcStat, dest) if (opts.filter) { return handleFilter(checkParentDir, destStat, src, dest, opts) } return checkParentDir(destStat, src, dest, opts) } async function checkPaths (src, dest, opts) { const { 0: srcStat, 1: destStat } = await getStats(src, dest, opts) if (destStat) { if (areIdentical(srcStat, destStat)) { throw new ERR_FS_CP_EINVAL({ message: 'src and dest cannot be the same', path: dest, syscall: 'cp', errno: EINVAL, }) } if (srcStat.isDirectory() && !destStat.isDirectory()) { throw new ERR_FS_CP_DIR_TO_NON_DIR({ message: `cannot overwrite directory ${src} ` + `with non-directory ${dest}`, path: dest, syscall: 'cp', errno: EISDIR, }) } if (!srcStat.isDirectory() && destStat.isDirectory()) { throw new ERR_FS_CP_NON_DIR_TO_DIR({ message: `cannot overwrite non-directory ${src} ` + `with directory ${dest}`, path: dest, syscall: 'cp', errno: ENOTDIR, }) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { throw new ERR_FS_CP_EINVAL({ message: `cannot copy ${src} to a subdirectory of self ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } return { srcStat, destStat } } function areIdentical (srcStat, destStat) { return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev } function getStats (src, dest, opts) { const statFunc = opts.dereference ? (file) => stat(file, { bigint: true }) : (file) => lstat(file, { bigint: true }) return Promise.all([ statFunc(src), statFunc(dest).catch((err) => { // istanbul ignore next: unsure how to cover. if (err.code === 'ENOENT') { return null } // istanbul ignore next: unsure how to cover. throw err }), ]) } async function checkParentDir (destStat, src, dest, opts) { const destParent = dirname(dest) const dirExists = await pathExists(destParent) if (dirExists) { return getStatsForCopy(destStat, src, dest, opts) } await mkdir(destParent, { recursive: true }) return getStatsForCopy(destStat, src, dest, opts) } function pathExists (dest) { return stat(dest).then( () => true, // istanbul ignore next: not sure when this would occur (err) => (err.code === 'ENOENT' ? false : Promise.reject(err))) } // Recursively check if dest parent is a subdirectory of src. // It works for all file types including symlinks since it // checks the src and dest inodes. It starts from the deepest // parent and stops once it reaches the src parent or the root path. async function checkParentPaths (src, srcStat, dest) { const srcParent = resolve(dirname(src)) const destParent = resolve(dirname(dest)) if (destParent === srcParent || destParent === parse(destParent).root) { return } let destStat try { destStat = await stat(destParent, { bigint: true }) } catch (err) { // istanbul ignore else: not sure when this would occur if (err.code === 'ENOENT') { return } // istanbul ignore next: not sure when this would occur throw err } if (areIdentical(srcStat, destStat)) { throw new ERR_FS_CP_EINVAL({ message: `cannot copy ${src} to a subdirectory of self ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } return checkParentPaths(src, srcStat, destParent) } const normalizePathToArray = (path) => resolve(path).split(sep).filter(Boolean) // Return true if dest is a subdir of src, otherwise false. // It only checks the path strings. function isSrcSubdir (src, dest) { const srcArr = normalizePathToArray(src) const destArr = normalizePathToArray(dest) return srcArr.every((cur, i) => destArr[i] === cur) } async function handleFilter (onInclude, destStat, src, dest, opts, cb) { const include = await opts.filter(src, dest) if (include) { return onInclude(destStat, src, dest, opts, cb) } } function startCopy (destStat, src, dest, opts) { if (opts.filter) { return handleFilter(getStatsForCopy, destStat, src, dest, opts) } return getStatsForCopy(destStat, src, dest, opts) } async function getStatsForCopy (destStat, src, dest, opts) { const statFn = opts.dereference ? stat : lstat const srcStat = await statFn(src) // istanbul ignore else: can't portably test FIFO if (srcStat.isDirectory() && opts.recursive) { return onDir(srcStat, destStat, src, dest, opts) } else if (srcStat.isDirectory()) { throw new ERR_FS_EISDIR({ message: `${src} is a directory (not copied)`, path: src, syscall: 'cp', errno: EINVAL, }) } else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) { return onFile(srcStat, destStat, src, dest, opts) } else if (srcStat.isSymbolicLink()) { return onLink(destStat, src, dest) } else if (srcStat.isSocket()) { throw new ERR_FS_CP_SOCKET({ message: `cannot copy a socket file: ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } else if (srcStat.isFIFO()) { throw new ERR_FS_CP_FIFO_PIPE({ message: `cannot copy a FIFO pipe: ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } // istanbul ignore next: should be unreachable throw new ERR_FS_CP_UNKNOWN({ message: `cannot copy an unknown file type: ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } function onFile (srcStat, destStat, src, dest, opts) { if (!destStat) { return _copyFile(srcStat, src, dest, opts) } return mayCopyFile(srcStat, src, dest, opts) } async function mayCopyFile (srcStat, src, dest, opts) { if (opts.force) { await unlink(dest) return _copyFile(srcStat, src, dest, opts) } else if (opts.errorOnExist) { throw new ERR_FS_CP_EEXIST({ message: `${dest} already exists`, path: dest, syscall: 'cp', errno: EEXIST, }) } } async function _copyFile (srcStat, src, dest, opts) { await copyFile(src, dest) if (opts.preserveTimestamps) { return handleTimestampsAndMode(srcStat.mode, src, dest) } return setDestMode(dest, srcStat.mode) } async function handleTimestampsAndMode (srcMode, src, dest) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcMode)) { await makeFileWritable(dest, srcMode) return setDestTimestampsAndMode(srcMode, src, dest) } return setDestTimestampsAndMode(srcMode, src, dest) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable (dest, srcMode) { return setDestMode(dest, srcMode | 0o200) } async function setDestTimestampsAndMode (srcMode, src, dest) { await setDestTimestamps(src, dest) return setDestMode(dest, srcMode) } function setDestMode (dest, srcMode) { return chmod(dest, srcMode) } async function setDestTimestamps (src, dest) { // The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) const updatedSrcStat = await stat(src) return utimes(dest, updatedSrcStat.atime, updatedSrcStat.mtime) } function onDir (srcStat, destStat, src, dest, opts) { if (!destStat) { return mkDirAndCopy(srcStat.mode, src, dest, opts) } return copyDir(src, dest, opts) } async function mkDirAndCopy (srcMode, src, dest, opts) { await mkdir(dest) await copyDir(src, dest, opts) return setDestMode(dest, srcMode) } async function copyDir (src, dest, opts) { const dir = await readdir(src) for (let i = 0; i < dir.length; i++) { const item = dir[i] const srcItem = join(src, item) const destItem = join(dest, item) const { destStat } = await checkPaths(srcItem, destItem, opts) await startCopy(destStat, srcItem, destItem, opts) } } async function onLink (destStat, src, dest) { let resolvedSrc = await readlink(src) if (!isAbsolute(resolvedSrc)) { resolvedSrc = resolve(dirname(src), resolvedSrc) } if (!destStat) { return symlink(resolvedSrc, dest) } let resolvedDest try { resolvedDest = await readlink(dest) } catch (err) { // Dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. // istanbul ignore next: can only test on windows if (err.code === 'EINVAL' || err.code === 'UNKNOWN') { return symlink(resolvedSrc, dest) } // istanbul ignore next: should not be possible throw err } if (!isAbsolute(resolvedDest)) { resolvedDest = resolve(dirname(dest), resolvedDest) } if (isSrcSubdir(resolvedSrc, resolvedDest)) { throw new ERR_FS_CP_EINVAL({ message: `cannot copy ${resolvedSrc} to a subdirectory of self ` + `${resolvedDest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } // Do not copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. const srcStat = await stat(src) if (srcStat.isDirectory() && isSrcSubdir(resolvedDest, resolvedSrc)) { throw new ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY({ message: `cannot overwrite ${resolvedDest} with ${resolvedSrc}`, path: dest, syscall: 'cp', errno: EINVAL, }) } return copyLink(resolvedSrc, dest) } async function copyLink (resolvedSrc, dest) { await unlink(dest) return symlink(resolvedSrc, dest) } module.exports = cp 'use strict' const cp = require('./cp/index.js') const withTempDir = require('./with-temp-dir.js') const readdirScoped = require('./readdir-scoped.js') const moveFile = require('./move-file.js') module.exports = { cp, withTempDir, readdirScoped, moveFile, } const { dirname, join, resolve, relative, isAbsolute } = require('path') const fs = require('fs/promises') const pathExists = async path => { try { await fs.access(path) return true } catch (er) { return er.code !== 'ENOENT' } } const moveFile = async (source, destination, options = {}, root = true, symlinks = []) => { if (!source || !destination) { throw new TypeError('`source` and `destination` file required') } options = { overwrite: true, ...options, } if (!options.overwrite && await pathExists(destination)) { throw new Error(`The destination file exists: ${destination}`) } await fs.mkdir(dirname(destination), { recursive: true }) try { await fs.rename(source, destination) } catch (error) { if (error.code === 'EXDEV' || error.code === 'EPERM') { const sourceStat = await fs.lstat(source) if (sourceStat.isDirectory()) { const files = await fs.readdir(source) await Promise.all(files.map((file) => moveFile(join(source, file), join(destination, file), options, false, symlinks) )) } else if (sourceStat.isSymbolicLink()) { symlinks.push({ source, destination }) } else { await fs.copyFile(source, destination) } } else { throw error } } if (root) { await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => { let target = await fs.readlink(symSource) // junction symlinks in windows will be absolute paths, so we need to // make sure they point to the symlink destination if (isAbsolute(target)) { target = resolve(symDestination, relative(symSource, target)) } // try to determine what the actual file is so we can create the correct // type of symlink in windows let targetStat = 'file' try { targetStat = await fs.stat(resolve(dirname(symSource), target)) if (targetStat.isDirectory()) { targetStat = 'junction' } } catch { // targetStat remains 'file' } await fs.symlink( target, symDestination, targetStat ) })) await fs.rm(source, { recursive: true, force: true }) } } module.exports = moveFile const { readdir } = require('fs/promises') const { join } = require('path') const readdirScoped = async (dir) => { const results = [] for (const item of await readdir(dir)) { if (item.startsWith('@')) { for (const scopedItem of await readdir(join(dir, item))) { results.push(join(item, scopedItem)) } } else { results.push(item) } } return results } module.exports = readdirScoped const { join, sep } = require('path') const getOptions = require('./common/get-options.js') const { mkdir, mkdtemp, rm } = require('fs/promises') // create a temp directory, ensure its permissions match its parent, then call // the supplied function passing it the path to the directory. clean up after // the function finishes, whether it throws or not const withTempDir = async (root, fn, opts) => { const options = getOptions(opts, { copy: ['tmpPrefix'], }) // create the directory await mkdir(root, { recursive: true }) const target = await mkdtemp(join(`${root}${sep}`, options.tmpPrefix || '')) let err let result try { result = await fn(target) } catch (_err) { err = _err } try { await rm(target, { force: true, recursive: true }) } catch { // ignore errors } if (err) { throw err } return result } module.exports = withTempDir { "name": "@npmcli/fs", "version": "4.0.0", "description": "filesystem utilities for the npm cli", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "scripts": { "snap": "tap", "test": "tap", "npmclilint": "npmcli-lint", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "postsnap": "npm run lintfix --", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/fs.git" }, "keywords": [ "npm", "oss" ], "author": "GitHub Inc.", "license": "ISC", "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.0.1" }, "dependencies": { "semver": "^7.3.5" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // The goal here is to minimize both git workload and // the number of refs we download over the network. // // Every method ends up with the checked out working dir // at the specified ref, and resolves with the git sha. // Only certain whitelisted hosts get shallow cloning. // Many hosts (including GHE) don't always support it. // A failed shallow fetch takes a LOT longer than a full // fetch in most cases, so we skip it entirely. // Set opts.gitShallow = true/false to force this behavior // one way or the other. const shallowHosts = new Set([ 'github.com', 'gist.github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org', ]) // we have to use url.parse until we add the same shim that hosted-git-info has // to handle scp:// urls const { parse } = require('url') // eslint-disable-line node/no-deprecated-api const path = require('path') const getRevs = require('./revs.js') const spawn = require('./spawn.js') const { isWindows } = require('./utils.js') const pickManifest = require('npm-pick-manifest') const fs = require('fs/promises') module.exports = (repo, ref = 'HEAD', target = null, opts = {}) => getRevs(repo, opts).then(revs => clone( repo, revs, ref, resolveRef(revs, ref, opts), target || defaultTarget(repo, opts.cwd), opts )) const maybeShallow = (repo, opts) => { if (opts.gitShallow === false || opts.gitShallow) { return opts.gitShallow } return shallowHosts.has(parse(repo).host) } const defaultTarget = (repo, /* istanbul ignore next */ cwd = process.cwd()) => path.resolve(cwd, path.basename(repo.replace(/[/\\]?\.git$/, ''))) const clone = (repo, revs, ref, revDoc, target, opts) => { if (!revDoc) { return unresolved(repo, ref, target, opts) } if (revDoc.sha === revs.refs.HEAD.sha) { return plain(repo, revDoc, target, opts) } if (revDoc.type === 'tag' || revDoc.type === 'branch') { return branch(repo, revDoc, target, opts) } return other(repo, revDoc, target, opts) } const resolveRef = (revs, ref, opts) => { const { spec = {} } = opts ref = spec.gitCommittish || ref /* istanbul ignore next - will fail anyway, can't pull */ if (!revs) { return null } if (spec.gitRange) { return pickManifest(revs, spec.gitRange, opts) } if (!ref) { return revs.refs.HEAD } if (revs.refs[ref]) { return revs.refs[ref] } if (revs.shas[ref]) { return revs.refs[revs.shas[ref][0]] } return null } // pull request or some other kind of advertised ref const other = (repo, revDoc, target, opts) => { const shallow = maybeShallow(repo, opts) const fetchOrigin = ['fetch', 'origin', revDoc.rawRef] .concat(shallow ? ['--depth=1'] : []) const git = (args) => spawn(args, { ...opts, cwd: target }) return fs.mkdir(target, { recursive: true }) .then(() => git(['init'])) .then(() => isWindows(opts) ? git(['config', '--local', '--add', 'core.longpaths', 'true']) : null) .then(() => git(['remote', 'add', 'origin', repo])) .then(() => git(fetchOrigin)) .then(() => git(['checkout', revDoc.sha])) .then(() => updateSubmodules(target, opts)) .then(() => revDoc.sha) } // tag or branches. use -b const branch = (repo, revDoc, target, opts) => { const args = [ 'clone', '-b', revDoc.ref, repo, target, '--recurse-submodules', ] if (maybeShallow(repo, opts)) { args.push('--depth=1') } if (isWindows(opts)) { args.push('--config', 'core.longpaths=true') } return spawn(args, opts).then(() => revDoc.sha) } // just the head. clone it const plain = (repo, revDoc, target, opts) => { const args = [ 'clone', repo, target, '--recurse-submodules', ] if (maybeShallow(repo, opts)) { args.push('--depth=1') } if (isWindows(opts)) { args.push('--config', 'core.longpaths=true') } return spawn(args, opts).then(() => revDoc.sha) } const updateSubmodules = async (target, opts) => { const hasSubmodules = await fs.stat(`${target}/.gitmodules`) .then(() => true) .catch(() => false) if (!hasSubmodules) { return null } return spawn([ 'submodule', 'update', '-q', '--init', '--recursive', ], { ...opts, cwd: target }) } const unresolved = (repo, ref, target, opts) => { // can't do this one shallowly, because the ref isn't advertised // but we can avoid checking out the working dir twice, at least const lp = isWindows(opts) ? ['--config', 'core.longpaths=true'] : [] const cloneArgs = ['clone', '--mirror', '-q', repo, target + '/.git'] const git = (args) => spawn(args, { ...opts, cwd: target }) return fs.mkdir(target, { recursive: true }) .then(() => git(cloneArgs.concat(lp))) .then(() => git(['init'])) .then(() => git(['checkout', ref])) .then(() => updateSubmodules(target, opts)) .then(() => git(['rev-parse', '--revs-only', 'HEAD'])) .then(({ stdout }) => stdout.trim()) } const maxRetry = 3 class GitError extends Error { shouldRetry () { return false } } class GitConnectionError extends GitError { constructor () { super('A git connection error occurred') } shouldRetry (number) { return number < maxRetry } } class GitPathspecError extends GitError { constructor () { super('The git reference could not be found') } } class GitUnknownError extends GitError { constructor () { super('An unknown git error occurred') } } module.exports = { GitConnectionError, GitPathspecError, GitUnknownError, } const is = require('./is.js') const { dirname } = require('path') module.exports = async ({ cwd = process.cwd(), root } = {}) => { while (true) { if (await is({ cwd })) { return cwd } const next = dirname(cwd) if (cwd === root || cwd === next) { return null } cwd = next } } module.exports = { clone: require('./clone.js'), revs: require('./revs.js'), spawn: require('./spawn.js'), is: require('./is.js'), find: require('./find.js'), isClean: require('./is-clean.js'), errors: require('./errors.js'), } const spawn = require('./spawn.js') module.exports = (opts = {}) => spawn(['status', '--porcelain=v1', '-uno'], opts) .then(res => !res.stdout.trim().split(/\r?\n+/) .map(l => l.trim()).filter(l => l).length) // not an airtight indicator, but a good gut-check to even bother trying const { stat } = require('fs/promises') module.exports = ({ cwd = process.cwd() } = {}) => stat(cwd + '/.git').then(() => true, () => false) // turn an array of lines from `git ls-remote` into a thing // vaguely resembling a packument, where docs are a resolved ref const semver = require('semver') module.exports = lines => finish(lines.reduce(linesToRevsReducer, { versions: {}, 'dist-tags': {}, refs: {}, shas: {}, })) const finish = revs => distTags(shaList(peelTags(revs))) // We can check out shallow clones on specific SHAs if we have a ref const shaList = revs => { Object.keys(revs.refs).forEach(ref => { const doc = revs.refs[ref] if (!revs.shas[doc.sha]) { revs.shas[doc.sha] = [ref] } else { revs.shas[doc.sha].push(ref) } }) return revs } // Replace any tags with their ^{} counterparts, if those exist const peelTags = revs => { Object.keys(revs.refs).filter(ref => ref.endsWith('^{}')).forEach(ref => { const peeled = revs.refs[ref] const unpeeled = revs.refs[ref.replace(/\^\{\}$/, '')] if (unpeeled) { unpeeled.sha = peeled.sha delete revs.refs[ref] } }) return revs } const distTags = revs => { // not entirely sure what situations would result in an // ichabod repo, but best to be careful in Sleepy Hollow anyway const HEAD = revs.refs.HEAD || /* istanbul ignore next */ {} const versions = Object.keys(revs.versions) versions.forEach(v => { // simulate a dist-tags with latest pointing at the // 'latest' branch if one exists and is a version, // or HEAD if not. const ver = revs.versions[v] if (revs.refs.latest && ver.sha === revs.refs.latest.sha) { revs['dist-tags'].latest = v } else if (ver.sha === HEAD.sha) { revs['dist-tags'].HEAD = v if (!revs.refs.latest) { revs['dist-tags'].latest = v } } }) return revs } const refType = ref => { if (ref.startsWith('refs/tags/')) { return 'tag' } if (ref.startsWith('refs/heads/')) { return 'branch' } if (ref.startsWith('refs/pull/')) { return 'pull' } if (ref === 'HEAD') { return 'head' } // Could be anything, ignore for now /* istanbul ignore next */ return 'other' } // return the doc, or null if we should ignore it. const lineToRevDoc = line => { const split = line.trim().split(/\s+/, 2) if (split.length < 2) { return null } const sha = split[0].trim() const rawRef = split[1].trim() const type = refType(rawRef) if (type === 'tag') { // refs/tags/foo^{} is the 'peeled tag', ie the commit // that is tagged by refs/tags/foo they resolve to the same // content, just different objects in git's data structure. // But, we care about the thing the tag POINTS to, not the tag // object itself, so we only look at the peeled tag refs, and // ignore the pointer. // For now, though, we have to save both, because some tags // don't have peels, if they were not annotated. const ref = rawRef.slice('refs/tags/'.length) return { sha, ref, rawRef, type } } if (type === 'branch') { const ref = rawRef.slice('refs/heads/'.length) return { sha, ref, rawRef, type } } if (type === 'pull') { // NB: merged pull requests installable with #pull/123/merge // for the merged pr, or #pull/123 for the PR head const ref = rawRef.slice('refs/'.length).replace(/\/head$/, '') return { sha, ref, rawRef, type } } if (type === 'head') { const ref = 'HEAD' return { sha, ref, rawRef, type } } // at this point, all we can do is leave the ref un-munged return { sha, ref: rawRef, rawRef, type } } const linesToRevsReducer = (revs, line) => { const doc = lineToRevDoc(line) if (!doc) { return revs } revs.refs[doc.ref] = doc revs.refs[doc.rawRef] = doc if (doc.type === 'tag') { // try to pull a semver value out of tags like `release-v1.2.3` // which is a pretty common pattern. const match = !doc.ref.endsWith('^{}') && doc.ref.match(/v?(\d+\.\d+\.\d+(?:[-+].+)?)$/) if (match && semver.valid(match[1], true)) { revs.versions[semver.clean(match[1], true)] = doc } } return revs } const { GitConnectionError, GitPathspecError, GitUnknownError, } = require('./errors.js') const connectionErrorRe = new RegExp([ 'remote error: Internal Server Error', 'The remote end hung up unexpectedly', 'Connection timed out', 'Operation timed out', 'Failed to connect to .* Timed out', 'Connection reset by peer', 'SSL_ERROR_SYSCALL', 'The requested URL returned error: 503', ].join('|')) const missingPathspecRe = /pathspec .* did not match any file\(s\) known to git/ function makeError (er) { const message = er.stderr let gitEr if (connectionErrorRe.test(message)) { gitEr = new GitConnectionError(message) } else if (missingPathspecRe.test(message)) { gitEr = new GitPathspecError(message) } else { gitEr = new GitUnknownError(message) } return Object.assign(gitEr, er) } module.exports = makeError const fs = require('node:fs') const os = require('node:os') const path = require('node:path') const ini = require('ini') const gitConfigPath = path.join(os.homedir(), '.gitconfig') let cachedConfig = null // Function to load and cache the git config const loadGitConfig = () => { if (cachedConfig === null) { try { cachedConfig = {} if (fs.existsSync(gitConfigPath)) { const configContent = fs.readFileSync(gitConfigPath, 'utf-8') cachedConfig = ini.parse(configContent) } } catch (error) { cachedConfig = {} } } return cachedConfig } const checkGitConfigs = () => { const config = loadGitConfig() return { sshCommandSetInConfig: config?.core?.sshCommand !== undefined, askPassSetInConfig: config?.core?.askpass !== undefined, } } const sshCommandSetInEnv = process.env.GIT_SSH_COMMAND !== undefined const askPassSetInEnv = process.env.GIT_ASKPASS !== undefined const { sshCommandSetInConfig, askPassSetInConfig } = checkGitConfigs() // Values we want to set if they're not already defined by the end user // This defaults to accepting new ssh host key fingerprints const finalGitEnv = { ...(askPassSetInEnv || askPassSetInConfig ? {} : { GIT_ASKPASS: 'echo', }), ...(sshCommandSetInEnv || sshCommandSetInConfig ? {} : { GIT_SSH_COMMAND: 'ssh -oStrictHostKeyChecking=accept-new', }), } module.exports = (opts = {}) => ({ stdioString: true, ...opts, shell: false, env: opts.env || { ...finalGitEnv, ...process.env }, }) // Export the loadGitConfig function for testing module.exports.loadGitConfig = loadGitConfig const pinflight = require('promise-inflight') const spawn = require('./spawn.js') const { LRUCache } = require('lru-cache') const revsCache = new LRUCache({ max: 100, ttl: 5 * 60 * 1000, }) const linesToRevs = require('./lines-to-revs.js') module.exports = async (repo, opts = {}) => { if (!opts.noGitRevCache) { const cached = revsCache.get(repo) if (cached) { return cached } } return pinflight(`ls-remote:${repo}`, () => spawn(['ls-remote', repo], opts) .then(({ stdout }) => linesToRevs(stdout.trim().split('\n'))) .then(revs => { revsCache.set(repo, revs) return revs }) ) } const spawn = require('@npmcli/promise-spawn') const promiseRetry = require('promise-retry') const { log } = require('proc-log') const makeError = require('./make-error.js') const makeOpts = require('./opts.js') module.exports = (gitArgs, opts = {}) => { const whichGit = require('./which.js') const gitPath = whichGit(opts) if (gitPath instanceof Error) { return Promise.reject(gitPath) } // undocumented option, mostly only here for tests const args = opts.allowReplace || gitArgs[0] === '--no-replace-objects' ? gitArgs : ['--no-replace-objects', ...gitArgs] let retryOpts = opts.retry if (retryOpts === null || retryOpts === undefined) { retryOpts = { retries: opts.fetchRetries || 2, factor: opts.fetchRetryFactor || 10, maxTimeout: opts.fetchRetryMaxtimeout || 60000, minTimeout: opts.fetchRetryMintimeout || 1000, } } return promiseRetry((retryFn, number) => { if (number !== 1) { log.silly('git', `Retrying git command: ${ args.join(' ')} attempt # ${number}`) } return spawn(gitPath, args, makeOpts(opts)) .catch(er => { const gitError = makeError(er) if (!gitError.shouldRetry(number)) { throw gitError } retryFn(gitError) }) }, retryOpts) } const isWindows = opts => (opts.fakePlatform || process.platform) === 'win32' exports.isWindows = isWindows const which = require('which') let gitPath try { gitPath = which.sync('git') } catch { // ignore errors } module.exports = (opts = {}) => { if (opts.git) { return opts.git } if (!gitPath || opts.git === false) { return Object.assign(new Error('No git binary found in $PATH'), { code: 'ENOGIT' }) } return gitPath } { "name": "@npmcli/git", "version": "6.0.1", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "description": "a util for spawning git from npm CLI contexts", "repository": { "type": "git", "url": "git+https://github.com/npm/git.git" }, "author": "GitHub Inc.", "license": "ISC", "scripts": { "lint": "npm run eslint", "snap": "tap", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "timeout": 600, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "npm-package-arg": "^11.0.0", "slash": "^3.0.0", "tap": "^16.0.1" }, "dependencies": { "@npmcli/promise-spawn": "^8.0.0", "ini": "^5.0.0", "lru-cache": "^10.0.1", "npm-pick-manifest": "^10.0.0", "proc-log": "^5.0.0", "promise-inflight": "^1.0.1", "promise-retry": "^2.0.1", "semver": "^7.3.5", "which": "^5.0.0" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true } } The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # @npmcli/installed-package-contents Get the list of files installed in a package in node_modules, including bundled dependencies. This is useful if you want to remove a package node from the tree _without_ removing its child nodes, for example to extract a new version of the dependency into place safely. It's sort of the reflection of [npm-packlist](http://npm.im/npm-packlist), but for listing out the _installed_ files rather than the files that _will_ be installed. This is of course a much simpler operation, because we don't have to handle ignore files or package.json `files` lists. ## USAGE ```js // programmatic usage const pkgContents = require('@npmcli/installed-package-contents') pkgContents({ path: 'node_modules/foo', depth: 1 }).then(files => { // files is an array of items that need to be passed to // rimraf or moved out of the way to make the folder empty // if foo bundled dependencies, those will be included. // It will not traverse into child directories, because we set // depth:1 in the options. // If the folder doesn't exist, this returns an empty array. }) pkgContents({ path: 'node_modules/foo', depth: Infinity }).then(files => { // setting depth:Infinity tells it to keep walking forever // until it hits something that isn't a directory, so we'll // just get the list of all files, but not their containing // directories. }) ``` As a CLI: ```bash $ installed-package-contents node_modules/bundle-some -d1 node_modules/.bin/some node_modules/bundle-some/package.json node_modules/bundle-some/node_modules/@scope/baz node_modules/bundle-some/node_modules/.bin/foo node_modules/bundle-some/node_modules/foo ``` CLI options: ``` Usage: installed-package-contents [-d --depth=] Lists the files installed for a package specified by . Options: -d --depth= Provide a numeric value ("Infinity" is allowed) to specify how deep in the file tree to traverse. Default=1 -h --help Show this usage information ``` ## OPTIONS * `depth` Number, default `1`. How deep to traverse through folders to get contents. Typically you'd want to set this to either `1` (to get the surface files and folders) or `Infinity` (to get all files), but any other positive number is supported as well. If set to `0` or a negative number, returns the path provided and (if it is a package) its set of linked bins. * `path` Required. Path to the package in `node_modules` where traversal should begin. ## RETURN VALUE A Promise that resolves to an array of fully-resolved files and folders matching the criteria. This includes all bundled dependencies in `node_modules`, and any linked executables in `node_modules/.bin` that the package caused to be installed. An empty or missing package folder will return an empty array. Empty directories _within_ package contents are listed, even if the `depth` argument would cause them to be traversed into. ## CAVEAT If using this module to generate a list of files that should be recursively removed to clear away the package, note that this will leave empty directories behind in certain cases: - If all child packages are bundled dependencies, then the `node_modules` folder will remain. - If all child packages within a given scope were bundled dependencies, then the `node_modules/@scope` folder will remain. - If all linked bin scripts were removed, then an empty `node_modules/.bin` folder will remain. In the interest of speed and algorithmic complexity, this module does _not_ do a subsequent readdir to see if it would remove all directory entries, though it would be easier to look at if it returned `node_modules` or `.bin` in that case rather than the contents. However, if the intent is to pass these arguments to `rimraf`, it hardly makes sense to do _two_ `readdir` calls just so that we can have the luxury of having to make a third. Since the primary use case is to delete a package's contents so that they can be re-filled with a new version of that package, this caveat does not pose a problem. Empty directories are already ignored by both npm and git. #! /usr/bin/env node const { relative } = require('path') const pkgContents = require('../') const usage = `Usage: installed-package-contents [-d --depth=] Lists the files installed for a package specified by . Options: -d --depth= Provide a numeric value ("Infinity" is allowed) to specify how deep in the file tree to traverse. Default=1 -h --help Show this usage information` const options = {} process.argv.slice(2).forEach(arg => { let match if ((match = arg.match(/^(?:--depth=|-d)([0-9]+|Infinity)/))) { options.depth = +match[1] } else if (arg === '-h' || arg === '--help') { console.log(usage) process.exit(0) } else { options.path = arg } }) if (!options.path) { console.error('ERROR: no path provided') console.error(usage) process.exit(1) } const cwd = process.cwd() pkgContents(options) .then(list => list.sort().forEach(p => console.log(relative(cwd, p)))) .catch(/* istanbul ignore next - pretty unusual */ er => { console.error(er) process.exit(1) }) // to GET CONTENTS for folder at PATH (which may be a PACKAGE): // - if PACKAGE, read path/package.json // - if bins in ../node_modules/.bin, add those to result // - if depth >= maxDepth, add PATH to result, and finish // - readdir(PATH, with file types) // - add all FILEs in PATH to result // - if PARENT: // - if depth < maxDepth, add GET CONTENTS of all DIRs in PATH // - else, add all DIRs in PATH // - if no parent // - if no bundled deps, // - if depth < maxDepth, add GET CONTENTS of DIRs in path except // node_modules // - else, add all DIRs in path other than node_modules // - if has bundled deps, // - get list of bundled deps // - add GET CONTENTS of bundled deps, PACKAGE=true, depth + 1 const bundled = require('npm-bundled') const { readFile, readdir, stat } = require('fs/promises') const { resolve, basename, dirname } = require('path') const normalizePackageBin = require('npm-normalize-package-bin') const readPackage = ({ path, packageJsonCache }) => packageJsonCache.has(path) ? Promise.resolve(packageJsonCache.get(path)) : readFile(path).then(json => { const pkg = normalizePackageBin(JSON.parse(json)) packageJsonCache.set(path, pkg) return pkg }).catch(() => null) // just normalize bundle deps and bin, that's all we care about here. const normalized = Symbol('package data has been normalized') const rpj = ({ path, packageJsonCache }) => readPackage({ path, packageJsonCache }) .then(pkg => { if (!pkg || pkg[normalized]) { return pkg } if (pkg.bundledDependencies && !pkg.bundleDependencies) { pkg.bundleDependencies = pkg.bundledDependencies delete pkg.bundledDependencies } const bd = pkg.bundleDependencies if (bd === true) { pkg.bundleDependencies = [ ...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.optionalDependencies || {}), ] } if (typeof bd === 'object' && !Array.isArray(bd)) { pkg.bundleDependencies = Object.keys(bd) } pkg[normalized] = true return pkg }) const pkgContents = async ({ path, depth = 1, currentDepth = 0, pkg = null, result = null, packageJsonCache = null, }) => { if (!result) { result = new Set() } if (!packageJsonCache) { packageJsonCache = new Map() } if (pkg === true) { return rpj({ path: path + '/package.json', packageJsonCache }) .then(p => pkgContents({ path, depth, currentDepth, pkg: p, result, packageJsonCache, })) } if (pkg) { // add all bins to result if they exist if (pkg.bin) { const dir = dirname(path) const scope = basename(dir) const nm = /^@.+/.test(scope) ? dirname(dir) : dir const binFiles = [] Object.keys(pkg.bin).forEach(b => { const base = resolve(nm, '.bin', b) binFiles.push(base, base + '.cmd', base + '.ps1') }) const bins = await Promise.all( binFiles.map(b => stat(b).then(() => b).catch(() => null)) ) bins.filter(b => b).forEach(b => result.add(b)) } } if (currentDepth >= depth) { result.add(path) return result } // we'll need bundle list later, so get that now in parallel const [dirEntries, bundleDeps] = await Promise.all([ readdir(path, { withFileTypes: true }), currentDepth === 0 && pkg && pkg.bundleDependencies ? bundled({ path, packageJsonCache }) : null, ]).catch(() => []) // not a thing, probably a missing folder if (!dirEntries) { return result } // empty folder, just add the folder itself to the result if (!dirEntries.length && !bundleDeps && currentDepth !== 0) { result.add(path) return result } const recursePromises = [] for (const entry of dirEntries) { const p = resolve(path, entry.name) if (entry.isDirectory() === false) { result.add(p) continue } if (currentDepth !== 0 || entry.name !== 'node_modules') { if (currentDepth < depth - 1) { recursePromises.push(pkgContents({ path: p, packageJsonCache, depth, currentDepth: currentDepth + 1, result, })) } else { result.add(p) } continue } } if (bundleDeps) { // bundle deps are all folders // we always recurse to get pkg bins, but if currentDepth is too high, // it'll return early before walking their contents. recursePromises.push(...bundleDeps.map(dep => { const p = resolve(path, 'node_modules', dep) return pkgContents({ path: p, packageJsonCache, pkg: true, depth, currentDepth: currentDepth + 1, result, }) })) } if (recursePromises.length) { await Promise.all(recursePromises) } return result } module.exports = ({ path, ...opts }) => pkgContents({ path: resolve(path), ...opts, pkg: true, }).then(results => [...results]) { "name": "@npmcli/installed-package-contents", "version": "3.0.0", "description": "Get the list of files installed in a package in node_modules, including bundled dependencies", "author": "GitHub Inc.", "main": "lib/index.js", "bin": { "installed-package-contents": "bin/index.js" }, "license": "ISC", "scripts": { "test": "tap", "snap": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.3.0" }, "dependencies": { "npm-bundled": "^4.0.0", "npm-normalize-package-bin": "^4.0.0" }, "repository": { "type": "git", "url": "git+https://github.com/npm/installed-package-contents.git" }, "files": [ "bin/", "lib/" ], "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const path = require('path') const getName = require('@npmcli/name-from-folder') const { minimatch } = require('minimatch') const pkgJson = require('@npmcli/package-json') const { glob } = require('glob') function appendNegatedPatterns (allPatterns) { const patterns = [] const negatedPatterns = [] for (let pattern of allPatterns) { const excl = pattern.match(/^!+/) if (excl) { pattern = pattern.slice(excl[0].length) } // strip off any / or ./ from the start of the pattern. /foo => foo pattern = pattern.replace(/^\.?\/+/, '') // an odd number of ! means a negated pattern. !!foo ==> foo const negate = excl && excl[0].length % 2 === 1 if (negate) { negatedPatterns.push(pattern) } else { // remove negated patterns that appeared before this pattern to avoid // ignoring paths that were matched afterwards // e.g: ['packages/**', '!packages/b/**', 'packages/b/a'] // in the above list, the last pattern overrides the negated pattern // right before it. In effect, the above list would become: // ['packages/**', 'packages/b/a'] // The order matters here which is why we must do it inside the loop // as opposed to doing it all together at the end. for (let i = 0; i < negatedPatterns.length; ++i) { const negatedPattern = negatedPatterns[i] if (minimatch(pattern, negatedPattern)) { negatedPatterns.splice(i, 1) } } patterns.push(pattern) } } // use the negated patterns to eagerly remove all the patterns that // can be removed to avoid unnecessary crawling for (const negated of negatedPatterns) { for (const pattern of minimatch.match(patterns, negated)) { patterns.splice(patterns.indexOf(pattern), 1) } } return { patterns, negatedPatterns } } function getPatterns (workspaces) { const workspacesDeclaration = Array.isArray(workspaces.packages) ? workspaces.packages : workspaces if (!Array.isArray(workspacesDeclaration)) { throw getError({ message: 'workspaces config expects an Array', code: 'EWORKSPACESCONFIG', }) } return appendNegatedPatterns(workspacesDeclaration) } function getPackageName (pkg, pathname) { return pkg.name || getName(pathname) } // make sure glob pattern only matches folders function getGlobPattern (pattern) { pattern = pattern.replace(/\\/g, '/') return pattern.endsWith('/') ? pattern : `${pattern}/` } function getError ({ Type = TypeError, message, code }) { return Object.assign(new Type(message), { code }) } function reverseResultMap (map) { return new Map(Array.from(map, item => item.reverse())) } async function mapWorkspaces (opts = {}) { if (!opts || !opts.pkg) { throw getError({ message: 'mapWorkspaces missing pkg info', code: 'EMAPWORKSPACESPKG', }) } if (!opts.cwd) { opts.cwd = process.cwd() } const { workspaces = [] } = opts.pkg const { patterns, negatedPatterns } = getPatterns(workspaces) const results = new Map() if (!patterns.length && !negatedPatterns.length) { return results } const seen = new Map() const getGlobOpts = () => ({ ...opts, ignore: [ ...opts.ignore || [], '**/node_modules/**', // just ignore the negated patterns to avoid unnecessary crawling ...negatedPatterns, ], }) let matches = await glob(patterns.map((p) => getGlobPattern(p)), getGlobOpts()) // preserves glob@8 behavior matches = matches.sort((a, b) => a.localeCompare(b, 'en')) // we must preserve the order of results according to the given list of // workspace patterns const orderedMatches = [] for (const pattern of patterns) { orderedMatches.push(...matches.filter((m) => { return minimatch(m, pattern, { partial: true, windowsPathsNoEscape: true }) })) } for (const match of orderedMatches) { let pkg try { pkg = await pkgJson.normalize(path.join(opts.cwd, match)) } catch (err) { if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { continue } else { throw err } } const name = getPackageName(pkg.content, pkg.path) let seenPackagePathnames = seen.get(name) if (!seenPackagePathnames) { seenPackagePathnames = new Set() seen.set(name, seenPackagePathnames) } seenPackagePathnames.add(pkg.path) } const errorMessageArray = ['must not have multiple workspaces with the same name'] for (const [packageName, seenPackagePathnames] of seen) { if (seenPackagePathnames.size > 1) { addDuplicateErrorMessages(errorMessageArray, packageName, seenPackagePathnames) } else { results.set(packageName, seenPackagePathnames.values().next().value) } } if (errorMessageArray.length > 1) { throw getError({ Type: Error, message: errorMessageArray.join('\n'), code: 'EDUPLICATEWORKSPACE', }) } return results } function addDuplicateErrorMessages (messageArray, packageName, packagePathnames) { messageArray.push( `package '${packageName}' has conflicts in the following paths:` ) for (const packagePathname of packagePathnames) { messageArray.push( ' ' + packagePathname ) } } mapWorkspaces.virtual = function (opts = {}) { if (!opts || !opts.lockfile) { throw getError({ message: 'mapWorkspaces.virtual missing lockfile info', code: 'EMAPWORKSPACESLOCKFILE', }) } if (!opts.cwd) { opts.cwd = process.cwd() } const { packages = {} } = opts.lockfile const { workspaces = [] } = packages[''] || {} // uses a pathname-keyed map in order to negate the exact items const results = new Map() const { patterns, negatedPatterns } = getPatterns(workspaces) if (!patterns.length && !negatedPatterns.length) { return results } negatedPatterns.push('**/node_modules/**') const packageKeys = Object.keys(packages) for (const pattern of negatedPatterns) { for (const packageKey of minimatch.match(packageKeys, pattern)) { packageKeys.splice(packageKeys.indexOf(packageKey), 1) } } for (const pattern of patterns) { for (const packageKey of minimatch.match(packageKeys, pattern)) { const packagePathname = path.join(opts.cwd, packageKey) const name = getPackageName(packages[packageKey], packagePathname) results.set(packagePathname, name) } } // Invert pathname-keyed to a proper name-to-pathnames Map return reverseResultMap(results) } module.exports = mapWorkspaces { "name": "@npmcli/map-workspaces", "version": "4.0.2", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "engines": { "node": "^18.17.0 || >=20.5.0" }, "description": "Retrieves a name:pathname Map for a given workspaces config", "repository": { "type": "git", "url": "git+https://github.com/npm/map-workspaces.git" }, "keywords": [ "npm", "npmcli", "libnpm", "cli", "workspaces", "map-workspaces" ], "author": "GitHub Inc.", "license": "ISC", "scripts": { "lint": "npm run eslint", "pretest": "npm run lint", "test": "tap", "snap": "tap", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.4", "tap": "^16.0.1" }, "dependencies": { "@npmcli/name-from-folder": "^3.0.0", "@npmcli/package-json": "^6.0.0", "glob": "^10.2.2", "minimatch": "^9.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.4", "publish": "true" } } The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const hash = require('./hash.js') const semver = require('semver') const semverOpt = { includePrerelease: true, loose: true } const getDepSpec = require('./get-dep-spec.js') // any fields that we don't want in the cache need to be hidden const _source = Symbol('source') const _packument = Symbol('packument') const _versionVulnMemo = Symbol('versionVulnMemo') const _updated = Symbol('updated') const _options = Symbol('options') const _specVulnMemo = Symbol('specVulnMemo') const _testVersion = Symbol('testVersion') const _testVersions = Symbol('testVersions') const _calculateRange = Symbol('calculateRange') const _markVulnerable = Symbol('markVulnerable') const _testSpec = Symbol('testSpec') class Advisory { constructor (name, source, options = {}) { this.source = source.id this[_source] = source this[_options] = options this.name = name if (!source.name) { source.name = name } this.dependency = source.name if (this.type === 'advisory') { this.title = source.title this.url = source.url } else { this.title = `Depends on vulnerable versions of ${source.name}` this.url = null } this.severity = source.severity || 'high' this.versions = [] this.vulnerableVersions = [] this.cwe = source.cwe this.cvss = source.cvss // advisories have the range, metavulns do not // if an advisory doesn't specify range, assume all are vulnerable this.range = this.type === 'advisory' ? source.vulnerable_versions || '*' : null this.id = hash(this) this[_packument] = null // memoized list of which versions are vulnerable this[_versionVulnMemo] = new Map() // memoized list of which dependency specs are vulnerable this[_specVulnMemo] = new Map() this[_updated] = false } // true if we updated from what we had in cache get updated () { return this[_updated] } get type () { return this.dependency === this.name ? 'advisory' : 'metavuln' } get packument () { return this[_packument] } // load up the data from a cache entry and a fetched packument load (cached, packument) { // basic data integrity gutcheck if (!cached || typeof cached !== 'object') { throw new TypeError('invalid cached data, expected object') } if (!packument || typeof packument !== 'object') { throw new TypeError('invalid packument data, expected object') } if (cached.id && cached.id !== this.id) { throw Object.assign(new Error('loading from incorrect cache entry'), { expected: this.id, actual: cached.id, }) } if (packument.name !== this.name) { throw Object.assign(new Error('loading from incorrect packument'), { expected: this.name, actual: packument.name, }) } if (this[_packument]) { throw new Error('advisory object already loaded') } // if we have a range from the initialization, and the cached // data has a *different* range, then we know we have to recalc. // just don't use the cached data, so we will definitely not match later if (!this.range || cached.range && cached.range === this.range) { Object.assign(this, cached) } this[_packument] = packument const pakuVersions = Object.keys(packument.versions || {}) const allVersions = new Set([...pakuVersions, ...this.versions]) const versionsAdded = [] const versionsRemoved = [] for (const v of allVersions) { if (!this.versions.includes(v)) { versionsAdded.push(v) this.versions.push(v) } else if (!pakuVersions.includes(v)) { versionsRemoved.push(v) } } // strip out any removed versions from our lists, and sort by semver this.versions = semver.sort(this.versions.filter(v => !versionsRemoved.includes(v)), semverOpt) // if no changes, then just return what we got from cache // versions added or removed always means we changed // otherwise, advisories change if the range changes, and // metavulns change if the source was updated const unchanged = this.type === 'advisory' ? this.range && this.range === cached.range : !this[_source].updated // if the underlying source changed, by an advisory updating the // range, or a source advisory being updated, then we have to re-check // otherwise, only recheck the new ones. this.vulnerableVersions = !unchanged ? [] : semver.sort(this.vulnerableVersions.filter(v => !versionsRemoved.includes(v)), semverOpt) if (unchanged && !versionsAdded.length && !versionsRemoved.length) { // nothing added or removed, nothing to do here. use the cached copy. return this } this[_updated] = true // test any versions newly added if (!unchanged || versionsAdded.length) { this[_testVersions](unchanged ? versionsAdded : this.versions) } this.vulnerableVersions = semver.sort(this.vulnerableVersions, semverOpt) // metavulns have to calculate their range, since cache is invalidated // advisories just get their range from the advisory above if (this.type === 'metavuln') { this[_calculateRange]() } return this } [_calculateRange] () { // calling semver.simplifyRange with a massive list of versions, and those // versions all concatenated with `||` is a geometric CPU explosion! // we can try to be a *little* smarter up front by doing x-y for all // contiguous version sets in the list const ranges = [] this.versions = semver.sort(this.versions, semverOpt) this.vulnerableVersions = semver.sort(this.vulnerableVersions, semverOpt) for (let v = 0, vulnVer = 0; v < this.versions.length; v++) { // figure out the vulnerable subrange const vr = [this.versions[v]] while (v < this.versions.length) { if (this.versions[v] !== this.vulnerableVersions[vulnVer]) { // we don't test prerelease versions, so just skip past it if (/-/.test(this.versions[v])) { v++ continue } break } if (vr.length > 1) { vr[1] = this.versions[v] } else { vr.push(this.versions[v]) } v++ vulnVer++ } // it'll either be just the first version, which means no overlap, // or the start and end versions, which might be the same version if (vr.length > 1) { const tail = this.versions[this.versions.length - 1] ranges.push(vr[1] === tail ? `>=${vr[0]}` : vr[0] === vr[1] ? vr[0] : vr.join(' - ')) } } const metavuln = ranges.join(' || ').trim() this.range = !metavuln ? '<0.0.0-0' : semver.simplifyRange(this.versions, metavuln, semverOpt) } // returns true if marked as vulnerable, false if ok // spec is a dependency specifier, for metavuln cases // where the version might not be in the packument. if // we have the packument and spec is not provided, then // we use the dependency version from the manifest. testVersion (version, spec = null) { const sv = String(version) if (this[_versionVulnMemo].has(sv)) { return this[_versionVulnMemo].get(sv) } const result = this[_testVersion](version, spec) if (result) { this[_markVulnerable](version) } this[_versionVulnMemo].set(sv, !!result) return result } [_markVulnerable] (version) { const sv = String(version) if (!this.vulnerableVersions.includes(sv)) { this.vulnerableVersions.push(sv) } } [_testVersion] (version, spec) { const sv = String(version) if (this.vulnerableVersions.includes(sv)) { return true } if (this.type === 'advisory') { // advisory, just test range return semver.satisfies(version, this.range, semverOpt) } // check the dependency of this version on the vulnerable dep // if we got a version that's not in the packument, fall back on // the spec provided, if possible. const mani = this[_packument]?.versions?.[version] || { dependencies: { [this.dependency]: spec, }, } if (!spec) { spec = getDepSpec(mani, this.dependency) } // no dep, no vuln if (spec === null) { return false } if (!semver.validRange(spec, semverOpt)) { // not a semver range, nothing we can hope to do about it return true } const bd = mani.bundleDependencies const bundled = bd && bd.includes(this[_source].name) // XXX if bundled, then semver.intersects() means vulnerable // else, pick a manifest and see if it can't be avoided // try to pick a version of the dep that isn't vulnerable const avoid = this[_source].range if (bundled) { return semver.intersects(spec, avoid, semverOpt) } return this[_source].testSpec(spec) } testSpec (spec) { // testing all the versions is a bit costly, and the spec tends to stay // consistent across multiple versions, so memoize this as well, in case // we're testing lots of versions. const memo = this[_specVulnMemo] if (memo.has(spec)) { return memo.get(spec) } const res = this[_testSpec](spec) memo.set(spec, res) return res } [_testSpec] (spec) { for (const v of this.versions) { const satisfies = semver.satisfies(v, spec) if (!satisfies) { continue } if (!this.testVersion(v)) { return false } } // either vulnerable, or not installable because nothing satisfied // either way, best avoided. return true } [_testVersions] (versions) { if (!versions.length) { return } // set of lists of versions const versionSets = new Set() versions = semver.sort(versions.map(v => semver.parse(v, semverOpt))) // start out with the versions grouped by major and minor let last = versions[0].major + '.' + versions[0].minor let list = [] versionSets.add(list) for (const v of versions) { const k = v.major + '.' + v.minor if (k !== last) { last = k list = [] versionSets.add(list) } list.push(v) } for (const set of versionSets) { // it's common to have version lists like: // 1.0.0 // 1.0.1-alpha.0 // 1.0.1-alpha.1 // ... // 1.0.1-alpha.999 // 1.0.1 // 1.0.2-alpha.0 // ... // 1.0.2-alpha.99 // 1.0.2 // with a huge number of prerelease versions that are not installable // anyway. // If mid has a prerelease tag, and set[0] does not, then walk it // back until we hit a non-prerelease version // If mid has a prerelease tag, and set[set.length-1] does not, // then walk it forward until we hit a version without a prerelease tag // Similarly, if the head/tail is a prerelease, but there is a non-pr // version in the set, then start there instead. let h = 0 const origHeadVuln = this.testVersion(set[h]) while (h < set.length && /-/.test(String(set[h]))) { h++ } // don't filter out the whole list! they might all be pr's if (h === set.length) { h = 0 } else if (origHeadVuln) { // if the original was vulnerable, assume so are all of these for (let hh = 0; hh < h; hh++) { this[_markVulnerable](set[hh]) } } let t = set.length - 1 const origTailVuln = this.testVersion(set[t]) while (t > h && /-/.test(String(set[t]))) { t-- } // don't filter out the whole list! might all be pr's if (t === h) { t = set.length - 1 } else if (origTailVuln) { // if original tail was vulnerable, assume these are as well for (let tt = set.length - 1; tt > t; tt--) { this[_markVulnerable](set[tt]) } } const headVuln = h === 0 ? origHeadVuln : this.testVersion(set[h]) const tailVuln = t === set.length - 1 ? origTailVuln : this.testVersion(set[t]) // if head and tail both vulnerable, whole list is thrown out if (headVuln && tailVuln) { for (let v = h; v < t; v++) { this[_markVulnerable](set[v]) } continue } // if length is 2 or 1, then we marked them all already if (t < h + 2) { continue } const mid = Math.floor(set.length / 2) const pre = set.slice(0, mid) const post = set.slice(mid) // if the parent list wasn't prereleases, then drop pr tags // from end of the pre list, and beginning of the post list, // marking as vulnerable if the midpoint item we picked is. if (!/-/.test(String(pre[0]))) { const midVuln = this.testVersion(pre[pre.length - 1]) while (/-/.test(String(pre[pre.length - 1]))) { const v = pre.pop() if (midVuln) { this[_markVulnerable](v) } } } if (!/-/.test(String(post[post.length - 1]))) { const midVuln = this.testVersion(post[0]) while (/-/.test(String(post[0]))) { const v = post.shift() if (midVuln) { this[_markVulnerable](v) } } } versionSets.add(pre) versionSets.add(post) } } } module.exports = Advisory module.exports = (mani, name) => { // skip dev because that only matters at the root, // where we aren't fetching a manifest from the registry // with multiple versions anyway. const { dependencies: deps = {}, optionalDependencies: optDeps = {}, peerDependencies: peerDeps = {}, } = mani return deps && typeof deps[name] === 'string' ? deps[name] : optDeps && typeof optDeps[name] === 'string' ? optDeps[name] : peerDeps && typeof peerDeps[name] === 'string' ? peerDeps[name] : null } const { createHash } = require('crypto') module.exports = ({ name, source }) => createHash('sha512') .update(JSON.stringify([name, source])) .digest('base64') // this is the public class that is used by consumers. // the Advisory class handles all the calculation, and this // class handles all the IO with the registry and cache. const pacote = require('pacote') const cacache = require('cacache') const { time } = require('proc-log') const Advisory = require('./advisory.js') const { homedir } = require('os') const jsonParse = require('json-parse-even-better-errors') const _packument = Symbol('packument') const _cachePut = Symbol('cachePut') const _cacheGet = Symbol('cacheGet') const _cacheData = Symbol('cacheData') const _packuments = Symbol('packuments') const _cache = Symbol('cache') const _options = Symbol('options') const _advisories = Symbol('advisories') const _calculate = Symbol('calculate') class Calculator { constructor (options = {}) { this[_options] = { ...options } this[_cache] = this[_options].cache || (homedir() + '/.npm/_cacache') this[_options].cache = this[_cache] this[_packuments] = new Map() this[_cacheData] = new Map() this[_advisories] = new Map() } get cache () { return this[_cache] } get options () { return { ...this[_options] } } async calculate (name, source) { const k = `security-advisory:${name}:${source.id}` if (this[_advisories].has(k)) { return this[_advisories].get(k) } const p = this[_calculate](name, source) this[_advisories].set(k, p) return p } async [_calculate] (name, source) { const k = `security-advisory:${name}:${source.id}` const timeEnd = time.start(`metavuln:calculate:${k}`) const advisory = new Advisory(name, source, this[_options]) // load packument and cached advisory const [cached, packument] = await Promise.all([ this[_cacheGet](advisory), this[_packument](name), ]) const timeEndLoad = time.start(`metavuln:load:${k}`) advisory.load(cached, packument) timeEndLoad() if (advisory.updated) { await this[_cachePut](advisory) } this[_advisories].set(k, advisory) timeEnd() return advisory } async [_cachePut] (advisory) { const { name, id } = advisory const key = `security-advisory:${name}:${id}` const timeEnd = time.start(`metavuln:cache:put:${key}`) const data = JSON.stringify(advisory) const options = { ...this[_options] } this[_cacheData].set(key, jsonParse(data)) await cacache.put(this[_cache], key, data, options).catch(() => {}) timeEnd() } async [_cacheGet] (advisory) { const { name, id } = advisory const key = `security-advisory:${name}:${id}` /* istanbul ignore if - should be impossible, since we memoize the * advisory object itself using the same key, just being cautious */ if (this[_cacheData].has(key)) { return this[_cacheData].get(key) } const timeEnd = time.start(`metavuln:cache:get:${key}`) const p = cacache.get(this[_cache], key, { ...this[_options] }) .catch(() => ({ data: '{}' })) .then(({ data }) => { data = jsonParse(data) timeEnd() this[_cacheData].set(key, data) return data }) this[_cacheData].set(key, p) return p } async [_packument] (name) { if (this[_packuments].has(name)) { return this[_packuments].get(name) } const timeEnd = time.start(`metavuln:packument:${name}`) const p = pacote.packument(name, { ...this[_options] }) .catch(() => { // presumably not something from the registry. // an empty packument will have an effective range of * return { name, versions: {}, } }) .then(paku => { timeEnd() this[_packuments].set(name, paku) return paku }) this[_packuments].set(name, p) return p } } module.exports = Calculator { "name": "@npmcli/metavuln-calculator", "version": "9.0.0", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "description": "Calculate meta-vulnerabilities from package security advisories", "repository": { "type": "git", "url": "git+https://github.com/npm/metavuln-calculator.git" }, "author": "GitHub Inc.", "license": "ISC", "scripts": { "test": "tap", "posttest": "npm run lint", "snap": "tap", "postsnap": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force" }, "tap": { "check-coverage": true, "coverage-map": "map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.4", "require-inject": "^1.4.4", "tap": "^16.0.1" }, "dependencies": { "cacache": "^19.0.0", "json-parse-even-better-errors": "^4.0.0", "pacote": "^21.0.0", "proc-log": "^5.0.0", "semver": "^7.3.5" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.4", "publish": "true", "ciVersions": [ "16.14.0", "16.x", "18.0.0", "18.x" ] } } The ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const { basename, dirname } = require('path') const getName = (parent, base) => parent.charAt(0) === '@' ? `${parent}/${base}` : base module.exports = dir => dir ? getName(basename(dirname(dir)), basename(dir)) : false { "name": "@npmcli/name-from-folder", "version": "3.0.0", "files": [ "bin/", "lib/" ], "main": "lib/index.js", "description": "Get the package name from a folder path", "repository": { "type": "git", "url": "git+https://github.com/npm/name-from-folder.git" }, "author": "GitHub Inc.", "license": "ISC", "scripts": { "test": "tap", "snap": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.3.2" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } ISC License: Copyright (c) 2023 by GitHub Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const util = require('util') const fs = require('fs') const { stat } = fs.promises || { stat: util.promisify(fs.stat) } async function isNodeGypPackage (path) { return await stat(`${path}/binding.gyp`) .then(st => st.isFile()) .catch(() => false) } module.exports = { isNodeGypPackage, defaultGypInstallScript: 'node-gyp rebuild', } { "name": "@npmcli/node-gyp", "version": "4.0.0", "description": "Tools for dealing with node-gyp packages", "scripts": { "test": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/node-gyp.git" }, "keywords": [ "npm", "cli", "node-gyp" ], "files": [ "bin/", "lib/" ], "main": "lib/index.js", "author": "GitHub Inc.", "license": "ISC", "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.0.1" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } ISC License Copyright GitHub Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const { readFile, writeFile } = require('node:fs/promises') const { resolve } = require('node:path') const parseJSON = require('json-parse-even-better-errors') const updateDeps = require('./update-dependencies.js') const updateScripts = require('./update-scripts.js') const updateWorkspaces = require('./update-workspaces.js') const normalize = require('./normalize.js') const { read, parse } = require('./read-package.js') const { packageSort } = require('./sort.js') // a list of handy specialized helper functions that take // care of special cases that are handled by the npm cli const knownSteps = new Set([ updateDeps, updateScripts, updateWorkspaces, ]) // list of all keys that are handled by "knownSteps" helpers const knownKeys = new Set([ ...updateDeps.knownKeys, 'scripts', 'workspaces', ]) class PackageJson { static normalizeSteps = Object.freeze([ '_id', '_attributes', 'bundledDependencies', 'bundleDependencies', 'optionalDedupe', 'scripts', 'funding', 'bin', ]) // npm pkg fix static fixSteps = Object.freeze([ 'binRefs', 'bundleDependencies', 'bundleDependenciesFalse', 'fixNameField', 'fixVersionField', 'fixRepositoryField', 'fixDependencies', 'devDependencies', 'scriptpath', ]) static prepareSteps = Object.freeze([ '_id', '_attributes', 'bundledDependencies', 'bundleDependencies', 'bundleDependenciesDeleteFalse', 'gypfile', 'serverjs', 'scriptpath', 'authors', 'readme', 'mans', 'binDir', 'gitHead', 'fillTypes', 'normalizeData', 'binRefs', ]) // create a new empty package.json, so we can save at the given path even // though we didn't start from a parsed file static async create (path, opts = {}) { const p = new PackageJson() await p.create(path) if (opts.data) { return p.update(opts.data) } return p } // Loads a package.json at given path and JSON parses static async load (path, opts = {}) { const p = new PackageJson() // Avoid try/catch if we aren't going to create if (!opts.create) { return p.load(path) } try { return await p.load(path) } catch (err) { if (!err.message.startsWith('Could not read package.json')) { throw err } return await p.create(path) } } // npm pkg fix static async fix (path, opts) { const p = new PackageJson() await p.load(path, true) return p.fix(opts) } // read-package-json compatible behavior static async prepare (path, opts) { const p = new PackageJson() await p.load(path, true) return p.prepare(opts) } // read-package-json-fast compatible behavior static async normalize (path, opts) { const p = new PackageJson() await p.load(path) return p.normalize(opts) } #path #manifest #readFileContent = '' #canSave = true // Load content from given path async load (path, parseIndex) { this.#path = path let parseErr try { this.#readFileContent = await read(this.filename) } catch (err) { if (!parseIndex) { throw err } parseErr = err } if (parseErr) { const indexFile = resolve(this.path, 'index.js') let indexFileContent try { indexFileContent = await readFile(indexFile, 'utf8') } catch (err) { throw parseErr } try { this.fromComment(indexFileContent) } catch (err) { throw parseErr } // This wasn't a package.json so prevent saving this.#canSave = false return this } return this.fromJSON(this.#readFileContent) } // Load data from a JSON string/buffer fromJSON (data) { this.#manifest = parse(data) return this } fromContent (data) { this.#manifest = data this.#canSave = false return this } // Load data from a comment // /**package { "name": "foo", "version": "1.2.3", ... } **/ fromComment (data) { data = data.split(/^\/\*\*package(?:\s|$)/m) if (data.length < 2) { throw new Error('File has no package in comments') } data = data[1] data = data.split(/\*\*\/$/m) if (data.length < 2) { throw new Error('File has no package in comments') } data = data[0] data = data.replace(/^\s*\*/mg, '') this.#manifest = parseJSON(data) return this } get content () { return this.#manifest } get path () { return this.#path } get filename () { if (this.path) { return resolve(this.path, 'package.json') } return undefined } create (path) { this.#path = path this.#manifest = {} return this } // This should be the ONLY way to set content in the manifest update (content) { if (!this.content) { throw new Error('Can not update without content. Please `load` or `create`') } for (const step of knownSteps) { this.#manifest = step({ content, originalContent: this.content }) } // unknown properties will just be overwitten for (const [key, value] of Object.entries(content)) { if (!knownKeys.has(key)) { this.content[key] = value } } return this } async save ({ sort } = {}) { if (!this.#canSave) { throw new Error('No package.json to save to') } const { [Symbol.for('indent')]: indent, [Symbol.for('newline')]: newline, ...rest } = this.content const format = indent === undefined ? ' ' : indent const eol = newline === undefined ? '\n' : newline const content = sort ? packageSort(rest) : rest const fileContent = `${ JSON.stringify(content, null, format) }\n` .replace(/\n/g, eol) if (fileContent.trim() !== this.#readFileContent.trim()) { const written = await writeFile(this.filename, fileContent) this.#readFileContent = fileContent return written } } async normalize (opts = {}) { if (!opts.steps) { opts.steps = this.constructor.normalizeSteps } await normalize(this, opts) return this } async prepare (opts = {}) { if (!opts.steps) { opts.steps = this.constructor.prepareSteps } await normalize(this, opts) return this } async fix (opts = {}) { // This one is not overridable opts.steps = this.constructor.fixSteps await normalize(this, opts) return this } } module.exports = PackageJson // Originally normalize-package-data const url = require('node:url') const hostedGitInfo = require('hosted-git-info') const validateLicense = require('validate-npm-package-license') const typos = { dependancies: 'dependencies', dependecies: 'dependencies', depdenencies: 'dependencies', devEependencies: 'devDependencies', depends: 'dependencies', 'dev-dependencies': 'devDependencies', devDependences: 'devDependencies', devDepenencies: 'devDependencies', devdependencies: 'devDependencies', repostitory: 'repository', repo: 'repository', prefereGlobal: 'preferGlobal', hompage: 'homepage', hampage: 'homepage', autohr: 'author', autor: 'author', contributers: 'contributors', publicationConfig: 'publishConfig', script: 'scripts', } const isEmail = str => str.includes('@') && (str.indexOf('@') < str.lastIndexOf('.')) // Extracts description from contents of a readme file in markdown format function extractDescription (description) { // the first block of text before the first heading that isn't the first line heading const lines = description.trim().split('\n') let start = 0 // skip initial empty lines and lines that start with # while (lines[start]?.trim().match(/^(#|$)/)) { start++ } let end = start + 1 // keep going till we get to the end or an empty line while (end < lines.length && lines[end].trim()) { end++ } return lines.slice(start, end).join(' ').trim() } function stringifyPerson (person) { if (typeof person !== 'string') { const name = person.name || '' const u = person.url || person.web const wrappedUrl = u ? (' (' + u + ')') : '' const e = person.email || person.mail const wrappedEmail = e ? (' <' + e + '>') : '' person = name + wrappedEmail + wrappedUrl } const matchedName = person.match(/^([^(<]+)/) const matchedUrl = person.match(/\(([^()]+)\)/) const matchedEmail = person.match(/<([^<>]+)>/) const parsed = {} if (matchedName?.[0].trim()) { parsed.name = matchedName[0].trim() } if (matchedEmail) { parsed.email = matchedEmail[1] } if (matchedUrl) { parsed.url = matchedUrl[1] } return parsed } function normalizeData (data, changes) { // fixDescriptionField if (data.description && typeof data.description !== 'string') { changes?.push(`'description' field should be a string`) delete data.description } if (data.readme && !data.description && data.readme !== 'ERROR: No README data found!') { data.description = extractDescription(data.readme) } if (data.description === undefined) { delete data.description } if (!data.description) { changes?.push('No description') } // fixModulesField if (data.modules) { changes?.push(`modules field is deprecated`) delete data.modules } // fixFilesField const files = data.files if (files && !Array.isArray(files)) { changes?.push(`Invalid 'files' member`) delete data.files } else if (data.files) { data.files = data.files.filter(function (file) { if (!file || typeof file !== 'string') { changes?.push(`Invalid filename in 'files' list: ${file}`) return false } else { return true } }) } // fixManField if (data.man && typeof data.man === 'string') { data.man = [data.man] } // fixBugsField if (!data.bugs && data.repository?.url) { const hosted = hostedGitInfo.fromUrl(data.repository.url) if (hosted && hosted.bugs()) { data.bugs = { url: hosted.bugs() } } } else if (data.bugs) { if (typeof data.bugs === 'string') { if (isEmail(data.bugs)) { data.bugs = { email: data.bugs } /* eslint-disable-next-line node/no-deprecated-api */ } else if (url.parse(data.bugs).protocol) { data.bugs = { url: data.bugs } } else { changes?.push(`Bug string field must be url, email, or {email,url}`) } } else { for (const k in data.bugs) { if (['web', 'name'].includes(k)) { changes?.push(`bugs['${k}'] should probably be bugs['url'].`) data.bugs.url = data.bugs[k] delete data.bugs[k] } } const oldBugs = data.bugs data.bugs = {} if (oldBugs.url) { /* eslint-disable-next-line node/no-deprecated-api */ if (typeof (oldBugs.url) === 'string' && url.parse(oldBugs.url).protocol) { data.bugs.url = oldBugs.url } else { changes?.push('bugs.url field must be a string url. Deleted.') } } if (oldBugs.email) { if (typeof (oldBugs.email) === 'string' && isEmail(oldBugs.email)) { data.bugs.email = oldBugs.email } else { changes?.push('bugs.email field must be a string email. Deleted.') } } } if (!data.bugs.email && !data.bugs.url) { delete data.bugs changes?.push('Normalized value of bugs field is an empty object. Deleted.') } } // fixKeywordsField if (typeof data.keywords === 'string') { data.keywords = data.keywords.split(/,\s+/) } if (data.keywords && !Array.isArray(data.keywords)) { delete data.keywords changes?.push(`keywords should be an array of strings`) } else if (data.keywords) { data.keywords = data.keywords.filter(function (kw) { if (typeof kw !== 'string' || !kw) { changes?.push(`keywords should be an array of strings`) return false } else { return true } }) } // fixBundleDependenciesField const bdd = 'bundledDependencies' const bd = 'bundleDependencies' if (data[bdd] && !data[bd]) { data[bd] = data[bdd] delete data[bdd] } if (data[bd] && !Array.isArray(data[bd])) { changes?.push(`Invalid 'bundleDependencies' list. Must be array of package names`) delete data[bd] } else if (data[bd]) { data[bd] = data[bd].filter(function (filtered) { if (!filtered || typeof filtered !== 'string') { changes?.push(`Invalid bundleDependencies member: ${filtered}`) return false } else { if (!data.dependencies) { data.dependencies = {} } if (!Object.prototype.hasOwnProperty.call(data.dependencies, filtered)) { changes?.push(`Non-dependency in bundleDependencies: ${filtered}`) data.dependencies[filtered] = '*' } return true } }) } // fixHomepageField if (!data.homepage && data.repository && data.repository.url) { const hosted = hostedGitInfo.fromUrl(data.repository.url) if (hosted) { data.homepage = hosted.docs() } } if (data.homepage) { if (typeof data.homepage !== 'string') { changes?.push('homepage field must be a string url. Deleted.') delete data.homepage } else { /* eslint-disable-next-line node/no-deprecated-api */ if (!url.parse(data.homepage).protocol) { data.homepage = 'http://' + data.homepage } } } // fixReadmeField if (!data.readme) { changes?.push('No README data') data.readme = 'ERROR: No README data found!' } // fixLicenseField const license = data.license || data.licence if (!license) { changes?.push('No license field.') } else if (typeof (license) !== 'string' || license.length < 1 || license.trim() === '') { changes?.push('license should be a valid SPDX license expression') } else if (!validateLicense(license).validForNewPackages) { changes?.push('license should be a valid SPDX license expression') } // fixPeople if (data.author) { data.author = stringifyPerson(data.author) } ['maintainers', 'contributors'].forEach(function (set) { if (!Array.isArray(data[set])) { return } data[set] = data[set].map(stringifyPerson) }) // fixTypos for (const d in typos) { if (Object.prototype.hasOwnProperty.call(data, d)) { changes?.push(`${d} should probably be ${typos[d]}.`) } } } module.exports = { normalizeData } const valid = require('semver/functions/valid') const clean = require('semver/functions/clean') const fs = require('node:fs/promises') const path = require('node:path') const { log } = require('proc-log') /** * @type {import('hosted-git-info')} */ let _hostedGitInfo function lazyHostedGitInfo () { if (!_hostedGitInfo) { _hostedGitInfo = require('hosted-git-info') } return _hostedGitInfo } /** * @type {import('glob').glob} */ let _glob function lazyLoadGlob () { if (!_glob) { _glob = require('glob').glob } return _glob } // used to be npm-normalize-package-bin function normalizePackageBin (pkg, changes) { if (pkg.bin) { if (typeof pkg.bin === 'string' && pkg.name) { changes?.push('"bin" was converted to an object') pkg.bin = { [pkg.name]: pkg.bin } } else if (Array.isArray(pkg.bin)) { changes?.push('"bin" was converted to an object') pkg.bin = pkg.bin.reduce((acc, k) => { acc[path.basename(k)] = k return acc }, {}) } if (typeof pkg.bin === 'object') { for (const binKey in pkg.bin) { if (typeof pkg.bin[binKey] !== 'string') { delete pkg.bin[binKey] changes?.push(`removed invalid "bin[${binKey}]"`) continue } const base = path.basename(secureAndUnixifyPath(binKey)) if (!base) { delete pkg.bin[binKey] changes?.push(`removed invalid "bin[${binKey}]"`) continue } const binTarget = secureAndUnixifyPath(pkg.bin[binKey]) if (!binTarget) { delete pkg.bin[binKey] changes?.push(`removed invalid "bin[${binKey}]"`) continue } if (base !== binKey) { delete pkg.bin[binKey] changes?.push(`"bin[${binKey}]" was renamed to "bin[${base}]"`) } if (binTarget !== pkg.bin[binKey]) { changes?.push(`"bin[${base}]" script name was cleaned`) } pkg.bin[base] = binTarget } if (Object.keys(pkg.bin).length === 0) { changes?.push('empty "bin" was removed') delete pkg.bin } return pkg } } delete pkg.bin } function normalizePackageMan (pkg, changes) { if (pkg.man) { const mans = [] for (const man of (Array.isArray(pkg.man) ? pkg.man : [pkg.man])) { if (typeof man !== 'string') { changes?.push(`removed invalid "man [${man}]"`) } else { mans.push(secureAndUnixifyPath(man)) } } if (!mans.length) { changes?.push('empty "man" was removed') } else { pkg.man = mans return pkg } } delete pkg.man } function isCorrectlyEncodedName (spec) { return !spec.match(/[/@\s+%:]/) && spec === encodeURIComponent(spec) } function isValidScopedPackageName (spec) { if (spec.charAt(0) !== '@') { return false } const rest = spec.slice(1).split('/') if (rest.length !== 2) { return false } return rest[0] && rest[1] && rest[0] === encodeURIComponent(rest[0]) && rest[1] === encodeURIComponent(rest[1]) } function unixifyPath (ref) { return ref.replace(/\\|:/g, '/') } function secureAndUnixifyPath (ref) { const secured = unixifyPath(path.join('.', path.join('/', unixifyPath(ref)))) return secured.startsWith('./') ? '' : secured } // We don't want the `changes` array in here by default because this is a hot // path for parsing packuments during install. So the calling method passes it // in if it wants to track changes. const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) => { if (!pkg.content) { throw new Error('Can not normalize without content') } const data = pkg.content const scripts = data.scripts || {} const pkgId = `${data.name ?? ''}@${data.version ?? ''}` // name and version are load bearing so we have to clean them up first if (steps.includes('fixNameField') || steps.includes('normalizeData')) { if (!data.name && !strict) { changes?.push('Missing "name" field was set to an empty string') data.name = '' } else { if (typeof data.name !== 'string') { throw new Error('name field must be a string.') } if (!strict) { const name = data.name.trim() if (data.name !== name) { changes?.push(`Whitespace was trimmed from "name"`) data.name = name } } if (data.name.startsWith('.') || !(isValidScopedPackageName(data.name) || isCorrectlyEncodedName(data.name)) || (strict && (!allowLegacyCase) && data.name !== data.name.toLowerCase()) || data.name.toLowerCase() === 'node_modules' || data.name.toLowerCase() === 'favicon.ico') { throw new Error('Invalid name: ' + JSON.stringify(data.name)) } } } if (steps.includes('fixVersionField') || steps.includes('normalizeData')) { // allow "loose" semver 1.0 versions in non-strict mode // enforce strict semver 2.0 compliance in strict mode const loose = !strict if (!data.version) { data.version = '' } else { if (!valid(data.version, loose)) { throw new Error(`Invalid version: "${data.version}"`) } const version = clean(data.version, loose) if (version !== data.version) { changes?.push(`"version" was cleaned and set to "${version}"`) data.version = version } } } // remove attributes that start with "_" if (steps.includes('_attributes')) { for (const key in data) { if (key.startsWith('_')) { changes?.push(`"${key}" was removed`) delete pkg.content[key] } } } // build the "_id" attribute if (steps.includes('_id')) { if (data.name && data.version) { changes?.push(`"_id" was set to ${pkgId}`) data._id = pkgId } } // fix bundledDependencies typo // normalize bundleDependencies if (steps.includes('bundledDependencies')) { if (data.bundleDependencies === undefined && data.bundledDependencies !== undefined) { data.bundleDependencies = data.bundledDependencies } changes?.push(`Deleted incorrect "bundledDependencies"`) delete data.bundledDependencies } // expand "bundleDependencies: true or translate from object" if (steps.includes('bundleDependencies')) { const bd = data.bundleDependencies if (bd === false && !steps.includes('bundleDependenciesDeleteFalse')) { changes?.push(`"bundleDependencies" was changed from "false" to "[]"`) data.bundleDependencies = [] } else if (bd === true) { changes?.push(`"bundleDependencies" was auto-populated from "dependencies"`) data.bundleDependencies = Object.keys(data.dependencies || {}) } else if (bd && typeof bd === 'object') { if (!Array.isArray(bd)) { changes?.push(`"bundleDependencies" was changed from an object to an array`) data.bundleDependencies = Object.keys(bd) } } else if ('bundleDependencies' in data) { changes?.push(`"bundleDependencies" was removed`) delete data.bundleDependencies } } // it was once common practice to list deps both in optionalDependencies and // in dependencies, to support npm versions that did not know about // optionalDependencies. This is no longer a relevant need, so duplicating // the deps in two places is unnecessary and excessive. if (steps.includes('optionalDedupe')) { if (data.dependencies && data.optionalDependencies && typeof data.optionalDependencies === 'object') { for (const name in data.optionalDependencies) { changes?.push(`optionalDependencies."${name}" was removed`) delete data.dependencies[name] } if (!Object.keys(data.dependencies).length) { changes?.push(`Empty "optionalDependencies" was removed`) delete data.dependencies } } } // add "install" attribute if any "*.gyp" files exist if (steps.includes('gypfile')) { if (!scripts.install && !scripts.preinstall && data.gypfile !== false) { const files = await lazyLoadGlob()('*.gyp', { cwd: pkg.path }) if (files.length) { scripts.install = 'node-gyp rebuild' data.scripts = scripts data.gypfile = true changes?.push(`"scripts.install" was set to "node-gyp rebuild"`) changes?.push(`"gypfile" was set to "true"`) } } } // add "start" attribute if "server.js" exists if (steps.includes('serverjs') && !scripts.start) { try { await fs.access(path.join(pkg.path, 'server.js')) scripts.start = 'node server.js' data.scripts = scripts changes?.push('"scripts.start" was set to "node server.js"') } catch { // do nothing } } // strip "node_modules/.bin" from scripts entries // remove invalid scripts entries (non-strings) if ((steps.includes('scripts') || steps.includes('scriptpath')) && data.scripts !== undefined) { const spre = /^(\.[/\\])?node_modules[/\\].bin[\\/]/ if (typeof data.scripts === 'object') { for (const name in data.scripts) { if (typeof data.scripts[name] !== 'string') { delete data.scripts[name] changes?.push(`Invalid scripts."${name}" was removed`) } else if (steps.includes('scriptpath') && spre.test(data.scripts[name])) { data.scripts[name] = data.scripts[name].replace(spre, '') changes?.push(`scripts entry "${name}" was fixed to remove node_modules/.bin reference`) } } } else { changes?.push(`Removed invalid "scripts"`) delete data.scripts } } if (steps.includes('funding')) { if (data.funding && typeof data.funding === 'string') { data.funding = { url: data.funding } changes?.push(`"funding" was changed to an object with a url attribute`) } } // populate "authors" attribute if (steps.includes('authors') && !data.contributors) { try { const authorData = await fs.readFile(path.join(pkg.path, 'AUTHORS'), 'utf8') const authors = authorData.split(/\r?\n/g) .map(line => line.replace(/^\s*#.*$/, '').trim()) .filter(line => line) data.contributors = authors changes?.push('"contributors" was auto-populated with the contents of the "AUTHORS" file') } catch { // do nothing } } // populate "readme" attribute if (steps.includes('readme') && !data.readme) { const mdre = /\.m?a?r?k?d?o?w?n?$/i const files = await lazyLoadGlob()('{README,README.*}', { cwd: pkg.path, nocase: true, mark: true, }) let readmeFile for (const file of files) { // don't accept directories. if (!file.endsWith(path.sep)) { if (file.match(mdre)) { readmeFile = file break } if (file.endsWith('README')) { readmeFile = file } } } if (readmeFile) { const readmeData = await fs.readFile(path.join(pkg.path, readmeFile), 'utf8') data.readme = readmeData data.readmeFilename = readmeFile changes?.push(`"readme" was set to the contents of ${readmeFile}`) changes?.push(`"readmeFilename" was set to ${readmeFile}`) } if (!data.readme) { data.readme = 'ERROR: No README data found!' } } // expand directories.man if (steps.includes('mans')) { if (data.directories?.man && !data.man) { const manDir = secureAndUnixifyPath(data.directories.man) const cwd = path.resolve(pkg.path, manDir) const files = await lazyLoadGlob()('**/*.[0-9]', { cwd }) data.man = files.map(man => path.relative(pkg.path, path.join(cwd, man)).split(path.sep).join('/') ) } normalizePackageMan(data, changes) } if (steps.includes('bin') || steps.includes('binDir') || steps.includes('binRefs')) { normalizePackageBin(data, changes) } // expand "directories.bin" if (steps.includes('binDir') && data.directories?.bin && !data.bin) { const binsDir = path.resolve(pkg.path, secureAndUnixifyPath(data.directories.bin)) const bins = await lazyLoadGlob()('**', { cwd: binsDir }) data.bin = bins.reduce((acc, binFile) => { if (binFile && !binFile.startsWith('.')) { const binName = path.basename(binFile) acc[binName] = path.join(data.directories.bin, binFile) } return acc }, {}) // *sigh* normalizePackageBin(data, changes) } // populate "gitHead" attribute if (steps.includes('gitHead') && !data.gitHead) { const git = require('@npmcli/git') const gitRoot = await git.find({ cwd: pkg.path, root }) let head if (gitRoot) { try { head = await fs.readFile(path.resolve(gitRoot, '.git/HEAD'), 'utf8') } catch (err) { // do nothing } } let headData if (head) { if (head.startsWith('ref: ')) { const headRef = head.replace(/^ref: /, '').trim() const headFile = path.resolve(gitRoot, '.git', headRef) try { headData = await fs.readFile(headFile, 'utf8') headData = headData.replace(/^ref: /, '').trim() } catch (err) { // do nothing } if (!headData) { const packFile = path.resolve(gitRoot, '.git/packed-refs') try { let refs = await fs.readFile(packFile, 'utf8') if (refs) { refs = refs.split('\n') for (let i = 0; i < refs.length; i++) { const match = refs[i].match(/^([0-9a-f]{40}) (.+)$/) if (match && match[2].trim() === headRef) { headData = match[1] break } } } } catch { // do nothing } } } else { headData = head.trim() } } if (headData) { data.gitHead = headData } } // populate "types" attribute if (steps.includes('fillTypes')) { const index = data.main || 'index.js' if (typeof index !== 'string') { throw new TypeError('The "main" attribute must be of type string.') } // TODO exports is much more complicated than this in verbose format // We need to support for instance // "exports": { // ".": [ // { // "default": "./lib/npm.js" // }, // "./lib/npm.js" // ], // "./package.json": "./package.json" // }, // as well as conditional exports // if (data.exports && typeof data.exports === 'string') { // index = data.exports // } // if (data.exports && data.exports['.']) { // index = data.exports['.'] // if (typeof index !== 'string') { // } // } const extless = path.join(path.dirname(index), path.basename(index, path.extname(index))) const dts = `./${extless}.d.ts` const hasDTSFields = 'types' in data || 'typings' in data if (!hasDTSFields) { try { await fs.access(path.join(pkg.path, dts)) data.types = dts.split(path.sep).join('/') } catch { // do nothing } } } // "normalizeData" from "read-package-json", which was just a call through to // "normalize-package-data". We only call the "fixer" functions because // outside of that it was also clobbering _id (which we already conditionally // do) and also adding the gypfile script (which we also already // conditionally do) // Some steps are isolated so we can do a limited subset of these in `fix` if (steps.includes('fixRepositoryField') || steps.includes('normalizeData')) { if (data.repositories) { changes?.push(`"repository" was set to the first entry in "repositories" (${data.repository})`) data.repository = data.repositories[0] } if (data.repository) { if (typeof data.repository === 'string') { changes?.push('"repository" was changed from a string to an object') data.repository = { type: 'git', url: data.repository, } } if (data.repository.url) { const hosted = lazyHostedGitInfo().fromUrl(data.repository.url) let r if (hosted) { if (hosted.getDefaultRepresentation() === 'shortcut') { r = hosted.https() } else { r = hosted.toString() } if (r !== data.repository.url) { changes?.push(`"repository.url" was normalized to "${r}"`) data.repository.url = r } } } } } if (steps.includes('fixDependencies') || steps.includes('normalizeData')) { // peerDependencies? // devDependencies is meaningless here, it's ignored on an installed package for (const type of ['dependencies', 'devDependencies', 'optionalDependencies']) { if (data[type]) { let secondWarning = true if (typeof data[type] === 'string') { changes?.push(`"${type}" was converted from a string into an object`) data[type] = data[type].trim().split(/[\n\r\s\t ,]+/) secondWarning = false } if (Array.isArray(data[type])) { if (secondWarning) { changes?.push(`"${type}" was converted from an array into an object`) } const o = {} for (const d of data[type]) { if (typeof d === 'string') { const dep = d.trim().split(/(:?[@\s><=])/) const dn = dep.shift() const dv = dep.join('').replace(/^@/, '').trim() o[dn] = dv } } data[type] = o } } } // normalize-package-data used to put optional dependencies BACK into // dependencies here, we no longer do this for (const deps of ['dependencies', 'devDependencies']) { if (deps in data) { if (!data[deps] || typeof data[deps] !== 'object') { changes?.push(`Removed invalid "${deps}"`) delete data[deps] } else { for (const d in data[deps]) { const r = data[deps][d] if (typeof r !== 'string') { changes?.push(`Removed invalid "${deps}.${d}"`) delete data[deps][d] } const hosted = lazyHostedGitInfo().fromUrl(data[deps][d])?.toString() if (hosted && hosted !== data[deps][d]) { changes?.push(`Normalized git reference to "${deps}.${d}"`) data[deps][d] = hosted.toString() } } } } } } // TODO some of this is duplicated in other steps here, a future breaking change may be able to remove the duplicates involved in this step if (steps.includes('normalizeData')) { const { normalizeData } = require('./normalize-data.js') normalizeData(data, changes) } // Warn if the bin references don't point to anything. This might be better // in normalize-package-data if it had access to the file path. if (steps.includes('binRefs') && data.bin instanceof Object) { for (const key in data.bin) { try { await fs.access(path.resolve(pkg.path, data.bin[key])) } catch { log.warn('package-json', pkgId, `No bin file found at ${data.bin[key]}`) // XXX: should a future breaking change delete bin entries that cannot be accessed? } } } } module.exports = normalize // This is JUST the code needed to open a package.json file and parse it. // It's isolated out so that code needing to parse a package.json file can do so in the same way as this module does, without needing to require the whole module, or needing to require the underlying parsing library. const { readFile } = require('fs/promises') const parseJSON = require('json-parse-even-better-errors') async function read (filename) { try { const data = await readFile(filename, 'utf8') return data } catch (err) { err.message = `Could not read package.json: ${err}` throw err } } function parse (data) { try { const content = parseJSON(data) return content } catch (err) { err.message = `Invalid package.json: ${err}` throw err } } // This is what most external libs will use. // PackageJson will call read and parse separately async function readPackage (filename) { const data = await read(filename) const content = parse(data) return content } module.exports = { read, parse, readPackage, } /** * arbitrary sort order for package.json largely pulled from: * https://github.com/keithamus/sort-package-json/blob/main/defaultRules.md * * cross checked with: * https://github.com/npm/types/blob/main/types/index.d.ts#L104 * https://docs.npmjs.com/cli/configuring-npm/package-json */ function packageSort (json) { const { name, version, private: isPrivate, description, keywords, homepage, bugs, repository, funding, license, author, maintainers, contributors, type, imports, exports, main, browser, types, bin, man, directories, files, workspaces, scripts, config, dependencies, devDependencies, peerDependencies, peerDependenciesMeta, optionalDependencies, bundledDependencies, bundleDependencies, engines, os, cpu, publishConfig, devEngines, licenses, overrides, ...rest } = json return { ...(typeof name !== 'undefined' ? { name } : {}), ...(typeof version !== 'undefined' ? { version } : {}), ...(typeof isPrivate !== 'undefined' ? { private: isPrivate } : {}), ...(typeof description !== 'undefined' ? { description } : {}), ...(typeof keywords !== 'undefined' ? { keywords } : {}), ...(typeof homepage !== 'undefined' ? { homepage } : {}), ...(typeof bugs !== 'undefined' ? { bugs } : {}), ...(typeof repository !== 'undefined' ? { repository } : {}), ...(typeof funding !== 'undefined' ? { funding } : {}), ...(typeof license !== 'undefined' ? { license } : {}), ...(typeof author !== 'undefined' ? { author } : {}), ...(typeof maintainers !== 'undefined' ? { maintainers } : {}), ...(typeof contributors !== 'undefined' ? { contributors } : {}), ...(typeof type !== 'undefined' ? { type } : {}), ...(typeof imports !== 'undefined' ? { imports } : {}), ...(typeof exports !== 'undefined' ? { exports } : {}), ...(typeof main !== 'undefined' ? { main } : {}), ...(typeof browser !== 'undefined' ? { browser } : {}), ...(typeof types !== 'undefined' ? { types } : {}), ...(typeof bin !== 'undefined' ? { bin } : {}), ...(typeof man !== 'undefined' ? { man } : {}), ...(typeof directories !== 'undefined' ? { directories } : {}), ...(typeof files !== 'undefined' ? { files } : {}), ...(typeof workspaces !== 'undefined' ? { workspaces } : {}), ...(typeof scripts !== 'undefined' ? { scripts } : {}), ...(typeof config !== 'undefined' ? { config } : {}), ...(typeof dependencies !== 'undefined' ? { dependencies } : {}), ...(typeof devDependencies !== 'undefined' ? { devDependencies } : {}), ...(typeof peerDependencies !== 'undefined' ? { peerDependencies } : {}), ...(typeof peerDependenciesMeta !== 'undefined' ? { peerDependenciesMeta } : {}), ...(typeof optionalDependencies !== 'undefined' ? { optionalDependencies } : {}), ...(typeof bundledDependencies !== 'undefined' ? { bundledDependencies } : {}), ...(typeof bundleDependencies !== 'undefined' ? { bundleDependencies } : {}), ...(typeof engines !== 'undefined' ? { engines } : {}), ...(typeof os !== 'undefined' ? { os } : {}), ...(typeof cpu !== 'undefined' ? { cpu } : {}), ...(typeof publishConfig !== 'undefined' ? { publishConfig } : {}), ...(typeof devEngines !== 'undefined' ? { devEngines } : {}), ...(typeof licenses !== 'undefined' ? { licenses } : {}), ...(typeof overrides !== 'undefined' ? { overrides } : {}), ...rest, } } module.exports = { packageSort, } const depTypes = new Set([ 'dependencies', 'optionalDependencies', 'devDependencies', 'peerDependencies', ]) // sort alphabetically all types of deps for a given package const orderDeps = (content) => { for (const type of depTypes) { if (content && content[type]) { content[type] = Object.keys(content[type]) .sort((a, b) => a.localeCompare(b, 'en')) .reduce((res, key) => { res[key] = content[type][key] return res }, {}) } } return content } const updateDependencies = ({ content, originalContent }) => { const pkg = orderDeps({ ...content, }) // optionalDependencies don't need to be repeated in two places if (pkg.dependencies) { if (pkg.optionalDependencies) { for (const name of Object.keys(pkg.optionalDependencies)) { delete pkg.dependencies[name] } } } const result = { ...originalContent } // loop through all types of dependencies and update package json pkg for (const type of depTypes) { if (pkg[type]) { result[type] = pkg[type] } // prune empty type props from resulting object const emptyDepType = pkg[type] && typeof pkg === 'object' && Object.keys(pkg[type]).length === 0 if (emptyDepType) { delete result[type] } } // if original package.json had dep in peerDeps AND deps, preserve that. const { dependencies: origProd, peerDependencies: origPeer } = originalContent || {} const { peerDependencies: newPeer } = result if (origProd && origPeer && newPeer) { // we have original prod/peer deps, and new peer deps // copy over any that were in both in the original for (const name of Object.keys(origPeer)) { if (origProd[name] !== undefined && newPeer[name] !== undefined) { result.dependencies = result.dependencies || {} result.dependencies[name] = newPeer[name] } } } return result } updateDependencies.knownKeys = depTypes module.exports = updateDependencies const updateScripts = ({ content, originalContent = {} }) => { const newScripts = content.scripts if (!newScripts) { return originalContent } // validate scripts content being appended const hasInvalidScripts = () => Object.entries(newScripts) .some(([key, value]) => typeof key !== 'string' || typeof value !== 'string') if (hasInvalidScripts()) { throw Object.assign( new TypeError( 'package.json scripts should be a key-value pair of strings.'), { code: 'ESCRIPTSINVALID' } ) } return { ...originalContent, scripts: { ...newScripts, }, } } module.exports = updateScripts const updateWorkspaces = ({ content, originalContent = {} }) => { const newWorkspaces = content.workspaces if (!newWorkspaces) { return originalContent } // validate workspaces content being appended const hasInvalidWorkspaces = () => newWorkspaces.some(w => !(typeof w === 'string')) if (!newWorkspaces.length || hasInvalidWorkspaces()) { throw Object.assign( new TypeError('workspaces should be an array of strings.'), { code: 'EWORKSPACESINVALID' } ) } return { ...originalContent, workspaces: [ ...newWorkspaces, ], } } module.exports = updateWorkspaces { "name": "@npmcli/package-json", "version": "6.1.1", "description": "Programmatic API to update package.json", "keywords": [ "npm", "oss" ], "repository": { "type": "git", "url": "git+https://github.com/npm/package-json.git" }, "license": "ISC", "author": "GitHub Inc.", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "scripts": { "snap": "tap", "test": "tap", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "postsnap": "npm run lintfix --", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "dependencies": { "@npmcli/git": "^6.0.0", "glob": "^10.2.2", "hosted-git-info": "^8.0.0", "json-parse-even-better-errors": "^4.0.0", "proc-log": "^5.0.0", "semver": "^7.5.3", "validate-npm-package-license": "^3.0.4" }, "devDependencies": { "@npmcli/eslint-config": "^5.1.0", "@npmcli/template-oss": "4.23.6", "read-package-json": "^7.0.0", "read-package-json-fast": "^4.0.0", "tap": "^16.0.1" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "publish": "true" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' // eslint-disable-next-line max-len // this code adapted from: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ const cmd = (input, doubleEscape) => { if (!input.length) { return '""' } let result if (!/[ \t\n\v"]/.test(input)) { result = input } else { result = '"' for (let i = 0; i <= input.length; ++i) { let slashCount = 0 while (input[i] === '\\') { ++i ++slashCount } if (i === input.length) { result += '\\'.repeat(slashCount * 2) break } if (input[i] === '"') { result += '\\'.repeat(slashCount * 2 + 1) result += input[i] } else { result += '\\'.repeat(slashCount) result += input[i] } } result += '"' } // and finally, prefix shell meta chars with a ^ result = result.replace(/[ !%^&()<>|"]/g, '^$&') if (doubleEscape) { result = result.replace(/[ !%^&()<>|"]/g, '^$&') } return result } const sh = (input) => { if (!input.length) { return `''` } if (!/[\t\n\r "#$&'()*;<>?\\`|~]/.test(input)) { return input } // replace single quotes with '\'' and wrap the whole result in a fresh set of quotes const result = `'${input.replace(/'/g, `'\\''`)}'` // if the input string already had single quotes around it, clean those up .replace(/^(?:'')+(?!$)/, '') .replace(/\\'''/g, `\\'`) return result } module.exports = { cmd, sh, } 'use strict' const { spawn } = require('child_process') const os = require('os') const which = require('which') const escape = require('./escape.js') // 'extra' object is for decorating the error a bit more const promiseSpawn = (cmd, args, opts = {}, extra = {}) => { if (opts.shell) { return spawnWithShell(cmd, args, opts, extra) } let resolve, reject const promise = new Promise((_resolve, _reject) => { resolve = _resolve reject = _reject }) // Create error here so we have a more useful stack trace when rejecting const closeError = new Error('command failed') const stdout = [] const stderr = [] const getResult = (result) => ({ cmd, args, ...result, ...stdioResult(stdout, stderr, opts), ...extra, }) const rejectWithOpts = (er, erOpts) => { const resultError = getResult(erOpts) reject(Object.assign(er, resultError)) } const proc = spawn(cmd, args, opts) promise.stdin = proc.stdin promise.process = proc proc.on('error', rejectWithOpts) if (proc.stdout) { proc.stdout.on('data', c => stdout.push(c)) proc.stdout.on('error', rejectWithOpts) } if (proc.stderr) { proc.stderr.on('data', c => stderr.push(c)) proc.stderr.on('error', rejectWithOpts) } proc.on('close', (code, signal) => { if (code || signal) { rejectWithOpts(closeError, { code, signal }) } else { resolve(getResult({ code, signal })) } }) return promise } const spawnWithShell = (cmd, args, opts, extra) => { let command = opts.shell // if shell is set to true, we use a platform default. we can't let the core // spawn method decide this for us because we need to know what shell is in use // ahead of time so that we can escape arguments properly. we don't need coverage here. if (command === true) { // istanbul ignore next command = process.platform === 'win32' ? process.env.ComSpec : 'sh' } const options = { ...opts, shell: false } const realArgs = [] let script = cmd // first, determine if we're in windows because if we are we need to know if we're // running an .exe or a .cmd/.bat since the latter requires extra escaping const isCmd = /(?:^|\\)cmd(?:\.exe)?$/i.test(command) if (isCmd) { let doubleEscape = false // find the actual command we're running let initialCmd = '' let insideQuotes = false for (let i = 0; i < cmd.length; ++i) { const char = cmd.charAt(i) if (char === ' ' && !insideQuotes) { break } initialCmd += char if (char === '"' || char === "'") { insideQuotes = !insideQuotes } } let pathToInitial try { pathToInitial = which.sync(initialCmd, { path: (options.env && findInObject(options.env, 'PATH')) || process.env.PATH, pathext: (options.env && findInObject(options.env, 'PATHEXT')) || process.env.PATHEXT, }).toLowerCase() } catch (err) { pathToInitial = initialCmd.toLowerCase() } doubleEscape = pathToInitial.endsWith('.cmd') || pathToInitial.endsWith('.bat') for (const arg of args) { script += ` ${escape.cmd(arg, doubleEscape)}` } realArgs.push('/d', '/s', '/c', script) options.windowsVerbatimArguments = true } else { for (const arg of args) { script += ` ${escape.sh(arg)}` } realArgs.push('-c', script) } return promiseSpawn(command, realArgs, options, extra) } // open a file with the default application as defined by the user's OS const open = (_args, opts = {}, extra = {}) => { const options = { ...opts, shell: true } const args = [].concat(_args) let platform = process.platform // process.platform === 'linux' may actually indicate WSL, if that's the case // open the argument with sensible-browser which is pre-installed // In WSL, set the default browser using, for example, // export BROWSER="/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" // or // export BROWSER="/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" // To permanently set the default browser, add the appropriate entry to your shell's // RC file, e.g. .bashrc or .zshrc. if (platform === 'linux' && os.release().toLowerCase().includes('microsoft')) { platform = 'wsl' if (!process.env.BROWSER) { return Promise.reject( new Error('Set the BROWSER environment variable to your desired browser.')) } } let command = options.command if (!command) { if (platform === 'win32') { // spawnWithShell does not do the additional os.release() check, so we // have to force the shell here to make sure we treat WSL as windows. options.shell = process.env.ComSpec // also, the start command accepts a title so to make sure that we don't // accidentally interpret the first arg as the title, we stick an empty // string immediately after the start command command = 'start ""' } else if (platform === 'wsl') { command = 'sensible-browser' } else if (platform === 'darwin') { command = 'open' } else { command = 'xdg-open' } } return spawnWithShell(command, args, options, extra) } promiseSpawn.open = open const isPipe = (stdio = 'pipe', fd) => { if (stdio === 'pipe' || stdio === null) { return true } if (Array.isArray(stdio)) { return isPipe(stdio[fd], fd) } return false } const stdioResult = (stdout, stderr, { stdioString = true, stdio }) => { const result = { stdout: null, stderr: null, } // stdio is [stdin, stdout, stderr] if (isPipe(stdio, 1)) { result.stdout = Buffer.concat(stdout) if (stdioString) { result.stdout = result.stdout.toString().trim() } } if (isPipe(stdio, 2)) { result.stderr = Buffer.concat(stderr) if (stdioString) { result.stderr = result.stderr.toString().trim() } } return result } // case insensitive lookup in an object const findInObject = (obj, key) => { key = key.toLowerCase() for (const objKey of Object.keys(obj).sort()) { if (objKey.toLowerCase() === key) { return obj[objKey] } } } module.exports = promiseSpawn { "name": "@npmcli/promise-spawn", "version": "8.0.2", "files": [ "bin/", "lib/" ], "main": "./lib/index.js", "description": "spawn processes the way the npm cli likes to do", "repository": { "type": "git", "url": "git+https://github.com/npm/promise-spawn.git" }, "author": "GitHub Inc.", "license": "ISC", "scripts": { "test": "tap", "snap": "tap", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "postsnap": "npm run lintfix --", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.4", "spawk": "^1.7.1", "tap": "^16.0.1" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.4", "publish": true }, "dependencies": { "which": "^5.0.0" } } ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' const parser = require('postcss-selector-parser') const arrayDelimiter = Symbol('arrayDelimiter') const escapeSlashes = str => str.replace(/\//g, '\\/') const unescapeSlashes = str => str.replace(/\\\//g, '/') // recursively fixes up any :attr pseudo-class found const fixupAttr = astNode => { const properties = [] const matcher = {} for (const selectorAstNode of astNode.nodes) { const [firstAstNode] = selectorAstNode.nodes if (firstAstNode.type === 'tag') { properties.push(firstAstNode.value) } } const lastSelectorAstNode = astNode.nodes.pop() const [attributeAstNode] = lastSelectorAstNode.nodes if (attributeAstNode.value === ':attr') { const appendParts = fixupAttr(attributeAstNode) properties.push(arrayDelimiter, ...appendParts.lookupProperties) matcher.qualifiedAttribute = appendParts.attributeMatcher.qualifiedAttribute matcher.operator = appendParts.attributeMatcher.operator matcher.value = appendParts.attributeMatcher.value // backwards compatibility matcher.attribute = appendParts.attributeMatcher.attribute if (appendParts.attributeMatcher.insensitive) { matcher.insensitive = true } } else { if (attributeAstNode.type !== 'attribute') { throw Object.assign( new Error('`:attr` pseudo-class expects an attribute matcher as the last value'), { code: 'EQUERYATTR' } ) } matcher.qualifiedAttribute = unescapeSlashes(attributeAstNode.qualifiedAttribute) matcher.operator = attributeAstNode.operator matcher.value = attributeAstNode.value // backwards compatibility matcher.attribute = matcher.qualifiedAttribute if (attributeAstNode.insensitive) { matcher.insensitive = true } } astNode.lookupProperties = properties astNode.attributeMatcher = matcher astNode.nodes.length = 0 return astNode } // fixed up nested pseudo nodes will have their internal selectors moved // to a new root node that will be referenced by the `nestedNode` property, // this tweak makes it simpler to reuse `retrieveNodesFromParsedAst` to // recursively parse and extract results from the internal selectors const fixupNestedPseudo = astNode => { // create a new ast root node and relocate any children // selectors of the current ast node to this new root const newRootNode = parser.root() astNode.nestedNode = newRootNode newRootNode.nodes = [...astNode.nodes] // clean up the ast by removing the children nodes from the // current ast node while also cleaning up their `parent` refs astNode.nodes.length = 0 for (const currAstNode of newRootNode.nodes) { currAstNode.parent = newRootNode } // recursively fixup nodes of any nested selector transformAst(newRootNode) } // :semver(, [version|range|selector], [function]) // note: the first or second parameter must be a static version or range const fixupSemverSpecs = astNode => { // if we have three nodes, the last is the semver function to use, pull that out first if (astNode.nodes.length === 3) { const funcNode = astNode.nodes.pop().nodes[0] if (funcNode.type === 'tag') { astNode.semverFunc = funcNode.value } else if (funcNode.type === 'string') { // a string is always in some type of quotes, we don't want those so slice them off astNode.semverFunc = funcNode.value.slice(1, -1) } else { // anything that isn't a tag or a string isn't a function name throw Object.assign( new Error('`:semver` pseudo-class expects a function name as last value'), { code: 'ESEMVERFUNC' } ) } } // now if we have 1 node, it's a static value // istanbul ignore else if (astNode.nodes.length === 1) { const semverNode = astNode.nodes.pop() astNode.semverValue = semverNode.nodes.reduce((res, next) => `${res}${String(next)}`, '') } else if (astNode.nodes.length === 2) { // and if we have two nodes, one of them is a static value and we need to determine which it is for (let i = 0; i < astNode.nodes.length; ++i) { const type = astNode.nodes[i].nodes[0].type // the type of the first child may be combinator for ranges, such as >14 if (type === 'tag' || type === 'combinator') { const semverNode = astNode.nodes.splice(i, 1)[0] astNode.semverValue = semverNode.nodes.reduce((res, next) => `${res}${String(next)}`, '') astNode.semverPosition = i break } } if (typeof astNode.semverValue === 'undefined') { throw Object.assign( new Error('`:semver` pseudo-class expects a static value in the first or second position'), { code: 'ESEMVERVALUE' } ) } } // if we got here, the last remaining child should be attribute selector if (astNode.nodes.length === 1) { fixupAttr(astNode) } else { // if we don't have a selector, we default to `[version]` astNode.attributeMatcher = { insensitive: false, attribute: 'version', qualifiedAttribute: 'version', } astNode.lookupProperties = [] } astNode.nodes.length = 0 } const fixupTypes = astNode => { const [valueAstNode] = astNode.nodes[0].nodes const { value } = valueAstNode || {} astNode.typeValue = value astNode.nodes.length = 0 } const fixupPaths = astNode => { astNode.pathValue = unescapeSlashes(String(astNode.nodes[0])) astNode.nodes.length = 0 } const fixupOutdated = astNode => { if (astNode.nodes.length) { astNode.outdatedKind = String(astNode.nodes[0]) astNode.nodes.length = 0 } } const fixupVuln = astNode => { const vulns = [] if (astNode.nodes.length) { for (const selector of astNode.nodes) { const vuln = {} for (const node of selector.nodes) { if (node.type !== 'attribute') { throw Object.assign( new Error(':vuln pseudo-class only accepts attribute matchers or "cwe" tag'), { code: 'EQUERYATTR' } ) } if (!['severity', 'cwe'].includes(node._attribute)) { throw Object.assign( new Error(':vuln pseudo-class only matches "severity" and "cwe" attributes'), { code: 'EQUERYATTR' } ) } if (!node.operator) { node.operator = '=' node.value = '*' } if (node.operator !== '=') { throw Object.assign( new Error(':vuln pseudo-class attribute selector only accepts "=" operator', node), { code: 'EQUERYATTR' } ) } if (!vuln[node._attribute]) { vuln[node._attribute] = [] } vuln[node._attribute].push(node._value) } vulns.push(vuln) } astNode.vulns = vulns astNode.nodes.length = 0 } } // a few of the supported ast nodes need to be tweaked in order to properly be // interpreted as proper arborist query selectors, namely semver ranges from // both ids and :semver pseudo-class selectors need to be translated from what // are usually multiple ast nodes, such as: tag:1, class:.0, class:.0 to a // single `1.0.0` value, other pseudo-class selectors also get preprocessed in // order to make it simpler to execute later when traversing each ast node // using rootNode.walk(), such as :path, :type, etc. transformAst handles all // these modifications to the parsed ast by doing an extra, initial traversal // of the parsed ast from the query and modifying the parsed nodes accordingly const transformAst = selector => { selector.walk((nextAstNode) => { switch (nextAstNode.value) { case ':attr': return fixupAttr(nextAstNode) case ':is': case ':has': case ':not': return fixupNestedPseudo(nextAstNode) case ':path': return fixupPaths(nextAstNode) case ':semver': return fixupSemverSpecs(nextAstNode) case ':type': return fixupTypes(nextAstNode) case ':outdated': return fixupOutdated(nextAstNode) case ':vuln': return fixupVuln(nextAstNode) } }) } const queryParser = (query) => { // if query is an empty string or any falsy // value, just returns an empty result if (!query) { return [] } return parser(transformAst) .astSync(escapeSlashes(query), { lossless: false }) } module.exports = { parser: queryParser, arrayDelimiter, } { "name": "@npmcli/query", "version": "4.0.0", "description": "npm query parser and tools", "main": "lib/index.js", "scripts": { "test": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "contributors": [ { "name": "Ruy Adorno", "url": "https://ruyadorno.com", "twitter": "ruyadorno" } ], "keywords": [ "ast", "npm", "npmcli", "parser", "postcss", "postcss-selector-parser", "query" ], "author": "GitHub Inc.", "license": "ISC", "files": [ "bin/", "lib/" ], "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.2.0" }, "dependencies": { "postcss-selector-parser": "^6.1.2" }, "repository": { "type": "git", "url": "git+https://github.com/npm/query.git" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } MIT License Copyright (c) 2024 npm 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. function filterError (input) { return { errorType: input.name, message: input.message, stack: input.stack, ...(input.code ? { code: input.code } : {}), ...(input.statusCode ? { statusCode: input.statusCode } : {}), } } const deepMap = (input, handler = v => v, path = ['$'], seen = new Set([input])) => { // this is in an effort to maintain bole's error logging behavior if (path.join('.') === '$' && input instanceof Error) { return deepMap({ err: filterError(input) }, handler, path, seen) } if (input instanceof Error) { return deepMap(filterError(input), handler, path, seen) } if (input instanceof Buffer) { return `[unable to log instanceof buffer]` } if (input instanceof Uint8Array) { return `[unable to log instanceof Uint8Array]` } if (Array.isArray(input)) { const result = [] for (let i = 0; i < input.length; i++) { const element = input[i] const elementPath = [...path, i] if (element instanceof Object) { if (!seen.has(element)) { // avoid getting stuck in circular reference seen.add(element) result.push(deepMap(handler(element, elementPath), handler, elementPath, seen)) } } else { result.push(handler(element, elementPath)) } } return result } if (input === null) { return null } else if (typeof input === 'object' || typeof input === 'function') { const result = {} for (const propertyName of Object.getOwnPropertyNames(input)) { // skip logging internal properties if (propertyName.startsWith('_')) { continue } try { const property = input[propertyName] const propertyPath = [...path, propertyName] if (property instanceof Object) { if (!seen.has(property)) { // avoid getting stuck in circular reference seen.add(property) result[propertyName] = deepMap( handler(property, propertyPath), handler, propertyPath, seen ) } } else { result[propertyName] = handler(property, propertyPath) } } catch (err) { // a getter may throw an error result[propertyName] = `[error getting value: ${err.message}]` } } return result } return handler(input, path) } module.exports = { deepMap } const matchers = require('./matchers') const { redactUrlPassword } = require('./utils') const REPLACE = '***' const redact = (value) => { if (typeof value !== 'string' || !value) { return value } return redactUrlPassword(value, REPLACE) .replace(matchers.NPM_SECRET.pattern, `npm_${REPLACE}`) .replace(matchers.UUID.pattern, REPLACE) } // split on \s|= similar to how nopt parses options const splitAndRedact = (str) => { // stateful regex, don't move out of this scope const splitChars = /[\s=]/g let match = null let result = '' let index = 0 while (match = splitChars.exec(str)) { result += redact(str.slice(index, match.index)) + match[0] index = splitChars.lastIndex } return result + redact(str.slice(index)) } // replaces auth info in an array of arguments or in a strings const redactLog = (arg) => { if (typeof arg === 'string') { return splitAndRedact(arg) } else if (Array.isArray(arg)) { return arg.map((a) => typeof a === 'string' ? splitAndRedact(a) : a) } return arg } module.exports = { redact, redactLog, } const TYPE_REGEX = 'regex' const TYPE_URL = 'url' const TYPE_PATH = 'path' const NPM_SECRET = { type: TYPE_REGEX, pattern: /\b(npms?_)[a-zA-Z0-9]{36,48}\b/gi, replacement: `[REDACTED_NPM_SECRET]`, } const AUTH_HEADER = { type: TYPE_REGEX, pattern: /\b(Basic\s+|Bearer\s+)[\w+=\-.]+\b/gi, replacement: `[REDACTED_AUTH_HEADER]`, } const JSON_WEB_TOKEN = { type: TYPE_REGEX, pattern: /\b[A-Za-z0-9-_]{10,}(?!\.\d+\.)\.[A-Za-z0-9-_]{3,}\.[A-Za-z0-9-_]{20,}\b/gi, replacement: `[REDACTED_JSON_WEB_TOKEN]`, } const UUID = { type: TYPE_REGEX, pattern: /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, replacement: `[REDACTED_UUID]`, } const URL_MATCHER = { type: TYPE_REGEX, pattern: /(?:https?|ftp):\/\/[^\s/"$.?#].[^\s"]*/gi, replacement: '[REDACTED_URL]', } const DEEP_HEADER_AUTHORIZATION = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.headers.authorization'), replacement: '[REDACTED_HEADER_AUTHORIZATION]', } const DEEP_HEADER_SET_COOKIE = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.headers.set-cookie'), replacement: '[REDACTED_HEADER_SET_COOKIE]', } const REWRITE_REQUEST = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.request'), replacement: (input) => ({ method: input?.method, path: input?.path, headers: input?.headers, url: input?.url, }), } const REWRITE_RESPONSE = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.response'), replacement: (input) => ({ data: input?.data, status: input?.status, headers: input?.headers, }), } module.exports = { TYPE_REGEX, TYPE_URL, TYPE_PATH, NPM_SECRET, AUTH_HEADER, JSON_WEB_TOKEN, UUID, URL_MATCHER, DEEP_HEADER_AUTHORIZATION, DEEP_HEADER_SET_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, } const { AUTH_HEADER, JSON_WEB_TOKEN, NPM_SECRET, DEEP_HEADER_AUTHORIZATION, DEEP_HEADER_SET_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, } = require('./matchers') const { redactUrlMatcher, redactUrlPasswordMatcher, redactMatchers, } = require('./utils') const { deepMap } = require('./deep-map') const _redact = redactMatchers( NPM_SECRET, AUTH_HEADER, JSON_WEB_TOKEN, DEEP_HEADER_AUTHORIZATION, DEEP_HEADER_SET_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, redactUrlMatcher( redactUrlPasswordMatcher() ) ) const redact = (input) => deepMap(input, (value, path) => _redact(value, { path })) module.exports = { redact } const { URL_MATCHER, TYPE_URL, TYPE_REGEX, TYPE_PATH, } = require('./matchers') /** * creates a string of asterisks, * this forces a minimum asterisk for security purposes */ const asterisk = (length = 0) => { length = typeof length === 'string' ? length.length : length if (length < 8) { return '*'.repeat(8) } return '*'.repeat(length) } /** * escapes all special regex chars * @see https://stackoverflow.com/a/9310752 * @see https://github.com/tc39/proposal-regex-escaping */ const escapeRegExp = (text) => { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, `\\$&`) } /** * provieds a regex "or" of the url versions of a string */ const urlEncodeRegexGroup = (value) => { const decoded = decodeURIComponent(value) const encoded = encodeURIComponent(value) const union = [...new Set([encoded, decoded, value])].map(escapeRegExp).join('|') return union } /** * a tagged template literal that returns a regex ensures all variables are excaped */ const urlEncodeRegexTag = (strings, ...values) => { let pattern = '' for (let i = 0; i < values.length; i++) { pattern += strings[i] + `(${urlEncodeRegexGroup(values[i])})` } pattern += strings[strings.length - 1] return new RegExp(pattern) } /** * creates a matcher for redacting url hostname */ const redactUrlHostnameMatcher = ({ hostname, replacement } = {}) => ({ type: TYPE_URL, predicate: ({ url }) => url.hostname === hostname, pattern: ({ url }) => { return urlEncodeRegexTag`(^${url.protocol}//${url.username}:.+@)?${url.hostname}` }, replacement: `$1${replacement || asterisk()}`, }) /** * creates a matcher for redacting url search / query parameter values */ const redactUrlSearchParamsMatcher = ({ param, replacement } = {}) => ({ type: TYPE_URL, predicate: ({ url }) => url.searchParams.has(param), pattern: ({ url }) => urlEncodeRegexTag`(${param}=)${url.searchParams.get(param)}`, replacement: `$1${replacement || asterisk()}`, }) /** creates a matcher for redacting the url password */ const redactUrlPasswordMatcher = ({ replacement } = {}) => ({ type: TYPE_URL, predicate: ({ url }) => url.password, pattern: ({ url }) => urlEncodeRegexTag`(^${url.protocol}//${url.username}:)${url.password}`, replacement: `$1${replacement || asterisk()}`, }) const redactUrlReplacement = (...matchers) => (subValue) => { try { const url = new URL(subValue) return redactMatchers(...matchers)(subValue, { url }) } catch (err) { return subValue } } /** * creates a matcher / submatcher for urls, this function allows you to first * collect all urls within a larger string and then pass those urls to a * submatcher * * @example * console.log("this will first match all urls, then pass those urls to the password patcher") * redactMatchers(redactUrlMatcher(redactUrlPasswordMatcher())) * * @example * console.log( * "this will assume you are passing in a string that is a url, and will redact the password" * ) * redactMatchers(redactUrlPasswordMatcher()) * */ const redactUrlMatcher = (...matchers) => { return { ...URL_MATCHER, replacement: redactUrlReplacement(...matchers), } } const matcherFunctions = { [TYPE_REGEX]: (matcher) => (value) => { if (typeof value === 'string') { value = value.replace(matcher.pattern, matcher.replacement) } return value }, [TYPE_URL]: (matcher) => (value, ctx) => { if (typeof value === 'string') { try { const url = ctx?.url || new URL(value) const { predicate, pattern } = matcher const predicateValue = predicate({ url }) if (predicateValue) { value = value.replace(pattern({ url }), matcher.replacement) } } catch (_e) { return value } } return value }, [TYPE_PATH]: (matcher) => (value, ctx) => { const rawPath = ctx?.path const path = rawPath.join('.').toLowerCase() const { predicate, replacement } = matcher const replace = typeof replacement === 'function' ? replacement : () => replacement const shouldRun = predicate({ rawPath, path }) if (shouldRun) { value = replace(value, { rawPath, path }) } return value }, } /** converts a matcher to a function */ const redactMatcher = (matcher) => { return matcherFunctions[matcher.type](matcher) } /** converts a series of matchers to a function */ const redactMatchers = (...matchers) => (value, ctx) => { const flatMatchers = matchers.flat() return flatMatchers.reduce((result, matcher) => { const fn = (typeof matcher === 'function') ? matcher : redactMatcher(matcher) return fn(result, ctx) }, value) } /** * replacement handler, keeping $1 (if it exists) and replacing the * rest of the string with asterisks, maintaining string length */ const redactDynamicReplacement = () => (value, start) => { if (typeof start === 'number') { return asterisk(value) } return start + asterisk(value.substring(start.length).length) } /** * replacement handler, keeping $1 (if it exists) and replacing the * rest of the string with a fixed number of asterisks */ const redactFixedReplacement = (length) => (_value, start) => { if (typeof start === 'number') { return asterisk(length) } return start + asterisk(length) } const redactUrlPassword = (value, replacement) => { return redactMatchers(redactUrlPasswordMatcher({ replacement }))(value) } module.exports = { asterisk, escapeRegExp, urlEncodeRegexGroup, urlEncodeRegexTag, redactUrlHostnameMatcher, redactUrlSearchParamsMatcher, redactUrlPasswordMatcher, redactUrlMatcher, redactUrlReplacement, redactDynamicReplacement, redactFixedReplacement, redactMatchers, redactUrlPassword, } { "name": "@npmcli/redact", "version": "3.0.0", "description": "Redact sensitive npm information from output", "main": "lib/index.js", "exports": { ".": "./lib/index.js", "./server": "./lib/server.js", "./package.json": "./package.json" }, "scripts": { "test": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "keywords": [], "author": "GitHub Inc.", "license": "ISC", "files": [ "bin/", "lib/" ], "repository": { "type": "git", "url": "git+https://github.com/npm/redact.git" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ], "timeout": 120 }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.3.10" }, "engines": { "node": "^18.17.0 || >=20.5.0" } } The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const { stat } = require('node:fs/promises') const { resolve } = require('node:path') module.exports = async path => { try { const st = await stat(resolve(path, 'server.js')) return st.isFile() } catch (er) { return false } } /* eslint camelcase: "off" */ const setPATH = require('./set-path.js') const { resolve } = require('path') const npm_config_node_gyp = require.resolve('node-gyp/bin/node-gyp.js') const makeSpawnArgs = options => { const { event, path, scriptShell = true, binPaths, env, stdio, cmd, args, stdioString, } = options const spawnEnv = setPATH(path, binPaths, { // we need to at least save the PATH environment var ...process.env, ...env, npm_package_json: resolve(path, 'package.json'), npm_lifecycle_event: event, npm_lifecycle_script: cmd, npm_config_node_gyp, }) const spawnOpts = { env: spawnEnv, stdioString, stdio, cwd: path, shell: scriptShell, } return [cmd, args, spawnOpts] } module.exports = makeSpawnArgs #!/usr/bin/env sh node "$npm_config_node_gyp" "$@" @node "%npm_config_node_gyp%" %* const packageEnvs = (vals, prefix, env = {}) => { for (const [key, val] of Object.entries(vals)) { if (val === undefined) { continue } else if (val === null || val === false) { env[`${prefix}${key}`] = '' } else if (Array.isArray(val)) { val.forEach((item, index) => { packageEnvs({ [`${key}_${index}`]: item }, `${prefix}`, env) }) } else if (typeof val === 'object') { packageEnvs(val, `${prefix}${key}_`, env) } else { env[`${prefix}${key}`] = String(val) } } return env } // https://github.com/npm/rfcs/pull/183 defines which fields we put into the environment module.exports = pkg => { return packageEnvs({ name: pkg.name, version: pkg.version, config: pkg.config, engines: pkg.engines, bin: pkg.bin, }, 'npm_package_') } const makeSpawnArgs = require('./make-spawn-args.js') const promiseSpawn = require('@npmcli/promise-spawn') const packageEnvs = require('./package-envs.js') const { isNodeGypPackage, defaultGypInstallScript } = require('@npmcli/node-gyp') const signalManager = require('./signal-manager.js') const isServerPackage = require('./is-server-package.js') const runScriptPkg = async options => { const { event, path, scriptShell, binPaths = false, env = {}, stdio = 'pipe', pkg, args = [], stdioString, // how long to wait for a process.kill signal // only exposed here so that we can make the test go a bit faster. signalTimeout = 500, } = options const { scripts = {}, gypfile } = pkg let cmd = null if (options.cmd) { cmd = options.cmd } else if (pkg.scripts && pkg.scripts[event]) { cmd = pkg.scripts[event] } else if ( // If there is no preinstall or install script, default to rebuilding node-gyp packages. event === 'install' && !scripts.install && !scripts.preinstall && gypfile !== false && await isNodeGypPackage(path) ) { cmd = defaultGypInstallScript } else if (event === 'start' && await isServerPackage(path)) { cmd = 'node server.js' } if (!cmd) { return { code: 0, signal: null } } let inputEnd = () => {} if (stdio === 'inherit') { let banner if (pkg._id) { banner = `\n> ${pkg._id} ${event}\n` } else { banner = `\n> ${event}\n` } banner += `> ${cmd.trim().replace(/\n/g, '\n> ')}` if (args.length) { banner += ` ${args.join(' ')}` } banner += '\n' const { output, input } = require('proc-log') output.standard(banner) inputEnd = input.start() } const [spawnShell, spawnArgs, spawnOpts] = makeSpawnArgs({ event, path, scriptShell, binPaths, env: { ...env, ...packageEnvs(pkg) }, stdio, cmd, args, stdioString, }) const p = promiseSpawn(spawnShell, spawnArgs, spawnOpts, { event, script: cmd, pkgid: pkg._id, path, }) if (stdio === 'inherit') { signalManager.add(p.process) } if (p.stdin) { p.stdin.end() } return p.catch(er => { const { signal } = er // coverage disabled because win32 never emits signals /* istanbul ignore next */ if (stdio === 'inherit' && signal) { // by the time we reach here, the child has already exited. we send the // signal back to ourselves again so that npm will exit with the same // status as the child process.kill(process.pid, signal) // just in case we don't die, reject after 500ms // this also keeps the node process open long enough to actually // get the signal, rather than terminating gracefully. return new Promise((res, rej) => setTimeout(() => rej(er), signalTimeout)) } else { throw er } }).finally(inputEnd) } module.exports = runScriptPkg const PackageJson = require('@npmcli/package-json') const runScriptPkg = require('./run-script-pkg.js') const validateOptions = require('./validate-options.js') const isServerPackage = require('./is-server-package.js') const runScript = async options => { validateOptions(options) if (options.pkg) { return runScriptPkg(options) } const { content: pkg } = await PackageJson.normalize(options.path) return runScriptPkg({ ...options, pkg }) } module.exports = Object.assign(runScript, { isServerPackage }) const { resolve, dirname, delimiter } = require('path') // the path here is relative, even though it does not need to be // in order to make the posix tests pass in windows const nodeGypPath = resolve(__dirname, '../lib/node-gyp-bin') // Windows typically calls its PATH environ 'Path', but this is not // guaranteed, nor is it guaranteed to be the only one. Merge them // all together in the order they appear in the object. const setPATH = (projectPath, binPaths, env) => { const PATH = Object.keys(env).filter(p => /^path$/i.test(p) && env[p]) .map(p => env[p].split(delimiter)) .reduce((set, p) => set.concat(p.filter(concatted => !set.includes(concatted))), []) .join(delimiter) const pathArr = [] if (binPaths) { pathArr.push(...binPaths) } // unshift the ./node_modules/.bin from every folder // walk up until dirname() does nothing, at the root // XXX we should specify a cwd that we don't go above let p = projectPath let pp do { pathArr.push(resolve(p, 'node_modules', '.bin')) pp = p p = dirname(p) } while (p !== pp) pathArr.push(nodeGypPath, PATH) const pathVal = pathArr.join(delimiter) // XXX include the node-gyp-bin path somehow? Probably better for // npm or arborist or whoever to just provide that by putting it in // the PATH environ, since that's preserved anyway. for (const key of Object.keys(env)) { if (/^path$/i.test(key)) { env[key] = pathVal } } return env } module.exports = setPATH const runningProcs = new Set() let handlersInstalled = false const forwardedSignals = [ 'SIGINT', 'SIGTERM', ] // no-op, this is so receiving the signal doesn't cause us to exit immediately // instead, we exit after all children have exited when we re-send the signal // to ourselves. see the catch handler at the bottom of run-script-pkg.js const handleSignal = signal => { for (const proc of runningProcs) { proc.kill(signal) } } const setupListeners = () => { for (const signal of forwardedSignals) { process.on(signal, handleSignal) } handlersInstalled = true } const cleanupListeners = () => { if (runningProcs.size === 0) { for (const signal of forwardedSignals) { process.removeListener(signal, handleSignal) } handlersInstalled = false } } const add = proc => { runningProcs.add(proc) if (!handlersInstalled) { setupListeners() } proc.once('exit', () => { runningProcs.delete(proc) cleanupListeners() }) } module.exports = { add, handleSignal, forwardedSignals, } const validateOptions = options => { if (typeof options !== 'object' || !options) { throw new TypeError('invalid options object provided to runScript') } const { event, path, scriptShell, env = {}, stdio = 'pipe', args = [], cmd, } = options if (!event || typeof event !== 'string') { throw new TypeError('valid event not provided to runScript') } if (!path || typeof path !== 'string') { throw new TypeError('valid path not provided to runScript') } if (scriptShell !== undefined && typeof scriptShell !== 'string') { throw new TypeError('invalid scriptShell option provided to runScript') } if (typeof env !== 'object' || !env) { throw new TypeError('invalid env option provided to runScript') } if (typeof stdio !== 'string' && !Array.isArray(stdio)) { throw new TypeError('invalid stdio option provided to runScript') } if (!Array.isArray(args) || args.some(a => typeof a !== 'string')) { throw new TypeError('invalid args option provided to runScript') } if (cmd !== undefined && typeof cmd !== 'string') { throw new TypeError('invalid cmd option provided to runScript') } } module.exports = validateOptions { "name": "@npmcli/run-script", "version": "9.0.2", "description": "Run a lifecycle script for a package (descendant of npm-lifecycle)", "author": "GitHub Inc.", "license": "ISC", "scripts": { "test": "tap", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "postlint": "template-oss-check", "snap": "tap", "posttest": "npm run lint", "template-oss-apply": "template-oss-apply --force" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.4", "spawk": "^1.8.1", "tap": "^16.0.1" }, "dependencies": { "@npmcli/node-gyp": "^4.0.0", "@npmcli/package-json": "^6.0.0", "@npmcli/promise-spawn": "^8.0.0", "node-gyp": "^11.0.0", "proc-log": "^5.0.0", "which": "^5.0.0" }, "files": [ "bin/", "lib/" ], "main": "lib/run-script.js", "repository": { "type": "git", "url": "git+https://github.com/npm/run-script.git" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.4", "publish": "true" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 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 (50%) 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (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-2.0 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. 'use strict'; // This example shows how to understand if a default value is used or not. // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const options = { file: { short: 'f', type: 'string', default: 'FOO' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); const isFileDefault = !tokens.some((token) => token.kind === 'option' && token.name === 'file' ); console.log(values); console.log(`Is the file option [${values.file}] the default value? ${isFileDefault}`); // Try the following: // node is-default-value.js // node is-default-value.js -f FILE // node is-default-value.js --file FILE 'use strict'; // This is an example of using tokens to add a custom behaviour. // // Require the use of `=` for long options and values by blocking // the use of space separated values. // So allow `--foo=bar`, and not allow `--foo bar`. // // Note: this is not a common behaviour, most CLIs allow both forms. // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const options = { file: { short: 'f', type: 'string' }, log: { type: 'string' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); const badToken = tokens.find((token) => token.kind === 'option' && token.value != null && token.rawName.startsWith('--') && !token.inlineValue ); if (badToken) { throw new Error(`Option value for '${badToken.rawName}' must be inline, like '${badToken.rawName}=VALUE'`); } console.log(values); // Try the following: // node limit-long-syntax.js -f FILE --log=LOG // node limit-long-syntax.js --file FILE 'use strict'; // This example is used in the documentation. // How might I add my own support for --no-foo? // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const options = { 'color': { type: 'boolean' }, 'no-color': { type: 'boolean' }, 'logfile': { type: 'string' }, 'no-logfile': { type: 'boolean' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); // Reprocess the option tokens and overwrite the returned values. tokens .filter((token) => token.kind === 'option') .forEach((token) => { if (token.name.startsWith('no-')) { // Store foo:false for --no-foo const positiveName = token.name.slice(3); values[positiveName] = false; delete values[token.name]; } else { // Resave value so last one wins if both --foo and --no-foo. values[token.name] = token.value ?? true; } }); const color = values.color; const logfile = values.logfile ?? 'default.log'; console.log({ logfile, color }); // Try the following: // node negate.js // node negate.js --no-logfile --no-color // negate.js --logfile=test.log --color // node negate.js --no-logfile --logfile=test.log --color --no-color 'use strict'; // This is an example of using tokens to add a custom behaviour. // // Throw an error if an option is used more than once. // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const options = { ding: { type: 'boolean', short: 'd' }, beep: { type: 'boolean', short: 'b' } }; const { values, tokens } = parseArgs({ options, tokens: true }); const seenBefore = new Set(); tokens.forEach((token) => { if (token.kind !== 'option') return; if (seenBefore.has(token.name)) { throw new Error(`option '${token.name}' used multiple times`); } seenBefore.add(token.name); }); console.log(values); // Try the following: // node no-repeated-options --ding --beep // node no-repeated-options --beep -b // node no-repeated-options -ddd // This is an example of using tokens to add a custom behaviour. // // This adds a option order check so that --some-unstable-option // may only be used after --enable-experimental-options // // Note: this is not a common behaviour, the order of different options // does not usually matter. import { parseArgs } from '../index.js'; function findTokenIndex(tokens, target) { return tokens.findIndex((token) => token.kind === 'option' && token.name === target ); } const experimentalName = 'enable-experimental-options'; const unstableName = 'some-unstable-option'; const options = { [experimentalName]: { type: 'boolean' }, [unstableName]: { type: 'boolean' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); const experimentalIndex = findTokenIndex(tokens, experimentalName); const unstableIndex = findTokenIndex(tokens, unstableName); if (unstableIndex !== -1 && ((experimentalIndex === -1) || (unstableIndex < experimentalIndex))) { throw new Error(`'--${experimentalName}' must be specified before '--${unstableName}'`); } console.log(values); /* eslint-disable max-len */ // Try the following: // node ordered-options.mjs // node ordered-options.mjs --some-unstable-option // node ordered-options.mjs --some-unstable-option --enable-experimental-options // node ordered-options.mjs --enable-experimental-options --some-unstable-option 'use strict'; // This example is used in the documentation. // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const args = ['-f', '--bar', 'b']; const options = { foo: { type: 'boolean', short: 'f' }, bar: { type: 'string' } }; const { values, positionals } = parseArgs({ args, options }); console.log(values, positionals); // Try the following: // node simple-hard-coded.js 'use strict'; const { ArrayPrototypeForEach, ArrayPrototypeIncludes, ArrayPrototypeMap, ArrayPrototypePush, ArrayPrototypePushApply, ArrayPrototypeShift, ArrayPrototypeSlice, ArrayPrototypeUnshiftApply, ObjectEntries, ObjectPrototypeHasOwnProperty: ObjectHasOwn, StringPrototypeCharAt, StringPrototypeIndexOf, StringPrototypeSlice, StringPrototypeStartsWith, } = require('./internal/primordials'); const { validateArray, validateBoolean, validateBooleanArray, validateObject, validateString, validateStringArray, validateUnion, } = require('./internal/validators'); const { kEmptyObject, } = require('./internal/util'); const { findLongOptionForShort, isLoneLongOption, isLoneShortOption, isLongOptionAndValue, isOptionValue, isOptionLikeValue, isShortOptionAndValue, isShortOptionGroup, useDefaultValueOption, objectGetOwn, optionsGetOwn, } = require('./utils'); const { codes: { ERR_INVALID_ARG_VALUE, ERR_PARSE_ARGS_INVALID_OPTION_VALUE, ERR_PARSE_ARGS_UNKNOWN_OPTION, ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL, }, } = require('./internal/errors'); function getMainArgs() { // Work out where to slice process.argv for user supplied arguments. // Check node options for scenarios where user CLI args follow executable. const execArgv = process.execArgv; if (ArrayPrototypeIncludes(execArgv, '-e') || ArrayPrototypeIncludes(execArgv, '--eval') || ArrayPrototypeIncludes(execArgv, '-p') || ArrayPrototypeIncludes(execArgv, '--print')) { return ArrayPrototypeSlice(process.argv, 1); } // Normally first two arguments are executable and script, then CLI arguments return ArrayPrototypeSlice(process.argv, 2); } /** * In strict mode, throw for possible usage errors like --foo --bar * * @param {object} token - from tokens as available from parseArgs */ function checkOptionLikeValue(token) { if (!token.inlineValue && isOptionLikeValue(token.value)) { // Only show short example if user used short option. const example = StringPrototypeStartsWith(token.rawName, '--') ? `'${token.rawName}=-XYZ'` : `'--${token.name}=-XYZ' or '${token.rawName}-XYZ'`; const errorMessage = `Option '${token.rawName}' argument is ambiguous. Did you forget to specify the option argument for '${token.rawName}'? To specify an option argument starting with a dash use ${example}.`; throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(errorMessage); } } /** * In strict mode, throw for usage errors. * * @param {object} config - from config passed to parseArgs * @param {object} token - from tokens as available from parseArgs */ function checkOptionUsage(config, token) { if (!ObjectHasOwn(config.options, token.name)) { throw new ERR_PARSE_ARGS_UNKNOWN_OPTION( token.rawName, config.allowPositionals); } const short = optionsGetOwn(config.options, token.name, 'short'); const shortAndLong = `${short ? `-${short}, ` : ''}--${token.name}`; const type = optionsGetOwn(config.options, token.name, 'type'); if (type === 'string' && typeof token.value !== 'string') { throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong} ' argument missing`); } // (Idiomatic test for undefined||null, expecting undefined.) if (type === 'boolean' && token.value != null) { throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong}' does not take an argument`); } } /** * Store the option value in `values`. * * @param {string} longOption - long option name e.g. 'foo' * @param {string|undefined} optionValue - value from user args * @param {object} options - option configs, from parseArgs({ options }) * @param {object} values - option values returned in `values` by parseArgs */ function storeOption(longOption, optionValue, options, values) { if (longOption === '__proto__') { return; // No. Just no. } // We store based on the option value rather than option type, // preserving the users intent for author to deal with. const newValue = optionValue ?? true; if (optionsGetOwn(options, longOption, 'multiple')) { // Always store value in array, including for boolean. // values[longOption] starts out not present, // first value is added as new array [newValue], // subsequent values are pushed to existing array. // (note: values has null prototype, so simpler usage) if (values[longOption]) { ArrayPrototypePush(values[longOption], newValue); } else { values[longOption] = [newValue]; } } else { values[longOption] = newValue; } } /** * Store the default option value in `values`. * * @param {string} longOption - long option name e.g. 'foo' * @param {string * | boolean * | string[] * | boolean[]} optionValue - default value from option config * @param {object} values - option values returned in `values` by parseArgs */ function storeDefaultOption(longOption, optionValue, values) { if (longOption === '__proto__') { return; // No. Just no. } values[longOption] = optionValue; } /** * Process args and turn into identified tokens: * - option (along with value, if any) * - positional * - option-terminator * * @param {string[]} args - from parseArgs({ args }) or mainArgs * @param {object} options - option configs, from parseArgs({ options }) */ function argsToTokens(args, options) { const tokens = []; let index = -1; let groupCount = 0; const remainingArgs = ArrayPrototypeSlice(args); while (remainingArgs.length > 0) { const arg = ArrayPrototypeShift(remainingArgs); const nextArg = remainingArgs[0]; if (groupCount > 0) groupCount--; else index++; // Check if `arg` is an options terminator. // Guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html if (arg === '--') { // Everything after a bare '--' is considered a positional argument. ArrayPrototypePush(tokens, { kind: 'option-terminator', index }); ArrayPrototypePushApply( tokens, ArrayPrototypeMap(remainingArgs, (arg) => { return { kind: 'positional', index: ++index, value: arg }; }) ); break; // Finished processing args, leave while loop. } if (isLoneShortOption(arg)) { // e.g. '-f' const shortOption = StringPrototypeCharAt(arg, 1); const longOption = findLongOptionForShort(shortOption, options); let value; let inlineValue; if (optionsGetOwn(options, longOption, 'type') === 'string' && isOptionValue(nextArg)) { // e.g. '-f', 'bar' value = ArrayPrototypeShift(remainingArgs); inlineValue = false; } ArrayPrototypePush( tokens, { kind: 'option', name: longOption, rawName: arg, index, value, inlineValue }); if (value != null) ++index; continue; } if (isShortOptionGroup(arg, options)) { // Expand -fXzy to -f -X -z -y const expanded = []; for (let index = 1; index < arg.length; index++) { const shortOption = StringPrototypeCharAt(arg, index); const longOption = findLongOptionForShort(shortOption, options); if (optionsGetOwn(options, longOption, 'type') !== 'string' || index === arg.length - 1) { // Boolean option, or last short in group. Well formed. ArrayPrototypePush(expanded, `-${shortOption}`); } else { // String option in middle. Yuck. // Expand -abfFILE to -a -b -fFILE ArrayPrototypePush(expanded, `-${StringPrototypeSlice(arg, index)}`); break; // finished short group } } ArrayPrototypeUnshiftApply(remainingArgs, expanded); groupCount = expanded.length; continue; } if (isShortOptionAndValue(arg, options)) { // e.g. -fFILE const shortOption = StringPrototypeCharAt(arg, 1); const longOption = findLongOptionForShort(shortOption, options); const value = StringPrototypeSlice(arg, 2); ArrayPrototypePush( tokens, { kind: 'option', name: longOption, rawName: `-${shortOption}`, index, value, inlineValue: true }); continue; } if (isLoneLongOption(arg)) { // e.g. '--foo' const longOption = StringPrototypeSlice(arg, 2); let value; let inlineValue; if (optionsGetOwn(options, longOption, 'type') === 'string' && isOptionValue(nextArg)) { // e.g. '--foo', 'bar' value = ArrayPrototypeShift(remainingArgs); inlineValue = false; } ArrayPrototypePush( tokens, { kind: 'option', name: longOption, rawName: arg, index, value, inlineValue }); if (value != null) ++index; continue; } if (isLongOptionAndValue(arg)) { // e.g. --foo=bar const equalIndex = StringPrototypeIndexOf(arg, '='); const longOption = StringPrototypeSlice(arg, 2, equalIndex); const value = StringPrototypeSlice(arg, equalIndex + 1); ArrayPrototypePush( tokens, { kind: 'option', name: longOption, rawName: `--${longOption}`, index, value, inlineValue: true }); continue; } ArrayPrototypePush(tokens, { kind: 'positional', index, value: arg }); } return tokens; } const parseArgs = (config = kEmptyObject) => { const args = objectGetOwn(config, 'args') ?? getMainArgs(); const strict = objectGetOwn(config, 'strict') ?? true; const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict; const returnTokens = objectGetOwn(config, 'tokens') ?? false; const options = objectGetOwn(config, 'options') ?? { __proto__: null }; // Bundle these up for passing to strict-mode checks. const parseConfig = { args, strict, options, allowPositionals }; // Validate input configuration. validateArray(args, 'args'); validateBoolean(strict, 'strict'); validateBoolean(allowPositionals, 'allowPositionals'); validateBoolean(returnTokens, 'tokens'); validateObject(options, 'options'); ArrayPrototypeForEach( ObjectEntries(options), ({ 0: longOption, 1: optionConfig }) => { validateObject(optionConfig, `options.${longOption}`); // type is required const optionType = objectGetOwn(optionConfig, 'type'); validateUnion(optionType, `options.${longOption}.type`, ['string', 'boolean']); if (ObjectHasOwn(optionConfig, 'short')) { const shortOption = optionConfig.short; validateString(shortOption, `options.${longOption}.short`); if (shortOption.length !== 1) { throw new ERR_INVALID_ARG_VALUE( `options.${longOption}.short`, shortOption, 'must be a single character' ); } } const multipleOption = objectGetOwn(optionConfig, 'multiple'); if (ObjectHasOwn(optionConfig, 'multiple')) { validateBoolean(multipleOption, `options.${longOption}.multiple`); } const defaultValue = objectGetOwn(optionConfig, 'default'); if (defaultValue !== undefined) { let validator; switch (optionType) { case 'string': validator = multipleOption ? validateStringArray : validateString; break; case 'boolean': validator = multipleOption ? validateBooleanArray : validateBoolean; break; } validator(defaultValue, `options.${longOption}.default`); } } ); // Phase 1: identify tokens const tokens = argsToTokens(args, options); // Phase 2: process tokens into parsed option values and positionals const result = { values: { __proto__: null }, positionals: [], }; if (returnTokens) { result.tokens = tokens; } ArrayPrototypeForEach(tokens, (token) => { if (token.kind === 'option') { if (strict) { checkOptionUsage(parseConfig, token); checkOptionLikeValue(token); } storeOption(token.name, token.value, options, result.values); } else if (token.kind === 'positional') { if (!allowPositionals) { throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(token.value); } ArrayPrototypePush(result.positionals, token.value); } }); // Phase 3: fill in default values for missing args ArrayPrototypeForEach(ObjectEntries(options), ({ 0: longOption, 1: optionConfig }) => { const mustSetDefault = useDefaultValueOption(longOption, optionConfig, result.values); if (mustSetDefault) { storeDefaultOption(longOption, objectGetOwn(optionConfig, 'default'), result.values); } }); return result; }; module.exports = { parseArgs, }; 'use strict'; class ERR_INVALID_ARG_TYPE extends TypeError { constructor(name, expected, actual) { super(`${name} must be ${expected} got ${actual}`); this.code = 'ERR_INVALID_ARG_TYPE'; } } class ERR_INVALID_ARG_VALUE extends TypeError { constructor(arg1, arg2, expected) { super(`The property ${arg1} ${expected}. Received '${arg2}'`); this.code = 'ERR_INVALID_ARG_VALUE'; } } class ERR_PARSE_ARGS_INVALID_OPTION_VALUE extends Error { constructor(message) { super(message); this.code = 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'; } } class ERR_PARSE_ARGS_UNKNOWN_OPTION extends Error { constructor(option, allowPositionals) { const suggestDashDash = allowPositionals ? `. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- ${JSON.stringify(option)}` : ''; super(`Unknown option '${option}'${suggestDashDash}`); this.code = 'ERR_PARSE_ARGS_UNKNOWN_OPTION'; } } class ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL extends Error { constructor(positional) { super(`Unexpected argument '${positional}'. This command does not take positional arguments`); this.code = 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'; } } module.exports = { codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_PARSE_ARGS_INVALID_OPTION_VALUE, ERR_PARSE_ARGS_UNKNOWN_OPTION, ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL, } }; /* This file is copied from https://github.com/nodejs/node/blob/v14.19.3/lib/internal/per_context/primordials.js under the following license: Copyright Node.js contributors. All rights reserved. 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. */ 'use strict'; /* eslint-disable node-core/prefer-primordials */ // This file subclasses and stores the JS builtins that come from the VM // so that Node.js's builtin modules do not need to later look these up from // the global proxy, which can be mutated by users. // Use of primordials have sometimes a dramatic impact on performance, please // benchmark all changes made in performance-sensitive areas of the codebase. // See: https://github.com/nodejs/node/pull/38248 const primordials = {}; const { defineProperty: ReflectDefineProperty, getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor, ownKeys: ReflectOwnKeys, } = Reflect; // `uncurryThis` is equivalent to `func => Function.prototype.call.bind(func)`. // It is using `bind.bind(call)` to avoid using `Function.prototype.bind` // and `Function.prototype.call` after it may have been mutated by users. const { apply, bind, call } = Function.prototype; const uncurryThis = bind.bind(call); primordials.uncurryThis = uncurryThis; // `applyBind` is equivalent to `func => Function.prototype.apply.bind(func)`. // It is using `bind.bind(apply)` to avoid using `Function.prototype.bind` // and `Function.prototype.apply` after it may have been mutated by users. const applyBind = bind.bind(apply); primordials.applyBind = applyBind; // Methods that accept a variable number of arguments, and thus it's useful to // also create `${prefix}${key}Apply`, which uses `Function.prototype.apply`, // instead of `Function.prototype.call`, and thus doesn't require iterator // destructuring. const varargsMethods = [ // 'ArrayPrototypeConcat' is omitted, because it performs the spread // on its own for arrays and array-likes with a truthy // @@isConcatSpreadable symbol property. 'ArrayOf', 'ArrayPrototypePush', 'ArrayPrototypeUnshift', // 'FunctionPrototypeCall' is omitted, since there's 'ReflectApply' // and 'FunctionPrototypeApply'. 'MathHypot', 'MathMax', 'MathMin', 'StringPrototypeConcat', 'TypedArrayOf', ]; function getNewKey(key) { return typeof key === 'symbol' ? `Symbol${key.description[7].toUpperCase()}${key.description.slice(8)}` : `${key[0].toUpperCase()}${key.slice(1)}`; } function copyAccessor(dest, prefix, key, { enumerable, get, set }) { ReflectDefineProperty(dest, `${prefix}Get${key}`, { value: uncurryThis(get), enumerable }); if (set !== undefined) { ReflectDefineProperty(dest, `${prefix}Set${key}`, { value: uncurryThis(set), enumerable }); } } function copyPropsRenamed(src, dest, prefix) { for (const key of ReflectOwnKeys(src)) { const newKey = getNewKey(key); const desc = ReflectGetOwnPropertyDescriptor(src, key); if ('get' in desc) { copyAccessor(dest, prefix, newKey, desc); } else { const name = `${prefix}${newKey}`; ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { // `src` is bound as the `this` so that the static `this` points // to the object it was defined on, // e.g.: `ArrayOfApply` gets a `this` of `Array`: value: applyBind(desc.value, src), }); } } } } function copyPropsRenamedBound(src, dest, prefix) { for (const key of ReflectOwnKeys(src)) { const newKey = getNewKey(key); const desc = ReflectGetOwnPropertyDescriptor(src, key); if ('get' in desc) { copyAccessor(dest, prefix, newKey, desc); } else { const { value } = desc; if (typeof value === 'function') { desc.value = value.bind(src); } const name = `${prefix}${newKey}`; ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { value: applyBind(value, src), }); } } } } function copyPrototype(src, dest, prefix) { for (const key of ReflectOwnKeys(src)) { const newKey = getNewKey(key); const desc = ReflectGetOwnPropertyDescriptor(src, key); if ('get' in desc) { copyAccessor(dest, prefix, newKey, desc); } else { const { value } = desc; if (typeof value === 'function') { desc.value = uncurryThis(value); } const name = `${prefix}${newKey}`; ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { value: applyBind(value), }); } } } } // Create copies of configurable value properties of the global object [ 'Proxy', 'globalThis', ].forEach((name) => { // eslint-disable-next-line no-restricted-globals primordials[name] = globalThis[name]; }); // Create copies of URI handling functions [ decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, ].forEach((fn) => { primordials[fn.name] = fn; }); // Create copies of the namespace objects [ 'JSON', 'Math', 'Proxy', 'Reflect', ].forEach((name) => { // eslint-disable-next-line no-restricted-globals copyPropsRenamed(global[name], primordials, name); }); // Create copies of intrinsic objects [ 'Array', 'ArrayBuffer', 'BigInt', 'BigInt64Array', 'BigUint64Array', 'Boolean', 'DataView', 'Date', 'Error', 'EvalError', 'Float32Array', 'Float64Array', 'Function', 'Int16Array', 'Int32Array', 'Int8Array', 'Map', 'Number', 'Object', 'RangeError', 'ReferenceError', 'RegExp', 'Set', 'String', 'Symbol', 'SyntaxError', 'TypeError', 'URIError', 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray', 'WeakMap', 'WeakSet', ].forEach((name) => { // eslint-disable-next-line no-restricted-globals const original = global[name]; primordials[name] = original; copyPropsRenamed(original, primordials, name); copyPrototype(original.prototype, primordials, `${name}Prototype`); }); // Create copies of intrinsic objects that require a valid `this` to call // static methods. // Refs: https://www.ecma-international.org/ecma-262/#sec-promise.all [ 'Promise', ].forEach((name) => { // eslint-disable-next-line no-restricted-globals const original = global[name]; primordials[name] = original; copyPropsRenamedBound(original, primordials, name); copyPrototype(original.prototype, primordials, `${name}Prototype`); }); // Create copies of abstract intrinsic objects that are not directly exposed // on the global object. // Refs: https://tc39.es/ecma262/#sec-%typedarray%-intrinsic-object [ { name: 'TypedArray', original: Reflect.getPrototypeOf(Uint8Array) }, { name: 'ArrayIterator', original: { prototype: Reflect.getPrototypeOf(Array.prototype[Symbol.iterator]()), } }, { name: 'StringIterator', original: { prototype: Reflect.getPrototypeOf(String.prototype[Symbol.iterator]()), } }, ].forEach(({ name, original }) => { primordials[name] = original; // The static %TypedArray% methods require a valid `this`, but can't be bound, // as they need a subclass constructor as the receiver: copyPrototype(original, primordials, name); copyPrototype(original.prototype, primordials, `${name}Prototype`); }); /* eslint-enable node-core/prefer-primordials */ const { ArrayPrototypeForEach, FunctionPrototypeCall, Map, ObjectFreeze, ObjectSetPrototypeOf, Set, SymbolIterator, WeakMap, WeakSet, } = primordials; // Because these functions are used by `makeSafe`, which is exposed // on the `primordials` object, it's important to use const references // to the primordials that they use: const createSafeIterator = (factory, next) => { class SafeIterator { constructor(iterable) { this._iterator = factory(iterable); } next() { return next(this._iterator); } [SymbolIterator]() { return this; } } ObjectSetPrototypeOf(SafeIterator.prototype, null); ObjectFreeze(SafeIterator.prototype); ObjectFreeze(SafeIterator); return SafeIterator; }; primordials.SafeArrayIterator = createSafeIterator( primordials.ArrayPrototypeSymbolIterator, primordials.ArrayIteratorPrototypeNext ); primordials.SafeStringIterator = createSafeIterator( primordials.StringPrototypeSymbolIterator, primordials.StringIteratorPrototypeNext ); const copyProps = (src, dest) => { ArrayPrototypeForEach(ReflectOwnKeys(src), (key) => { if (!ReflectGetOwnPropertyDescriptor(dest, key)) { ReflectDefineProperty( dest, key, ReflectGetOwnPropertyDescriptor(src, key)); } }); }; const makeSafe = (unsafe, safe) => { if (SymbolIterator in unsafe.prototype) { const dummy = new unsafe(); let next; // We can reuse the same `next` method. ArrayPrototypeForEach(ReflectOwnKeys(unsafe.prototype), (key) => { if (!ReflectGetOwnPropertyDescriptor(safe.prototype, key)) { const desc = ReflectGetOwnPropertyDescriptor(unsafe.prototype, key); if ( typeof desc.value === 'function' && desc.value.length === 0 && SymbolIterator in (FunctionPrototypeCall(desc.value, dummy) ?? {}) ) { const createIterator = uncurryThis(desc.value); next = next ?? uncurryThis(createIterator(dummy).next); const SafeIterator = createSafeIterator(createIterator, next); desc.value = function() { return new SafeIterator(this); }; } ReflectDefineProperty(safe.prototype, key, desc); } }); } else { copyProps(unsafe.prototype, safe.prototype); } copyProps(unsafe, safe); ObjectSetPrototypeOf(safe.prototype, null); ObjectFreeze(safe.prototype); ObjectFreeze(safe); return safe; }; primordials.makeSafe = makeSafe; // Subclass the constructors because we need to use their prototype // methods later. // Defining the `constructor` is necessary here to avoid the default // constructor which uses the user-mutable `%ArrayIteratorPrototype%.next`. primordials.SafeMap = makeSafe( Map, class SafeMap extends Map { constructor(i) { super(i); } // eslint-disable-line no-useless-constructor } ); primordials.SafeWeakMap = makeSafe( WeakMap, class SafeWeakMap extends WeakMap { constructor(i) { super(i); } // eslint-disable-line no-useless-constructor } ); primordials.SafeSet = makeSafe( Set, class SafeSet extends Set { constructor(i) { super(i); } // eslint-disable-line no-useless-constructor } ); primordials.SafeWeakSet = makeSafe( WeakSet, class SafeWeakSet extends WeakSet { constructor(i) { super(i); } // eslint-disable-line no-useless-constructor } ); ObjectSetPrototypeOf(primordials, null); ObjectFreeze(primordials); module.exports = primordials; 'use strict'; // This is a placeholder for util.js in node.js land. const { ObjectCreate, ObjectFreeze, } = require('./primordials'); const kEmptyObject = ObjectFreeze(ObjectCreate(null)); module.exports = { kEmptyObject, }; 'use strict'; // This file is a proxy of the original file located at: // https://github.com/nodejs/node/blob/main/lib/internal/validators.js // Every addition or modification to this file must be evaluated // during the PR review. const { ArrayIsArray, ArrayPrototypeIncludes, ArrayPrototypeJoin, } = require('./primordials'); const { codes: { ERR_INVALID_ARG_TYPE } } = require('./errors'); function validateString(value, name) { if (typeof value !== 'string') { throw new ERR_INVALID_ARG_TYPE(name, 'String', value); } } function validateUnion(value, name, union) { if (!ArrayPrototypeIncludes(union, value)) { throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value); } } function validateBoolean(value, name) { if (typeof value !== 'boolean') { throw new ERR_INVALID_ARG_TYPE(name, 'Boolean', value); } } function validateArray(value, name) { if (!ArrayIsArray(value)) { throw new ERR_INVALID_ARG_TYPE(name, 'Array', value); } } function validateStringArray(value, name) { validateArray(value, name); for (let i = 0; i < value.length; i++) { validateString(value[i], `${name}[${i}]`); } } function validateBooleanArray(value, name) { validateArray(value, name); for (let i = 0; i < value.length; i++) { validateBoolean(value[i], `${name}[${i}]`); } } /** * @param {unknown} value * @param {string} name * @param {{ * allowArray?: boolean, * allowFunction?: boolean, * nullable?: boolean * }} [options] */ function validateObject(value, name, options) { const useDefaultOptions = options == null; const allowArray = useDefaultOptions ? false : options.allowArray; const allowFunction = useDefaultOptions ? false : options.allowFunction; const nullable = useDefaultOptions ? false : options.nullable; if ((!nullable && value === null) || (!allowArray && ArrayIsArray(value)) || (typeof value !== 'object' && ( !allowFunction || typeof value !== 'function' ))) { throw new ERR_INVALID_ARG_TYPE(name, 'Object', value); } } module.exports = { validateArray, validateObject, validateString, validateStringArray, validateUnion, validateBoolean, validateBooleanArray, }; { "name": "@pkgjs/parseargs", "version": "0.11.0", "description": "Polyfill of future proposal for `util.parseArgs()`", "engines": { "node": ">=14" }, "main": "index.js", "exports": { ".": "./index.js", "./package.json": "./package.json" }, "scripts": { "coverage": "c8 --check-coverage tape 'test/*.js'", "test": "c8 tape 'test/*.js'", "posttest": "eslint .", "fix": "npm run posttest -- --fix" }, "repository": { "type": "git", "url": "git@github.com:pkgjs/parseargs.git" }, "keywords": [], "author": "", "license": "MIT", "bugs": { "url": "https://github.com/pkgjs/parseargs/issues" }, "homepage": "https://github.com/pkgjs/parseargs#readme", "devDependencies": { "c8": "^7.10.0", "eslint": "^8.2.0", "eslint-plugin-node-core": "iansu/eslint-plugin-node-core", "tape": "^5.2.2" } } 'use strict'; const { ArrayPrototypeFind, ObjectEntries, ObjectPrototypeHasOwnProperty: ObjectHasOwn, StringPrototypeCharAt, StringPrototypeIncludes, StringPrototypeStartsWith, } = require('./internal/primordials'); const { validateObject, } = require('./internal/validators'); // These are internal utilities to make the parsing logic easier to read, and // add lots of detail for the curious. They are in a separate file to allow // unit testing, although that is not essential (this could be rolled into // main file and just tested implicitly via API). // // These routines are for internal use, not for export to client. /** * Return the named property, but only if it is an own property. */ function objectGetOwn(obj, prop) { if (ObjectHasOwn(obj, prop)) return obj[prop]; } /** * Return the named options property, but only if it is an own property. */ function optionsGetOwn(options, longOption, prop) { if (ObjectHasOwn(options, longOption)) return objectGetOwn(options[longOption], prop); } /** * Determines if the argument may be used as an option value. * @example * isOptionValue('V') // returns true * isOptionValue('-v') // returns true (greedy) * isOptionValue('--foo') // returns true (greedy) * isOptionValue(undefined) // returns false */ function isOptionValue(value) { if (value == null) return false; // Open Group Utility Conventions are that an option-argument // is the argument after the option, and may start with a dash. return true; // greedy! } /** * Detect whether there is possible confusion and user may have omitted * the option argument, like `--port --verbose` when `port` of type:string. * In strict mode we throw errors if value is option-like. */ function isOptionLikeValue(value) { if (value == null) return false; return value.length > 1 && StringPrototypeCharAt(value, 0) === '-'; } /** * Determines if `arg` is just a short option. * @example '-f' */ function isLoneShortOption(arg) { return arg.length === 2 && StringPrototypeCharAt(arg, 0) === '-' && StringPrototypeCharAt(arg, 1) !== '-'; } /** * Determines if `arg` is a lone long option. * @example * isLoneLongOption('a') // returns false * isLoneLongOption('-a') // returns false * isLoneLongOption('--foo') // returns true * isLoneLongOption('--foo=bar') // returns false */ function isLoneLongOption(arg) { return arg.length > 2 && StringPrototypeStartsWith(arg, '--') && !StringPrototypeIncludes(arg, '=', 3); } /** * Determines if `arg` is a long option and value in the same argument. * @example * isLongOptionAndValue('--foo') // returns false * isLongOptionAndValue('--foo=bar') // returns true */ function isLongOptionAndValue(arg) { return arg.length > 2 && StringPrototypeStartsWith(arg, '--') && StringPrototypeIncludes(arg, '=', 3); } /** * Determines if `arg` is a short option group. * * See Guideline 5 of the [Open Group Utility Conventions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html). * One or more options without option-arguments, followed by at most one * option that takes an option-argument, should be accepted when grouped * behind one '-' delimiter. * @example * isShortOptionGroup('-a', {}) // returns false * isShortOptionGroup('-ab', {}) // returns true * // -fb is an option and a value, not a short option group * isShortOptionGroup('-fb', { * options: { f: { type: 'string' } } * }) // returns false * isShortOptionGroup('-bf', { * options: { f: { type: 'string' } } * }) // returns true * // -bfb is an edge case, return true and caller sorts it out * isShortOptionGroup('-bfb', { * options: { f: { type: 'string' } } * }) // returns true */ function isShortOptionGroup(arg, options) { if (arg.length <= 2) return false; if (StringPrototypeCharAt(arg, 0) !== '-') return false; if (StringPrototypeCharAt(arg, 1) === '-') return false; const firstShort = StringPrototypeCharAt(arg, 1); const longOption = findLongOptionForShort(firstShort, options); return optionsGetOwn(options, longOption, 'type') !== 'string'; } /** * Determine if arg is a short string option followed by its value. * @example * isShortOptionAndValue('-a', {}); // returns false * isShortOptionAndValue('-ab', {}); // returns false * isShortOptionAndValue('-fFILE', { * options: { foo: { short: 'f', type: 'string' }} * }) // returns true */ function isShortOptionAndValue(arg, options) { validateObject(options, 'options'); if (arg.length <= 2) return false; if (StringPrototypeCharAt(arg, 0) !== '-') return false; if (StringPrototypeCharAt(arg, 1) === '-') return false; const shortOption = StringPrototypeCharAt(arg, 1); const longOption = findLongOptionForShort(shortOption, options); return optionsGetOwn(options, longOption, 'type') === 'string'; } /** * Find the long option associated with a short option. Looks for a configured * `short` and returns the short option itself if a long option is not found. * @example * findLongOptionForShort('a', {}) // returns 'a' * findLongOptionForShort('b', { * options: { bar: { short: 'b' } } * }) // returns 'bar' */ function findLongOptionForShort(shortOption, options) { validateObject(options, 'options'); const longOptionEntry = ArrayPrototypeFind( ObjectEntries(options), ({ 1: optionConfig }) => objectGetOwn(optionConfig, 'short') === shortOption ); return longOptionEntry?.[0] ?? shortOption; } /** * Check if the given option includes a default value * and that option has not been set by the input args. * * @param {string} longOption - long option name e.g. 'foo' * @param {object} optionConfig - the option configuration properties * @param {object} values - option values returned in `values` by parseArgs */ function useDefaultValueOption(longOption, optionConfig, values) { return objectGetOwn(optionConfig, 'default') !== undefined && values[longOption] === undefined; } module.exports = { findLongOptionForShort, isLoneLongOption, isLoneShortOption, isLongOptionAndValue, isOptionValue, isOptionLikeValue, isShortOptionAndValue, isShortOptionGroup, useDefaultValueOption, objectGetOwn, optionsGetOwn, }; Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 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 (50%) 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 The Sigstore Authors Licensed under the Apache License, Version 2.0 (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-2.0 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. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toMessageSignatureBundle = toMessageSignatureBundle; exports.toDSSEBundle = toDSSEBundle; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const protobuf_specs_1 = require("@sigstore/protobuf-specs"); const bundle_1 = require("./bundle"); // Message signature bundle - $case: 'messageSignature' function toMessageSignatureBundle(options) { return { mediaType: options.certificateChain ? bundle_1.BUNDLE_V02_MEDIA_TYPE : bundle_1.BUNDLE_V03_MEDIA_TYPE, content: { $case: 'messageSignature', messageSignature: { messageDigest: { algorithm: protobuf_specs_1.HashAlgorithm.SHA2_256, digest: options.digest, }, signature: options.signature, }, }, verificationMaterial: toVerificationMaterial(options), }; } // DSSE envelope bundle - $case: 'dsseEnvelope' function toDSSEBundle(options) { return { mediaType: options.certificateChain ? bundle_1.BUNDLE_V02_MEDIA_TYPE : bundle_1.BUNDLE_V03_MEDIA_TYPE, content: { $case: 'dsseEnvelope', dsseEnvelope: toEnvelope(options), }, verificationMaterial: toVerificationMaterial(options), }; } function toEnvelope(options) { return { payloadType: options.artifactType, payload: options.artifact, signatures: [toSignature(options)], }; } function toSignature(options) { return { keyid: options.keyHint || '', sig: options.signature, }; } // Verification material function toVerificationMaterial(options) { return { content: toKeyContent(options), tlogEntries: [], timestampVerificationData: { rfc3161Timestamps: [] }, }; } function toKeyContent(options) { if (options.certificate) { if (options.certificateChain) { return { $case: 'x509CertificateChain', x509CertificateChain: { certificates: [{ rawBytes: options.certificate }], }, }; } else { return { $case: 'certificate', certificate: { rawBytes: options.certificate }, }; } } else { return { $case: 'publicKey', publicKey: { hint: options.keyHint || '', }, }; } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = void 0; exports.isBundleWithCertificateChain = isBundleWithCertificateChain; exports.isBundleWithPublicKey = isBundleWithPublicKey; exports.isBundleWithMessageSignature = isBundleWithMessageSignature; exports.isBundleWithDsseEnvelope = isBundleWithDsseEnvelope; exports.BUNDLE_V01_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1'; exports.BUNDLE_V02_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.2'; exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.3'; exports.BUNDLE_V03_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle.v0.3+json'; // Type guards for bundle variants. function isBundleWithCertificateChain(b) { return b.verificationMaterial.content.$case === 'x509CertificateChain'; } function isBundleWithPublicKey(b) { return b.verificationMaterial.content.$case === 'publicKey'; } function isBundleWithMessageSignature(b) { return b.content.$case === 'messageSignature'; } function isBundleWithDsseEnvelope(b) { return b.content.$case === 'dsseEnvelope'; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValidationError = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ class ValidationError extends Error { constructor(message, fields) { super(message); this.fields = fields; } } exports.ValidationError = ValidationError; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isBundleV01 = exports.assertBundleV02 = exports.assertBundleV01 = exports.assertBundleLatest = exports.assertBundle = exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = exports.ValidationError = exports.isBundleWithPublicKey = exports.isBundleWithMessageSignature = exports.isBundleWithDsseEnvelope = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = exports.toMessageSignatureBundle = exports.toDSSEBundle = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ var build_1 = require("./build"); Object.defineProperty(exports, "toDSSEBundle", { enumerable: true, get: function () { return build_1.toDSSEBundle; } }); Object.defineProperty(exports, "toMessageSignatureBundle", { enumerable: true, get: function () { return build_1.toMessageSignatureBundle; } }); var bundle_1 = require("./bundle"); Object.defineProperty(exports, "BUNDLE_V01_MEDIA_TYPE", { enumerable: true, get: function () { return bundle_1.BUNDLE_V01_MEDIA_TYPE; } }); Object.defineProperty(exports, "BUNDLE_V02_MEDIA_TYPE", { enumerable: true, get: function () { return bundle_1.BUNDLE_V02_MEDIA_TYPE; } }); Object.defineProperty(exports, "BUNDLE_V03_LEGACY_MEDIA_TYPE", { enumerable: true, get: function () { return bundle_1.BUNDLE_V03_LEGACY_MEDIA_TYPE; } }); Object.defineProperty(exports, "BUNDLE_V03_MEDIA_TYPE", { enumerable: true, get: function () { return bundle_1.BUNDLE_V03_MEDIA_TYPE; } }); Object.defineProperty(exports, "isBundleWithCertificateChain", { enumerable: true, get: function () { return bundle_1.isBundleWithCertificateChain; } }); Object.defineProperty(exports, "isBundleWithDsseEnvelope", { enumerable: true, get: function () { return bundle_1.isBundleWithDsseEnvelope; } }); Object.defineProperty(exports, "isBundleWithMessageSignature", { enumerable: true, get: function () { return bundle_1.isBundleWithMessageSignature; } }); Object.defineProperty(exports, "isBundleWithPublicKey", { enumerable: true, get: function () { return bundle_1.isBundleWithPublicKey; } }); var error_1 = require("./error"); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return error_1.ValidationError; } }); var serialized_1 = require("./serialized"); Object.defineProperty(exports, "bundleFromJSON", { enumerable: true, get: function () { return serialized_1.bundleFromJSON; } }); Object.defineProperty(exports, "bundleToJSON", { enumerable: true, get: function () { return serialized_1.bundleToJSON; } }); Object.defineProperty(exports, "envelopeFromJSON", { enumerable: true, get: function () { return serialized_1.envelopeFromJSON; } }); Object.defineProperty(exports, "envelopeToJSON", { enumerable: true, get: function () { return serialized_1.envelopeToJSON; } }); var validate_1 = require("./validate"); Object.defineProperty(exports, "assertBundle", { enumerable: true, get: function () { return validate_1.assertBundle; } }); Object.defineProperty(exports, "assertBundleLatest", { enumerable: true, get: function () { return validate_1.assertBundleLatest; } }); Object.defineProperty(exports, "assertBundleV01", { enumerable: true, get: function () { return validate_1.assertBundleV01; } }); Object.defineProperty(exports, "assertBundleV02", { enumerable: true, get: function () { return validate_1.assertBundleV02; } }); Object.defineProperty(exports, "isBundleV01", { enumerable: true, get: function () { return validate_1.isBundleV01; } }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const protobuf_specs_1 = require("@sigstore/protobuf-specs"); const bundle_1 = require("./bundle"); const validate_1 = require("./validate"); const bundleFromJSON = (obj) => { const bundle = protobuf_specs_1.Bundle.fromJSON(obj); switch (bundle.mediaType) { case bundle_1.BUNDLE_V01_MEDIA_TYPE: (0, validate_1.assertBundleV01)(bundle); break; case bundle_1.BUNDLE_V02_MEDIA_TYPE: (0, validate_1.assertBundleV02)(bundle); break; default: (0, validate_1.assertBundleLatest)(bundle); break; } return bundle; }; exports.bundleFromJSON = bundleFromJSON; const bundleToJSON = (bundle) => { return protobuf_specs_1.Bundle.toJSON(bundle); }; exports.bundleToJSON = bundleToJSON; const envelopeFromJSON = (obj) => { return protobuf_specs_1.Envelope.fromJSON(obj); }; exports.envelopeFromJSON = envelopeFromJSON; const envelopeToJSON = (envelope) => { return protobuf_specs_1.Envelope.toJSON(envelope); }; exports.envelopeToJSON = envelopeToJSON; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assertBundle = assertBundle; exports.assertBundleV01 = assertBundleV01; exports.isBundleV01 = isBundleV01; exports.assertBundleV02 = assertBundleV02; exports.assertBundleLatest = assertBundleLatest; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("./error"); // Performs basic validation of a Sigstore bundle to ensure that all required // fields are populated. This is not a complete validation of the bundle, but // rather a check that the bundle is in a valid state to be processed by the // rest of the code. function assertBundle(b) { const invalidValues = validateBundleBase(b); if (invalidValues.length > 0) { throw new error_1.ValidationError('invalid bundle', invalidValues); } } // Asserts that the given bundle conforms to the v0.1 bundle format. function assertBundleV01(b) { const invalidValues = []; invalidValues.push(...validateBundleBase(b)); invalidValues.push(...validateInclusionPromise(b)); if (invalidValues.length > 0) { throw new error_1.ValidationError('invalid v0.1 bundle', invalidValues); } } // Type guard to determine if Bundle is a v0.1 bundle. function isBundleV01(b) { try { assertBundleV01(b); return true; } catch (e) { return false; } } // Asserts that the given bundle conforms to the v0.2 bundle format. function assertBundleV02(b) { const invalidValues = []; invalidValues.push(...validateBundleBase(b)); invalidValues.push(...validateInclusionProof(b)); if (invalidValues.length > 0) { throw new error_1.ValidationError('invalid v0.2 bundle', invalidValues); } } // Asserts that the given bundle conforms to the newest (0.3) bundle format. function assertBundleLatest(b) { const invalidValues = []; invalidValues.push(...validateBundleBase(b)); invalidValues.push(...validateInclusionProof(b)); invalidValues.push(...validateNoCertificateChain(b)); if (invalidValues.length > 0) { throw new error_1.ValidationError('invalid bundle', invalidValues); } } function validateBundleBase(b) { const invalidValues = []; // Media type validation if (b.mediaType === undefined || (!b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\+json;version=\d\.\d/) && !b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\.v\d\.\d\+json/))) { invalidValues.push('mediaType'); } // Content-related validation if (b.content === undefined) { invalidValues.push('content'); } else { switch (b.content.$case) { case 'messageSignature': if (b.content.messageSignature.messageDigest === undefined) { invalidValues.push('content.messageSignature.messageDigest'); } else { if (b.content.messageSignature.messageDigest.digest.length === 0) { invalidValues.push('content.messageSignature.messageDigest.digest'); } } if (b.content.messageSignature.signature.length === 0) { invalidValues.push('content.messageSignature.signature'); } break; case 'dsseEnvelope': if (b.content.dsseEnvelope.payload.length === 0) { invalidValues.push('content.dsseEnvelope.payload'); } if (b.content.dsseEnvelope.signatures.length !== 1) { invalidValues.push('content.dsseEnvelope.signatures'); } else { if (b.content.dsseEnvelope.signatures[0].sig.length === 0) { invalidValues.push('content.dsseEnvelope.signatures[0].sig'); } } break; } } // Verification material-related validation if (b.verificationMaterial === undefined) { invalidValues.push('verificationMaterial'); } else { if (b.verificationMaterial.content === undefined) { invalidValues.push('verificationMaterial.content'); } else { switch (b.verificationMaterial.content.$case) { case 'x509CertificateChain': if (b.verificationMaterial.content.x509CertificateChain.certificates .length === 0) { invalidValues.push('verificationMaterial.content.x509CertificateChain.certificates'); } b.verificationMaterial.content.x509CertificateChain.certificates.forEach((cert, i) => { if (cert.rawBytes.length === 0) { invalidValues.push(`verificationMaterial.content.x509CertificateChain.certificates[${i}].rawBytes`); } }); break; case 'certificate': if (b.verificationMaterial.content.certificate.rawBytes.length === 0) { invalidValues.push('verificationMaterial.content.certificate.rawBytes'); } break; } } if (b.verificationMaterial.tlogEntries === undefined) { invalidValues.push('verificationMaterial.tlogEntries'); } else { if (b.verificationMaterial.tlogEntries.length > 0) { b.verificationMaterial.tlogEntries.forEach((entry, i) => { if (entry.logId === undefined) { invalidValues.push(`verificationMaterial.tlogEntries[${i}].logId`); } if (entry.kindVersion === undefined) { invalidValues.push(`verificationMaterial.tlogEntries[${i}].kindVersion`); } }); } } } return invalidValues; } // Necessary for V01 bundles function validateInclusionPromise(b) { const invalidValues = []; if (b.verificationMaterial && b.verificationMaterial.tlogEntries?.length > 0) { b.verificationMaterial.tlogEntries.forEach((entry, i) => { if (entry.inclusionPromise === undefined) { invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionPromise`); } }); } return invalidValues; } // Necessary for V02 and later bundles function validateInclusionProof(b) { const invalidValues = []; if (b.verificationMaterial && b.verificationMaterial.tlogEntries?.length > 0) { b.verificationMaterial.tlogEntries.forEach((entry, i) => { if (entry.inclusionProof === undefined) { invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof`); } else { if (entry.inclusionProof.checkpoint === undefined) { invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof.checkpoint`); } } }); } return invalidValues; } // Necessary for V03 and later bundles function validateNoCertificateChain(b) { const invalidValues = []; /* istanbul ignore next */ if (b.verificationMaterial?.content?.$case === 'x509CertificateChain') { invalidValues.push('verificationMaterial.content.$case'); } return invalidValues; } { "name": "@sigstore/bundle", "version": "3.0.0", "description": "Sigstore bundle type", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "clean": "shx rm -rf dist *.tsbuildinfo", "build": "tsc --build", "test": "jest" }, "files": [ "dist", "store" ], "author": "bdehamer@github.com", "license": "Apache-2.0", "repository": { "type": "git", "url": "git+https://github.com/sigstore/sigstore-js.git" }, "bugs": { "url": "https://github.com/sigstore/sigstore-js/issues" }, "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/bundle#readme", "publishConfig": { "provenance": true }, "dependencies": { "@sigstore/protobuf-specs": "^0.3.2" }, "engines": { "node": "^18.17.0 || >=20.5.0" } } Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 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 (50%) 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 The Sigstore Authors Licensed under the Apache License, Version 2.0 (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-2.0 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. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ASN1TypeError = exports.ASN1ParseError = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ class ASN1ParseError extends Error { } exports.ASN1ParseError = ASN1ParseError; class ASN1TypeError extends Error { } exports.ASN1TypeError = ASN1TypeError; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ASN1Obj = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ var obj_1 = require("./obj"); Object.defineProperty(exports, "ASN1Obj", { enumerable: true, get: function () { return obj_1.ASN1Obj; } }); "use strict"; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.decodeLength = decodeLength; exports.encodeLength = encodeLength; const error_1 = require("./error"); // Decodes the length of a DER-encoded ANS.1 element from the supplied stream. // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes function decodeLength(stream) { const buf = stream.getUint8(); // If the most significant bit is UNSET the length is just the value of the // byte. if ((buf & 0x80) === 0x00) { return buf; } // Otherwise, the lower 7 bits of the first byte indicate the number of bytes // that follow to encode the length. const byteCount = buf & 0x7f; // Ensure the encoded length can safely fit in a JS number. if (byteCount > 6) { throw new error_1.ASN1ParseError('length exceeds 6 byte limit'); } // Iterate over the bytes that encode the length. let len = 0; for (let i = 0; i < byteCount; i++) { len = len * 256 + stream.getUint8(); } // This is a valid ASN.1 length encoding, but we don't support it. if (len === 0) { throw new error_1.ASN1ParseError('indefinite length encoding not supported'); } return len; } // Translates the supplied value to a DER-encoded length. function encodeLength(len) { if (len < 128) { return Buffer.from([len]); } // Bitwise operations on large numbers are not supported in JS, so we need to // use BigInts. let val = BigInt(len); const bytes = []; while (val > 0n) { bytes.unshift(Number(val & 255n)); val = val >> 8n; } return Buffer.from([0x80 | bytes.length, ...bytes]); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ASN1Obj = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const stream_1 = require("../stream"); const error_1 = require("./error"); const length_1 = require("./length"); const parse_1 = require("./parse"); const tag_1 = require("./tag"); class ASN1Obj { constructor(tag, value, subs) { this.tag = tag; this.value = value; this.subs = subs; } // Constructs an ASN.1 object from a Buffer of DER-encoded bytes. static parseBuffer(buf) { return parseStream(new stream_1.ByteStream(buf)); } toDER() { const valueStream = new stream_1.ByteStream(); if (this.subs.length > 0) { for (const sub of this.subs) { valueStream.appendView(sub.toDER()); } } else { valueStream.appendView(this.value); } const value = valueStream.buffer; // Concat tag/length/value const obj = new stream_1.ByteStream(); obj.appendChar(this.tag.toDER()); obj.appendView((0, length_1.encodeLength)(value.length)); obj.appendView(value); return obj.buffer; } ///////////////////////////////////////////////////////////////////////////// // Convenience methods for parsing ASN.1 primitives into JS types // Returns the ASN.1 object's value as a boolean. Throws an error if the // object is not a boolean. toBoolean() { if (!this.tag.isBoolean()) { throw new error_1.ASN1TypeError('not a boolean'); } return (0, parse_1.parseBoolean)(this.value); } // Returns the ASN.1 object's value as a BigInt. Throws an error if the // object is not an integer. toInteger() { if (!this.tag.isInteger()) { throw new error_1.ASN1TypeError('not an integer'); } return (0, parse_1.parseInteger)(this.value); } // Returns the ASN.1 object's value as an OID string. Throws an error if the // object is not an OID. toOID() { if (!this.tag.isOID()) { throw new error_1.ASN1TypeError('not an OID'); } return (0, parse_1.parseOID)(this.value); } // Returns the ASN.1 object's value as a Date. Throws an error if the object // is not either a UTCTime or a GeneralizedTime. toDate() { switch (true) { case this.tag.isUTCTime(): return (0, parse_1.parseTime)(this.value, true); case this.tag.isGeneralizedTime(): return (0, parse_1.parseTime)(this.value, false); default: throw new error_1.ASN1TypeError('not a date'); } } // Returns the ASN.1 object's value as a number[] where each number is the // value of a bit in the bit string. Throws an error if the object is not a // bit string. toBitString() { if (!this.tag.isBitString()) { throw new error_1.ASN1TypeError('not a bit string'); } return (0, parse_1.parseBitString)(this.value); } } exports.ASN1Obj = ASN1Obj; ///////////////////////////////////////////////////////////////////////////// // Internal stream parsing functions function parseStream(stream) { // Parse tag, length, and value from stream const tag = new tag_1.ASN1Tag(stream.getUint8()); const len = (0, length_1.decodeLength)(stream); const value = stream.slice(stream.position, len); const start = stream.position; let subs = []; // If the object is constructed, parse its children. Sometimes, children // are embedded in OCTESTRING objects, so we need to check those // for children as well. if (tag.constructed) { subs = collectSubs(stream, len); } else if (tag.isOctetString()) { // Attempt to parse children of OCTETSTRING objects. If anything fails, // assume the object is not constructed and treat as primitive. try { subs = collectSubs(stream, len); } catch (e) { // Fail silently and treat as primitive } } // If there are no children, move stream cursor to the end of the object if (subs.length === 0) { stream.seek(start + len); } return new ASN1Obj(tag, value, subs); } function collectSubs(stream, len) { // Calculate end of object content const end = stream.position + len; // Make sure there are enough bytes left in the stream. This should never // happen, cause it'll get caught when the stream is sliced in parseStream. // Leaving as an extra check just in case. /* istanbul ignore if */ if (end > stream.length) { throw new error_1.ASN1ParseError('invalid length'); } // Parse all children const subs = []; while (stream.position < end) { subs.push(parseStream(stream)); } // When we're done parsing children, we should be at the end of the object if (stream.position !== end) { throw new error_1.ASN1ParseError('invalid length'); } return subs; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseInteger = parseInteger; exports.parseStringASCII = parseStringASCII; exports.parseTime = parseTime; exports.parseOID = parseOID; exports.parseBoolean = parseBoolean; exports.parseBitString = parseBitString; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const RE_TIME_SHORT_YEAR = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/; const RE_TIME_LONG_YEAR = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/; // Parse a BigInt from the DER-encoded buffer // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer function parseInteger(buf) { let pos = 0; const end = buf.length; let val = buf[pos]; const neg = val > 0x7f; // Consume any padding bytes const pad = neg ? 0xff : 0x00; while (val == pad && ++pos < end) { val = buf[pos]; } // Calculate remaining bytes to read const len = end - pos; if (len === 0) return BigInt(neg ? -1 : 0); // Handle two's complement for negative numbers val = neg ? val - 256 : val; // Parse remaining bytes let n = BigInt(val); for (let i = pos + 1; i < end; ++i) { n = n * BigInt(256) + BigInt(buf[i]); } return n; } // Parse an ASCII string from the DER-encoded buffer // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean function parseStringASCII(buf) { return buf.toString('ascii'); } // Parse a Date from the DER-encoded buffer // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5.1 function parseTime(buf, shortYear) { const timeStr = parseStringASCII(buf); // Parse the time string into matches - captured groups start at index 1 const m = shortYear ? RE_TIME_SHORT_YEAR.exec(timeStr) : RE_TIME_LONG_YEAR.exec(timeStr); if (!m) { throw new Error('invalid time'); } // Translate dates with a 2-digit year to 4 digits per the spec if (shortYear) { let year = Number(m[1]); year += year >= 50 ? 1900 : 2000; m[1] = year.toString(); } // Translate to ISO8601 format and parse return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`); } // Parse an OID from the DER-encoded buffer // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier function parseOID(buf) { let pos = 0; const end = buf.length; // Consume first byte which encodes the first two OID components let n = buf[pos++]; const first = Math.floor(n / 40); const second = n % 40; let oid = `${first}.${second}`; // Consume remaining bytes let val = 0; for (; pos < end; ++pos) { n = buf[pos]; val = (val << 7) + (n & 0x7f); // If the left-most bit is NOT set, then this is the last byte in the // sequence and we can add the value to the OID and reset the accumulator if ((n & 0x80) === 0) { oid += `.${val}`; val = 0; } } return oid; } // Parse a boolean from the DER-encoded buffer // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean function parseBoolean(buf) { return buf[0] !== 0; } // Parse a bit string from the DER-encoded buffer // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-bit-string function parseBitString(buf) { // First byte tell us how many unused bits are in the last byte const unused = buf[0]; const start = 1; const end = buf.length; const bits = []; for (let i = start; i < end; ++i) { const byte = buf[i]; // The skip value is only used for the last byte const skip = i === end - 1 ? unused : 0; // Iterate over each bit in the byte (most significant first) for (let j = 7; j >= skip; --j) { // Read the bit and add it to the bit string bits.push((byte >> j) & 0x01); } } return bits; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ASN1Tag = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("./error"); const UNIVERSAL_TAG = { BOOLEAN: 0x01, INTEGER: 0x02, BIT_STRING: 0x03, OCTET_STRING: 0x04, OBJECT_IDENTIFIER: 0x06, SEQUENCE: 0x10, SET: 0x11, PRINTABLE_STRING: 0x13, UTC_TIME: 0x17, GENERALIZED_TIME: 0x18, }; const TAG_CLASS = { UNIVERSAL: 0x00, APPLICATION: 0x01, CONTEXT_SPECIFIC: 0x02, PRIVATE: 0x03, }; // https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes class ASN1Tag { constructor(enc) { // Bits 0 through 4 are the tag number this.number = enc & 0x1f; // Bit 5 is the constructed bit this.constructed = (enc & 0x20) === 0x20; // Bit 6 & 7 are the class this.class = enc >> 6; if (this.number === 0x1f) { throw new error_1.ASN1ParseError('long form tags not supported'); } if (this.class === TAG_CLASS.UNIVERSAL && this.number === 0x00) { throw new error_1.ASN1ParseError('unsupported tag 0x00'); } } isUniversal() { return this.class === TAG_CLASS.UNIVERSAL; } isContextSpecific(num) { const res = this.class === TAG_CLASS.CONTEXT_SPECIFIC; return num !== undefined ? res && this.number === num : res; } isBoolean() { return this.isUniversal() && this.number === UNIVERSAL_TAG.BOOLEAN; } isInteger() { return this.isUniversal() && this.number === UNIVERSAL_TAG.INTEGER; } isBitString() { return this.isUniversal() && this.number === UNIVERSAL_TAG.BIT_STRING; } isOctetString() { return this.isUniversal() && this.number === UNIVERSAL_TAG.OCTET_STRING; } isOID() { return (this.isUniversal() && this.number === UNIVERSAL_TAG.OBJECT_IDENTIFIER); } isUTCTime() { return this.isUniversal() && this.number === UNIVERSAL_TAG.UTC_TIME; } isGeneralizedTime() { return this.isUniversal() && this.number === UNIVERSAL_TAG.GENERALIZED_TIME; } toDER() { return this.number | (this.constructed ? 0x20 : 0x00) | (this.class << 6); } } exports.ASN1Tag = ASN1Tag; "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createPublicKey = createPublicKey; exports.digest = digest; exports.verify = verify; exports.bufferEqual = bufferEqual; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const crypto_1 = __importDefault(require("crypto")); function createPublicKey(key, type = 'spki') { if (typeof key === 'string') { return crypto_1.default.createPublicKey(key); } else { return crypto_1.default.createPublicKey({ key, format: 'der', type: type }); } } function digest(algorithm, ...data) { const hash = crypto_1.default.createHash(algorithm); for (const d of data) { hash.update(d); } return hash.digest(); } function verify(data, key, signature, algorithm) { // The try/catch is to work around an issue in Node 14.x where verify throws // an error in some scenarios if the signature is invalid. try { return crypto_1.default.verify(algorithm, data, key, signature); } catch (e) { /* istanbul ignore next */ return false; } } function bufferEqual(a, b) { try { return crypto_1.default.timingSafeEqual(a, b); } catch { /* istanbul ignore next */ return false; } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.preAuthEncoding = preAuthEncoding; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const PAE_PREFIX = 'DSSEv1'; // DSSE Pre-Authentication Encoding function preAuthEncoding(payloadType, payload) { const prefix = [ PAE_PREFIX, payloadType.length, payloadType, payload.length, '', ].join(' '); return Buffer.concat([Buffer.from(prefix, 'ascii'), payload]); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.base64Encode = base64Encode; exports.base64Decode = base64Decode; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const BASE64_ENCODING = 'base64'; const UTF8_ENCODING = 'utf-8'; function base64Encode(str) { return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING); } function base64Decode(str) { return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING); } "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = exports.ByteStream = exports.RFC3161Timestamp = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = exports.ASN1Obj = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ var asn1_1 = require("./asn1"); Object.defineProperty(exports, "ASN1Obj", { enumerable: true, get: function () { return asn1_1.ASN1Obj; } }); exports.crypto = __importStar(require("./crypto")); exports.dsse = __importStar(require("./dsse")); exports.encoding = __importStar(require("./encoding")); exports.json = __importStar(require("./json")); exports.pem = __importStar(require("./pem")); var rfc3161_1 = require("./rfc3161"); Object.defineProperty(exports, "RFC3161Timestamp", { enumerable: true, get: function () { return rfc3161_1.RFC3161Timestamp; } }); var stream_1 = require("./stream"); Object.defineProperty(exports, "ByteStream", { enumerable: true, get: function () { return stream_1.ByteStream; } }); var x509_1 = require("./x509"); Object.defineProperty(exports, "EXTENSION_OID_SCT", { enumerable: true, get: function () { return x509_1.EXTENSION_OID_SCT; } }); Object.defineProperty(exports, "X509Certificate", { enumerable: true, get: function () { return x509_1.X509Certificate; } }); Object.defineProperty(exports, "X509SCTExtension", { enumerable: true, get: function () { return x509_1.X509SCTExtension; } }); "use strict"; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.canonicalize = canonicalize; // JSON canonicalization per https://github.com/cyberphone/json-canonicalization // eslint-disable-next-line @typescript-eslint/no-explicit-any function canonicalize(object) { let buffer = ''; if (object === null || typeof object !== 'object' || object.toJSON != null) { // Primitives or toJSONable objects buffer += JSON.stringify(object); } else if (Array.isArray(object)) { // Array - maintain element order buffer += '['; let first = true; object.forEach((element) => { if (!first) { buffer += ','; } first = false; // recursive call buffer += canonicalize(element); }); buffer += ']'; } else { // Object - Sort properties before serializing buffer += '{'; let first = true; Object.keys(object) .sort() .forEach((property) => { if (!first) { buffer += ','; } first = false; buffer += JSON.stringify(property); buffer += ':'; // recursive call buffer += canonicalize(object[property]); }); buffer += '}'; } return buffer; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SHA2_HASH_ALGOS = exports.ECDSA_SIGNATURE_ALGOS = void 0; exports.ECDSA_SIGNATURE_ALGOS = { '1.2.840.10045.4.3.1': 'sha224', '1.2.840.10045.4.3.2': 'sha256', '1.2.840.10045.4.3.3': 'sha384', '1.2.840.10045.4.3.4': 'sha512', }; exports.SHA2_HASH_ALGOS = { '2.16.840.1.101.3.4.2.1': 'sha256', '2.16.840.1.101.3.4.2.2': 'sha384', '2.16.840.1.101.3.4.2.3': 'sha512', }; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toDER = toDER; exports.fromDER = fromDER; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const PEM_HEADER = /-----BEGIN (.*)-----/; const PEM_FOOTER = /-----END (.*)-----/; function toDER(certificate) { let der = ''; certificate.split('\n').forEach((line) => { if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) { return; } der += line; }); return Buffer.from(der, 'base64'); } // Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM // encoding dictates that each certificate should have a trailing newline after // the footer. function fromDER(certificate, type = 'CERTIFICATE') { // Base64-encode the certificate. const der = certificate.toString('base64'); // Split the certificate into lines of 64 characters. const lines = der.match(/.{1,64}/g) || ''; return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`] .join('\n') .concat('\n'); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RFC3161TimestampVerificationError = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ class RFC3161TimestampVerificationError extends Error { } exports.RFC3161TimestampVerificationError = RFC3161TimestampVerificationError; "use strict"; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.RFC3161Timestamp = void 0; var timestamp_1 = require("./timestamp"); Object.defineProperty(exports, "RFC3161Timestamp", { enumerable: true, get: function () { return timestamp_1.RFC3161Timestamp; } }); "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RFC3161Timestamp = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const asn1_1 = require("../asn1"); const crypto = __importStar(require("../crypto")); const oid_1 = require("../oid"); const error_1 = require("./error"); const tstinfo_1 = require("./tstinfo"); const OID_PKCS9_CONTENT_TYPE_SIGNED_DATA = '1.2.840.113549.1.7.2'; const OID_PKCS9_CONTENT_TYPE_TSTINFO = '1.2.840.113549.1.9.16.1.4'; const OID_PKCS9_MESSAGE_DIGEST_KEY = '1.2.840.113549.1.9.4'; class RFC3161Timestamp { constructor(asn1) { this.root = asn1; } static parse(der) { const asn1 = asn1_1.ASN1Obj.parseBuffer(der); return new RFC3161Timestamp(asn1); } get status() { return this.pkiStatusInfoObj.subs[0].toInteger(); } get contentType() { return this.contentTypeObj.toOID(); } get eContentType() { return this.eContentTypeObj.toOID(); } get signingTime() { return this.tstInfo.genTime; } get signerIssuer() { return this.signerSidObj.subs[0].value; } get signerSerialNumber() { return this.signerSidObj.subs[1].value; } get signerDigestAlgorithm() { const oid = this.signerDigestAlgorithmObj.subs[0].toOID(); return oid_1.SHA2_HASH_ALGOS[oid]; } get signatureAlgorithm() { const oid = this.signatureAlgorithmObj.subs[0].toOID(); return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; } get signatureValue() { return this.signatureValueObj.value; } get tstInfo() { // Need to unpack tstInfo from an OCTET STRING return new tstinfo_1.TSTInfo(this.eContentObj.subs[0].subs[0]); } verify(data, publicKey) { if (!this.timeStampTokenObj) { throw new error_1.RFC3161TimestampVerificationError('timeStampToken is missing'); } // Check for expected ContentInfo content type if (this.contentType !== OID_PKCS9_CONTENT_TYPE_SIGNED_DATA) { throw new error_1.RFC3161TimestampVerificationError(`incorrect content type: ${this.contentType}`); } // Check for expected encapsulated content type if (this.eContentType !== OID_PKCS9_CONTENT_TYPE_TSTINFO) { throw new error_1.RFC3161TimestampVerificationError(`incorrect encapsulated content type: ${this.eContentType}`); } // Check that the tstInfo references the correct artifact this.tstInfo.verify(data); // Check that the signed message digest matches the tstInfo this.verifyMessageDigest(); // Check that the signature is valid for the signed attributes this.verifySignature(publicKey); } verifyMessageDigest() { // Check that the tstInfo matches the signed data const tstInfoDigest = crypto.digest(this.signerDigestAlgorithm, this.tstInfo.raw); const expectedDigest = this.messageDigestAttributeObj.subs[1].subs[0].value; if (!crypto.bufferEqual(tstInfoDigest, expectedDigest)) { throw new error_1.RFC3161TimestampVerificationError('signed data does not match tstInfo'); } } verifySignature(key) { // Encode the signed attributes for verification const signedAttrs = this.signedAttrsObj.toDER(); signedAttrs[0] = 0x31; // Change context-specific tag to SET // Check that the signature is valid for the signed attributes const verified = crypto.verify(signedAttrs, key, this.signatureValue, this.signatureAlgorithm); if (!verified) { throw new error_1.RFC3161TimestampVerificationError('signature verification failed'); } } // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 get pkiStatusInfoObj() { // pkiStatusInfo is the first element of the timestamp response sequence return this.root.subs[0]; } // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 get timeStampTokenObj() { // timeStampToken is the first element of the timestamp response sequence return this.root.subs[1]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-3 get contentTypeObj() { return this.timeStampTokenObj.subs[0]; } // https://www.rfc-editor.org/rfc/rfc5652#section-3 get signedDataObj() { const obj = this.timeStampTokenObj.subs.find((sub) => sub.tag.isContextSpecific(0x00)); return obj.subs[0]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1 get encapContentInfoObj() { return this.signedDataObj.subs[2]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1 get signerInfosObj() { // SignerInfos is the last element of the signed data sequence const sd = this.signedDataObj; return sd.subs[sd.subs.length - 1]; } // https://www.rfc-editor.org/rfc/rfc5652#section-5.1 get signerInfoObj() { // Only supporting one signer return this.signerInfosObj.subs[0]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2 get eContentTypeObj() { return this.encapContentInfoObj.subs[0]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2 get eContentObj() { return this.encapContentInfoObj.subs[1]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 get signedAttrsObj() { const signedAttrs = this.signerInfoObj.subs.find((sub) => sub.tag.isContextSpecific(0x00)); return signedAttrs; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 get messageDigestAttributeObj() { const messageDigest = this.signedAttrsObj.subs.find((sub) => sub.subs[0].tag.isOID() && sub.subs[0].toOID() === OID_PKCS9_MESSAGE_DIGEST_KEY); return messageDigest; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 get signerSidObj() { return this.signerInfoObj.subs[1]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 get signerDigestAlgorithmObj() { // Signature is the 2nd element of the signerInfoObj object return this.signerInfoObj.subs[2]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 get signatureAlgorithmObj() { // Signature is the 4th element of the signerInfoObj object return this.signerInfoObj.subs[4]; } // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 get signatureValueObj() { // Signature is the 6th element of the signerInfoObj object return this.signerInfoObj.subs[5]; } } exports.RFC3161Timestamp = RFC3161Timestamp; "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TSTInfo = void 0; const crypto = __importStar(require("../crypto")); const oid_1 = require("../oid"); const error_1 = require("./error"); class TSTInfo { constructor(asn1) { this.root = asn1; } get version() { return this.root.subs[0].toInteger(); } get genTime() { return this.root.subs[4].toDate(); } get messageImprintHashAlgorithm() { const oid = this.messageImprintObj.subs[0].subs[0].toOID(); return oid_1.SHA2_HASH_ALGOS[oid]; } get messageImprintHashedMessage() { return this.messageImprintObj.subs[1].value; } get raw() { return this.root.toDER(); } verify(data) { const digest = crypto.digest(this.messageImprintHashAlgorithm, data); if (!crypto.bufferEqual(digest, this.messageImprintHashedMessage)) { throw new error_1.RFC3161TimestampVerificationError('message imprint does not match artifact'); } } // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 get messageImprintObj() { return this.root.subs[2]; } } exports.TSTInfo = TSTInfo; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ByteStream = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ class StreamError extends Error { } class ByteStream { constructor(buffer) { this.start = 0; if (buffer) { this.buf = buffer; this.view = Buffer.from(buffer); } else { this.buf = new ArrayBuffer(0); this.view = Buffer.from(this.buf); } } get buffer() { return this.view.subarray(0, this.start); } get length() { return this.view.byteLength; } get position() { return this.start; } seek(position) { this.start = position; } // Returns a Buffer containing the specified number of bytes starting at the // given start position. slice(start, len) { const end = start + len; if (end > this.length) { throw new StreamError('request past end of buffer'); } return this.view.subarray(start, end); } appendChar(char) { this.ensureCapacity(1); this.view[this.start] = char; this.start += 1; } appendUint16(num) { this.ensureCapacity(2); const value = new Uint16Array([num]); const view = new Uint8Array(value.buffer); this.view[this.start] = view[1]; this.view[this.start + 1] = view[0]; this.start += 2; } appendUint24(num) { this.ensureCapacity(3); const value = new Uint32Array([num]); const view = new Uint8Array(value.buffer); this.view[this.start] = view[2]; this.view[this.start + 1] = view[1]; this.view[this.start + 2] = view[0]; this.start += 3; } appendView(view) { this.ensureCapacity(view.length); this.view.set(view, this.start); this.start += view.length; } getBlock(size) { if (size <= 0) { return Buffer.alloc(0); } if (this.start + size > this.view.length) { throw new Error('request past end of buffer'); } const result = this.view.subarray(this.start, this.start + size); this.start += size; return result; } getUint8() { return this.getBlock(1)[0]; } getUint16() { const block = this.getBlock(2); return (block[0] << 8) | block[1]; } ensureCapacity(size) { if (this.start + size > this.view.byteLength) { const blockSize = ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0); this.realloc(this.view.byteLength + blockSize); } } realloc(size) { const newArray = new ArrayBuffer(size); const newView = Buffer.from(newArray); // Copy the old buffer into the new one newView.set(this.view); this.buf = newArray; this.view = newView; } } exports.ByteStream = ByteStream; ByteStream.BLOCK_SIZE = 1024; "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const asn1_1 = require("../asn1"); const crypto = __importStar(require("../crypto")); const oid_1 = require("../oid"); const pem = __importStar(require("../pem")); const ext_1 = require("./ext"); const EXTENSION_OID_SUBJECT_KEY_ID = '2.5.29.14'; const EXTENSION_OID_KEY_USAGE = '2.5.29.15'; const EXTENSION_OID_SUBJECT_ALT_NAME = '2.5.29.17'; const EXTENSION_OID_BASIC_CONSTRAINTS = '2.5.29.19'; const EXTENSION_OID_AUTHORITY_KEY_ID = '2.5.29.35'; exports.EXTENSION_OID_SCT = '1.3.6.1.4.1.11129.2.4.2'; class X509Certificate { constructor(asn1) { this.root = asn1; } static parse(cert) { const der = typeof cert === 'string' ? pem.toDER(cert) : cert; const asn1 = asn1_1.ASN1Obj.parseBuffer(der); return new X509Certificate(asn1); } get tbsCertificate() { return this.tbsCertificateObj; } get version() { // version number is the first element of the version context specific tag const ver = this.versionObj.subs[0].toInteger(); return `v${(ver + BigInt(1)).toString()}`; } get serialNumber() { return this.serialNumberObj.value; } get notBefore() { // notBefore is the first element of the validity sequence return this.validityObj.subs[0].toDate(); } get notAfter() { // notAfter is the second element of the validity sequence return this.validityObj.subs[1].toDate(); } get issuer() { return this.issuerObj.value; } get subject() { return this.subjectObj.value; } get publicKey() { return this.subjectPublicKeyInfoObj.toDER(); } get signatureAlgorithm() { const oid = this.signatureAlgorithmObj.subs[0].toOID(); return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; } get signatureValue() { // Signature value is a bit string, so we need to skip the first byte return this.signatureValueObj.value.subarray(1); } get subjectAltName() { const ext = this.extSubjectAltName; return ext?.uri || /* istanbul ignore next */ ext?.rfc822Name; } get extensions() { // The extension list is the first (and only) element of the extensions // context specific tag /* istanbul ignore next */ const extSeq = this.extensionsObj?.subs[0]; /* istanbul ignore next */ return extSeq?.subs || []; } get extKeyUsage() { const ext = this.findExtension(EXTENSION_OID_KEY_USAGE); return ext ? new ext_1.X509KeyUsageExtension(ext) : undefined; } get extBasicConstraints() { const ext = this.findExtension(EXTENSION_OID_BASIC_CONSTRAINTS); return ext ? new ext_1.X509BasicConstraintsExtension(ext) : undefined; } get extSubjectAltName() { const ext = this.findExtension(EXTENSION_OID_SUBJECT_ALT_NAME); return ext ? new ext_1.X509SubjectAlternativeNameExtension(ext) : undefined; } get extAuthorityKeyID() { const ext = this.findExtension(EXTENSION_OID_AUTHORITY_KEY_ID); return ext ? new ext_1.X509AuthorityKeyIDExtension(ext) : undefined; } get extSubjectKeyID() { const ext = this.findExtension(EXTENSION_OID_SUBJECT_KEY_ID); return ext ? new ext_1.X509SubjectKeyIDExtension(ext) : /* istanbul ignore next */ undefined; } get extSCT() { const ext = this.findExtension(exports.EXTENSION_OID_SCT); return ext ? new ext_1.X509SCTExtension(ext) : undefined; } get isCA() { const ca = this.extBasicConstraints?.isCA || false; // If the KeyUsage extension is present, keyCertSign must be set if (this.extKeyUsage) { return ca && this.extKeyUsage.keyCertSign; } // TODO: test coverage for this case /* istanbul ignore next */ return ca; } extension(oid) { const ext = this.findExtension(oid); return ext ? new ext_1.X509Extension(ext) : undefined; } verify(issuerCertificate) { // Use the issuer's public key if provided, otherwise use the subject's const publicKey = issuerCertificate?.publicKey || this.publicKey; const key = crypto.createPublicKey(publicKey); return crypto.verify(this.tbsCertificate.toDER(), key, this.signatureValue, this.signatureAlgorithm); } validForDate(date) { return this.notBefore <= date && date <= this.notAfter; } equals(other) { return this.root.toDER().equals(other.root.toDER()); } // Creates a copy of the certificate with a new buffer clone() { const der = this.root.toDER(); const clone = Buffer.alloc(der.length); der.copy(clone); return X509Certificate.parse(clone); } findExtension(oid) { // Find the extension with the given OID. The OID will always be the first // element of the extension sequence return this.extensions.find((ext) => ext.subs[0].toOID() === oid); } ///////////////////////////////////////////////////////////////////////////// // The following properties use the documented x509 structure to locate the // desired ASN.1 object // https://www.rfc-editor.org/rfc/rfc5280#section-4.1 // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.1 get tbsCertificateObj() { // tbsCertificate is the first element of the certificate sequence return this.root.subs[0]; } // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2 get signatureAlgorithmObj() { // signatureAlgorithm is the second element of the certificate sequence return this.root.subs[1]; } // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.3 get signatureValueObj() { // signatureValue is the third element of the certificate sequence return this.root.subs[2]; } // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.1 get versionObj() { // version is the first element of the tbsCertificate sequence return this.tbsCertificateObj.subs[0]; } // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.2 get serialNumberObj() { // serialNumber is the second element of the tbsCertificate sequence return this.tbsCertificateObj.subs[1]; } // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4 get issuerObj() { // issuer is the fourth element of the tbsCertificate sequence return this.tbsCertificateObj.subs[3]; } // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5 get validityObj() { // version is the fifth element of the tbsCertificate sequence return this.tbsCertificateObj.subs[4]; } // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.6 get subjectObj() { // subject is the sixth element of the tbsCertificate sequence return this.tbsCertificateObj.subs[5]; } // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7 get subjectPublicKeyInfoObj() { // subjectPublicKeyInfo is the seventh element of the tbsCertificate sequence return this.tbsCertificateObj.subs[6]; } // Extensions can't be located by index because their position varies. Instead, // we need to find the extensions context specific tag // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.9 get extensionsObj() { return this.tbsCertificateObj.subs.find((sub) => sub.tag.isContextSpecific(0x03)); } } exports.X509Certificate = X509Certificate; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.X509SCTExtension = exports.X509SubjectKeyIDExtension = exports.X509AuthorityKeyIDExtension = exports.X509SubjectAlternativeNameExtension = exports.X509KeyUsageExtension = exports.X509BasicConstraintsExtension = exports.X509Extension = void 0; const stream_1 = require("../stream"); const sct_1 = require("./sct"); // https://www.rfc-editor.org/rfc/rfc5280#section-4.1 class X509Extension { constructor(asn1) { this.root = asn1; } get oid() { return this.root.subs[0].toOID(); } get critical() { // The critical field is optional and will be the second element of the // extension sequence if present. Default to false if not present. return this.root.subs.length === 3 ? this.root.subs[1].toBoolean() : false; } get value() { return this.extnValueObj.value; } get valueObj() { return this.extnValueObj; } get extnValueObj() { // The extnValue field will be the last element of the extension sequence return this.root.subs[this.root.subs.length - 1]; } } exports.X509Extension = X509Extension; // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9 class X509BasicConstraintsExtension extends X509Extension { get isCA() { return this.sequence.subs[0]?.toBoolean() ?? false; } get pathLenConstraint() { return this.sequence.subs.length > 1 ? this.sequence.subs[1].toInteger() : undefined; } // The extnValue field contains a single sequence wrapping the isCA and // pathLenConstraint. get sequence() { return this.extnValueObj.subs[0]; } } exports.X509BasicConstraintsExtension = X509BasicConstraintsExtension; // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3 class X509KeyUsageExtension extends X509Extension { get digitalSignature() { return this.bitString[0] === 1; } get keyCertSign() { return this.bitString[5] === 1; } get crlSign() { return this.bitString[6] === 1; } // The extnValue field contains a single bit string which is a bit mask // indicating which key usages are enabled. get bitString() { return this.extnValueObj.subs[0].toBitString(); } } exports.X509KeyUsageExtension = X509KeyUsageExtension; // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6 class X509SubjectAlternativeNameExtension extends X509Extension { get rfc822Name() { return this.findGeneralName(0x01)?.value.toString('ascii'); } get uri() { return this.findGeneralName(0x06)?.value.toString('ascii'); } // Retrieve the value of an otherName with the given OID. otherName(oid) { const otherName = this.findGeneralName(0x00); if (otherName === undefined) { return undefined; } // The otherName is a sequence containing an OID and a value. // Need to check that the OID matches the one we're looking for. const otherNameOID = otherName.subs[0].toOID(); if (otherNameOID !== oid) { return undefined; } // The otherNameValue is a sequence containing the actual value. const otherNameValue = otherName.subs[1]; return otherNameValue.subs[0].value.toString('ascii'); } findGeneralName(tag) { return this.generalNames.find((gn) => gn.tag.isContextSpecific(tag)); } // The extnValue field contains a sequence of GeneralNames. get generalNames() { return this.extnValueObj.subs[0].subs; } } exports.X509SubjectAlternativeNameExtension = X509SubjectAlternativeNameExtension; // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1 class X509AuthorityKeyIDExtension extends X509Extension { get keyIdentifier() { return this.findSequenceMember(0x00)?.value; } findSequenceMember(tag) { return this.sequence.subs.find((el) => el.tag.isContextSpecific(tag)); } // The extnValue field contains a single sequence wrapping the keyIdentifier get sequence() { return this.extnValueObj.subs[0]; } } exports.X509AuthorityKeyIDExtension = X509AuthorityKeyIDExtension; // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.2 class X509SubjectKeyIDExtension extends X509Extension { get keyIdentifier() { return this.extnValueObj.subs[0].value; } } exports.X509SubjectKeyIDExtension = X509SubjectKeyIDExtension; // https://www.rfc-editor.org/rfc/rfc6962#section-3.3 class X509SCTExtension extends X509Extension { constructor(asn1) { super(asn1); } get signedCertificateTimestamps() { const buf = this.extnValueObj.subs[0].value; const stream = new stream_1.ByteStream(buf); // The overall list length is encoded in the first two bytes -- note this // is the length of the list in bytes, NOT the number of SCTs in the list const end = stream.getUint16() + 2; const sctList = []; while (stream.position < end) { // Read the length of the next SCT const sctLength = stream.getUint16(); // Slice out the bytes for the next SCT and parse it const sct = stream.getBlock(sctLength); sctList.push(sct_1.SignedCertificateTimestamp.parse(sct)); } if (stream.position !== end) { throw new Error('SCT list length does not match actual length'); } return sctList; } } exports.X509SCTExtension = X509SCTExtension; "use strict"; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; var cert_1 = require("./cert"); Object.defineProperty(exports, "EXTENSION_OID_SCT", { enumerable: true, get: function () { return cert_1.EXTENSION_OID_SCT; } }); Object.defineProperty(exports, "X509Certificate", { enumerable: true, get: function () { return cert_1.X509Certificate; } }); var ext_1 = require("./ext"); Object.defineProperty(exports, "X509SCTExtension", { enumerable: true, get: function () { return ext_1.X509SCTExtension; } }); "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SignedCertificateTimestamp = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const crypto = __importStar(require("../crypto")); const stream_1 = require("../stream"); class SignedCertificateTimestamp { constructor(options) { this.version = options.version; this.logID = options.logID; this.timestamp = options.timestamp; this.extensions = options.extensions; this.hashAlgorithm = options.hashAlgorithm; this.signatureAlgorithm = options.signatureAlgorithm; this.signature = options.signature; } get datetime() { return new Date(Number(this.timestamp.readBigInt64BE())); } // Returns the hash algorithm used to generate the SCT's signature. // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 get algorithm() { switch (this.hashAlgorithm) { /* istanbul ignore next */ case 0: return 'none'; /* istanbul ignore next */ case 1: return 'md5'; /* istanbul ignore next */ case 2: return 'sha1'; /* istanbul ignore next */ case 3: return 'sha224'; case 4: return 'sha256'; /* istanbul ignore next */ case 5: return 'sha384'; /* istanbul ignore next */ case 6: return 'sha512'; /* istanbul ignore next */ default: return 'unknown'; } } verify(preCert, key) { // Assemble the digitally-signed struct (the data over which the signature // was generated). // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 const stream = new stream_1.ByteStream(); stream.appendChar(this.version); stream.appendChar(0x00); // SignatureType = certificate_timestamp(0) stream.appendView(this.timestamp); stream.appendUint16(0x01); // LogEntryType = precert_entry(1) stream.appendView(preCert); stream.appendUint16(this.extensions.byteLength); /* istanbul ignore next - extensions are very uncommon */ if (this.extensions.byteLength > 0) { stream.appendView(this.extensions); } return crypto.verify(stream.buffer, key, this.signature, this.algorithm); } // Parses a SignedCertificateTimestamp from a buffer. SCTs are encoded using // TLS encoding which means the fields and lengths of most fields are // specified as part of the SCT and TLS specs. // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 static parse(buf) { const stream = new stream_1.ByteStream(buf); // Version - enum { v1(0), (255) } const version = stream.getUint8(); // Log ID - struct { opaque key_id[32]; } const logID = stream.getBlock(32); // Timestamp - uint64 const timestamp = stream.getBlock(8); // Extensions - opaque extensions<0..2^16-1>; const extenstionLength = stream.getUint16(); const extensions = stream.getBlock(extenstionLength); // Hash algo - enum { sha256(4), . . . (255) } const hashAlgorithm = stream.getUint8(); // Signature algo - enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } const signatureAlgorithm = stream.getUint8(); // Signature - opaque signature<0..2^16-1>; const sigLength = stream.getUint16(); const signature = stream.getBlock(sigLength); // Check that we read the entire buffer if (stream.position !== buf.length) { throw new Error('SCT buffer length mismatch'); } return new SignedCertificateTimestamp({ version, logID, timestamp, extensions, hashAlgorithm, signatureAlgorithm, signature, }); } } exports.SignedCertificateTimestamp = SignedCertificateTimestamp; { "name": "@sigstore/core", "version": "2.0.0", "description": "Base library for Sigstore", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "clean": "shx rm -rf dist *.tsbuildinfo", "build": "tsc --build", "test": "jest" }, "files": [ "dist" ], "author": "bdehamer@github.com", "license": "Apache-2.0", "repository": { "type": "git", "url": "git+https://github.com/sigstore/sigstore-js.git" }, "bugs": { "url": "https://github.com/sigstore/sigstore-js/issues" }, "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/core#readme", "publishConfig": { "provenance": true }, "engines": { "node": "^18.17.0 || >=20.5.0" } } Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 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 (50%) 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 The Sigstore Authors Licensed under the Apache License, Version 2.0 (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-2.0 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. "use strict"; /* eslint-disable */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Signature = exports.Envelope = void 0; function createBaseEnvelope() { return { payload: Buffer.alloc(0), payloadType: "", signatures: [] }; } exports.Envelope = { fromJSON(object) { return { payload: isSet(object.payload) ? Buffer.from(bytesFromBase64(object.payload)) : Buffer.alloc(0), payloadType: isSet(object.payloadType) ? String(object.payloadType) : "", signatures: Array.isArray(object?.signatures) ? object.signatures.map((e) => exports.Signature.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.payload !== undefined && (obj.payload = base64FromBytes(message.payload !== undefined ? message.payload : Buffer.alloc(0))); message.payloadType !== undefined && (obj.payloadType = message.payloadType); if (message.signatures) { obj.signatures = message.signatures.map((e) => e ? exports.Signature.toJSON(e) : undefined); } else { obj.signatures = []; } return obj; }, }; function createBaseSignature() { return { sig: Buffer.alloc(0), keyid: "" }; } exports.Signature = { fromJSON(object) { return { sig: isSet(object.sig) ? Buffer.from(bytesFromBase64(object.sig)) : Buffer.alloc(0), keyid: isSet(object.keyid) ? String(object.keyid) : "", }; }, toJSON(message) { const obj = {}; message.sig !== undefined && (obj.sig = base64FromBytes(message.sig !== undefined ? message.sig : Buffer.alloc(0))); message.keyid !== undefined && (obj.keyid = message.keyid); return obj; }, }; var tsProtoGlobalThis = (() => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } throw "Unable to locate global object"; })(); function bytesFromBase64(b64) { if (tsProtoGlobalThis.Buffer) { return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); } else { const bin = tsProtoGlobalThis.atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } } function base64FromBytes(arr) { if (tsProtoGlobalThis.Buffer) { return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); } else { const bin = []; arr.forEach((byte) => { bin.push(String.fromCharCode(byte)); }); return tsProtoGlobalThis.btoa(bin.join("")); } } function isSet(value) { return value !== null && value !== undefined; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CloudEventBatch = exports.CloudEvent_CloudEventAttributeValue = exports.CloudEvent_AttributesEntry = exports.CloudEvent = void 0; /* eslint-disable */ const any_1 = require("./google/protobuf/any"); const timestamp_1 = require("./google/protobuf/timestamp"); function createBaseCloudEvent() { return { id: "", source: "", specVersion: "", type: "", attributes: {}, data: undefined }; } exports.CloudEvent = { fromJSON(object) { return { id: isSet(object.id) ? String(object.id) : "", source: isSet(object.source) ? String(object.source) : "", specVersion: isSet(object.specVersion) ? String(object.specVersion) : "", type: isSet(object.type) ? String(object.type) : "", attributes: isObject(object.attributes) ? Object.entries(object.attributes).reduce((acc, [key, value]) => { acc[key] = exports.CloudEvent_CloudEventAttributeValue.fromJSON(value); return acc; }, {}) : {}, data: isSet(object.binaryData) ? { $case: "binaryData", binaryData: Buffer.from(bytesFromBase64(object.binaryData)) } : isSet(object.textData) ? { $case: "textData", textData: String(object.textData) } : isSet(object.protoData) ? { $case: "protoData", protoData: any_1.Any.fromJSON(object.protoData) } : undefined, }; }, toJSON(message) { const obj = {}; message.id !== undefined && (obj.id = message.id); message.source !== undefined && (obj.source = message.source); message.specVersion !== undefined && (obj.specVersion = message.specVersion); message.type !== undefined && (obj.type = message.type); obj.attributes = {}; if (message.attributes) { Object.entries(message.attributes).forEach(([k, v]) => { obj.attributes[k] = exports.CloudEvent_CloudEventAttributeValue.toJSON(v); }); } message.data?.$case === "binaryData" && (obj.binaryData = message.data?.binaryData !== undefined ? base64FromBytes(message.data?.binaryData) : undefined); message.data?.$case === "textData" && (obj.textData = message.data?.textData); message.data?.$case === "protoData" && (obj.protoData = message.data?.protoData ? any_1.Any.toJSON(message.data?.protoData) : undefined); return obj; }, }; function createBaseCloudEvent_AttributesEntry() { return { key: "", value: undefined }; } exports.CloudEvent_AttributesEntry = { fromJSON(object) { return { key: isSet(object.key) ? String(object.key) : "", value: isSet(object.value) ? exports.CloudEvent_CloudEventAttributeValue.fromJSON(object.value) : undefined, }; }, toJSON(message) { const obj = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value ? exports.CloudEvent_CloudEventAttributeValue.toJSON(message.value) : undefined); return obj; }, }; function createBaseCloudEvent_CloudEventAttributeValue() { return { attr: undefined }; } exports.CloudEvent_CloudEventAttributeValue = { fromJSON(object) { return { attr: isSet(object.ceBoolean) ? { $case: "ceBoolean", ceBoolean: Boolean(object.ceBoolean) } : isSet(object.ceInteger) ? { $case: "ceInteger", ceInteger: Number(object.ceInteger) } : isSet(object.ceString) ? { $case: "ceString", ceString: String(object.ceString) } : isSet(object.ceBytes) ? { $case: "ceBytes", ceBytes: Buffer.from(bytesFromBase64(object.ceBytes)) } : isSet(object.ceUri) ? { $case: "ceUri", ceUri: String(object.ceUri) } : isSet(object.ceUriRef) ? { $case: "ceUriRef", ceUriRef: String(object.ceUriRef) } : isSet(object.ceTimestamp) ? { $case: "ceTimestamp", ceTimestamp: fromJsonTimestamp(object.ceTimestamp) } : undefined, }; }, toJSON(message) { const obj = {}; message.attr?.$case === "ceBoolean" && (obj.ceBoolean = message.attr?.ceBoolean); message.attr?.$case === "ceInteger" && (obj.ceInteger = Math.round(message.attr?.ceInteger)); message.attr?.$case === "ceString" && (obj.ceString = message.attr?.ceString); message.attr?.$case === "ceBytes" && (obj.ceBytes = message.attr?.ceBytes !== undefined ? base64FromBytes(message.attr?.ceBytes) : undefined); message.attr?.$case === "ceUri" && (obj.ceUri = message.attr?.ceUri); message.attr?.$case === "ceUriRef" && (obj.ceUriRef = message.attr?.ceUriRef); message.attr?.$case === "ceTimestamp" && (obj.ceTimestamp = message.attr?.ceTimestamp.toISOString()); return obj; }, }; function createBaseCloudEventBatch() { return { events: [] }; } exports.CloudEventBatch = { fromJSON(object) { return { events: Array.isArray(object?.events) ? object.events.map((e) => exports.CloudEvent.fromJSON(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.events) { obj.events = message.events.map((e) => e ? exports.CloudEvent.toJSON(e) : undefined); } else { obj.events = []; } return obj; }, }; var tsProtoGlobalThis = (() => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } throw "Unable to locate global object"; })(); function bytesFromBase64(b64) { if (tsProtoGlobalThis.Buffer) { return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); } else { const bin = tsProtoGlobalThis.atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } } function base64FromBytes(arr) { if (tsProtoGlobalThis.Buffer) { return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); } else { const bin = []; arr.forEach((byte) => { bin.push(String.fromCharCode(byte)); }); return tsProtoGlobalThis.btoa(bin.join("")); } } function fromTimestamp(t) { let millis = Number(t.seconds) * 1_000; millis += t.nanos / 1_000_000; return new Date(millis); } function fromJsonTimestamp(o) { if (o instanceof Date) { return o; } else if (typeof o === "string") { return new Date(o); } else { return fromTimestamp(timestamp_1.Timestamp.fromJSON(o)); } } function isObject(value) { return typeof value === "object" && value !== null; } function isSet(value) { return value !== null && value !== undefined; } "use strict"; /* eslint-disable */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FieldBehavior = void 0; exports.fieldBehaviorFromJSON = fieldBehaviorFromJSON; exports.fieldBehaviorToJSON = fieldBehaviorToJSON; /** * An indicator of the behavior of a given field (for example, that a field * is required in requests, or given as output but ignored as input). * This **does not** change the behavior in protocol buffers itself; it only * denotes the behavior and may affect how API tooling handles the field. * * Note: This enum **may** receive new values in the future. */ var FieldBehavior; (function (FieldBehavior) { /** FIELD_BEHAVIOR_UNSPECIFIED - Conventional default for enums. Do not use this. */ FieldBehavior[FieldBehavior["FIELD_BEHAVIOR_UNSPECIFIED"] = 0] = "FIELD_BEHAVIOR_UNSPECIFIED"; /** * OPTIONAL - Specifically denotes a field as optional. * While all fields in protocol buffers are optional, this may be specified * for emphasis if appropriate. */ FieldBehavior[FieldBehavior["OPTIONAL"] = 1] = "OPTIONAL"; /** * REQUIRED - Denotes a field as required. * This indicates that the field **must** be provided as part of the request, * and failure to do so will cause an error (usually `INVALID_ARGUMENT`). */ FieldBehavior[FieldBehavior["REQUIRED"] = 2] = "REQUIRED"; /** * OUTPUT_ONLY - Denotes a field as output only. * This indicates that the field is provided in responses, but including the * field in a request does nothing (the server *must* ignore it and * *must not* throw an error as a result of the field's presence). */ FieldBehavior[FieldBehavior["OUTPUT_ONLY"] = 3] = "OUTPUT_ONLY"; /** * INPUT_ONLY - Denotes a field as input only. * This indicates that the field is provided in requests, and the * corresponding field is not included in output. */ FieldBehavior[FieldBehavior["INPUT_ONLY"] = 4] = "INPUT_ONLY"; /** * IMMUTABLE - Denotes a field as immutable. * This indicates that the field may be set once in a request to create a * resource, but may not be changed thereafter. */ FieldBehavior[FieldBehavior["IMMUTABLE"] = 5] = "IMMUTABLE"; /** * UNORDERED_LIST - Denotes that a (repeated) field is an unordered list. * This indicates that the service may provide the elements of the list * in any arbitrary order, rather than the order the user originally * provided. Additionally, the list's order may or may not be stable. */ FieldBehavior[FieldBehavior["UNORDERED_LIST"] = 6] = "UNORDERED_LIST"; })(FieldBehavior || (exports.FieldBehavior = FieldBehavior = {})); function fieldBehaviorFromJSON(object) { switch (object) { case 0: case "FIELD_BEHAVIOR_UNSPECIFIED": return FieldBehavior.FIELD_BEHAVIOR_UNSPECIFIED; case 1: case "OPTIONAL": return FieldBehavior.OPTIONAL; case 2: case "REQUIRED": return FieldBehavior.REQUIRED; case 3: case "OUTPUT_ONLY": return FieldBehavior.OUTPUT_ONLY; case 4: case "INPUT_ONLY": return FieldBehavior.INPUT_ONLY; case 5: case "IMMUTABLE": return FieldBehavior.IMMUTABLE; case 6: case "UNORDERED_LIST": return FieldBehavior.UNORDERED_LIST; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior"); } } function fieldBehaviorToJSON(object) { switch (object) { case FieldBehavior.FIELD_BEHAVIOR_UNSPECIFIED: return "FIELD_BEHAVIOR_UNSPECIFIED"; case FieldBehavior.OPTIONAL: return "OPTIONAL"; case FieldBehavior.REQUIRED: return "REQUIRED"; case FieldBehavior.OUTPUT_ONLY: return "OUTPUT_ONLY"; case FieldBehavior.INPUT_ONLY: return "INPUT_ONLY"; case FieldBehavior.IMMUTABLE: return "IMMUTABLE"; case FieldBehavior.UNORDERED_LIST: return "UNORDERED_LIST"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior"); } } var tsProtoGlobalThis = (() => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } throw "Unable to locate global object"; })(); "use strict"; /* eslint-disable */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Any = void 0; function createBaseAny() { return { typeUrl: "", value: Buffer.alloc(0) }; } exports.Any = { fromJSON(object) { return { typeUrl: isSet(object.typeUrl) ? String(object.typeUrl) : "", value: isSet(object.value) ? Buffer.from(bytesFromBase64(object.value)) : Buffer.alloc(0), }; }, toJSON(message) { const obj = {}; message.typeUrl !== undefined && (obj.typeUrl = message.typeUrl); message.value !== undefined && (obj.value = base64FromBytes(message.value !== undefined ? message.value : Buffer.alloc(0))); return obj; }, }; var tsProtoGlobalThis = (() => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } throw "Unable to locate global object"; })(); function bytesFromBase64(b64) { if (tsProtoGlobalThis.Buffer) { return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); } else { const bin = tsProtoGlobalThis.atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } } function base64FromBytes(arr) { if (tsProtoGlobalThis.Buffer) { return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); } else { const bin = []; arr.forEach((byte) => { bin.push(String.fromCharCode(byte)); }); return tsProtoGlobalThis.btoa(bin.join("")); } } function isSet(value) { return value !== null && value !== undefined; } "use strict"; /* eslint-disable */ Object.defineProperty(exports, "__esModule", { value: true }); exports.GeneratedCodeInfo_Annotation = exports.GeneratedCodeInfo = exports.SourceCodeInfo_Location = exports.SourceCodeInfo = exports.UninterpretedOption_NamePart = exports.UninterpretedOption = exports.MethodOptions = exports.ServiceOptions = exports.EnumValueOptions = exports.EnumOptions = exports.OneofOptions = exports.FieldOptions = exports.MessageOptions = exports.FileOptions = exports.MethodDescriptorProto = exports.ServiceDescriptorProto = exports.EnumValueDescriptorProto = exports.EnumDescriptorProto_EnumReservedRange = exports.EnumDescriptorProto = exports.OneofDescriptorProto = exports.FieldDescriptorProto = exports.ExtensionRangeOptions = exports.DescriptorProto_ReservedRange = exports.DescriptorProto_ExtensionRange = exports.DescriptorProto = exports.FileDescriptorProto = exports.FileDescriptorSet = exports.MethodOptions_IdempotencyLevel = exports.FieldOptions_JSType = exports.FieldOptions_CType = exports.FileOptions_OptimizeMode = exports.FieldDescriptorProto_Label = exports.FieldDescriptorProto_Type = void 0; exports.fieldDescriptorProto_TypeFromJSON = fieldDescriptorProto_TypeFromJSON; exports.fieldDescriptorProto_TypeToJSON = fieldDescriptorProto_TypeToJSON; exports.fieldDescriptorProto_LabelFromJSON = fieldDescriptorProto_LabelFromJSON; exports.fieldDescriptorProto_LabelToJSON = fieldDescriptorProto_LabelToJSON; exports.fileOptions_OptimizeModeFromJSON = fileOptions_OptimizeModeFromJSON; exports.fileOptions_OptimizeModeToJSON = fileOptions_OptimizeModeToJSON; exports.fieldOptions_CTypeFromJSON = fieldOptions_CTypeFromJSON; exports.fieldOptions_CTypeToJSON = fieldOptions_CTypeToJSON; exports.fieldOptions_JSTypeFromJSON = fieldOptions_JSTypeFromJSON; exports.fieldOptions_JSTypeToJSON = fieldOptions_JSTypeToJSON; exports.methodOptions_IdempotencyLevelFromJSON = methodOptions_IdempotencyLevelFromJSON; exports.methodOptions_IdempotencyLevelToJSON = methodOptions_IdempotencyLevelToJSON; var FieldDescriptorProto_Type; (function (FieldDescriptorProto_Type) { /** * TYPE_DOUBLE - 0 is reserved for errors. * Order is weird for historical reasons. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_DOUBLE"] = 1] = "TYPE_DOUBLE"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FLOAT"] = 2] = "TYPE_FLOAT"; /** * TYPE_INT64 - Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if * negative values are likely. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_INT64"] = 3] = "TYPE_INT64"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_UINT64"] = 4] = "TYPE_UINT64"; /** * TYPE_INT32 - Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if * negative values are likely. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_INT32"] = 5] = "TYPE_INT32"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FIXED64"] = 6] = "TYPE_FIXED64"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FIXED32"] = 7] = "TYPE_FIXED32"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_BOOL"] = 8] = "TYPE_BOOL"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_STRING"] = 9] = "TYPE_STRING"; /** * TYPE_GROUP - Tag-delimited aggregate. * Group type is deprecated and not supported in proto3. However, Proto3 * implementations should still be able to parse the group wire format and * treat group fields as unknown fields. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_GROUP"] = 10] = "TYPE_GROUP"; /** TYPE_MESSAGE - Length-delimited aggregate. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_MESSAGE"] = 11] = "TYPE_MESSAGE"; /** TYPE_BYTES - New in version 2. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_BYTES"] = 12] = "TYPE_BYTES"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_UINT32"] = 13] = "TYPE_UINT32"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_ENUM"] = 14] = "TYPE_ENUM"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SFIXED32"] = 15] = "TYPE_SFIXED32"; FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SFIXED64"] = 16] = "TYPE_SFIXED64"; /** TYPE_SINT32 - Uses ZigZag encoding. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SINT32"] = 17] = "TYPE_SINT32"; /** TYPE_SINT64 - Uses ZigZag encoding. */ FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SINT64"] = 18] = "TYPE_SINT64"; })(FieldDescriptorProto_Type || (exports.FieldDescriptorProto_Type = FieldDescriptorProto_Type = {})); function fieldDescriptorProto_TypeFromJSON(object) { switch (object) { case 1: case "TYPE_DOUBLE": return FieldDescriptorProto_Type.TYPE_DOUBLE; case 2: case "TYPE_FLOAT": return FieldDescriptorProto_Type.TYPE_FLOAT; case 3: case "TYPE_INT64": return FieldDescriptorProto_Type.TYPE_INT64; case 4: case "TYPE_UINT64": return FieldDescriptorProto_Type.TYPE_UINT64; case 5: case "TYPE_INT32": return FieldDescriptorProto_Type.TYPE_INT32; case 6: case "TYPE_FIXED64": return FieldDescriptorProto_Type.TYPE_FIXED64; case 7: case "TYPE_FIXED32": return FieldDescriptorProto_Type.TYPE_FIXED32; case 8: case "TYPE_BOOL": return FieldDescriptorProto_Type.TYPE_BOOL; case 9: case "TYPE_STRING": return FieldDescriptorProto_Type.TYPE_STRING; case 10: case "TYPE_GROUP": return FieldDescriptorProto_Type.TYPE_GROUP; case 11: case "TYPE_MESSAGE": return FieldDescriptorProto_Type.TYPE_MESSAGE; case 12: case "TYPE_BYTES": return FieldDescriptorProto_Type.TYPE_BYTES; case 13: case "TYPE_UINT32": return FieldDescriptorProto_Type.TYPE_UINT32; case 14: case "TYPE_ENUM": return FieldDescriptorProto_Type.TYPE_ENUM; case 15: case "TYPE_SFIXED32": return FieldDescriptorProto_Type.TYPE_SFIXED32; case 16: case "TYPE_SFIXED64": return FieldDescriptorProto_Type.TYPE_SFIXED64; case 17: case "TYPE_SINT32": return FieldDescriptorProto_Type.TYPE_SINT32; case 18: case "TYPE_SINT64": return FieldDescriptorProto_Type.TYPE_SINT64; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type"); } } function fieldDescriptorProto_TypeToJSON(object) { switch (object) { case FieldDescriptorProto_Type.TYPE_DOUBLE: return "TYPE_DOUBLE"; case FieldDescriptorProto_Type.TYPE_FLOAT: return "TYPE_FLOAT"; case FieldDescriptorProto_Type.TYPE_INT64: return "TYPE_INT64"; case FieldDescriptorProto_Type.TYPE_UINT64: return "TYPE_UINT64"; case FieldDescriptorProto_Type.TYPE_INT32: return "TYPE_INT32"; case FieldDescriptorProto_Type.TYPE_FIXED64: return "TYPE_FIXED64"; case FieldDescriptorProto_Type.TYPE_FIXED32: return "TYPE_FIXED32"; case FieldDescriptorProto_Type.TYPE_BOOL: return "TYPE_BOOL"; case FieldDescriptorProto_Type.TYPE_STRING: return "TYPE_STRING"; case FieldDescriptorProto_Type.TYPE_GROUP: return "TYPE_GROUP"; case FieldDescriptorProto_Type.TYPE_MESSAGE: return "TYPE_MESSAGE"; case FieldDescriptorProto_Type.TYPE_BYTES: return "TYPE_BYTES"; case FieldDescriptorProto_Type.TYPE_UINT32: return "TYPE_UINT32"; case FieldDescriptorProto_Type.TYPE_ENUM: return "TYPE_ENUM"; case FieldDescriptorProto_Type.TYPE_SFIXED32: return "TYPE_SFIXED32"; case FieldDescriptorProto_Type.TYPE_SFIXED64: return "TYPE_SFIXED64"; case FieldDescriptorProto_Type.TYPE_SINT32: return "TYPE_SINT32"; case FieldDescriptorProto_Type.TYPE_SINT64: return "TYPE_SINT64"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type"); } } var FieldDescriptorProto_Label; (function (FieldDescriptorProto_Label) { /** LABEL_OPTIONAL - 0 is reserved for errors */ FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_OPTIONAL"] = 1] = "LABEL_OPTIONAL"; FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_REQUIRED"] = 2] = "LABEL_REQUIRED"; FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_REPEATED"] = 3] = "LABEL_REPEATED"; })(FieldDescriptorProto_Label || (exports.FieldDescriptorProto_Label = FieldDescriptorProto_Label = {})); function fieldDescriptorProto_LabelFromJSON(object) { switch (object) { case 1: case "LABEL_OPTIONAL": return FieldDescriptorProto_Label.LABEL_OPTIONAL; case 2: case "LABEL_REQUIRED": return FieldDescriptorProto_Label.LABEL_REQUIRED; case 3: case "LABEL_REPEATED": return FieldDescriptorProto_Label.LABEL_REPEATED; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label"); } } function fieldDescriptorProto_LabelToJSON(object) { switch (object) { case FieldDescriptorProto_Label.LABEL_OPTIONAL: return "LABEL_OPTIONAL"; case FieldDescriptorProto_Label.LABEL_REQUIRED: return "LABEL_REQUIRED"; case FieldDescriptorProto_Label.LABEL_REPEATED: return "LABEL_REPEATED"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label"); } } /** Generated classes can be optimized for speed or code size. */ var FileOptions_OptimizeMode; (function (FileOptions_OptimizeMode) { /** SPEED - Generate complete code for parsing, serialization, */ FileOptions_OptimizeMode[FileOptions_OptimizeMode["SPEED"] = 1] = "SPEED"; /** CODE_SIZE - etc. */ FileOptions_OptimizeMode[FileOptions_OptimizeMode["CODE_SIZE"] = 2] = "CODE_SIZE"; /** LITE_RUNTIME - Generate code using MessageLite and the lite runtime. */ FileOptions_OptimizeMode[FileOptions_OptimizeMode["LITE_RUNTIME"] = 3] = "LITE_RUNTIME"; })(FileOptions_OptimizeMode || (exports.FileOptions_OptimizeMode = FileOptions_OptimizeMode = {})); function fileOptions_OptimizeModeFromJSON(object) { switch (object) { case 1: case "SPEED": return FileOptions_OptimizeMode.SPEED; case 2: case "CODE_SIZE": return FileOptions_OptimizeMode.CODE_SIZE; case 3: case "LITE_RUNTIME": return FileOptions_OptimizeMode.LITE_RUNTIME; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode"); } } function fileOptions_OptimizeModeToJSON(object) { switch (object) { case FileOptions_OptimizeMode.SPEED: return "SPEED"; case FileOptions_OptimizeMode.CODE_SIZE: return "CODE_SIZE"; case FileOptions_OptimizeMode.LITE_RUNTIME: return "LITE_RUNTIME"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode"); } } var FieldOptions_CType; (function (FieldOptions_CType) { /** STRING - Default mode. */ FieldOptions_CType[FieldOptions_CType["STRING"] = 0] = "STRING"; FieldOptions_CType[FieldOptions_CType["CORD"] = 1] = "CORD"; FieldOptions_CType[FieldOptions_CType["STRING_PIECE"] = 2] = "STRING_PIECE"; })(FieldOptions_CType || (exports.FieldOptions_CType = FieldOptions_CType = {})); function fieldOptions_CTypeFromJSON(object) { switch (object) { case 0: case "STRING": return FieldOptions_CType.STRING; case 1: case "CORD": return FieldOptions_CType.CORD; case 2: case "STRING_PIECE": return FieldOptions_CType.STRING_PIECE; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType"); } } function fieldOptions_CTypeToJSON(object) { switch (object) { case FieldOptions_CType.STRING: return "STRING"; case FieldOptions_CType.CORD: return "CORD"; case FieldOptions_CType.STRING_PIECE: return "STRING_PIECE"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType"); } } var FieldOptions_JSType; (function (FieldOptions_JSType) { /** JS_NORMAL - Use the default type. */ FieldOptions_JSType[FieldOptions_JSType["JS_NORMAL"] = 0] = "JS_NORMAL"; /** JS_STRING - Use JavaScript strings. */ FieldOptions_JSType[FieldOptions_JSType["JS_STRING"] = 1] = "JS_STRING"; /** JS_NUMBER - Use JavaScript numbers. */ FieldOptions_JSType[FieldOptions_JSType["JS_NUMBER"] = 2] = "JS_NUMBER"; })(FieldOptions_JSType || (exports.FieldOptions_JSType = FieldOptions_JSType = {})); function fieldOptions_JSTypeFromJSON(object) { switch (object) { case 0: case "JS_NORMAL": return FieldOptions_JSType.JS_NORMAL; case 1: case "JS_STRING": return FieldOptions_JSType.JS_STRING; case 2: case "JS_NUMBER": return FieldOptions_JSType.JS_NUMBER; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType"); } } function fieldOptions_JSTypeToJSON(object) { switch (object) { case FieldOptions_JSType.JS_NORMAL: return "JS_NORMAL"; case FieldOptions_JSType.JS_STRING: return "JS_STRING"; case FieldOptions_JSType.JS_NUMBER: return "JS_NUMBER"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType"); } } /** * Is this method side-effect-free (or safe in HTTP parlance), or idempotent, * or neither? HTTP based RPC implementation may choose GET verb for safe * methods, and PUT verb for idempotent methods instead of the default POST. */ var MethodOptions_IdempotencyLevel; (function (MethodOptions_IdempotencyLevel) { MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = 0] = "IDEMPOTENCY_UNKNOWN"; /** NO_SIDE_EFFECTS - implies idempotent */ MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["NO_SIDE_EFFECTS"] = 1] = "NO_SIDE_EFFECTS"; /** IDEMPOTENT - idempotent, but may have side effects */ MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENT"] = 2] = "IDEMPOTENT"; })(MethodOptions_IdempotencyLevel || (exports.MethodOptions_IdempotencyLevel = MethodOptions_IdempotencyLevel = {})); function methodOptions_IdempotencyLevelFromJSON(object) { switch (object) { case 0: case "IDEMPOTENCY_UNKNOWN": return MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN; case 1: case "NO_SIDE_EFFECTS": return MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS; case 2: case "IDEMPOTENT": return MethodOptions_IdempotencyLevel.IDEMPOTENT; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel"); } } function methodOptions_IdempotencyLevelToJSON(object) { switch (object) { case MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN: return "IDEMPOTENCY_UNKNOWN"; case MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS: return "NO_SIDE_EFFECTS"; case MethodOptions_IdempotencyLevel.IDEMPOTENT: return "IDEMPOTENT"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel"); } } function createBaseFileDescriptorSet() { return { file: [] }; } exports.FileDescriptorSet = { fromJSON(object) { return { file: Array.isArray(object?.file) ? object.file.map((e) => exports.FileDescriptorProto.fromJSON(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.file) { obj.file = message.file.map((e) => e ? exports.FileDescriptorProto.toJSON(e) : undefined); } else { obj.file = []; } return obj; }, }; function createBaseFileDescriptorProto() { return { name: "", package: "", dependency: [], publicDependency: [], weakDependency: [], messageType: [], enumType: [], service: [], extension: [], options: undefined, sourceCodeInfo: undefined, syntax: "", }; } exports.FileDescriptorProto = { fromJSON(object) { return { name: isSet(object.name) ? String(object.name) : "", package: isSet(object.package) ? String(object.package) : "", dependency: Array.isArray(object?.dependency) ? object.dependency.map((e) => String(e)) : [], publicDependency: Array.isArray(object?.publicDependency) ? object.publicDependency.map((e) => Number(e)) : [], weakDependency: Array.isArray(object?.weakDependency) ? object.weakDependency.map((e) => Number(e)) : [], messageType: Array.isArray(object?.messageType) ? object.messageType.map((e) => exports.DescriptorProto.fromJSON(e)) : [], enumType: Array.isArray(object?.enumType) ? object.enumType.map((e) => exports.EnumDescriptorProto.fromJSON(e)) : [], service: Array.isArray(object?.service) ? object.service.map((e) => exports.ServiceDescriptorProto.fromJSON(e)) : [], extension: Array.isArray(object?.extension) ? object.extension.map((e) => exports.FieldDescriptorProto.fromJSON(e)) : [], options: isSet(object.options) ? exports.FileOptions.fromJSON(object.options) : undefined, sourceCodeInfo: isSet(object.sourceCodeInfo) ? exports.SourceCodeInfo.fromJSON(object.sourceCodeInfo) : undefined, syntax: isSet(object.syntax) ? String(object.syntax) : "", }; }, toJSON(message) { const obj = {}; message.name !== undefined && (obj.name = message.name); message.package !== undefined && (obj.package = message.package); if (message.dependency) { obj.dependency = message.dependency.map((e) => e); } else { obj.dependency = []; } if (message.publicDependency) { obj.publicDependency = message.publicDependency.map((e) => Math.round(e)); } else { obj.publicDependency = []; } if (message.weakDependency) { obj.weakDependency = message.weakDependency.map((e) => Math.round(e)); } else { obj.weakDependency = []; } if (message.messageType) { obj.messageType = message.messageType.map((e) => e ? exports.DescriptorProto.toJSON(e) : undefined); } else { obj.messageType = []; } if (message.enumType) { obj.enumType = message.enumType.map((e) => e ? exports.EnumDescriptorProto.toJSON(e) : undefined); } else { obj.enumType = []; } if (message.service) { obj.service = message.service.map((e) => e ? exports.ServiceDescriptorProto.toJSON(e) : undefined); } else { obj.service = []; } if (message.extension) { obj.extension = message.extension.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined); } else { obj.extension = []; } message.options !== undefined && (obj.options = message.options ? exports.FileOptions.toJSON(message.options) : undefined); message.sourceCodeInfo !== undefined && (obj.sourceCodeInfo = message.sourceCodeInfo ? exports.SourceCodeInfo.toJSON(message.sourceCodeInfo) : undefined); message.syntax !== undefined && (obj.syntax = message.syntax); return obj; }, }; function createBaseDescriptorProto() { return { name: "", field: [], extension: [], nestedType: [], enumType: [], extensionRange: [], oneofDecl: [], options: undefined, reservedRange: [], reservedName: [], }; } exports.DescriptorProto = { fromJSON(object) { return { name: isSet(object.name) ? String(object.name) : "", field: Array.isArray(object?.field) ? object.field.map((e) => exports.FieldDescriptorProto.fromJSON(e)) : [], extension: Array.isArray(object?.extension) ? object.extension.map((e) => exports.FieldDescriptorProto.fromJSON(e)) : [], nestedType: Array.isArray(object?.nestedType) ? object.nestedType.map((e) => exports.DescriptorProto.fromJSON(e)) : [], enumType: Array.isArray(object?.enumType) ? object.enumType.map((e) => exports.EnumDescriptorProto.fromJSON(e)) : [], extensionRange: Array.isArray(object?.extensionRange) ? object.extensionRange.map((e) => exports.DescriptorProto_ExtensionRange.fromJSON(e)) : [], oneofDecl: Array.isArray(object?.oneofDecl) ? object.oneofDecl.map((e) => exports.OneofDescriptorProto.fromJSON(e)) : [], options: isSet(object.options) ? exports.MessageOptions.fromJSON(object.options) : undefined, reservedRange: Array.isArray(object?.reservedRange) ? object.reservedRange.map((e) => exports.DescriptorProto_ReservedRange.fromJSON(e)) : [], reservedName: Array.isArray(object?.reservedName) ? object.reservedName.map((e) => String(e)) : [], }; }, toJSON(message) { const obj = {}; message.name !== undefined && (obj.name = message.name); if (message.field) { obj.field = message.field.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined); } else { obj.field = []; } if (message.extension) { obj.extension = message.extension.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined); } else { obj.extension = []; } if (message.nestedType) { obj.nestedType = message.nestedType.map((e) => e ? exports.DescriptorProto.toJSON(e) : undefined); } else { obj.nestedType = []; } if (message.enumType) { obj.enumType = message.enumType.map((e) => e ? exports.EnumDescriptorProto.toJSON(e) : undefined); } else { obj.enumType = []; } if (message.extensionRange) { obj.extensionRange = message.extensionRange.map((e) => e ? exports.DescriptorProto_ExtensionRange.toJSON(e) : undefined); } else { obj.extensionRange = []; } if (message.oneofDecl) { obj.oneofDecl = message.oneofDecl.map((e) => e ? exports.OneofDescriptorProto.toJSON(e) : undefined); } else { obj.oneofDecl = []; } message.options !== undefined && (obj.options = message.options ? exports.MessageOptions.toJSON(message.options) : undefined); if (message.reservedRange) { obj.reservedRange = message.reservedRange.map((e) => e ? exports.DescriptorProto_ReservedRange.toJSON(e) : undefined); } else { obj.reservedRange = []; } if (message.reservedName) { obj.reservedName = message.reservedName.map((e) => e); } else { obj.reservedName = []; } return obj; }, }; function createBaseDescriptorProto_ExtensionRange() { return { start: 0, end: 0, options: undefined }; } exports.DescriptorProto_ExtensionRange = { fromJSON(object) { return { start: isSet(object.start) ? Number(object.start) : 0, end: isSet(object.end) ? Number(object.end) : 0, options: isSet(object.options) ? exports.ExtensionRangeOptions.fromJSON(object.options) : undefined, }; }, toJSON(message) { const obj = {}; message.start !== undefined && (obj.start = Math.round(message.start)); message.end !== undefined && (obj.end = Math.round(message.end)); message.options !== undefined && (obj.options = message.options ? exports.ExtensionRangeOptions.toJSON(message.options) : undefined); return obj; }, }; function createBaseDescriptorProto_ReservedRange() { return { start: 0, end: 0 }; } exports.DescriptorProto_ReservedRange = { fromJSON(object) { return { start: isSet(object.start) ? Number(object.start) : 0, end: isSet(object.end) ? Number(object.end) : 0 }; }, toJSON(message) { const obj = {}; message.start !== undefined && (obj.start = Math.round(message.start)); message.end !== undefined && (obj.end = Math.round(message.end)); return obj; }, }; function createBaseExtensionRangeOptions() { return { uninterpretedOption: [] }; } exports.ExtensionRangeOptions = { fromJSON(object) { return { uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseFieldDescriptorProto() { return { name: "", number: 0, label: 1, type: 1, typeName: "", extendee: "", defaultValue: "", oneofIndex: 0, jsonName: "", options: undefined, proto3Optional: false, }; } exports.FieldDescriptorProto = { fromJSON(object) { return { name: isSet(object.name) ? String(object.name) : "", number: isSet(object.number) ? Number(object.number) : 0, label: isSet(object.label) ? fieldDescriptorProto_LabelFromJSON(object.label) : 1, type: isSet(object.type) ? fieldDescriptorProto_TypeFromJSON(object.type) : 1, typeName: isSet(object.typeName) ? String(object.typeName) : "", extendee: isSet(object.extendee) ? String(object.extendee) : "", defaultValue: isSet(object.defaultValue) ? String(object.defaultValue) : "", oneofIndex: isSet(object.oneofIndex) ? Number(object.oneofIndex) : 0, jsonName: isSet(object.jsonName) ? String(object.jsonName) : "", options: isSet(object.options) ? exports.FieldOptions.fromJSON(object.options) : undefined, proto3Optional: isSet(object.proto3Optional) ? Boolean(object.proto3Optional) : false, }; }, toJSON(message) { const obj = {}; message.name !== undefined && (obj.name = message.name); message.number !== undefined && (obj.number = Math.round(message.number)); message.label !== undefined && (obj.label = fieldDescriptorProto_LabelToJSON(message.label)); message.type !== undefined && (obj.type = fieldDescriptorProto_TypeToJSON(message.type)); message.typeName !== undefined && (obj.typeName = message.typeName); message.extendee !== undefined && (obj.extendee = message.extendee); message.defaultValue !== undefined && (obj.defaultValue = message.defaultValue); message.oneofIndex !== undefined && (obj.oneofIndex = Math.round(message.oneofIndex)); message.jsonName !== undefined && (obj.jsonName = message.jsonName); message.options !== undefined && (obj.options = message.options ? exports.FieldOptions.toJSON(message.options) : undefined); message.proto3Optional !== undefined && (obj.proto3Optional = message.proto3Optional); return obj; }, }; function createBaseOneofDescriptorProto() { return { name: "", options: undefined }; } exports.OneofDescriptorProto = { fromJSON(object) { return { name: isSet(object.name) ? String(object.name) : "", options: isSet(object.options) ? exports.OneofOptions.fromJSON(object.options) : undefined, }; }, toJSON(message) { const obj = {}; message.name !== undefined && (obj.name = message.name); message.options !== undefined && (obj.options = message.options ? exports.OneofOptions.toJSON(message.options) : undefined); return obj; }, }; function createBaseEnumDescriptorProto() { return { name: "", value: [], options: undefined, reservedRange: [], reservedName: [] }; } exports.EnumDescriptorProto = { fromJSON(object) { return { name: isSet(object.name) ? String(object.name) : "", value: Array.isArray(object?.value) ? object.value.map((e) => exports.EnumValueDescriptorProto.fromJSON(e)) : [], options: isSet(object.options) ? exports.EnumOptions.fromJSON(object.options) : undefined, reservedRange: Array.isArray(object?.reservedRange) ? object.reservedRange.map((e) => exports.EnumDescriptorProto_EnumReservedRange.fromJSON(e)) : [], reservedName: Array.isArray(object?.reservedName) ? object.reservedName.map((e) => String(e)) : [], }; }, toJSON(message) { const obj = {}; message.name !== undefined && (obj.name = message.name); if (message.value) { obj.value = message.value.map((e) => e ? exports.EnumValueDescriptorProto.toJSON(e) : undefined); } else { obj.value = []; } message.options !== undefined && (obj.options = message.options ? exports.EnumOptions.toJSON(message.options) : undefined); if (message.reservedRange) { obj.reservedRange = message.reservedRange.map((e) => e ? exports.EnumDescriptorProto_EnumReservedRange.toJSON(e) : undefined); } else { obj.reservedRange = []; } if (message.reservedName) { obj.reservedName = message.reservedName.map((e) => e); } else { obj.reservedName = []; } return obj; }, }; function createBaseEnumDescriptorProto_EnumReservedRange() { return { start: 0, end: 0 }; } exports.EnumDescriptorProto_EnumReservedRange = { fromJSON(object) { return { start: isSet(object.start) ? Number(object.start) : 0, end: isSet(object.end) ? Number(object.end) : 0 }; }, toJSON(message) { const obj = {}; message.start !== undefined && (obj.start = Math.round(message.start)); message.end !== undefined && (obj.end = Math.round(message.end)); return obj; }, }; function createBaseEnumValueDescriptorProto() { return { name: "", number: 0, options: undefined }; } exports.EnumValueDescriptorProto = { fromJSON(object) { return { name: isSet(object.name) ? String(object.name) : "", number: isSet(object.number) ? Number(object.number) : 0, options: isSet(object.options) ? exports.EnumValueOptions.fromJSON(object.options) : undefined, }; }, toJSON(message) { const obj = {}; message.name !== undefined && (obj.name = message.name); message.number !== undefined && (obj.number = Math.round(message.number)); message.options !== undefined && (obj.options = message.options ? exports.EnumValueOptions.toJSON(message.options) : undefined); return obj; }, }; function createBaseServiceDescriptorProto() { return { name: "", method: [], options: undefined }; } exports.ServiceDescriptorProto = { fromJSON(object) { return { name: isSet(object.name) ? String(object.name) : "", method: Array.isArray(object?.method) ? object.method.map((e) => exports.MethodDescriptorProto.fromJSON(e)) : [], options: isSet(object.options) ? exports.ServiceOptions.fromJSON(object.options) : undefined, }; }, toJSON(message) { const obj = {}; message.name !== undefined && (obj.name = message.name); if (message.method) { obj.method = message.method.map((e) => e ? exports.MethodDescriptorProto.toJSON(e) : undefined); } else { obj.method = []; } message.options !== undefined && (obj.options = message.options ? exports.ServiceOptions.toJSON(message.options) : undefined); return obj; }, }; function createBaseMethodDescriptorProto() { return { name: "", inputType: "", outputType: "", options: undefined, clientStreaming: false, serverStreaming: false, }; } exports.MethodDescriptorProto = { fromJSON(object) { return { name: isSet(object.name) ? String(object.name) : "", inputType: isSet(object.inputType) ? String(object.inputType) : "", outputType: isSet(object.outputType) ? String(object.outputType) : "", options: isSet(object.options) ? exports.MethodOptions.fromJSON(object.options) : undefined, clientStreaming: isSet(object.clientStreaming) ? Boolean(object.clientStreaming) : false, serverStreaming: isSet(object.serverStreaming) ? Boolean(object.serverStreaming) : false, }; }, toJSON(message) { const obj = {}; message.name !== undefined && (obj.name = message.name); message.inputType !== undefined && (obj.inputType = message.inputType); message.outputType !== undefined && (obj.outputType = message.outputType); message.options !== undefined && (obj.options = message.options ? exports.MethodOptions.toJSON(message.options) : undefined); message.clientStreaming !== undefined && (obj.clientStreaming = message.clientStreaming); message.serverStreaming !== undefined && (obj.serverStreaming = message.serverStreaming); return obj; }, }; function createBaseFileOptions() { return { javaPackage: "", javaOuterClassname: "", javaMultipleFiles: false, javaGenerateEqualsAndHash: false, javaStringCheckUtf8: false, optimizeFor: 1, goPackage: "", ccGenericServices: false, javaGenericServices: false, pyGenericServices: false, phpGenericServices: false, deprecated: false, ccEnableArenas: false, objcClassPrefix: "", csharpNamespace: "", swiftPrefix: "", phpClassPrefix: "", phpNamespace: "", phpMetadataNamespace: "", rubyPackage: "", uninterpretedOption: [], }; } exports.FileOptions = { fromJSON(object) { return { javaPackage: isSet(object.javaPackage) ? String(object.javaPackage) : "", javaOuterClassname: isSet(object.javaOuterClassname) ? String(object.javaOuterClassname) : "", javaMultipleFiles: isSet(object.javaMultipleFiles) ? Boolean(object.javaMultipleFiles) : false, javaGenerateEqualsAndHash: isSet(object.javaGenerateEqualsAndHash) ? Boolean(object.javaGenerateEqualsAndHash) : false, javaStringCheckUtf8: isSet(object.javaStringCheckUtf8) ? Boolean(object.javaStringCheckUtf8) : false, optimizeFor: isSet(object.optimizeFor) ? fileOptions_OptimizeModeFromJSON(object.optimizeFor) : 1, goPackage: isSet(object.goPackage) ? String(object.goPackage) : "", ccGenericServices: isSet(object.ccGenericServices) ? Boolean(object.ccGenericServices) : false, javaGenericServices: isSet(object.javaGenericServices) ? Boolean(object.javaGenericServices) : false, pyGenericServices: isSet(object.pyGenericServices) ? Boolean(object.pyGenericServices) : false, phpGenericServices: isSet(object.phpGenericServices) ? Boolean(object.phpGenericServices) : false, deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, ccEnableArenas: isSet(object.ccEnableArenas) ? Boolean(object.ccEnableArenas) : false, objcClassPrefix: isSet(object.objcClassPrefix) ? String(object.objcClassPrefix) : "", csharpNamespace: isSet(object.csharpNamespace) ? String(object.csharpNamespace) : "", swiftPrefix: isSet(object.swiftPrefix) ? String(object.swiftPrefix) : "", phpClassPrefix: isSet(object.phpClassPrefix) ? String(object.phpClassPrefix) : "", phpNamespace: isSet(object.phpNamespace) ? String(object.phpNamespace) : "", phpMetadataNamespace: isSet(object.phpMetadataNamespace) ? String(object.phpMetadataNamespace) : "", rubyPackage: isSet(object.rubyPackage) ? String(object.rubyPackage) : "", uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.javaPackage !== undefined && (obj.javaPackage = message.javaPackage); message.javaOuterClassname !== undefined && (obj.javaOuterClassname = message.javaOuterClassname); message.javaMultipleFiles !== undefined && (obj.javaMultipleFiles = message.javaMultipleFiles); message.javaGenerateEqualsAndHash !== undefined && (obj.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash); message.javaStringCheckUtf8 !== undefined && (obj.javaStringCheckUtf8 = message.javaStringCheckUtf8); message.optimizeFor !== undefined && (obj.optimizeFor = fileOptions_OptimizeModeToJSON(message.optimizeFor)); message.goPackage !== undefined && (obj.goPackage = message.goPackage); message.ccGenericServices !== undefined && (obj.ccGenericServices = message.ccGenericServices); message.javaGenericServices !== undefined && (obj.javaGenericServices = message.javaGenericServices); message.pyGenericServices !== undefined && (obj.pyGenericServices = message.pyGenericServices); message.phpGenericServices !== undefined && (obj.phpGenericServices = message.phpGenericServices); message.deprecated !== undefined && (obj.deprecated = message.deprecated); message.ccEnableArenas !== undefined && (obj.ccEnableArenas = message.ccEnableArenas); message.objcClassPrefix !== undefined && (obj.objcClassPrefix = message.objcClassPrefix); message.csharpNamespace !== undefined && (obj.csharpNamespace = message.csharpNamespace); message.swiftPrefix !== undefined && (obj.swiftPrefix = message.swiftPrefix); message.phpClassPrefix !== undefined && (obj.phpClassPrefix = message.phpClassPrefix); message.phpNamespace !== undefined && (obj.phpNamespace = message.phpNamespace); message.phpMetadataNamespace !== undefined && (obj.phpMetadataNamespace = message.phpMetadataNamespace); message.rubyPackage !== undefined && (obj.rubyPackage = message.rubyPackage); if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseMessageOptions() { return { messageSetWireFormat: false, noStandardDescriptorAccessor: false, deprecated: false, mapEntry: false, uninterpretedOption: [], }; } exports.MessageOptions = { fromJSON(object) { return { messageSetWireFormat: isSet(object.messageSetWireFormat) ? Boolean(object.messageSetWireFormat) : false, noStandardDescriptorAccessor: isSet(object.noStandardDescriptorAccessor) ? Boolean(object.noStandardDescriptorAccessor) : false, deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, mapEntry: isSet(object.mapEntry) ? Boolean(object.mapEntry) : false, uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.messageSetWireFormat !== undefined && (obj.messageSetWireFormat = message.messageSetWireFormat); message.noStandardDescriptorAccessor !== undefined && (obj.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor); message.deprecated !== undefined && (obj.deprecated = message.deprecated); message.mapEntry !== undefined && (obj.mapEntry = message.mapEntry); if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseFieldOptions() { return { ctype: 0, packed: false, jstype: 0, lazy: false, unverifiedLazy: false, deprecated: false, weak: false, uninterpretedOption: [], }; } exports.FieldOptions = { fromJSON(object) { return { ctype: isSet(object.ctype) ? fieldOptions_CTypeFromJSON(object.ctype) : 0, packed: isSet(object.packed) ? Boolean(object.packed) : false, jstype: isSet(object.jstype) ? fieldOptions_JSTypeFromJSON(object.jstype) : 0, lazy: isSet(object.lazy) ? Boolean(object.lazy) : false, unverifiedLazy: isSet(object.unverifiedLazy) ? Boolean(object.unverifiedLazy) : false, deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, weak: isSet(object.weak) ? Boolean(object.weak) : false, uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.ctype !== undefined && (obj.ctype = fieldOptions_CTypeToJSON(message.ctype)); message.packed !== undefined && (obj.packed = message.packed); message.jstype !== undefined && (obj.jstype = fieldOptions_JSTypeToJSON(message.jstype)); message.lazy !== undefined && (obj.lazy = message.lazy); message.unverifiedLazy !== undefined && (obj.unverifiedLazy = message.unverifiedLazy); message.deprecated !== undefined && (obj.deprecated = message.deprecated); message.weak !== undefined && (obj.weak = message.weak); if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseOneofOptions() { return { uninterpretedOption: [] }; } exports.OneofOptions = { fromJSON(object) { return { uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseEnumOptions() { return { allowAlias: false, deprecated: false, uninterpretedOption: [] }; } exports.EnumOptions = { fromJSON(object) { return { allowAlias: isSet(object.allowAlias) ? Boolean(object.allowAlias) : false, deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.allowAlias !== undefined && (obj.allowAlias = message.allowAlias); message.deprecated !== undefined && (obj.deprecated = message.deprecated); if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseEnumValueOptions() { return { deprecated: false, uninterpretedOption: [] }; } exports.EnumValueOptions = { fromJSON(object) { return { deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.deprecated !== undefined && (obj.deprecated = message.deprecated); if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseServiceOptions() { return { deprecated: false, uninterpretedOption: [] }; } exports.ServiceOptions = { fromJSON(object) { return { deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.deprecated !== undefined && (obj.deprecated = message.deprecated); if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseMethodOptions() { return { deprecated: false, idempotencyLevel: 0, uninterpretedOption: [] }; } exports.MethodOptions = { fromJSON(object) { return { deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, idempotencyLevel: isSet(object.idempotencyLevel) ? methodOptions_IdempotencyLevelFromJSON(object.idempotencyLevel) : 0, uninterpretedOption: Array.isArray(object?.uninterpretedOption) ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.deprecated !== undefined && (obj.deprecated = message.deprecated); message.idempotencyLevel !== undefined && (obj.idempotencyLevel = methodOptions_IdempotencyLevelToJSON(message.idempotencyLevel)); if (message.uninterpretedOption) { obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); } else { obj.uninterpretedOption = []; } return obj; }, }; function createBaseUninterpretedOption() { return { name: [], identifierValue: "", positiveIntValue: "0", negativeIntValue: "0", doubleValue: 0, stringValue: Buffer.alloc(0), aggregateValue: "", }; } exports.UninterpretedOption = { fromJSON(object) { return { name: Array.isArray(object?.name) ? object.name.map((e) => exports.UninterpretedOption_NamePart.fromJSON(e)) : [], identifierValue: isSet(object.identifierValue) ? String(object.identifierValue) : "", positiveIntValue: isSet(object.positiveIntValue) ? String(object.positiveIntValue) : "0", negativeIntValue: isSet(object.negativeIntValue) ? String(object.negativeIntValue) : "0", doubleValue: isSet(object.doubleValue) ? Number(object.doubleValue) : 0, stringValue: isSet(object.stringValue) ? Buffer.from(bytesFromBase64(object.stringValue)) : Buffer.alloc(0), aggregateValue: isSet(object.aggregateValue) ? String(object.aggregateValue) : "", }; }, toJSON(message) { const obj = {}; if (message.name) { obj.name = message.name.map((e) => e ? exports.UninterpretedOption_NamePart.toJSON(e) : undefined); } else { obj.name = []; } message.identifierValue !== undefined && (obj.identifierValue = message.identifierValue); message.positiveIntValue !== undefined && (obj.positiveIntValue = message.positiveIntValue); message.negativeIntValue !== undefined && (obj.negativeIntValue = message.negativeIntValue); message.doubleValue !== undefined && (obj.doubleValue = message.doubleValue); message.stringValue !== undefined && (obj.stringValue = base64FromBytes(message.stringValue !== undefined ? message.stringValue : Buffer.alloc(0))); message.aggregateValue !== undefined && (obj.aggregateValue = message.aggregateValue); return obj; }, }; function createBaseUninterpretedOption_NamePart() { return { namePart: "", isExtension: false }; } exports.UninterpretedOption_NamePart = { fromJSON(object) { return { namePart: isSet(object.namePart) ? String(object.namePart) : "", isExtension: isSet(object.isExtension) ? Boolean(object.isExtension) : false, }; }, toJSON(message) { const obj = {}; message.namePart !== undefined && (obj.namePart = message.namePart); message.isExtension !== undefined && (obj.isExtension = message.isExtension); return obj; }, }; function createBaseSourceCodeInfo() { return { location: [] }; } exports.SourceCodeInfo = { fromJSON(object) { return { location: Array.isArray(object?.location) ? object.location.map((e) => exports.SourceCodeInfo_Location.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.location) { obj.location = message.location.map((e) => e ? exports.SourceCodeInfo_Location.toJSON(e) : undefined); } else { obj.location = []; } return obj; }, }; function createBaseSourceCodeInfo_Location() { return { path: [], span: [], leadingComments: "", trailingComments: "", leadingDetachedComments: [] }; } exports.SourceCodeInfo_Location = { fromJSON(object) { return { path: Array.isArray(object?.path) ? object.path.map((e) => Number(e)) : [], span: Array.isArray(object?.span) ? object.span.map((e) => Number(e)) : [], leadingComments: isSet(object.leadingComments) ? String(object.leadingComments) : "", trailingComments: isSet(object.trailingComments) ? String(object.trailingComments) : "", leadingDetachedComments: Array.isArray(object?.leadingDetachedComments) ? object.leadingDetachedComments.map((e) => String(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.path) { obj.path = message.path.map((e) => Math.round(e)); } else { obj.path = []; } if (message.span) { obj.span = message.span.map((e) => Math.round(e)); } else { obj.span = []; } message.leadingComments !== undefined && (obj.leadingComments = message.leadingComments); message.trailingComments !== undefined && (obj.trailingComments = message.trailingComments); if (message.leadingDetachedComments) { obj.leadingDetachedComments = message.leadingDetachedComments.map((e) => e); } else { obj.leadingDetachedComments = []; } return obj; }, }; function createBaseGeneratedCodeInfo() { return { annotation: [] }; } exports.GeneratedCodeInfo = { fromJSON(object) { return { annotation: Array.isArray(object?.annotation) ? object.annotation.map((e) => exports.GeneratedCodeInfo_Annotation.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.annotation) { obj.annotation = message.annotation.map((e) => e ? exports.GeneratedCodeInfo_Annotation.toJSON(e) : undefined); } else { obj.annotation = []; } return obj; }, }; function createBaseGeneratedCodeInfo_Annotation() { return { path: [], sourceFile: "", begin: 0, end: 0 }; } exports.GeneratedCodeInfo_Annotation = { fromJSON(object) { return { path: Array.isArray(object?.path) ? object.path.map((e) => Number(e)) : [], sourceFile: isSet(object.sourceFile) ? String(object.sourceFile) : "", begin: isSet(object.begin) ? Number(object.begin) : 0, end: isSet(object.end) ? Number(object.end) : 0, }; }, toJSON(message) { const obj = {}; if (message.path) { obj.path = message.path.map((e) => Math.round(e)); } else { obj.path = []; } message.sourceFile !== undefined && (obj.sourceFile = message.sourceFile); message.begin !== undefined && (obj.begin = Math.round(message.begin)); message.end !== undefined && (obj.end = Math.round(message.end)); return obj; }, }; var tsProtoGlobalThis = (() => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } throw "Unable to locate global object"; })(); function bytesFromBase64(b64) { if (tsProtoGlobalThis.Buffer) { return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); } else { const bin = tsProtoGlobalThis.atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } } function base64FromBytes(arr) { if (tsProtoGlobalThis.Buffer) { return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); } else { const bin = []; arr.forEach((byte) => { bin.push(String.fromCharCode(byte)); }); return tsProtoGlobalThis.btoa(bin.join("")); } } function isSet(value) { return value !== null && value !== undefined; } "use strict"; /* eslint-disable */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Timestamp = void 0; function createBaseTimestamp() { return { seconds: "0", nanos: 0 }; } exports.Timestamp = { fromJSON(object) { return { seconds: isSet(object.seconds) ? String(object.seconds) : "0", nanos: isSet(object.nanos) ? Number(object.nanos) : 0, }; }, toJSON(message) { const obj = {}; message.seconds !== undefined && (obj.seconds = message.seconds); message.nanos !== undefined && (obj.nanos = Math.round(message.nanos)); return obj; }, }; function isSet(value) { return value !== null && value !== undefined; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Bundle = exports.VerificationMaterial = exports.TimestampVerificationData = void 0; /* eslint-disable */ const envelope_1 = require("./envelope"); const sigstore_common_1 = require("./sigstore_common"); const sigstore_rekor_1 = require("./sigstore_rekor"); function createBaseTimestampVerificationData() { return { rfc3161Timestamps: [] }; } exports.TimestampVerificationData = { fromJSON(object) { return { rfc3161Timestamps: Array.isArray(object?.rfc3161Timestamps) ? object.rfc3161Timestamps.map((e) => sigstore_common_1.RFC3161SignedTimestamp.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.rfc3161Timestamps) { obj.rfc3161Timestamps = message.rfc3161Timestamps.map((e) => e ? sigstore_common_1.RFC3161SignedTimestamp.toJSON(e) : undefined); } else { obj.rfc3161Timestamps = []; } return obj; }, }; function createBaseVerificationMaterial() { return { content: undefined, tlogEntries: [], timestampVerificationData: undefined }; } exports.VerificationMaterial = { fromJSON(object) { return { content: isSet(object.publicKey) ? { $case: "publicKey", publicKey: sigstore_common_1.PublicKeyIdentifier.fromJSON(object.publicKey) } : isSet(object.x509CertificateChain) ? { $case: "x509CertificateChain", x509CertificateChain: sigstore_common_1.X509CertificateChain.fromJSON(object.x509CertificateChain), } : isSet(object.certificate) ? { $case: "certificate", certificate: sigstore_common_1.X509Certificate.fromJSON(object.certificate) } : undefined, tlogEntries: Array.isArray(object?.tlogEntries) ? object.tlogEntries.map((e) => sigstore_rekor_1.TransparencyLogEntry.fromJSON(e)) : [], timestampVerificationData: isSet(object.timestampVerificationData) ? exports.TimestampVerificationData.fromJSON(object.timestampVerificationData) : undefined, }; }, toJSON(message) { const obj = {}; message.content?.$case === "publicKey" && (obj.publicKey = message.content?.publicKey ? sigstore_common_1.PublicKeyIdentifier.toJSON(message.content?.publicKey) : undefined); message.content?.$case === "x509CertificateChain" && (obj.x509CertificateChain = message.content?.x509CertificateChain ? sigstore_common_1.X509CertificateChain.toJSON(message.content?.x509CertificateChain) : undefined); message.content?.$case === "certificate" && (obj.certificate = message.content?.certificate ? sigstore_common_1.X509Certificate.toJSON(message.content?.certificate) : undefined); if (message.tlogEntries) { obj.tlogEntries = message.tlogEntries.map((e) => e ? sigstore_rekor_1.TransparencyLogEntry.toJSON(e) : undefined); } else { obj.tlogEntries = []; } message.timestampVerificationData !== undefined && (obj.timestampVerificationData = message.timestampVerificationData ? exports.TimestampVerificationData.toJSON(message.timestampVerificationData) : undefined); return obj; }, }; function createBaseBundle() { return { mediaType: "", verificationMaterial: undefined, content: undefined }; } exports.Bundle = { fromJSON(object) { return { mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", verificationMaterial: isSet(object.verificationMaterial) ? exports.VerificationMaterial.fromJSON(object.verificationMaterial) : undefined, content: isSet(object.messageSignature) ? { $case: "messageSignature", messageSignature: sigstore_common_1.MessageSignature.fromJSON(object.messageSignature) } : isSet(object.dsseEnvelope) ? { $case: "dsseEnvelope", dsseEnvelope: envelope_1.Envelope.fromJSON(object.dsseEnvelope) } : undefined, }; }, toJSON(message) { const obj = {}; message.mediaType !== undefined && (obj.mediaType = message.mediaType); message.verificationMaterial !== undefined && (obj.verificationMaterial = message.verificationMaterial ? exports.VerificationMaterial.toJSON(message.verificationMaterial) : undefined); message.content?.$case === "messageSignature" && (obj.messageSignature = message.content?.messageSignature ? sigstore_common_1.MessageSignature.toJSON(message.content?.messageSignature) : undefined); message.content?.$case === "dsseEnvelope" && (obj.dsseEnvelope = message.content?.dsseEnvelope ? envelope_1.Envelope.toJSON(message.content?.dsseEnvelope) : undefined); return obj; }, }; function isSet(value) { return value !== null && value !== undefined; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TimeRange = exports.X509CertificateChain = exports.SubjectAlternativeName = exports.X509Certificate = exports.DistinguishedName = exports.ObjectIdentifierValuePair = exports.ObjectIdentifier = exports.PublicKeyIdentifier = exports.PublicKey = exports.RFC3161SignedTimestamp = exports.LogId = exports.MessageSignature = exports.HashOutput = exports.SubjectAlternativeNameType = exports.PublicKeyDetails = exports.HashAlgorithm = void 0; exports.hashAlgorithmFromJSON = hashAlgorithmFromJSON; exports.hashAlgorithmToJSON = hashAlgorithmToJSON; exports.publicKeyDetailsFromJSON = publicKeyDetailsFromJSON; exports.publicKeyDetailsToJSON = publicKeyDetailsToJSON; exports.subjectAlternativeNameTypeFromJSON = subjectAlternativeNameTypeFromJSON; exports.subjectAlternativeNameTypeToJSON = subjectAlternativeNameTypeToJSON; /* eslint-disable */ const timestamp_1 = require("./google/protobuf/timestamp"); /** * Only a subset of the secure hash standard algorithms are supported. * See for more * details. * UNSPECIFIED SHOULD not be used, primary reason for inclusion is to force * any proto JSON serialization to emit the used hash algorithm, as default * option is to *omit* the default value of an enum (which is the first * value, represented by '0'. */ var HashAlgorithm; (function (HashAlgorithm) { HashAlgorithm[HashAlgorithm["HASH_ALGORITHM_UNSPECIFIED"] = 0] = "HASH_ALGORITHM_UNSPECIFIED"; HashAlgorithm[HashAlgorithm["SHA2_256"] = 1] = "SHA2_256"; HashAlgorithm[HashAlgorithm["SHA2_384"] = 2] = "SHA2_384"; HashAlgorithm[HashAlgorithm["SHA2_512"] = 3] = "SHA2_512"; HashAlgorithm[HashAlgorithm["SHA3_256"] = 4] = "SHA3_256"; HashAlgorithm[HashAlgorithm["SHA3_384"] = 5] = "SHA3_384"; })(HashAlgorithm || (exports.HashAlgorithm = HashAlgorithm = {})); function hashAlgorithmFromJSON(object) { switch (object) { case 0: case "HASH_ALGORITHM_UNSPECIFIED": return HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED; case 1: case "SHA2_256": return HashAlgorithm.SHA2_256; case 2: case "SHA2_384": return HashAlgorithm.SHA2_384; case 3: case "SHA2_512": return HashAlgorithm.SHA2_512; case 4: case "SHA3_256": return HashAlgorithm.SHA3_256; case 5: case "SHA3_384": return HashAlgorithm.SHA3_384; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); } } function hashAlgorithmToJSON(object) { switch (object) { case HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED: return "HASH_ALGORITHM_UNSPECIFIED"; case HashAlgorithm.SHA2_256: return "SHA2_256"; case HashAlgorithm.SHA2_384: return "SHA2_384"; case HashAlgorithm.SHA2_512: return "SHA2_512"; case HashAlgorithm.SHA3_256: return "SHA3_256"; case HashAlgorithm.SHA3_384: return "SHA3_384"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); } } /** * Details of a specific public key, capturing the the key encoding method, * and signature algorithm. * * PublicKeyDetails captures the public key/hash algorithm combinations * recommended in the Sigstore ecosystem. * * This is modelled as a linear set as we want to provide a small number of * opinionated options instead of allowing every possible permutation. * * Any changes to this enum MUST be reflected in the algorithm registry. * See: docs/algorithm-registry.md * * To avoid the possibility of contradicting formats such as PKCS1 with * ED25519 the valid permutations are listed as a linear set instead of a * cartesian set (i.e one combined variable instead of two, one for encoding * and one for the signature algorithm). */ var PublicKeyDetails; (function (PublicKeyDetails) { PublicKeyDetails[PublicKeyDetails["PUBLIC_KEY_DETAILS_UNSPECIFIED"] = 0] = "PUBLIC_KEY_DETAILS_UNSPECIFIED"; /** * PKCS1_RSA_PKCS1V5 - RSA * * @deprecated */ PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PKCS1V5"] = 1] = "PKCS1_RSA_PKCS1V5"; /** * PKCS1_RSA_PSS - See RFC8017 * * @deprecated */ PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PSS"] = 2] = "PKCS1_RSA_PSS"; /** @deprecated */ PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V5"] = 3] = "PKIX_RSA_PKCS1V5"; /** @deprecated */ PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS"] = 4] = "PKIX_RSA_PSS"; /** PKIX_RSA_PKCS1V15_2048_SHA256 - RSA public key in PKIX format, PKCS#1v1.5 signature */ PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_2048_SHA256"] = 9] = "PKIX_RSA_PKCS1V15_2048_SHA256"; PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_3072_SHA256"] = 10] = "PKIX_RSA_PKCS1V15_3072_SHA256"; PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_4096_SHA256"] = 11] = "PKIX_RSA_PKCS1V15_4096_SHA256"; /** PKIX_RSA_PSS_2048_SHA256 - RSA public key in PKIX format, RSASSA-PSS signature */ PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_2048_SHA256"] = 16] = "PKIX_RSA_PSS_2048_SHA256"; PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_3072_SHA256"] = 17] = "PKIX_RSA_PSS_3072_SHA256"; PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_4096_SHA256"] = 18] = "PKIX_RSA_PSS_4096_SHA256"; /** * PKIX_ECDSA_P256_HMAC_SHA_256 - ECDSA * * @deprecated */ PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_HMAC_SHA_256"] = 6] = "PKIX_ECDSA_P256_HMAC_SHA_256"; /** PKIX_ECDSA_P256_SHA_256 - See NIST FIPS 186-4 */ PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_SHA_256"] = 5] = "PKIX_ECDSA_P256_SHA_256"; PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P384_SHA_384"] = 12] = "PKIX_ECDSA_P384_SHA_384"; PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P521_SHA_512"] = 13] = "PKIX_ECDSA_P521_SHA_512"; /** PKIX_ED25519 - Ed 25519 */ PublicKeyDetails[PublicKeyDetails["PKIX_ED25519"] = 7] = "PKIX_ED25519"; PublicKeyDetails[PublicKeyDetails["PKIX_ED25519_PH"] = 8] = "PKIX_ED25519_PH"; /** * LMS_SHA256 - LMS and LM-OTS * * These keys and signatures may be used by private Sigstore * deployments, but are not currently supported by the public * good instance. * * USER WARNING: LMS and LM-OTS are both stateful signature schemes. * Using them correctly requires discretion and careful consideration * to ensure that individual secret keys are not used more than once. * In addition, LM-OTS is a single-use scheme, meaning that it * MUST NOT be used for more than one signature per LM-OTS key. * If you cannot maintain these invariants, you MUST NOT use these * schemes. */ PublicKeyDetails[PublicKeyDetails["LMS_SHA256"] = 14] = "LMS_SHA256"; PublicKeyDetails[PublicKeyDetails["LMOTS_SHA256"] = 15] = "LMOTS_SHA256"; })(PublicKeyDetails || (exports.PublicKeyDetails = PublicKeyDetails = {})); function publicKeyDetailsFromJSON(object) { switch (object) { case 0: case "PUBLIC_KEY_DETAILS_UNSPECIFIED": return PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED; case 1: case "PKCS1_RSA_PKCS1V5": return PublicKeyDetails.PKCS1_RSA_PKCS1V5; case 2: case "PKCS1_RSA_PSS": return PublicKeyDetails.PKCS1_RSA_PSS; case 3: case "PKIX_RSA_PKCS1V5": return PublicKeyDetails.PKIX_RSA_PKCS1V5; case 4: case "PKIX_RSA_PSS": return PublicKeyDetails.PKIX_RSA_PSS; case 9: case "PKIX_RSA_PKCS1V15_2048_SHA256": return PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256; case 10: case "PKIX_RSA_PKCS1V15_3072_SHA256": return PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256; case 11: case "PKIX_RSA_PKCS1V15_4096_SHA256": return PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256; case 16: case "PKIX_RSA_PSS_2048_SHA256": return PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256; case 17: case "PKIX_RSA_PSS_3072_SHA256": return PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256; case 18: case "PKIX_RSA_PSS_4096_SHA256": return PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256; case 6: case "PKIX_ECDSA_P256_HMAC_SHA_256": return PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256; case 5: case "PKIX_ECDSA_P256_SHA_256": return PublicKeyDetails.PKIX_ECDSA_P256_SHA_256; case 12: case "PKIX_ECDSA_P384_SHA_384": return PublicKeyDetails.PKIX_ECDSA_P384_SHA_384; case 13: case "PKIX_ECDSA_P521_SHA_512": return PublicKeyDetails.PKIX_ECDSA_P521_SHA_512; case 7: case "PKIX_ED25519": return PublicKeyDetails.PKIX_ED25519; case 8: case "PKIX_ED25519_PH": return PublicKeyDetails.PKIX_ED25519_PH; case 14: case "LMS_SHA256": return PublicKeyDetails.LMS_SHA256; case 15: case "LMOTS_SHA256": return PublicKeyDetails.LMOTS_SHA256; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); } } function publicKeyDetailsToJSON(object) { switch (object) { case PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED: return "PUBLIC_KEY_DETAILS_UNSPECIFIED"; case PublicKeyDetails.PKCS1_RSA_PKCS1V5: return "PKCS1_RSA_PKCS1V5"; case PublicKeyDetails.PKCS1_RSA_PSS: return "PKCS1_RSA_PSS"; case PublicKeyDetails.PKIX_RSA_PKCS1V5: return "PKIX_RSA_PKCS1V5"; case PublicKeyDetails.PKIX_RSA_PSS: return "PKIX_RSA_PSS"; case PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256: return "PKIX_RSA_PKCS1V15_2048_SHA256"; case PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256: return "PKIX_RSA_PKCS1V15_3072_SHA256"; case PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256: return "PKIX_RSA_PKCS1V15_4096_SHA256"; case PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256: return "PKIX_RSA_PSS_2048_SHA256"; case PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256: return "PKIX_RSA_PSS_3072_SHA256"; case PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256: return "PKIX_RSA_PSS_4096_SHA256"; case PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256: return "PKIX_ECDSA_P256_HMAC_SHA_256"; case PublicKeyDetails.PKIX_ECDSA_P256_SHA_256: return "PKIX_ECDSA_P256_SHA_256"; case PublicKeyDetails.PKIX_ECDSA_P384_SHA_384: return "PKIX_ECDSA_P384_SHA_384"; case PublicKeyDetails.PKIX_ECDSA_P521_SHA_512: return "PKIX_ECDSA_P521_SHA_512"; case PublicKeyDetails.PKIX_ED25519: return "PKIX_ED25519"; case PublicKeyDetails.PKIX_ED25519_PH: return "PKIX_ED25519_PH"; case PublicKeyDetails.LMS_SHA256: return "LMS_SHA256"; case PublicKeyDetails.LMOTS_SHA256: return "LMOTS_SHA256"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); } } var SubjectAlternativeNameType; (function (SubjectAlternativeNameType) { SubjectAlternativeNameType[SubjectAlternativeNameType["SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"] = 0] = "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; SubjectAlternativeNameType[SubjectAlternativeNameType["EMAIL"] = 1] = "EMAIL"; SubjectAlternativeNameType[SubjectAlternativeNameType["URI"] = 2] = "URI"; /** * OTHER_NAME - OID 1.3.6.1.4.1.57264.1.7 * See https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726417--othername-san * for more details. */ SubjectAlternativeNameType[SubjectAlternativeNameType["OTHER_NAME"] = 3] = "OTHER_NAME"; })(SubjectAlternativeNameType || (exports.SubjectAlternativeNameType = SubjectAlternativeNameType = {})); function subjectAlternativeNameTypeFromJSON(object) { switch (object) { case 0: case "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED": return SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED; case 1: case "EMAIL": return SubjectAlternativeNameType.EMAIL; case 2: case "URI": return SubjectAlternativeNameType.URI; case 3: case "OTHER_NAME": return SubjectAlternativeNameType.OTHER_NAME; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); } } function subjectAlternativeNameTypeToJSON(object) { switch (object) { case SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED: return "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; case SubjectAlternativeNameType.EMAIL: return "EMAIL"; case SubjectAlternativeNameType.URI: return "URI"; case SubjectAlternativeNameType.OTHER_NAME: return "OTHER_NAME"; default: throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); } } function createBaseHashOutput() { return { algorithm: 0, digest: Buffer.alloc(0) }; } exports.HashOutput = { fromJSON(object) { return { algorithm: isSet(object.algorithm) ? hashAlgorithmFromJSON(object.algorithm) : 0, digest: isSet(object.digest) ? Buffer.from(bytesFromBase64(object.digest)) : Buffer.alloc(0), }; }, toJSON(message) { const obj = {}; message.algorithm !== undefined && (obj.algorithm = hashAlgorithmToJSON(message.algorithm)); message.digest !== undefined && (obj.digest = base64FromBytes(message.digest !== undefined ? message.digest : Buffer.alloc(0))); return obj; }, }; function createBaseMessageSignature() { return { messageDigest: undefined, signature: Buffer.alloc(0) }; } exports.MessageSignature = { fromJSON(object) { return { messageDigest: isSet(object.messageDigest) ? exports.HashOutput.fromJSON(object.messageDigest) : undefined, signature: isSet(object.signature) ? Buffer.from(bytesFromBase64(object.signature)) : Buffer.alloc(0), }; }, toJSON(message) { const obj = {}; message.messageDigest !== undefined && (obj.messageDigest = message.messageDigest ? exports.HashOutput.toJSON(message.messageDigest) : undefined); message.signature !== undefined && (obj.signature = base64FromBytes(message.signature !== undefined ? message.signature : Buffer.alloc(0))); return obj; }, }; function createBaseLogId() { return { keyId: Buffer.alloc(0) }; } exports.LogId = { fromJSON(object) { return { keyId: isSet(object.keyId) ? Buffer.from(bytesFromBase64(object.keyId)) : Buffer.alloc(0) }; }, toJSON(message) { const obj = {}; message.keyId !== undefined && (obj.keyId = base64FromBytes(message.keyId !== undefined ? message.keyId : Buffer.alloc(0))); return obj; }, }; function createBaseRFC3161SignedTimestamp() { return { signedTimestamp: Buffer.alloc(0) }; } exports.RFC3161SignedTimestamp = { fromJSON(object) { return { signedTimestamp: isSet(object.signedTimestamp) ? Buffer.from(bytesFromBase64(object.signedTimestamp)) : Buffer.alloc(0), }; }, toJSON(message) { const obj = {}; message.signedTimestamp !== undefined && (obj.signedTimestamp = base64FromBytes(message.signedTimestamp !== undefined ? message.signedTimestamp : Buffer.alloc(0))); return obj; }, }; function createBasePublicKey() { return { rawBytes: undefined, keyDetails: 0, validFor: undefined }; } exports.PublicKey = { fromJSON(object) { return { rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : undefined, keyDetails: isSet(object.keyDetails) ? publicKeyDetailsFromJSON(object.keyDetails) : 0, validFor: isSet(object.validFor) ? exports.TimeRange.fromJSON(object.validFor) : undefined, }; }, toJSON(message) { const obj = {}; message.rawBytes !== undefined && (obj.rawBytes = message.rawBytes !== undefined ? base64FromBytes(message.rawBytes) : undefined); message.keyDetails !== undefined && (obj.keyDetails = publicKeyDetailsToJSON(message.keyDetails)); message.validFor !== undefined && (obj.validFor = message.validFor ? exports.TimeRange.toJSON(message.validFor) : undefined); return obj; }, }; function createBasePublicKeyIdentifier() { return { hint: "" }; } exports.PublicKeyIdentifier = { fromJSON(object) { return { hint: isSet(object.hint) ? String(object.hint) : "" }; }, toJSON(message) { const obj = {}; message.hint !== undefined && (obj.hint = message.hint); return obj; }, }; function createBaseObjectIdentifier() { return { id: [] }; } exports.ObjectIdentifier = { fromJSON(object) { return { id: Array.isArray(object?.id) ? object.id.map((e) => Number(e)) : [] }; }, toJSON(message) { const obj = {}; if (message.id) { obj.id = message.id.map((e) => Math.round(e)); } else { obj.id = []; } return obj; }, }; function createBaseObjectIdentifierValuePair() { return { oid: undefined, value: Buffer.alloc(0) }; } exports.ObjectIdentifierValuePair = { fromJSON(object) { return { oid: isSet(object.oid) ? exports.ObjectIdentifier.fromJSON(object.oid) : undefined, value: isSet(object.value) ? Buffer.from(bytesFromBase64(object.value)) : Buffer.alloc(0), }; }, toJSON(message) { const obj = {}; message.oid !== undefined && (obj.oid = message.oid ? exports.ObjectIdentifier.toJSON(message.oid) : undefined); message.value !== undefined && (obj.value = base64FromBytes(message.value !== undefined ? message.value : Buffer.alloc(0))); return obj; }, }; function createBaseDistinguishedName() { return { organization: "", commonName: "" }; } exports.DistinguishedName = { fromJSON(object) { return { organization: isSet(object.organization) ? String(object.organization) : "", commonName: isSet(object.commonName) ? String(object.commonName) : "", }; }, toJSON(message) { const obj = {}; message.organization !== undefined && (obj.organization = message.organization); message.commonName !== undefined && (obj.commonName = message.commonName); return obj; }, }; function createBaseX509Certificate() { return { rawBytes: Buffer.alloc(0) }; } exports.X509Certificate = { fromJSON(object) { return { rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : Buffer.alloc(0) }; }, toJSON(message) { const obj = {}; message.rawBytes !== undefined && (obj.rawBytes = base64FromBytes(message.rawBytes !== undefined ? message.rawBytes : Buffer.alloc(0))); return obj; }, }; function createBaseSubjectAlternativeName() { return { type: 0, identity: undefined }; } exports.SubjectAlternativeName = { fromJSON(object) { return { type: isSet(object.type) ? subjectAlternativeNameTypeFromJSON(object.type) : 0, identity: isSet(object.regexp) ? { $case: "regexp", regexp: String(object.regexp) } : isSet(object.value) ? { $case: "value", value: String(object.value) } : undefined, }; }, toJSON(message) { const obj = {}; message.type !== undefined && (obj.type = subjectAlternativeNameTypeToJSON(message.type)); message.identity?.$case === "regexp" && (obj.regexp = message.identity?.regexp); message.identity?.$case === "value" && (obj.value = message.identity?.value); return obj; }, }; function createBaseX509CertificateChain() { return { certificates: [] }; } exports.X509CertificateChain = { fromJSON(object) { return { certificates: Array.isArray(object?.certificates) ? object.certificates.map((e) => exports.X509Certificate.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.certificates) { obj.certificates = message.certificates.map((e) => e ? exports.X509Certificate.toJSON(e) : undefined); } else { obj.certificates = []; } return obj; }, }; function createBaseTimeRange() { return { start: undefined, end: undefined }; } exports.TimeRange = { fromJSON(object) { return { start: isSet(object.start) ? fromJsonTimestamp(object.start) : undefined, end: isSet(object.end) ? fromJsonTimestamp(object.end) : undefined, }; }, toJSON(message) { const obj = {}; message.start !== undefined && (obj.start = message.start.toISOString()); message.end !== undefined && (obj.end = message.end.toISOString()); return obj; }, }; var tsProtoGlobalThis = (() => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } throw "Unable to locate global object"; })(); function bytesFromBase64(b64) { if (tsProtoGlobalThis.Buffer) { return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); } else { const bin = tsProtoGlobalThis.atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } } function base64FromBytes(arr) { if (tsProtoGlobalThis.Buffer) { return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); } else { const bin = []; arr.forEach((byte) => { bin.push(String.fromCharCode(byte)); }); return tsProtoGlobalThis.btoa(bin.join("")); } } function fromTimestamp(t) { let millis = Number(t.seconds) * 1_000; millis += t.nanos / 1_000_000; return new Date(millis); } function fromJsonTimestamp(o) { if (o instanceof Date) { return o; } else if (typeof o === "string") { return new Date(o); } else { return fromTimestamp(timestamp_1.Timestamp.fromJSON(o)); } } function isSet(value) { return value !== null && value !== undefined; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TransparencyLogEntry = exports.InclusionPromise = exports.InclusionProof = exports.Checkpoint = exports.KindVersion = void 0; /* eslint-disable */ const sigstore_common_1 = require("./sigstore_common"); function createBaseKindVersion() { return { kind: "", version: "" }; } exports.KindVersion = { fromJSON(object) { return { kind: isSet(object.kind) ? String(object.kind) : "", version: isSet(object.version) ? String(object.version) : "", }; }, toJSON(message) { const obj = {}; message.kind !== undefined && (obj.kind = message.kind); message.version !== undefined && (obj.version = message.version); return obj; }, }; function createBaseCheckpoint() { return { envelope: "" }; } exports.Checkpoint = { fromJSON(object) { return { envelope: isSet(object.envelope) ? String(object.envelope) : "" }; }, toJSON(message) { const obj = {}; message.envelope !== undefined && (obj.envelope = message.envelope); return obj; }, }; function createBaseInclusionProof() { return { logIndex: "0", rootHash: Buffer.alloc(0), treeSize: "0", hashes: [], checkpoint: undefined }; } exports.InclusionProof = { fromJSON(object) { return { logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", rootHash: isSet(object.rootHash) ? Buffer.from(bytesFromBase64(object.rootHash)) : Buffer.alloc(0), treeSize: isSet(object.treeSize) ? String(object.treeSize) : "0", hashes: Array.isArray(object?.hashes) ? object.hashes.map((e) => Buffer.from(bytesFromBase64(e))) : [], checkpoint: isSet(object.checkpoint) ? exports.Checkpoint.fromJSON(object.checkpoint) : undefined, }; }, toJSON(message) { const obj = {}; message.logIndex !== undefined && (obj.logIndex = message.logIndex); message.rootHash !== undefined && (obj.rootHash = base64FromBytes(message.rootHash !== undefined ? message.rootHash : Buffer.alloc(0))); message.treeSize !== undefined && (obj.treeSize = message.treeSize); if (message.hashes) { obj.hashes = message.hashes.map((e) => base64FromBytes(e !== undefined ? e : Buffer.alloc(0))); } else { obj.hashes = []; } message.checkpoint !== undefined && (obj.checkpoint = message.checkpoint ? exports.Checkpoint.toJSON(message.checkpoint) : undefined); return obj; }, }; function createBaseInclusionPromise() { return { signedEntryTimestamp: Buffer.alloc(0) }; } exports.InclusionPromise = { fromJSON(object) { return { signedEntryTimestamp: isSet(object.signedEntryTimestamp) ? Buffer.from(bytesFromBase64(object.signedEntryTimestamp)) : Buffer.alloc(0), }; }, toJSON(message) { const obj = {}; message.signedEntryTimestamp !== undefined && (obj.signedEntryTimestamp = base64FromBytes(message.signedEntryTimestamp !== undefined ? message.signedEntryTimestamp : Buffer.alloc(0))); return obj; }, }; function createBaseTransparencyLogEntry() { return { logIndex: "0", logId: undefined, kindVersion: undefined, integratedTime: "0", inclusionPromise: undefined, inclusionProof: undefined, canonicalizedBody: Buffer.alloc(0), }; } exports.TransparencyLogEntry = { fromJSON(object) { return { logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, kindVersion: isSet(object.kindVersion) ? exports.KindVersion.fromJSON(object.kindVersion) : undefined, integratedTime: isSet(object.integratedTime) ? String(object.integratedTime) : "0", inclusionPromise: isSet(object.inclusionPromise) ? exports.InclusionPromise.fromJSON(object.inclusionPromise) : undefined, inclusionProof: isSet(object.inclusionProof) ? exports.InclusionProof.fromJSON(object.inclusionProof) : undefined, canonicalizedBody: isSet(object.canonicalizedBody) ? Buffer.from(bytesFromBase64(object.canonicalizedBody)) : Buffer.alloc(0), }; }, toJSON(message) { const obj = {}; message.logIndex !== undefined && (obj.logIndex = message.logIndex); message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); message.kindVersion !== undefined && (obj.kindVersion = message.kindVersion ? exports.KindVersion.toJSON(message.kindVersion) : undefined); message.integratedTime !== undefined && (obj.integratedTime = message.integratedTime); message.inclusionPromise !== undefined && (obj.inclusionPromise = message.inclusionPromise ? exports.InclusionPromise.toJSON(message.inclusionPromise) : undefined); message.inclusionProof !== undefined && (obj.inclusionProof = message.inclusionProof ? exports.InclusionProof.toJSON(message.inclusionProof) : undefined); message.canonicalizedBody !== undefined && (obj.canonicalizedBody = base64FromBytes(message.canonicalizedBody !== undefined ? message.canonicalizedBody : Buffer.alloc(0))); return obj; }, }; var tsProtoGlobalThis = (() => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } throw "Unable to locate global object"; })(); function bytesFromBase64(b64) { if (tsProtoGlobalThis.Buffer) { return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); } else { const bin = tsProtoGlobalThis.atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } } function base64FromBytes(arr) { if (tsProtoGlobalThis.Buffer) { return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); } else { const bin = []; arr.forEach((byte) => { bin.push(String.fromCharCode(byte)); }); return tsProtoGlobalThis.btoa(bin.join("")); } } function isSet(value) { return value !== null && value !== undefined; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClientTrustConfig = exports.SigningConfig = exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = void 0; /* eslint-disable */ const sigstore_common_1 = require("./sigstore_common"); function createBaseTransparencyLogInstance() { return { baseUrl: "", hashAlgorithm: 0, publicKey: undefined, logId: undefined, checkpointKeyId: undefined }; } exports.TransparencyLogInstance = { fromJSON(object) { return { baseUrl: isSet(object.baseUrl) ? String(object.baseUrl) : "", hashAlgorithm: isSet(object.hashAlgorithm) ? (0, sigstore_common_1.hashAlgorithmFromJSON)(object.hashAlgorithm) : 0, publicKey: isSet(object.publicKey) ? sigstore_common_1.PublicKey.fromJSON(object.publicKey) : undefined, logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, checkpointKeyId: isSet(object.checkpointKeyId) ? sigstore_common_1.LogId.fromJSON(object.checkpointKeyId) : undefined, }; }, toJSON(message) { const obj = {}; message.baseUrl !== undefined && (obj.baseUrl = message.baseUrl); message.hashAlgorithm !== undefined && (obj.hashAlgorithm = (0, sigstore_common_1.hashAlgorithmToJSON)(message.hashAlgorithm)); message.publicKey !== undefined && (obj.publicKey = message.publicKey ? sigstore_common_1.PublicKey.toJSON(message.publicKey) : undefined); message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); message.checkpointKeyId !== undefined && (obj.checkpointKeyId = message.checkpointKeyId ? sigstore_common_1.LogId.toJSON(message.checkpointKeyId) : undefined); return obj; }, }; function createBaseCertificateAuthority() { return { subject: undefined, uri: "", certChain: undefined, validFor: undefined }; } exports.CertificateAuthority = { fromJSON(object) { return { subject: isSet(object.subject) ? sigstore_common_1.DistinguishedName.fromJSON(object.subject) : undefined, uri: isSet(object.uri) ? String(object.uri) : "", certChain: isSet(object.certChain) ? sigstore_common_1.X509CertificateChain.fromJSON(object.certChain) : undefined, validFor: isSet(object.validFor) ? sigstore_common_1.TimeRange.fromJSON(object.validFor) : undefined, }; }, toJSON(message) { const obj = {}; message.subject !== undefined && (obj.subject = message.subject ? sigstore_common_1.DistinguishedName.toJSON(message.subject) : undefined); message.uri !== undefined && (obj.uri = message.uri); message.certChain !== undefined && (obj.certChain = message.certChain ? sigstore_common_1.X509CertificateChain.toJSON(message.certChain) : undefined); message.validFor !== undefined && (obj.validFor = message.validFor ? sigstore_common_1.TimeRange.toJSON(message.validFor) : undefined); return obj; }, }; function createBaseTrustedRoot() { return { mediaType: "", tlogs: [], certificateAuthorities: [], ctlogs: [], timestampAuthorities: [] }; } exports.TrustedRoot = { fromJSON(object) { return { mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", tlogs: Array.isArray(object?.tlogs) ? object.tlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) : [], certificateAuthorities: Array.isArray(object?.certificateAuthorities) ? object.certificateAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) : [], ctlogs: Array.isArray(object?.ctlogs) ? object.ctlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) : [], timestampAuthorities: Array.isArray(object?.timestampAuthorities) ? object.timestampAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.mediaType !== undefined && (obj.mediaType = message.mediaType); if (message.tlogs) { obj.tlogs = message.tlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); } else { obj.tlogs = []; } if (message.certificateAuthorities) { obj.certificateAuthorities = message.certificateAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); } else { obj.certificateAuthorities = []; } if (message.ctlogs) { obj.ctlogs = message.ctlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); } else { obj.ctlogs = []; } if (message.timestampAuthorities) { obj.timestampAuthorities = message.timestampAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); } else { obj.timestampAuthorities = []; } return obj; }, }; function createBaseSigningConfig() { return { mediaType: "", caUrl: "", oidcUrl: "", tlogUrls: [], tsaUrls: [] }; } exports.SigningConfig = { fromJSON(object) { return { mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", caUrl: isSet(object.caUrl) ? String(object.caUrl) : "", oidcUrl: isSet(object.oidcUrl) ? String(object.oidcUrl) : "", tlogUrls: Array.isArray(object?.tlogUrls) ? object.tlogUrls.map((e) => String(e)) : [], tsaUrls: Array.isArray(object?.tsaUrls) ? object.tsaUrls.map((e) => String(e)) : [], }; }, toJSON(message) { const obj = {}; message.mediaType !== undefined && (obj.mediaType = message.mediaType); message.caUrl !== undefined && (obj.caUrl = message.caUrl); message.oidcUrl !== undefined && (obj.oidcUrl = message.oidcUrl); if (message.tlogUrls) { obj.tlogUrls = message.tlogUrls.map((e) => e); } else { obj.tlogUrls = []; } if (message.tsaUrls) { obj.tsaUrls = message.tsaUrls.map((e) => e); } else { obj.tsaUrls = []; } return obj; }, }; function createBaseClientTrustConfig() { return { mediaType: "", trustedRoot: undefined, signingConfig: undefined }; } exports.ClientTrustConfig = { fromJSON(object) { return { mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", trustedRoot: isSet(object.trustedRoot) ? exports.TrustedRoot.fromJSON(object.trustedRoot) : undefined, signingConfig: isSet(object.signingConfig) ? exports.SigningConfig.fromJSON(object.signingConfig) : undefined, }; }, toJSON(message) { const obj = {}; message.mediaType !== undefined && (obj.mediaType = message.mediaType); message.trustedRoot !== undefined && (obj.trustedRoot = message.trustedRoot ? exports.TrustedRoot.toJSON(message.trustedRoot) : undefined); message.signingConfig !== undefined && (obj.signingConfig = message.signingConfig ? exports.SigningConfig.toJSON(message.signingConfig) : undefined); return obj; }, }; function isSet(value) { return value !== null && value !== undefined; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Input = exports.Artifact = exports.ArtifactVerificationOptions_ObserverTimestampOptions = exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = exports.ArtifactVerificationOptions_TimestampAuthorityOptions = exports.ArtifactVerificationOptions_CtlogOptions = exports.ArtifactVerificationOptions_TlogOptions = exports.ArtifactVerificationOptions = exports.PublicKeyIdentities = exports.CertificateIdentities = exports.CertificateIdentity = void 0; /* eslint-disable */ const sigstore_bundle_1 = require("./sigstore_bundle"); const sigstore_common_1 = require("./sigstore_common"); const sigstore_trustroot_1 = require("./sigstore_trustroot"); function createBaseCertificateIdentity() { return { issuer: "", san: undefined, oids: [] }; } exports.CertificateIdentity = { fromJSON(object) { return { issuer: isSet(object.issuer) ? String(object.issuer) : "", san: isSet(object.san) ? sigstore_common_1.SubjectAlternativeName.fromJSON(object.san) : undefined, oids: Array.isArray(object?.oids) ? object.oids.map((e) => sigstore_common_1.ObjectIdentifierValuePair.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; message.issuer !== undefined && (obj.issuer = message.issuer); message.san !== undefined && (obj.san = message.san ? sigstore_common_1.SubjectAlternativeName.toJSON(message.san) : undefined); if (message.oids) { obj.oids = message.oids.map((e) => e ? sigstore_common_1.ObjectIdentifierValuePair.toJSON(e) : undefined); } else { obj.oids = []; } return obj; }, }; function createBaseCertificateIdentities() { return { identities: [] }; } exports.CertificateIdentities = { fromJSON(object) { return { identities: Array.isArray(object?.identities) ? object.identities.map((e) => exports.CertificateIdentity.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.identities) { obj.identities = message.identities.map((e) => e ? exports.CertificateIdentity.toJSON(e) : undefined); } else { obj.identities = []; } return obj; }, }; function createBasePublicKeyIdentities() { return { publicKeys: [] }; } exports.PublicKeyIdentities = { fromJSON(object) { return { publicKeys: Array.isArray(object?.publicKeys) ? object.publicKeys.map((e) => sigstore_common_1.PublicKey.fromJSON(e)) : [], }; }, toJSON(message) { const obj = {}; if (message.publicKeys) { obj.publicKeys = message.publicKeys.map((e) => e ? sigstore_common_1.PublicKey.toJSON(e) : undefined); } else { obj.publicKeys = []; } return obj; }, }; function createBaseArtifactVerificationOptions() { return { signers: undefined, tlogOptions: undefined, ctlogOptions: undefined, tsaOptions: undefined, integratedTsOptions: undefined, observerOptions: undefined, }; } exports.ArtifactVerificationOptions = { fromJSON(object) { return { signers: isSet(object.certificateIdentities) ? { $case: "certificateIdentities", certificateIdentities: exports.CertificateIdentities.fromJSON(object.certificateIdentities), } : isSet(object.publicKeys) ? { $case: "publicKeys", publicKeys: exports.PublicKeyIdentities.fromJSON(object.publicKeys) } : undefined, tlogOptions: isSet(object.tlogOptions) ? exports.ArtifactVerificationOptions_TlogOptions.fromJSON(object.tlogOptions) : undefined, ctlogOptions: isSet(object.ctlogOptions) ? exports.ArtifactVerificationOptions_CtlogOptions.fromJSON(object.ctlogOptions) : undefined, tsaOptions: isSet(object.tsaOptions) ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.fromJSON(object.tsaOptions) : undefined, integratedTsOptions: isSet(object.integratedTsOptions) ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.fromJSON(object.integratedTsOptions) : undefined, observerOptions: isSet(object.observerOptions) ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.fromJSON(object.observerOptions) : undefined, }; }, toJSON(message) { const obj = {}; message.signers?.$case === "certificateIdentities" && (obj.certificateIdentities = message.signers?.certificateIdentities ? exports.CertificateIdentities.toJSON(message.signers?.certificateIdentities) : undefined); message.signers?.$case === "publicKeys" && (obj.publicKeys = message.signers?.publicKeys ? exports.PublicKeyIdentities.toJSON(message.signers?.publicKeys) : undefined); message.tlogOptions !== undefined && (obj.tlogOptions = message.tlogOptions ? exports.ArtifactVerificationOptions_TlogOptions.toJSON(message.tlogOptions) : undefined); message.ctlogOptions !== undefined && (obj.ctlogOptions = message.ctlogOptions ? exports.ArtifactVerificationOptions_CtlogOptions.toJSON(message.ctlogOptions) : undefined); message.tsaOptions !== undefined && (obj.tsaOptions = message.tsaOptions ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.toJSON(message.tsaOptions) : undefined); message.integratedTsOptions !== undefined && (obj.integratedTsOptions = message.integratedTsOptions ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.toJSON(message.integratedTsOptions) : undefined); message.observerOptions !== undefined && (obj.observerOptions = message.observerOptions ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.toJSON(message.observerOptions) : undefined); return obj; }, }; function createBaseArtifactVerificationOptions_TlogOptions() { return { threshold: 0, performOnlineVerification: false, disable: false }; } exports.ArtifactVerificationOptions_TlogOptions = { fromJSON(object) { return { threshold: isSet(object.threshold) ? Number(object.threshold) : 0, performOnlineVerification: isSet(object.performOnlineVerification) ? Boolean(object.performOnlineVerification) : false, disable: isSet(object.disable) ? Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); message.performOnlineVerification !== undefined && (obj.performOnlineVerification = message.performOnlineVerification); message.disable !== undefined && (obj.disable = message.disable); return obj; }, }; function createBaseArtifactVerificationOptions_CtlogOptions() { return { threshold: 0, disable: false }; } exports.ArtifactVerificationOptions_CtlogOptions = { fromJSON(object) { return { threshold: isSet(object.threshold) ? Number(object.threshold) : 0, disable: isSet(object.disable) ? Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); message.disable !== undefined && (obj.disable = message.disable); return obj; }, }; function createBaseArtifactVerificationOptions_TimestampAuthorityOptions() { return { threshold: 0, disable: false }; } exports.ArtifactVerificationOptions_TimestampAuthorityOptions = { fromJSON(object) { return { threshold: isSet(object.threshold) ? Number(object.threshold) : 0, disable: isSet(object.disable) ? Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); message.disable !== undefined && (obj.disable = message.disable); return obj; }, }; function createBaseArtifactVerificationOptions_TlogIntegratedTimestampOptions() { return { threshold: 0, disable: false }; } exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = { fromJSON(object) { return { threshold: isSet(object.threshold) ? Number(object.threshold) : 0, disable: isSet(object.disable) ? Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); message.disable !== undefined && (obj.disable = message.disable); return obj; }, }; function createBaseArtifactVerificationOptions_ObserverTimestampOptions() { return { threshold: 0, disable: false }; } exports.ArtifactVerificationOptions_ObserverTimestampOptions = { fromJSON(object) { return { threshold: isSet(object.threshold) ? Number(object.threshold) : 0, disable: isSet(object.disable) ? Boolean(object.disable) : false, }; }, toJSON(message) { const obj = {}; message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); message.disable !== undefined && (obj.disable = message.disable); return obj; }, }; function createBaseArtifact() { return { data: undefined }; } exports.Artifact = { fromJSON(object) { return { data: isSet(object.artifactUri) ? { $case: "artifactUri", artifactUri: String(object.artifactUri) } : isSet(object.artifact) ? { $case: "artifact", artifact: Buffer.from(bytesFromBase64(object.artifact)) } : isSet(object.artifactDigest) ? { $case: "artifactDigest", artifactDigest: sigstore_common_1.HashOutput.fromJSON(object.artifactDigest) } : undefined, }; }, toJSON(message) { const obj = {}; message.data?.$case === "artifactUri" && (obj.artifactUri = message.data?.artifactUri); message.data?.$case === "artifact" && (obj.artifact = message.data?.artifact !== undefined ? base64FromBytes(message.data?.artifact) : undefined); message.data?.$case === "artifactDigest" && (obj.artifactDigest = message.data?.artifactDigest ? sigstore_common_1.HashOutput.toJSON(message.data?.artifactDigest) : undefined); return obj; }, }; function createBaseInput() { return { artifactTrustRoot: undefined, artifactVerificationOptions: undefined, bundle: undefined, artifact: undefined, }; } exports.Input = { fromJSON(object) { return { artifactTrustRoot: isSet(object.artifactTrustRoot) ? sigstore_trustroot_1.TrustedRoot.fromJSON(object.artifactTrustRoot) : undefined, artifactVerificationOptions: isSet(object.artifactVerificationOptions) ? exports.ArtifactVerificationOptions.fromJSON(object.artifactVerificationOptions) : undefined, bundle: isSet(object.bundle) ? sigstore_bundle_1.Bundle.fromJSON(object.bundle) : undefined, artifact: isSet(object.artifact) ? exports.Artifact.fromJSON(object.artifact) : undefined, }; }, toJSON(message) { const obj = {}; message.artifactTrustRoot !== undefined && (obj.artifactTrustRoot = message.artifactTrustRoot ? sigstore_trustroot_1.TrustedRoot.toJSON(message.artifactTrustRoot) : undefined); message.artifactVerificationOptions !== undefined && (obj.artifactVerificationOptions = message.artifactVerificationOptions ? exports.ArtifactVerificationOptions.toJSON(message.artifactVerificationOptions) : undefined); message.bundle !== undefined && (obj.bundle = message.bundle ? sigstore_bundle_1.Bundle.toJSON(message.bundle) : undefined); message.artifact !== undefined && (obj.artifact = message.artifact ? exports.Artifact.toJSON(message.artifact) : undefined); return obj; }, }; var tsProtoGlobalThis = (() => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } throw "Unable to locate global object"; })(); function bytesFromBase64(b64) { if (tsProtoGlobalThis.Buffer) { return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); } else { const bin = tsProtoGlobalThis.atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } } function base64FromBytes(arr) { if (tsProtoGlobalThis.Buffer) { return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); } else { const bin = []; arr.forEach((byte) => { bin.push(String.fromCharCode(byte)); }); return tsProtoGlobalThis.btoa(bin.join("")); } } function isSet(value) { return value !== null && value !== undefined; } "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ __exportStar(require("./__generated__/envelope"), exports); __exportStar(require("./__generated__/sigstore_bundle"), exports); __exportStar(require("./__generated__/sigstore_common"), exports); __exportStar(require("./__generated__/sigstore_rekor"), exports); __exportStar(require("./__generated__/sigstore_trustroot"), exports); __exportStar(require("./__generated__/sigstore_verification"), exports); { "name": "@sigstore/protobuf-specs", "version": "0.3.3", "description": "code-signing for npm packages", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "build": "tsc" }, "repository": { "type": "git", "url": "git+https://github.com/sigstore/protobuf-specs.git" }, "files": [ "dist" ], "author": "bdehamer@github.com", "license": "Apache-2.0", "bugs": { "url": "https://github.com/sigstore/protobuf-specs/issues" }, "homepage": "https://github.com/sigstore/protobuf-specs#readme", "devDependencies": { "@tsconfig/node18": "^18.2.4", "@types/node": "^18.14.0", "typescript": "^5.7.2" }, "engines": { "node": "^18.17.0 || >=20.5.0" } } Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 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 (50%) 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 The Sigstore Authors Licensed under the Apache License, Version 2.0 (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-2.0 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. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseBundleBuilder = void 0; // BaseBundleBuilder is a base class for BundleBuilder implementations. It // provides a the basic wokflow for signing and witnessing an artifact. // Subclasses must implement the `package` method to assemble a valid bundle // with the generated signature and verification material. class BaseBundleBuilder { constructor(options) { this.signer = options.signer; this.witnesses = options.witnesses; } // Executes the signing/witnessing process for the given artifact. async create(artifact) { const signature = await this.prepare(artifact).then((blob) => this.signer.sign(blob)); const bundle = await this.package(artifact, signature); // Invoke all of the witnesses in parallel const verificationMaterials = await Promise.all(this.witnesses.map((witness) => witness.testify(bundle.content, publicKey(signature.key)))); // Collect the verification material from all of the witnesses const tlogEntryList = []; const timestampList = []; verificationMaterials.forEach(({ tlogEntries, rfc3161Timestamps }) => { tlogEntryList.push(...(tlogEntries ?? [])); timestampList.push(...(rfc3161Timestamps ?? [])); }); // Merge the collected verification material into the bundle bundle.verificationMaterial.tlogEntries = tlogEntryList; bundle.verificationMaterial.timestampVerificationData = { rfc3161Timestamps: timestampList, }; return bundle; } // Override this function to apply any pre-signing transformations to the // artifact. The returned buffer will be signed by the signer. The default // implementation simply returns the artifact data. async prepare(artifact) { return artifact.data; } } exports.BaseBundleBuilder = BaseBundleBuilder; // Extracts the public key from a KeyMaterial. Returns either the public key // or the certificate, depending on the type of key material. function publicKey(key) { switch (key.$case) { case 'publicKey': return key.publicKey; case 'x509Certificate': return key.certificate; } } "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.toMessageSignatureBundle = toMessageSignatureBundle; exports.toDSSEBundle = toDSSEBundle; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const sigstore = __importStar(require("@sigstore/bundle")); const util_1 = require("../util"); // Helper functions for assembling the parts of a Sigstore bundle // Message signature bundle - $case: 'messageSignature' function toMessageSignatureBundle(artifact, signature) { const digest = util_1.crypto.digest('sha256', artifact.data); return sigstore.toMessageSignatureBundle({ digest, signature: signature.signature, certificate: signature.key.$case === 'x509Certificate' ? util_1.pem.toDER(signature.key.certificate) : undefined, keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined, certificateChain: true, }); } // DSSE envelope bundle - $case: 'dsseEnvelope' function toDSSEBundle(artifact, signature, certificateChain) { return sigstore.toDSSEBundle({ artifact: artifact.data, artifactType: artifact.type, signature: signature.signature, certificate: signature.key.$case === 'x509Certificate' ? util_1.pem.toDER(signature.key.certificate) : undefined, keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined, certificateChain, }); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DSSEBundleBuilder = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const util_1 = require("../util"); const base_1 = require("./base"); const bundle_1 = require("./bundle"); // BundleBuilder implementation for DSSE wrapped attestations class DSSEBundleBuilder extends base_1.BaseBundleBuilder { constructor(options) { super(options); this.certificateChain = options.certificateChain ?? false; } // DSSE requires the artifact to be pre-encoded with the payload type // before the signature is generated. async prepare(artifact) { const a = artifactDefaults(artifact); return util_1.dsse.preAuthEncoding(a.type, a.data); } // Packages the artifact and signature into a DSSE bundle async package(artifact, signature) { return (0, bundle_1.toDSSEBundle)(artifactDefaults(artifact), signature, this.certificateChain); } } exports.DSSEBundleBuilder = DSSEBundleBuilder; // Defaults the artifact type to an empty string if not provided function artifactDefaults(artifact) { return { ...artifact, type: artifact.type ?? '', }; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0; var dsse_1 = require("./dsse"); Object.defineProperty(exports, "DSSEBundleBuilder", { enumerable: true, get: function () { return dsse_1.DSSEBundleBuilder; } }); var message_1 = require("./message"); Object.defineProperty(exports, "MessageSignatureBundleBuilder", { enumerable: true, get: function () { return message_1.MessageSignatureBundleBuilder; } }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MessageSignatureBundleBuilder = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const base_1 = require("./base"); const bundle_1 = require("./bundle"); // BundleBuilder implementation for raw message signatures class MessageSignatureBundleBuilder extends base_1.BaseBundleBuilder { constructor(options) { super(options); } async package(artifact, signature) { return (0, bundle_1.toMessageSignatureBundle)(artifact, signature); } } exports.MessageSignatureBundleBuilder = MessageSignatureBundleBuilder; "use strict"; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.InternalError = void 0; exports.internalError = internalError; const error_1 = require("./external/error"); class InternalError extends Error { constructor({ code, message, cause, }) { super(message); this.name = this.constructor.name; this.cause = cause; this.code = code; } } exports.InternalError = InternalError; function internalError(err, code, message) { if (err instanceof error_1.HTTPError) { message += ` - ${err.message}`; } throw new InternalError({ code: code, message: message, cause: err, }); } "use strict"; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.HTTPError = void 0; class HTTPError extends Error { constructor({ status, message, location, }) { super(`(${status}) ${message}`); this.statusCode = status; this.location = location; } } exports.HTTPError = HTTPError; "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchWithRetry = fetchWithRetry; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const http2_1 = require("http2"); const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); const proc_log_1 = require("proc-log"); const promise_retry_1 = __importDefault(require("promise-retry")); const util_1 = require("../util"); const error_1 = require("./error"); const { HTTP2_HEADER_LOCATION, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_USER_AGENT, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants; async function fetchWithRetry(url, options) { return (0, promise_retry_1.default)(async (retry, attemptNum) => { const method = options.method || 'POST'; const headers = { [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(), ...options.headers, }; const response = await (0, make_fetch_happen_1.default)(url, { method, headers, body: options.body, timeout: options.timeout, retry: false, // We're handling retries ourselves }).catch((reason) => { proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${reason}`); return retry(reason); }); if (response.ok) { return response; } else { const error = await errorFromResponse(response); proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${response.status}`); if (retryable(response.status)) { return retry(error); } else { throw error; } } }, retryOpts(options.retry)); } // Translate a Response into an HTTPError instance. This will attempt to parse // the response body for a message, but will default to the statusText if none // is found. const errorFromResponse = async (response) => { let message = response.statusText; const location = response.headers.get(HTTP2_HEADER_LOCATION) || undefined; const contentType = response.headers.get(HTTP2_HEADER_CONTENT_TYPE); // If response type is JSON, try to parse the body for a message if (contentType?.includes('application/json')) { try { const body = await response.json(); message = body.message || message; } catch (e) { // ignore } } return new error_1.HTTPError({ status: response.status, message: message, location: location, }); }; // Determine if a status code is retryable. This includes 5xx errors, 408, and // 429. const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR; // Normalize the retry options to the format expected by promise-retry const retryOpts = (retry) => { if (typeof retry === 'boolean') { return { retries: retry ? 1 : 0 }; } else if (typeof retry === 'number') { return { retries: retry }; } else { return { retries: 0, ...retry }; } }; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Fulcio = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const fetch_1 = require("./fetch"); /** * Fulcio API client. */ class Fulcio { constructor(options) { this.options = options; } async createSigningCertificate(request) { const { baseURL, retry, timeout } = this.options; const url = `${baseURL}/api/v2/signingCert`; const response = await (0, fetch_1.fetchWithRetry)(url, { headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), timeout, retry, }); return response.json(); } } exports.Fulcio = Fulcio; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Rekor = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const fetch_1 = require("./fetch"); /** * Rekor API client. */ class Rekor { constructor(options) { this.options = options; } /** * Create a new entry in the Rekor log. * @param propsedEntry {ProposedEntry} Data to create a new entry * @returns {Promise} The created entry */ async createEntry(propsedEntry) { const { baseURL, timeout, retry } = this.options; const url = `${baseURL}/api/v1/log/entries`; const response = await (0, fetch_1.fetchWithRetry)(url, { headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify(propsedEntry), timeout, retry, }); const data = await response.json(); return entryFromResponse(data); } /** * Get an entry from the Rekor log. * @param uuid {string} The UUID of the entry to retrieve * @returns {Promise} The retrieved entry */ async getEntry(uuid) { const { baseURL, timeout, retry } = this.options; const url = `${baseURL}/api/v1/log/entries/${uuid}`; const response = await (0, fetch_1.fetchWithRetry)(url, { method: 'GET', headers: { Accept: 'application/json', }, timeout, retry, }); const data = await response.json(); return entryFromResponse(data); } } exports.Rekor = Rekor; // Unpack the response from the Rekor API into a more convenient format. function entryFromResponse(data) { const entries = Object.entries(data); if (entries.length != 1) { throw new Error('Received multiple entries in Rekor response'); } // Grab UUID and entry data from the response const [uuid, entry] = entries[0]; return { ...entry, uuid, }; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TimestampAuthority = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const fetch_1 = require("./fetch"); class TimestampAuthority { constructor(options) { this.options = options; } async createTimestamp(request) { const { baseURL, timeout, retry } = this.options; const url = `${baseURL}/api/v1/timestamp`; const response = await (0, fetch_1.fetchWithRetry)(url, { headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), timeout, retry, }); return response.buffer(); } } exports.TimestampAuthority = TimestampAuthority; "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CIContextProvider = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); // Collection of all the CI-specific providers we have implemented const providers = [getGHAToken, getEnv]; /** * CIContextProvider is a composite identity provider which will iterate * over all of the CI-specific providers and return the token from the first * one that resolves. */ class CIContextProvider { /* istanbul ignore next */ constructor(audience = 'sigstore') { this.audience = audience; } // Invoke all registered ProviderFuncs and return the value of whichever one // resolves first. async getToken() { return Promise.any(providers.map((getToken) => getToken(this.audience))).catch(() => Promise.reject('CI: no tokens available')); } } exports.CIContextProvider = CIContextProvider; /** * getGHAToken can retrieve an OIDC token when running in a GitHub Actions * workflow */ async function getGHAToken(audience) { // Check to see if we're running in GitHub Actions if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { return Promise.reject('no token available'); } // Construct URL to request token w/ appropriate audience const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL); url.searchParams.append('audience', audience); const response = await (0, make_fetch_happen_1.default)(url.href, { retry: 2, headers: { Accept: 'application/json', Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`, }, }); return response.json().then((data) => data.value); } /** * getEnv can retrieve an OIDC token from an environment variable. * This matches the behavior of https://github.com/sigstore/cosign/tree/main/pkg/providers/envvar */ async function getEnv() { if (!process.env.SIGSTORE_ID_TOKEN) { return Promise.reject('no token available'); } return process.env.SIGSTORE_ID_TOKEN; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CIContextProvider = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ var ci_1 = require("./ci"); Object.defineProperty(exports, "CIContextProvider", { enumerable: true, get: function () { return ci_1.CIContextProvider; } }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = exports.CIContextProvider = exports.InternalError = exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0; var bundler_1 = require("./bundler"); Object.defineProperty(exports, "DSSEBundleBuilder", { enumerable: true, get: function () { return bundler_1.DSSEBundleBuilder; } }); Object.defineProperty(exports, "MessageSignatureBundleBuilder", { enumerable: true, get: function () { return bundler_1.MessageSignatureBundleBuilder; } }); var error_1 = require("./error"); Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return error_1.InternalError; } }); var identity_1 = require("./identity"); Object.defineProperty(exports, "CIContextProvider", { enumerable: true, get: function () { return identity_1.CIContextProvider; } }); var signer_1 = require("./signer"); Object.defineProperty(exports, "DEFAULT_FULCIO_URL", { enumerable: true, get: function () { return signer_1.DEFAULT_FULCIO_URL; } }); Object.defineProperty(exports, "FulcioSigner", { enumerable: true, get: function () { return signer_1.FulcioSigner; } }); var witness_1 = require("./witness"); Object.defineProperty(exports, "DEFAULT_REKOR_URL", { enumerable: true, get: function () { return witness_1.DEFAULT_REKOR_URL; } }); Object.defineProperty(exports, "RekorWitness", { enumerable: true, get: function () { return witness_1.RekorWitness; } }); Object.defineProperty(exports, "TSAWitness", { enumerable: true, get: function () { return witness_1.TSAWitness; } }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CAClient = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("../../error"); const fulcio_1 = require("../../external/fulcio"); class CAClient { constructor(options) { this.fulcio = new fulcio_1.Fulcio({ baseURL: options.fulcioBaseURL, retry: options.retry, timeout: options.timeout, }); } async createSigningCertificate(identityToken, publicKey, challenge) { const request = toCertificateRequest(identityToken, publicKey, challenge); try { const resp = await this.fulcio.createSigningCertificate(request); // Account for the fact that the response may contain either a // signedCertificateEmbeddedSct or a signedCertificateDetachedSct. const cert = resp.signedCertificateEmbeddedSct ? resp.signedCertificateEmbeddedSct : resp.signedCertificateDetachedSct; return cert.chain.certificates; } catch (err) { (0, error_1.internalError)(err, 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', 'error creating signing certificate'); } } } exports.CAClient = CAClient; function toCertificateRequest(identityToken, publicKey, challenge) { return { credentials: { oidcIdentityToken: identityToken, }, publicKeyRequest: { publicKey: { algorithm: 'ECDSA', content: publicKey, }, proofOfPossession: challenge.toString('base64'), }, }; } "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.EphemeralSigner = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const crypto_1 = __importDefault(require("crypto")); const EC_KEYPAIR_TYPE = 'ec'; const P256_CURVE = 'P-256'; // Signer implementation which uses an ephemeral keypair to sign artifacts. // The private key lives only in memory and is tied to the lifetime of the // EphemeralSigner instance. class EphemeralSigner { constructor() { this.keypair = crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, { namedCurve: P256_CURVE, }); } async sign(data) { const signature = crypto_1.default.sign(null, data, this.keypair.privateKey); const publicKey = this.keypair.publicKey .export({ format: 'pem', type: 'spki' }) .toString('ascii'); return { signature: signature, key: { $case: 'publicKey', publicKey }, }; } } exports.EphemeralSigner = EphemeralSigner; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("../../error"); const util_1 = require("../../util"); const ca_1 = require("./ca"); const ephemeral_1 = require("./ephemeral"); exports.DEFAULT_FULCIO_URL = 'https://fulcio.sigstore.dev'; // Signer implementation which can be used to decorate another signer // with a Fulcio-issued signing certificate for the signer's public key. // Must be instantiated with an identity provider which can provide a JWT // which represents the identity to be bound to the signing certificate. class FulcioSigner { constructor(options) { this.ca = new ca_1.CAClient({ ...options, fulcioBaseURL: options.fulcioBaseURL || /* istanbul ignore next */ exports.DEFAULT_FULCIO_URL, }); this.identityProvider = options.identityProvider; this.keyHolder = options.keyHolder || new ephemeral_1.EphemeralSigner(); } async sign(data) { // Retrieve identity token from the supplied identity provider const identityToken = await this.getIdentityToken(); // Extract challenge claim from OIDC token let subject; try { subject = util_1.oidc.extractJWTSubject(identityToken); } catch (err) { throw new error_1.InternalError({ code: 'IDENTITY_TOKEN_PARSE_ERROR', message: `invalid identity token: ${identityToken}`, cause: err, }); } // Construct challenge value by signing the subject claim const challenge = await this.keyHolder.sign(Buffer.from(subject)); if (challenge.key.$case !== 'publicKey') { throw new error_1.InternalError({ code: 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', message: 'unexpected format for signing key', }); } // Create signing certificate const certificates = await this.ca.createSigningCertificate(identityToken, challenge.key.publicKey, challenge.signature); // Generate artifact signature const signature = await this.keyHolder.sign(data); // Specifically returning only the first certificate in the chain // as the key. return { signature: signature.signature, key: { $case: 'x509Certificate', certificate: certificates[0], }, }; } async getIdentityToken() { try { return await this.identityProvider.getToken(); } catch (err) { throw new error_1.InternalError({ code: 'IDENTITY_TOKEN_READ_ERROR', message: 'error retrieving identity token', cause: err, }); } } } exports.FulcioSigner = FulcioSigner; "use strict"; /* istanbul ignore file */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ var fulcio_1 = require("./fulcio"); Object.defineProperty(exports, "DEFAULT_FULCIO_URL", { enumerable: true, get: function () { return fulcio_1.DEFAULT_FULCIO_URL; } }); Object.defineProperty(exports, "FulcioSigner", { enumerable: true, get: function () { return fulcio_1.FulcioSigner; } }); "use strict"; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ua = exports.oidc = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ var core_1 = require("@sigstore/core"); Object.defineProperty(exports, "crypto", { enumerable: true, get: function () { return core_1.crypto; } }); Object.defineProperty(exports, "dsse", { enumerable: true, get: function () { return core_1.dsse; } }); Object.defineProperty(exports, "encoding", { enumerable: true, get: function () { return core_1.encoding; } }); Object.defineProperty(exports, "json", { enumerable: true, get: function () { return core_1.json; } }); Object.defineProperty(exports, "pem", { enumerable: true, get: function () { return core_1.pem; } }); exports.oidc = __importStar(require("./oidc")); exports.ua = __importStar(require("./ua")); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extractJWTSubject = extractJWTSubject; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); function extractJWTSubject(jwt) { const parts = jwt.split('.', 3); const payload = JSON.parse(core_1.encoding.base64Decode(parts[1])); switch (payload.iss) { case 'https://accounts.google.com': case 'https://oauth2.sigstore.dev/auth': return payload.email; default: return payload.sub; } } "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getUserAgent = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const os_1 = __importDefault(require("os")); // Format User-Agent: / () // source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent const getUserAgent = () => { const packageVersion = require('../../package.json').version; const nodeVersion = process.version; const platformName = os_1.default.platform(); const archName = os_1.default.arch(); return `sigstore-js/${packageVersion} (Node ${nodeVersion}) (${platformName}/${archName})`; }; exports.getUserAgent = getUserAgent; "use strict"; /* istanbul ignore file */ Object.defineProperty(exports, "__esModule", { value: true }); exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ var tlog_1 = require("./tlog"); Object.defineProperty(exports, "DEFAULT_REKOR_URL", { enumerable: true, get: function () { return tlog_1.DEFAULT_REKOR_URL; } }); Object.defineProperty(exports, "RekorWitness", { enumerable: true, get: function () { return tlog_1.RekorWitness; } }); var tsa_1 = require("./tsa"); Object.defineProperty(exports, "TSAWitness", { enumerable: true, get: function () { return tsa_1.TSAWitness; } }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TLogClient = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("../../error"); const error_2 = require("../../external/error"); const rekor_1 = require("../../external/rekor"); class TLogClient { constructor(options) { this.fetchOnConflict = options.fetchOnConflict ?? false; this.rekor = new rekor_1.Rekor({ baseURL: options.rekorBaseURL, retry: options.retry, timeout: options.timeout, }); } async createEntry(proposedEntry) { let entry; try { entry = await this.rekor.createEntry(proposedEntry); } catch (err) { // If the entry already exists, fetch it (if enabled) if (entryExistsError(err) && this.fetchOnConflict) { // Grab the UUID of the existing entry from the location header /* istanbul ignore next */ const uuid = err.location.split('/').pop() || ''; try { entry = await this.rekor.getEntry(uuid); } catch (err) { (0, error_1.internalError)(err, 'TLOG_FETCH_ENTRY_ERROR', 'error fetching tlog entry'); } } else { (0, error_1.internalError)(err, 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry'); } } return entry; } } exports.TLogClient = TLogClient; function entryExistsError(value) { return (value instanceof error_2.HTTPError && value.statusCode === 409 && value.location !== undefined); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toProposedEntry = toProposedEntry; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const bundle_1 = require("@sigstore/bundle"); const util_1 = require("../../util"); const SHA256_ALGORITHM = 'sha256'; function toProposedEntry(content, publicKey, // TODO: Remove this parameter once have completely switched to 'dsse' entries entryType = 'dsse') { switch (content.$case) { case 'dsseEnvelope': // TODO: Remove this conditional once have completely ditched "intoto" entries if (entryType === 'intoto') { return toProposedIntotoEntry(content.dsseEnvelope, publicKey); } return toProposedDSSEEntry(content.dsseEnvelope, publicKey); case 'messageSignature': return toProposedHashedRekordEntry(content.messageSignature, publicKey); } } // Returns a properly formatted Rekor "hashedrekord" entry for the given digest // and signature function toProposedHashedRekordEntry(messageSignature, publicKey) { const hexDigest = messageSignature.messageDigest.digest.toString('hex'); const b64Signature = messageSignature.signature.toString('base64'); const b64Key = util_1.encoding.base64Encode(publicKey); return { apiVersion: '0.0.1', kind: 'hashedrekord', spec: { data: { hash: { algorithm: SHA256_ALGORITHM, value: hexDigest, }, }, signature: { content: b64Signature, publicKey: { content: b64Key, }, }, }, }; } // Returns a properly formatted Rekor "dsse" entry for the given DSSE envelope // and signature function toProposedDSSEEntry(envelope, publicKey) { const envelopeJSON = JSON.stringify((0, bundle_1.envelopeToJSON)(envelope)); const encodedKey = util_1.encoding.base64Encode(publicKey); return { apiVersion: '0.0.1', kind: 'dsse', spec: { proposedContent: { envelope: envelopeJSON, verifiers: [encodedKey], }, }, }; } // Returns a properly formatted Rekor "intoto" entry for the given DSSE // envelope and signature function toProposedIntotoEntry(envelope, publicKey) { // Calculate the value for the payloadHash field in the Rekor entry const payloadHash = util_1.crypto .digest(SHA256_ALGORITHM, envelope.payload) .toString('hex'); // Calculate the value for the hash field in the Rekor entry const envelopeHash = calculateDSSEHash(envelope, publicKey); // Collect values for re-creating the DSSE envelope. // Double-encode payload and signature cause that's what Rekor expects const payload = util_1.encoding.base64Encode(envelope.payload.toString('base64')); const sig = util_1.encoding.base64Encode(envelope.signatures[0].sig.toString('base64')); const keyid = envelope.signatures[0].keyid; const encodedKey = util_1.encoding.base64Encode(publicKey); // Create the envelope portion of the entry. Note the inclusion of the // publicKey in the signature struct is not a standard part of a DSSE // envelope, but is required by Rekor. const dsse = { payloadType: envelope.payloadType, payload: payload, signatures: [{ sig, publicKey: encodedKey }], }; // If the keyid is an empty string, Rekor seems to remove it altogether. We // need to do the same here so that we can properly recreate the entry for // verification. if (keyid.length > 0) { dsse.signatures[0].keyid = keyid; } return { apiVersion: '0.0.2', kind: 'intoto', spec: { content: { envelope: dsse, hash: { algorithm: SHA256_ALGORITHM, value: envelopeHash }, payloadHash: { algorithm: SHA256_ALGORITHM, value: payloadHash }, }, }, }; } // Calculates the hash of a DSSE envelope for inclusion in a Rekor entry. // There is no standard way to do this, so the scheme we're using as as // follows: // * payload is base64 encoded // * signature is base64 encoded (only the first signature is used) // * keyid is included ONLY if it is NOT an empty string // * The resulting JSON is canonicalized and hashed to a hex string function calculateDSSEHash(envelope, publicKey) { const dsse = { payloadType: envelope.payloadType, payload: envelope.payload.toString('base64'), signatures: [ { sig: envelope.signatures[0].sig.toString('base64'), publicKey }, ], }; // If the keyid is an empty string, Rekor seems to remove it altogether. if (envelope.signatures[0].keyid.length > 0) { dsse.signatures[0].keyid = envelope.signatures[0].keyid; } return util_1.crypto .digest(SHA256_ALGORITHM, util_1.json.canonicalize(dsse)) .toString('hex'); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const util_1 = require("../../util"); const client_1 = require("./client"); const entry_1 = require("./entry"); exports.DEFAULT_REKOR_URL = 'https://rekor.sigstore.dev'; class RekorWitness { constructor(options) { this.entryType = options.entryType; this.tlog = new client_1.TLogClient({ ...options, rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL, }); } async testify(content, publicKey) { const proposedEntry = (0, entry_1.toProposedEntry)(content, publicKey, this.entryType); const entry = await this.tlog.createEntry(proposedEntry); return toTransparencyLogEntry(entry); } } exports.RekorWitness = RekorWitness; function toTransparencyLogEntry(entry) { const logID = Buffer.from(entry.logID, 'hex'); // Parse entry body so we can extract the kind and version. const bodyJSON = util_1.encoding.base64Decode(entry.body); const entryBody = JSON.parse(bodyJSON); const promise = entry?.verification?.signedEntryTimestamp ? inclusionPromise(entry.verification.signedEntryTimestamp) : undefined; const proof = entry?.verification?.inclusionProof ? inclusionProof(entry.verification.inclusionProof) : undefined; const tlogEntry = { logIndex: entry.logIndex.toString(), logId: { keyId: logID, }, integratedTime: entry.integratedTime.toString(), kindVersion: { kind: entryBody.kind, version: entryBody.apiVersion, }, inclusionPromise: promise, inclusionProof: proof, canonicalizedBody: Buffer.from(entry.body, 'base64'), }; return { tlogEntries: [tlogEntry], }; } function inclusionPromise(promise) { return { signedEntryTimestamp: Buffer.from(promise, 'base64'), }; } function inclusionProof(proof) { return { logIndex: proof.logIndex.toString(), treeSize: proof.treeSize.toString(), rootHash: Buffer.from(proof.rootHash, 'hex'), hashes: proof.hashes.map((h) => Buffer.from(h, 'hex')), checkpoint: { envelope: proof.checkpoint, }, }; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TSAClient = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("../../error"); const tsa_1 = require("../../external/tsa"); const util_1 = require("../../util"); const SHA256_ALGORITHM = 'sha256'; class TSAClient { constructor(options) { this.tsa = new tsa_1.TimestampAuthority({ baseURL: options.tsaBaseURL, retry: options.retry, timeout: options.timeout, }); } async createTimestamp(signature) { const request = { artifactHash: util_1.crypto .digest(SHA256_ALGORITHM, signature) .toString('base64'), hashAlgorithm: SHA256_ALGORITHM, }; try { return await this.tsa.createTimestamp(request); } catch (err) { (0, error_1.internalError)(err, 'TSA_CREATE_TIMESTAMP_ERROR', 'error creating timestamp'); } } } exports.TSAClient = TSAClient; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TSAWitness = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const client_1 = require("./client"); class TSAWitness { constructor(options) { this.tsa = new client_1.TSAClient({ tsaBaseURL: options.tsaBaseURL, retry: options.retry, timeout: options.timeout, }); } async testify(content) { const signature = extractSignature(content); const timestamp = await this.tsa.createTimestamp(signature); return { rfc3161Timestamps: [{ signedTimestamp: timestamp }], }; } } exports.TSAWitness = TSAWitness; function extractSignature(content) { switch (content.$case) { case 'dsseEnvelope': return content.dsseEnvelope.signatures[0].sig; case 'messageSignature': return content.messageSignature.signature; } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); { "name": "@sigstore/sign", "version": "3.0.0", "description": "Sigstore signing library", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "clean": "shx rm -rf dist *.tsbuildinfo", "build": "tsc --build", "test": "jest" }, "files": [ "dist" ], "author": "bdehamer@github.com", "license": "Apache-2.0", "repository": { "type": "git", "url": "git+https://github.com/sigstore/sigstore-js.git" }, "bugs": { "url": "https://github.com/sigstore/sigstore-js/issues" }, "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/sign#readme", "publishConfig": { "provenance": true }, "devDependencies": { "@sigstore/jest": "^0.0.0", "@sigstore/mock": "^0.8.0", "@sigstore/rekor-types": "^3.0.0", "@types/make-fetch-happen": "^10.0.4", "@types/promise-retry": "^1.1.6" }, "dependencies": { "@sigstore/bundle": "^3.0.0", "@sigstore/core": "^2.0.0", "@sigstore/protobuf-specs": "^0.3.2", "make-fetch-happen": "^14.0.1", "proc-log": "^5.0.0", "promise-retry": "^2.0.1" }, "engines": { "node": "^18.17.0 || >=20.5.0" } } Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 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 (50%) 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 The Sigstore Authors Licensed under the Apache License, Version 2.0 (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-2.0 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. "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.appDataPath = appDataPath; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const os_1 = __importDefault(require("os")); const path_1 = __importDefault(require("path")); function appDataPath(name) { const homedir = os_1.default.homedir(); switch (process.platform) { /* istanbul ignore next */ case 'darwin': { const appSupport = path_1.default.join(homedir, 'Library', 'Application Support'); return path_1.default.join(appSupport, name); } /* istanbul ignore next */ case 'win32': { const localAppData = process.env.LOCALAPPDATA || path_1.default.join(homedir, 'AppData', 'Local'); return path_1.default.join(localAppData, name, 'Data'); } /* istanbul ignore next */ default: { const localData = process.env.XDG_DATA_HOME || path_1.default.join(homedir, '.local', 'share'); return path_1.default.join(localData, name); } } } "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TUFClient = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const tuf_js_1 = require("tuf-js"); const _1 = require("."); const target_1 = require("./target"); const TARGETS_DIR_NAME = 'targets'; class TUFClient { constructor(options) { const url = new URL(options.mirrorURL); const repoName = encodeURIComponent(url.host + url.pathname.replace(/\/$/, '')); const cachePath = path_1.default.join(options.cachePath, repoName); initTufCache(cachePath); seedCache({ cachePath, mirrorURL: options.mirrorURL, tufRootPath: options.rootPath, forceInit: options.forceInit, }); this.updater = initClient({ mirrorURL: options.mirrorURL, cachePath, forceCache: options.forceCache, retry: options.retry, timeout: options.timeout, }); } async refresh() { return this.updater.refresh(); } getTarget(targetName) { return (0, target_1.readTarget)(this.updater, targetName); } } exports.TUFClient = TUFClient; // Initializes the TUF cache directory structure including the initial // root.json file. If the cache directory does not exist, it will be // created. If the targets directory does not exist, it will be created. // If the root.json file does not exist, it will be copied from the // rootPath argument. function initTufCache(cachePath) { const targetsPath = path_1.default.join(cachePath, TARGETS_DIR_NAME); if (!fs_1.default.existsSync(cachePath)) { fs_1.default.mkdirSync(cachePath, { recursive: true }); } if (!fs_1.default.existsSync(targetsPath)) { fs_1.default.mkdirSync(targetsPath); } } // Populates the TUF cache with the initial root.json file. If the root.json // file does not exist (or we're forcing re-initialization), copy it from either // the rootPath argument or from one of the repo seeds. function seedCache({ cachePath, mirrorURL, tufRootPath, forceInit, }) { const cachedRootPath = path_1.default.join(cachePath, 'root.json'); // If the root.json file does not exist (or we're forcing re-initialization), // populate it either from the supplied rootPath or from one of the repo seeds. if (!fs_1.default.existsSync(cachedRootPath) || forceInit) { if (tufRootPath) { fs_1.default.copyFileSync(tufRootPath, cachedRootPath); } else { const seeds = require('../seeds.json'); const repoSeed = seeds[mirrorURL]; if (!repoSeed) { throw new _1.TUFError({ code: 'TUF_INIT_CACHE_ERROR', message: `No root.json found for mirror: ${mirrorURL}`, }); } fs_1.default.writeFileSync(cachedRootPath, Buffer.from(repoSeed['root.json'], 'base64')); // Copy any seed targets into the cache Object.entries(repoSeed.targets).forEach(([targetName, target]) => { fs_1.default.writeFileSync(path_1.default.join(cachePath, TARGETS_DIR_NAME, targetName), Buffer.from(target, 'base64')); }); } } } function initClient(options) { const config = { fetchTimeout: options.timeout, fetchRetry: options.retry, }; return new tuf_js_1.Updater({ metadataBaseUrl: options.mirrorURL, targetBaseUrl: `${options.mirrorURL}/targets`, metadataDir: options.cachePath, targetDir: path_1.default.join(options.cachePath, TARGETS_DIR_NAME), forceCache: options.forceCache, config, }); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TUFError = void 0; class TUFError extends Error { constructor({ code, message, cause, }) { super(message); this.code = code; this.cause = cause; this.name = this.constructor.name; } } exports.TUFError = TUFError; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TUFError = exports.DEFAULT_MIRROR_URL = void 0; exports.getTrustedRoot = getTrustedRoot; exports.initTUF = initTUF; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const protobuf_specs_1 = require("@sigstore/protobuf-specs"); const appdata_1 = require("./appdata"); const client_1 = require("./client"); exports.DEFAULT_MIRROR_URL = 'https://tuf-repo-cdn.sigstore.dev'; const DEFAULT_CACHE_DIR = 'sigstore-js'; const DEFAULT_RETRY = { retries: 2 }; const DEFAULT_TIMEOUT = 5000; const TRUSTED_ROOT_TARGET = 'trusted_root.json'; async function getTrustedRoot( /* istanbul ignore next */ options = {}) { const client = createClient(options); const trustedRoot = await client.getTarget(TRUSTED_ROOT_TARGET); return protobuf_specs_1.TrustedRoot.fromJSON(JSON.parse(trustedRoot)); } async function initTUF( /* istanbul ignore next */ options = {}) { const client = createClient(options); return client.refresh().then(() => client); } // Create a TUF client with default options function createClient(options) { /* istanbul ignore next */ return new client_1.TUFClient({ cachePath: options.cachePath || (0, appdata_1.appDataPath)(DEFAULT_CACHE_DIR), rootPath: options.rootPath, mirrorURL: options.mirrorURL || exports.DEFAULT_MIRROR_URL, retry: options.retry ?? DEFAULT_RETRY, timeout: options.timeout ?? DEFAULT_TIMEOUT, forceCache: options.forceCache ?? false, forceInit: options.forceInit ?? options.force ?? false, }); } var error_1 = require("./error"); Object.defineProperty(exports, "TUFError", { enumerable: true, get: function () { return error_1.TUFError; } }); "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.readTarget = readTarget; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const fs_1 = __importDefault(require("fs")); const error_1 = require("./error"); // Downloads and returns the specified target from the provided TUF Updater. async function readTarget(tuf, targetPath) { const path = await getTargetPath(tuf, targetPath); return new Promise((resolve, reject) => { fs_1.default.readFile(path, 'utf-8', (err, data) => { if (err) { reject(new error_1.TUFError({ code: 'TUF_READ_TARGET_ERROR', message: `error reading target ${path}`, cause: err, })); } else { resolve(data); } }); }); } // Returns the local path to the specified target. If the target is not yet // cached locally, the provided TUF Updater will be used to download and // cache the target. async function getTargetPath(tuf, target) { let targetInfo; try { targetInfo = await tuf.getTargetInfo(target); } catch (err) { throw new error_1.TUFError({ code: 'TUF_REFRESH_METADATA_ERROR', message: 'error refreshing TUF metadata', cause: err, }); } if (!targetInfo) { throw new error_1.TUFError({ code: 'TUF_FIND_TARGET_ERROR', message: `target ${target} not found`, }); } let path = await tuf.findCachedTarget(targetInfo); // An empty path here means the target has not been cached locally, or is // out of date. In either case, we need to download it. if (!path) { try { path = await tuf.downloadTarget(targetInfo); } catch (err) { throw new error_1.TUFError({ code: 'TUF_DOWNLOAD_TARGET_ERROR', message: `error downloading target ${path}`, cause: err, }); } } return path; } { "name": "@sigstore/tuf", "version": "3.0.0", "description": "Client for the Sigstore TUF repository", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "clean": "shx rm -rf dist *.tsbuildinfo", "build": "tsc --build", "test": "jest" }, "files": [ "dist", "seeds.json" ], "author": "bdehamer@github.com", "license": "Apache-2.0", "repository": { "type": "git", "url": "git+https://github.com/sigstore/sigstore-js.git" }, "bugs": { "url": "https://github.com/sigstore/sigstore-js/issues" }, "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/tuf#readme", "publishConfig": { "provenance": true }, "devDependencies": { "@sigstore/jest": "^0.0.0", "@tufjs/repo-mock": "^3.0.1", "@types/make-fetch-happen": "^10.0.4" }, "dependencies": { "@sigstore/protobuf-specs": "^0.3.2", "tuf-js": "^3.0.1" }, "engines": { "node": "^18.17.0 || >=20.5.0" } } {"https://tuf-repo-cdn.sigstore.dev":{"root.json":"ewogInNpZ25hdHVyZXMiOiBbCiAgewogICAia2V5aWQiOiAiNmYyNjAwODlkNTkyM2RhZjIwMTY2Y2E2NTdjNTQzYWY2MTgzNDZhYjk3MTg4NGE5OTk2MmIwMTk4OGJiZTBjMyIsCiAgICJzaWciOiAiMzA0NjAyMjEwMDhhYjFmNmYxN2Q0ZjllNmQ3ZGNmMWM4ODkxMmI2YjUzY2MxMDM4ODY0NGFlMWYwOWJjMzdhMDgyY2QwNjAwM2UwMjIxMDBlMTQ1ZWY0YzdiNzgyZDRlODEwN2I1MzQzN2U2NjlkMDQ3Njg5MmNlOTk5OTAzYWUzM2QxNDQ0ODM2Njk5NmU3IgogIH0sCiAgewogICAia2V5aWQiOiAiZTcxYTU0ZDU0MzgzNWJhODZhZGFkOTQ2MDM3OWM3NjQxZmI4NzI2ZDE2NGVhNzY2ODAxYTFjNTIyYWJhN2VhMiIsCiAgICJzaWciOiAiMzA0NTAyMjEwMGM3NjhiMmY4NmRhOTk1NjkwMTljMTYwYTA4MWRhNTRhZTM2YzM0YzBhMzEyMGQzY2I2OWI1M2I3ZDExMzc1OGUwMjIwNGY2NzE1MThmNjE3YjIwZDQ2NTM3ZmFlNmMzYjYzYmFlODkxM2Y0ZjE5NjIxNTYxMDVjYzRmMDE5YWMzNWM2YSIKICB9LAogIHsKICAgImtleWlkIjogIjIyZjRjYWVjNmQ4ZTZmOTU1NWFmNjZiM2Q0YzNjYjA2YTNiYjIzZmRjN2UzOWM5MTZjNjFmNDYyZTZmNTJiMDYiLAogICAic2lnIjogIjMwNDUwMjIxMDBiNDQzNGU2OTk1ZDM2OGQyM2U3NDc1OWFjZDBjYjkwMTNjODNhNWQzNTExZjBmOTk3ZWM1NGM0NTZhZTQzNTBhMDIyMDE1YjBlMjY1ZDE4MmQyYjYxZGM3NGUxNTVkOThiM2MzZmJlNTY0YmEwNTI4NmFhMTRjOGRmMDJjOWI3NTY1MTYiCiAgfSwKICB7CiAgICJrZXlpZCI6ICI2MTY0MzgzODEyNWI0NDBiNDBkYjY5NDJmNWNiNWEzMWMwZGMwNDM2ODMxNmViMmFhYTU4Yjk1OTA0YTU4MjIyIiwKICAgInNpZyI6ICIzMDQ1MDIyMTAwODJjNTg0MTFkOTg5ZWI5Zjg2MTQxMDg1N2Q0MjM4MTU5MGVjOTQyNGRiZGFhNTFlNzhlZDEzNTE1NDMxOTA0ZTAyMjAxMTgxODVkYTZhNmMyOTQ3MTMxYzE3Nzk3ZTJiYjc2MjBjZTI2ZTVmMzAxZDFjZWFjNWYyYTdlNThmOWRjZjJlIgogIH0sCiAgewogICAia2V5aWQiOiAiYTY4N2U1YmY0ZmFiODJiMGVlNThkNDZlMDVjOTUzNTE0NWEyYzlhZmI0NThmNDNkNDJiNDVjYTBmZGNlMmE3MCIsCiAgICJzaWciOiAiMzA0NjAyMjEwMGM3ODUxMzg1NGNhZTljMzJlYWE2Yjg4ZTE4OTEyZjQ4MDA2YzI3NTdhMjU4ZjkxNzMxMmNhYmE3NTk0OGViOWUwMjIxMDBkOWUxYjRjZTBhZGZlOWZkMmUyMTQ4ZDdmYTI3YTJmNDBiYTExMjJiZDY5ZGE3NjEyZDhkMTc3NmIwMTNjOTFkIgogIH0sCiAgewogICAia2V5aWQiOiAiZmRmYTgzYTA3YjVhODM1ODliODdkZWQ0MWY3N2YzOWQyMzJhZDkxZjdjY2U1Mjg2OGRhY2QwNmJhMDg5ODQ5ZiIsCiAgICJzaWciOiAiMzA0NTAyMjA1NjQ4M2EyZDVkOWVhOWNlYzZlMTFlYWRmYjMzYzQ4NGI2MTQyOThmYWNhMTVhY2YxYzQzMWIxMWVkN2Y3MzRjMDIyMTAwZDBjMWQ3MjZhZjkyYTg3ZTRlNjY0NTljYTVhZGYzOGEwNWI0NGUxZjk0MzE4NDIzZjk1NGJhZThiY2E1YmIyZSIKICB9LAogIHsKICAgImtleWlkIjogImUyZjU5YWNiOTQ4ODUxOTQwN2UxOGNiZmM5MzI5NTEwYmUwM2MwNGFjYTk5MjlkMmYwMzAxMzQzZmVjODU1MjMiLAogICAic2lnIjogIjMwNDYwMjIxMDBkMDA0ZGU4ODAyNGMzMmRjNTY1M2E5ZjQ4NDNjZmM1MjE1NDI3MDQ4YWQ5NjAwZDJjZjljOTY5ZTZlZGZmM2QyMDIyMTAwZDllYmI3OThmNWZjNjZhZjEwODk5ZGVjZTAxNGE4NjI4Y2NmM2M1NDAyY2Q0YTQyNzAyMDc0NzJmOGY2ZTcxMiIKICB9LAogIHsKICAgImtleWlkIjogIjNjMzQ0YWEwNjhmZDRjYzRlODdkYzUwYjYxMmMwMjQzMWZiYzc3MWU5NTAwMzk5MzY4M2EyYjBiZjI2MGNmMGUiLAogICAic2lnIjogIjMwNDYwMjIxMDBiN2IwOTk5NmM0NWNhMmQ0YjA1NjAzZTU2YmFlZmEyOTcxOGEwYjcxMTQ3Y2Y4YzZlNjYzNDliYWE2MTQ3N2RmMDIyMTAwYzRkYTgwYzcxN2I0ZmE3YmJhMGZkNWM3MmRhOGEwNDk5MzU4YjAxMzU4YjIzMDlmNDFkMTQ1NmVhMWU3ZTFkOSIKICB9LAogIHsKICAgImtleWlkIjogImVjODE2Njk3MzRlMDE3OTk2YzViODVmM2QwMmMzZGUxZGQ0NjM3YTE1MjAxOWZlMWFmMTI1ZDJmOTM2OGI5NWUiLAogICAic2lnIjogIjMwNDYwMjIxMDBiZTk3ODJjMzA3NDRlNDExYTgyZmE4NWI1MTM4ZDYwMWNlMTQ4YmMxOTI1OGFlYzY0ZTdlYzI0NDc4ZjM4ODEyMDIyMTAwY2FlZjYzZGNhZjFhNGI5YTUwMGQzYmQwZTNmMTY0ZWMxOGYxYjYzZDdhOTQ2MGQ5YWNhYjEwNjZkYjBmMDE2ZCIKICB9LAogIHsKICAgImtleWlkIjogIjFlMWQ2NWNlOThiMTBhZGRhZDQ3NjRmZWJmN2RkYTJkMDQzNmIzZDNhMzg5MzU3OWMwZGRkYWVhMjBlNTQ4NDkiLAogICAic2lnIjogIjMwNDUwMjIwNzQ2ZWMzZjg1MzRjZTU1NTMxZDBkMDFmZjY0OTY0ZWY0NDBkMWU3ZDJjNGMxNDI0MDliOGU5NzY5ZjFhZGE2ZjAyMjEwMGUzYjkyOWZjZDkzZWExOGZlYWEwODI1ODg3YTcyMTA0ODk4NzlhNjY3ODBjMDdhODNmNGJkNDZlMmYwOWFiM2IiCiAgfQogXSwKICJzaWduZWQiOiB7CiAgIl90eXBlIjogInJvb3QiLAogICJjb25zaXN0ZW50X3NuYXBzaG90IjogdHJ1ZSwKICAiZXhwaXJlcyI6ICIyMDI1LTAyLTE5VDA4OjA0OjMyWiIsCiAgImtleXMiOiB7CiAgICIyMmY0Y2FlYzZkOGU2Zjk1NTVhZjY2YjNkNGMzY2IwNmEzYmIyM2ZkYzdlMzljOTE2YzYxZjQ2MmU2ZjUyYjA2IjogewogICAgImtleWlkX2hhc2hfYWxnb3JpdGhtcyI6IFsKICAgICAic2hhMjU2IiwKICAgICAic2hhNTEyIgogICAgXSwKICAgICJrZXl0eXBlIjogImVjZHNhIiwKICAgICJrZXl2YWwiOiB7CiAgICAgInB1YmxpYyI6ICItLS0tLUJFR0lOIFBVQkxJQyBLRVktLS0tLVxuTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFekJ6Vk9tSENQb2pNVkxTSTM2NFdpaVY4TlByRFxuNklnUnhWbGlza3ovdit5M0pFUjVtY1ZHY09ObGlEY1dNQzVKMmxmSG1qUE5QaGI0SDd4bThMemZTQT09XG4tLS0tLUVORCBQVUJMSUMgS0VZLS0tLS1cbiIKICAgIH0sCiAgICAic2NoZW1lIjogImVjZHNhLXNoYTItbmlzdHAyNTYiLAogICAgIngtdHVmLW9uLWNpLWtleW93bmVyIjogIkBzYW50aWFnb3RvcnJlcyIKICAgfSwKICAgIjYxNjQzODM4MTI1YjQ0MGI0MGRiNjk0MmY1Y2I1YTMxYzBkYzA0MzY4MzE2ZWIyYWFhNThiOTU5MDRhNTgyMjIiOiB7CiAgICAia2V5aWRfaGFzaF9hbGdvcml0aG1zIjogWwogICAgICJzaGEyNTYiLAogICAgICJzaGE1MTIiCiAgICBdLAogICAgImtleXR5cGUiOiAiZWNkc2EiLAogICAgImtleXZhbCI6IHsKICAgICAicHVibGljIjogIi0tLS0tQkVHSU4gUFVCTElDIEtFWS0tLS0tXG5NRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVpbmlrU3NBUW1Za05lSDVlWXEvQ25JekxhYWNPXG54bFNhYXdRRE93cUt5L3RDcXhxNXh4UFNKYzIxSzRXSWhzOUd5T2tLZnp1ZVkzR0lMemNNSlo0Y1d3PT1cbi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLVxuIgogICAgfSwKICAgICJzY2hlbWUiOiAiZWNkc2Etc2hhMi1uaXN0cDI1NiIsCiAgICAieC10dWYtb24tY2kta2V5b3duZXIiOiAiQGJvYmNhbGxhd2F5IgogICB9LAogICAiNmYyNjAwODlkNTkyM2RhZjIwMTY2Y2E2NTdjNTQzYWY2MTgzNDZhYjk3MTg4NGE5OTk2MmIwMTk4OGJiZTBjMyI6IHsKICAgICJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCiAgICAgInNoYTI1NiIsCiAgICAgInNoYTUxMiIKICAgIF0sCiAgICAia2V5dHlwZSI6ICJlY2RzYSIsCiAgICAia2V5dmFsIjogewogICAgICJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXk4WEtzbWhCWURJOEpjMEd3ekJ4ZUtheDBjbTVcblNUS0VVNjVIUEZ1blVuNDFzVDhwaTBGak00SWtIei9ZVW13bUxVTzBXdDdseGhqNkJrTElLNHFZQXc9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCiAgICB9LAogICAgInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKICAgICJ4LXR1Zi1vbi1jaS1rZXlvd25lciI6ICJAZGxvcmVuYyIKICAgfSwKICAgIjcyNDdmMGRiYWQ4NWIxNDdlMTg2M2JhZGU3NjEyNDNjYzc4NWRjYjdhYTQxMGU3MTA1ZGQzZDJiNjFhMzZkMmMiOiB7CiAgICAia2V5aWRfaGFzaF9hbGdvcml0aG1zIjogWwogICAgICJzaGEyNTYiLAogICAgICJzaGE1MTIiCiAgICBdLAogICAgImtleXR5cGUiOiAiZWNkc2EiLAogICAgImtleXZhbCI6IHsKICAgICAicHVibGljIjogIi0tLS0tQkVHSU4gUFVCTElDIEtFWS0tLS0tXG5NRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVXUmlHcjUraiszSjVTc0grWnRyNW5FMkgyd083XG5CVituTzNzOTNnTGNhMThxVE96SFkxb1d5QUdEeWtNU3NHVFVCU3Q5RCtBbjBLZktzRDJtZlNNNDJRPT1cbi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLVxuIgogICAgfSwKICAgICJzY2hlbWUiOiAiZWNkc2Etc2hhMi1uaXN0cDI1NiIsCiAgICAieC10dWYtb24tY2ktb25saW5lLXVyaSI6ICJnY3BrbXM6Ly9wcm9qZWN0cy9zaWdzdG9yZS1yb290LXNpZ25pbmcvbG9jYXRpb25zL2dsb2JhbC9rZXlSaW5ncy9yb290L2NyeXB0b0tleXMvdGltZXN0YW1wIgogICB9LAogICAiYTY4N2U1YmY0ZmFiODJiMGVlNThkNDZlMDVjOTUzNTE0NWEyYzlhZmI0NThmNDNkNDJiNDVjYTBmZGNlMmE3MCI6IHsKICAgICJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCiAgICAgInNoYTI1NiIsCiAgICAgInNoYTUxMiIKICAgIF0sCiAgICAia2V5dHlwZSI6ICJlY2RzYSIsCiAgICAia2V5dmFsIjogewogICAgICJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTBnaHJoOTJMdzFZcjNpZEdWNVdxQ3RNREI4Q3hcbitEOGhkQzR3MlpMTklwbFZSb1ZHTHNrWWEzZ2hlTXlPamlKOGtQaTE1YVEyLy83UCtvajdVdkpQR3c9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCiAgICB9LAogICAgInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKICAgICJ4LXR1Zi1vbi1jaS1rZXlvd25lciI6ICJAam9zaHVhZ2wiCiAgIH0sCiAgICJlNzFhNTRkNTQzODM1YmE4NmFkYWQ5NDYwMzc5Yzc2NDFmYjg3MjZkMTY0ZWE3NjY4MDFhMWM1MjJhYmE3ZWEyIjogewogICAgImtleWlkX2hhc2hfYWxnb3JpdGhtcyI6IFsKICAgICAic2hhMjU2IiwKICAgICAic2hhNTEyIgogICAgXSwKICAgICJrZXl0eXBlIjogImVjZHNhIiwKICAgICJrZXl2YWwiOiB7CiAgICAgInB1YmxpYyI6ICItLS0tLUJFR0lOIFBVQkxJQyBLRVktLS0tLVxuTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFRVhzejNTWlhGYjhqTVY0Mmo2cEpseWpialI4S1xuTjNCd29jZXhxNkxNSWI1cXNXS09RdkxOMTZOVWVmTGM0SHN3T291bVJzVlZhYWpTcFFTNmZvYmtSdz09XG4tLS0tLUVORCBQVUJMSUMgS0VZLS0tLS1cbiIKICAgIH0sCiAgICAic2NoZW1lIjogImVjZHNhLXNoYTItbmlzdHAyNTYiLAogICAgIngtdHVmLW9uLWNpLWtleW93bmVyIjogIkBtbm02NzgiCiAgIH0KICB9LAogICJyb2xlcyI6IHsKICAgInJvb3QiOiB7CiAgICAia2V5aWRzIjogWwogICAgICI2ZjI2MDA4OWQ1OTIzZGFmMjAxNjZjYTY1N2M1NDNhZjYxODM0NmFiOTcxODg0YTk5OTYyYjAxOTg4YmJlMGMzIiwKICAgICAiZTcxYTU0ZDU0MzgzNWJhODZhZGFkOTQ2MDM3OWM3NjQxZmI4NzI2ZDE2NGVhNzY2ODAxYTFjNTIyYWJhN2VhMiIsCiAgICAgIjIyZjRjYWVjNmQ4ZTZmOTU1NWFmNjZiM2Q0YzNjYjA2YTNiYjIzZmRjN2UzOWM5MTZjNjFmNDYyZTZmNTJiMDYiLAogICAgICI2MTY0MzgzODEyNWI0NDBiNDBkYjY5NDJmNWNiNWEzMWMwZGMwNDM2ODMxNmViMmFhYTU4Yjk1OTA0YTU4MjIyIiwKICAgICAiYTY4N2U1YmY0ZmFiODJiMGVlNThkNDZlMDVjOTUzNTE0NWEyYzlhZmI0NThmNDNkNDJiNDVjYTBmZGNlMmE3MCIKICAgIF0sCiAgICAidGhyZXNob2xkIjogMwogICB9LAogICAic25hcHNob3QiOiB7CiAgICAia2V5aWRzIjogWwogICAgICI3MjQ3ZjBkYmFkODViMTQ3ZTE4NjNiYWRlNzYxMjQzY2M3ODVkY2I3YWE0MTBlNzEwNWRkM2QyYjYxYTM2ZDJjIgogICAgXSwKICAgICJ0aHJlc2hvbGQiOiAxLAogICAgIngtdHVmLW9uLWNpLWV4cGlyeS1wZXJpb2QiOiAzNjUwLAogICAgIngtdHVmLW9uLWNpLXNpZ25pbmctcGVyaW9kIjogMzY1CiAgIH0sCiAgICJ0YXJnZXRzIjogewogICAgImtleWlkcyI6IFsKICAgICAiNmYyNjAwODlkNTkyM2RhZjIwMTY2Y2E2NTdjNTQzYWY2MTgzNDZhYjk3MTg4NGE5OTk2MmIwMTk4OGJiZTBjMyIsCiAgICAgImU3MWE1NGQ1NDM4MzViYTg2YWRhZDk0NjAzNzljNzY0MWZiODcyNmQxNjRlYTc2NjgwMWExYzUyMmFiYTdlYTIiLAogICAgICIyMmY0Y2FlYzZkOGU2Zjk1NTVhZjY2YjNkNGMzY2IwNmEzYmIyM2ZkYzdlMzljOTE2YzYxZjQ2MmU2ZjUyYjA2IiwKICAgICAiNjE2NDM4MzgxMjViNDQwYjQwZGI2OTQyZjVjYjVhMzFjMGRjMDQzNjgzMTZlYjJhYWE1OGI5NTkwNGE1ODIyMiIsCiAgICAgImE2ODdlNWJmNGZhYjgyYjBlZTU4ZDQ2ZTA1Yzk1MzUxNDVhMmM5YWZiNDU4ZjQzZDQyYjQ1Y2EwZmRjZTJhNzAiCiAgICBdLAogICAgInRocmVzaG9sZCI6IDMKICAgfSwKICAgInRpbWVzdGFtcCI6IHsKICAgICJrZXlpZHMiOiBbCiAgICAgIjcyNDdmMGRiYWQ4NWIxNDdlMTg2M2JhZGU3NjEyNDNjYzc4NWRjYjdhYTQxMGU3MTA1ZGQzZDJiNjFhMzZkMmMiCiAgICBdLAogICAgInRocmVzaG9sZCI6IDEsCiAgICAieC10dWYtb24tY2ktZXhwaXJ5LXBlcmlvZCI6IDcsCiAgICAieC10dWYtb24tY2ktc2lnbmluZy1wZXJpb2QiOiA0CiAgIH0KICB9LAogICJzcGVjX3ZlcnNpb24iOiAiMS4wIiwKICAidmVyc2lvbiI6IDEwLAogICJ4LXR1Zi1vbi1jaS1leHBpcnktcGVyaW9kIjogMTgyLAogICJ4LXR1Zi1vbi1jaS1zaWduaW5nLXBlcmlvZCI6IDMxCiB9Cn0=","targets":{"trusted_root.json":"ewogICJtZWRpYVR5cGUiOiAiYXBwbGljYXRpb24vdm5kLmRldi5zaWdzdG9yZS50cnVzdGVkcm9vdCtqc29uO3ZlcnNpb249MC4xIiwKICAidGxvZ3MiOiBbCiAgICB7CiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vcmVrb3Iuc2lnc3RvcmUuZGV2IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUUyRzJZKzJ0YWJkVFY1QmNHaUJJeDBhOWZBRndya0JibUxTR3RrczRMM3FYNnlZWTB6dWZCbmhDOFVyL2l5NTVHaFdQLzlBL2JZMkxoQzMwTTkrUll0dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjEtMDEtMTJUMTE6NTM6MjcuMDAwWiIKICAgICAgICB9CiAgICAgIH0sCiAgICAgICJsb2dJZCI6IHsKICAgICAgICAia2V5SWQiOiAid05JOWF0UUdseitWV2ZPNkxSeWdINFFVZlkvOFc0UkZ3aVQ1aTVXUmdCMD0iCiAgICAgIH0KICAgIH0KICBdLAogICJjZXJ0aWZpY2F0ZUF1dGhvcml0aWVzIjogWwogICAgewogICAgICAic3ViamVjdCI6IHsKICAgICAgICAib3JnYW5pemF0aW9uIjogInNpZ3N0b3JlLmRldiIsCiAgICAgICAgImNvbW1vbk5hbWUiOiAic2lnc3RvcmUiCiAgICAgIH0sCiAgICAgICJ1cmkiOiAiaHR0cHM6Ly9mdWxjaW8uc2lnc3RvcmUuZGV2IiwKICAgICAgImNlcnRDaGFpbiI6IHsKICAgICAgICAiY2VydGlmaWNhdGVzIjogWwogICAgICAgICAgewogICAgICAgICAgICAicmF3Qnl0ZXMiOiAiTUlJQitEQ0NBWDZnQXdJQkFnSVROVmtEWm9DaW9mUERzeTdkZm02Z2VMYnVoekFLQmdncWhrak9QUVFEQXpBcU1SVXdFd1lEVlFRS0V3eHphV2R6ZEc5eVpTNWtaWFl4RVRBUEJnTlZCQU1UQ0hOcFozTjBiM0psTUI0WERUSXhNRE13TnpBek1qQXlPVm9YRFRNeE1ESXlNekF6TWpBeU9Wb3dLakVWTUJNR0ExVUVDaE1NYzJsbmMzUnZjbVV1WkdWMk1SRXdEd1lEVlFRREV3aHphV2R6ZEc5eVpUQjJNQkFHQnlxR1NNNDlBZ0VHQlN1QkJBQWlBMklBQkxTeUE3SWk1aytwTk84WkVXWTB5bGVtV0Rvd09rTmEza0wrR1pFNVo1R1dlaEw5L0E5YlJOQTNSYnJzWjVpMEpjYXN0YVJMN1NwNWZwL2pENWR4cWMvVWRUVm5sdlMxNmFuKzJZZnN3ZS9RdUxvbFJVQ3JjT0UyKzJpQTUrdHpkNk5tTUdRd0RnWURWUjBQQVFIL0JBUURBZ0VHTUJJR0ExVWRFd0VCL3dRSU1BWUJBZjhDQVFFd0hRWURWUjBPQkJZRUZNakZIUUJCbWlRcE1sRWs2dzJ1U3UxS0J0UHNNQjhHQTFVZEl3UVlNQmFBRk1qRkhRQkJtaVFwTWxFazZ3MnVTdTFLQnRQc01Bb0dDQ3FHU000OUJBTURBMmdBTUdVQ01IOGxpV0pmTXVpNnZYWEJoakRnWTRNd3NsbU4vVEp4VmUvODNXckZvbXdtTmYwNTZ5MVg0OEY5YzRtM2Ezb3pYQUl4QUtqUmF5NS9hai9qc0tLR0lrbVFhdGpJOHV1cEhyLytDeEZ2YUpXbXBZcU5rTERHUlUrOW9yemg1aEkyUnJjdWFRPT0iCiAgICAgICAgICB9CiAgICAgICAgXQogICAgICB9LAogICAgICAidmFsaWRGb3IiOiB7CiAgICAgICAgInN0YXJ0IjogIjIwMjEtMDMtMDdUMDM6MjA6MjkuMDAwWiIsCiAgICAgICAgImVuZCI6ICIyMDIyLTEyLTMxVDIzOjU5OjU5Ljk5OVoiCiAgICAgIH0KICAgIH0sCiAgICB7CiAgICAgICJzdWJqZWN0IjogewogICAgICAgICJvcmdhbml6YXRpb24iOiAic2lnc3RvcmUuZGV2IiwKICAgICAgICAiY29tbW9uTmFtZSI6ICJzaWdzdG9yZSIKICAgICAgfSwKICAgICAgInVyaSI6ICJodHRwczovL2Z1bGNpby5zaWdzdG9yZS5kZXYiLAogICAgICAiY2VydENoYWluIjogewogICAgICAgICJjZXJ0aWZpY2F0ZXMiOiBbCiAgICAgICAgICB7CiAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNSUlDR2pDQ0FhR2dBd0lCQWdJVUFMblZpVmZuVTBickphc21Sa0hybi9VbmZhUXdDZ1lJS29aSXpqMEVBd013S2pFVk1CTUdBMVVFQ2hNTWMybG5jM1J2Y21VdVpHVjJNUkV3RHdZRFZRUURFd2h6YVdkemRHOXlaVEFlRncweU1qQTBNVE15TURBMk1UVmFGdzB6TVRFd01EVXhNelUyTlRoYU1EY3hGVEFUQmdOVkJBb1RESE5wWjNOMGIzSmxMbVJsZGpFZU1Cd0dBMVVFQXhNVmMybG5jM1J2Y21VdGFXNTBaWEp0WldScFlYUmxNSFl3RUFZSEtvWkl6ajBDQVFZRks0RUVBQ0lEWWdBRThSVlMveXNIK05PdnVEWnlQSVp0aWxnVUY5TmxhcllwQWQ5SFAxdkJCSDFVNUNWNzdMU1M3czBaaUg0bkU3SHY3cHRTNkx2dlIvU1RrNzk4TFZnTXpMbEo0SGVJZkYzdEhTYWV4TGNZcFNBU3Ixa1MwTi9SZ0JKei85aldDaVhubzNzd2VUQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0V3WURWUjBsQkF3d0NnWUlLd1lCQlFVSEF3TXdFZ1lEVlIwVEFRSC9CQWd3QmdFQi93SUJBREFkQmdOVkhRNEVGZ1FVMzlQcHoxWWtFWmI1cU5qcEtGV2l4aTRZWkQ4d0h3WURWUjBqQkJnd0ZvQVVXTUFlWDVGRnBXYXBlc3lRb1pNaTBDckZ4Zm93Q2dZSUtvWkl6ajBFQXdNRFp3QXdaQUl3UENzUUs0RFlpWllEUElhRGk1SEZLbmZ4WHg2QVNTVm1FUmZzeW5ZQmlYMlg2U0pSblpVODQvOURaZG5GdnZ4bUFqQk90NlFwQmxjNEovMER4dmtUQ3FwY2x2emlMNkJDQ1BuamRsSUIzUHUzQnhzUG15Z1VZN0lpMnpiZENkbGlpb3c9IgogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgInJhd0J5dGVzIjogIk1JSUI5ekNDQVh5Z0F3SUJBZ0lVQUxaTkFQRmR4SFB3amVEbG9Ed3lZQ2hBTy80d0NnWUlLb1pJemowRUF3TXdLakVWTUJNR0ExVUVDaE1NYzJsbmMzUnZjbVV1WkdWMk1SRXdEd1lEVlFRREV3aHphV2R6ZEc5eVpUQWVGdzB5TVRFd01EY3hNelUyTlRsYUZ3MHpNVEV3TURVeE16VTJOVGhhTUNveEZUQVRCZ05WQkFvVERITnBaM04wYjNKbExtUmxkakVSTUE4R0ExVUVBeE1JYzJsbmMzUnZjbVV3ZGpBUUJnY3Foa2pPUFFJQkJnVXJnUVFBSWdOaUFBVDdYZUZUNHJiM1BRR3dTNElhanRMazMvT2xucGdhbmdhQmNsWXBzWUJyNWkrNHluQjA3Y2ViM0xQME9JT1pkeGV4WDY5YzVpVnV5SlJRK0h6MDV5aStVRjN1QldBbEhwaVM1c2gwK0gyR0hFN1NYcmsxRUM1bTFUcjE5TDlnZzkyall6QmhNQTRHQTFVZER3RUIvd1FFQXdJQkJqQVBCZ05WSFJNQkFmOEVCVEFEQVFIL01CMEdBMVVkRGdRV0JCUll3QjVma1VXbFpxbDZ6SkNoa3lMUUtzWEYrakFmQmdOVkhTTUVHREFXZ0JSWXdCNWZrVVdsWnFsNnpKQ2hreUxRS3NYRitqQUtCZ2dxaGtqT1BRUURBd05wQURCbUFqRUFqMW5IZVhacCsxM05XQk5hK0VEc0RQOEcxV1dnMXRDTVdQL1dIUHFwYVZvMGpoc3dlTkZaZ1NzMGVFN3dZSTRxQWpFQTJXQjlvdDk4c0lrb0YzdlpZZGQzL1Z0V0I1YjlUTk1lYTdJeC9zdEo1VGZjTExlQUJMRTRCTkpPc1E0dm5CSEoiCiAgICAgICAgICB9CiAgICAgICAgXQogICAgICB9LAogICAgICAidmFsaWRGb3IiOiB7CiAgICAgICAgInN0YXJ0IjogIjIwMjItMDQtMTNUMjA6MDY6MTUuMDAwWiIKICAgICAgfQogICAgfQogIF0sCiAgImN0bG9ncyI6IFsKICAgIHsKICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly9jdGZlLnNpZ3N0b3JlLmRldi90ZXN0IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUViZndSK1JKdWRYc2NnUkJScEtYMVhGRHkzUHl1ZER4ei9TZm5SaTFmVDhla3BmQmQyTzF1b3o3anIzWjhuS3p4QTY5RVVRK2VGQ0ZJM3pldWJQV1U3dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjEtMDMtMTRUMDA6MDA6MDAuMDAwWiIsCiAgICAgICAgICAiZW5kIjogIjIwMjItMTAtMzFUMjM6NTk6NTkuOTk5WiIKICAgICAgICB9CiAgICAgIH0sCiAgICAgICJsb2dJZCI6IHsKICAgICAgICAia2V5SWQiOiAiQ0dDUzhDaFMvMmhGMGRGcko0U2NSV2NZckJZOXd6alNiZWE4SWdZMmIzST0iCiAgICAgIH0KICAgIH0sCiAgICB7CiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vY3RmZS5zaWdzdG9yZS5kZXYvMjAyMiIsCiAgICAgICJoYXNoQWxnb3JpdGhtIjogIlNIQTJfMjU2IiwKICAgICAgInB1YmxpY0tleSI6IHsKICAgICAgICAicmF3Qnl0ZXMiOiAiTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFaVBTbEZpMENtRlRmRWpDVXFGOUh1Q0VjWVhOS0FhWWFsSUptQlo4eXllelBqVHFoeHJLQnBNbmFvY1Z0TEpCSTFlTTN1WG5RelFHQUpkSjRnczlGeXc9PSIsCiAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICJ2YWxpZEZvciI6IHsKICAgICAgICAgICJzdGFydCI6ICIyMDIyLTEwLTIwVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgfQogICAgICB9LAogICAgICAibG9nSWQiOiB7CiAgICAgICAgImtleUlkIjogIjNUMHdhc2JIRVRKakdSNGNtV2MzQXFKS1hyamVQSzMvaDRweWdDOHA3bzQ9IgogICAgICB9CiAgICB9CiAgXSwKICAidGltZXN0YW1wQXV0aG9yaXRpZXMiOiBbCiAgICB7CiAgICAgICJzdWJqZWN0IjogewogICAgICAgICJvcmdhbml6YXRpb24iOiAiR2l0SHViLCBJbmMuIiwKICAgICAgICAiY29tbW9uTmFtZSI6ICJJbnRlcm5hbCBTZXJ2aWNlcyBSb290IgogICAgICB9LAogICAgICAiY2VydENoYWluIjogewogICAgICAgICJjZXJ0aWZpY2F0ZXMiOiBbCiAgICAgICAgICB7CiAgICAgICAgICAgICJyYXdCeXRlcyI6ICJNSUlCM0RDQ0FXS2dBd0lCQWdJVWNoa05zSDM2WGEwNGIxTHFJYytxcjlEVmVjTXdDZ1lJS29aSXpqMEVBd013TWpFVk1CTUdBMVVFQ2hNTVIybDBTSFZpTENCSmJtTXVNUmt3RndZRFZRUURFeEJVVTBFZ2FXNTBaWEp0WldScFlYUmxNQjRYRFRJek1EUXhOREF3TURBd01Gb1hEVEkwTURReE16QXdNREF3TUZvd01qRVZNQk1HQTFVRUNoTU1SMmwwU0hWaUxDQkpibU11TVJrd0Z3WURWUVFERXhCVVUwRWdWR2x0WlhOMFlXMXdhVzVuTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFVUQ1Wk5iU3FZTWQ2cjhxcE9PRVg5aWJHblpUOUdzdVhPaHIvZjhVOUZKdWdCR0V4S1lwNDBPVUxTMGVyalpXN3hWOXhWNTJObkpmNU9lRHE0ZTVaS3FOV01GUXdEZ1lEVlIwUEFRSC9CQVFEQWdlQU1CTUdBMVVkSlFRTU1Bb0dDQ3NHQVFVRkJ3TUlNQXdHQTFVZEV3RUIvd1FDTUFBd0h3WURWUjBqQkJnd0ZvQVVhVzFSdWRPZ1Z0MGxlcVkwV0tZYnVQcjQ3d0F3Q2dZSUtvWkl6ajBFQXdNRGFBQXdaUUl3YlVIOUh2RDRlakNaSk9XUW5xQWxrcVVSbGx2dTlNOCtWcUxiaVJLK3pTZlpDWndzaWxqUm44TVFRUlNrWEVFNUFqRUFnK1Z4cXRvamZWZnU4RGh6emhDeDlHS0VUYkpIYjE5aVY3Mm1NS1ViREFGbXpaNmJROGI1NFpiOHRpZHk1YVdlIgogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgInJhd0J5dGVzIjogIk1JSUNFRENDQVpXZ0F3SUJBZ0lVWDhaTzVRWFA3dk40ZE1RNWU5c1UzbnViOE9nd0NnWUlLb1pJemowRUF3TXdPREVWTUJNR0ExVUVDaE1NUjJsMFNIVmlMQ0JKYm1NdU1SOHdIUVlEVlFRREV4WkpiblJsY201aGJDQlRaWEoyYVdObGN5QlNiMjkwTUI0WERUSXpNRFF4TkRBd01EQXdNRm9YRFRJNE1EUXhNakF3TURBd01Gb3dNakVWTUJNR0ExVUVDaE1NUjJsMFNIVmlMQ0JKYm1NdU1Sa3dGd1lEVlFRREV4QlVVMEVnYVc1MFpYSnRaV1JwWVhSbE1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFdk1MWS9kVFZidklKWUFOQXVzekV3Sm5RRTFsbGZ0eW55TUtJTWhoNDhIbXFiVnI1eWd5YnpzTFJMVktiQldPZFoyMWFlSnorZ1ppeXRaZXRxY3lGOVdsRVI1TkVNZjZKVjdaTm9qUXB4SHE0UkhHb0dTY2VRdi9xdlRpWnhFREtvMll3WkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RWdZRFZSMFRBUUgvQkFnd0JnRUIvd0lCQURBZEJnTlZIUTRFRmdRVWFXMVJ1ZE9nVnQwbGVxWTBXS1lidVByNDd3QXdId1lEVlIwakJCZ3dGb0FVOU5ZWWxvYm5BRzRjMC9xanh5SC9scS93eitRd0NnWUlLb1pJemowRUF3TURhUUF3WmdJeEFLMUIxODV5Z0NySVlGbElzM0dqc3dqbndTTUc2TFk4d29MVmRha0tEWnhWYThmOGNxTXMxRGhjeEowKzA5dzk1UUl4QU8rdEJ6Wms3dmpVSjlpSmdENFI2WldUeFFXS3FObTc0ak85OW8rbzlzdjRGSS9TWlRaVEZ5TW4wSUpFSGRObXlBPT0iCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAicmF3Qnl0ZXMiOiAiTUlJQjlEQ0NBWHFnQXdJQkFnSVVhL0pBa2RVaks0SlV3c3F0YWlSSkdXaHFMU293Q2dZSUtvWkl6ajBFQXdNd09ERVZNQk1HQTFVRUNoTU1SMmwwU0hWaUxDQkpibU11TVI4d0hRWURWUVFERXhaSmJuUmxjbTVoYkNCVFpYSjJhV05sY3lCU2IyOTBNQjRYRFRJek1EUXhOREF3TURBd01Gb1hEVE16TURReE1UQXdNREF3TUZvd09ERVZNQk1HQTFVRUNoTU1SMmwwU0hWaUxDQkpibU11TVI4d0hRWURWUVFERXhaSmJuUmxjbTVoYkNCVFpYSjJhV05sY3lCU2IyOTBNSFl3RUFZSEtvWkl6ajBDQVFZRks0RUVBQ0lEWWdBRWY5akZBWHh6NGt4NjhBSFJNT2tGQmhmbERjTVR2emFYejR4L0ZDY1hqSi8xcUVLb24vcVBJR25hVVJza0R0eU5iTkRPcGVKVERERnF0NDhpTVBybnpweDZJWndxZW1mVUpONHhCRVpmemErcFl0L2l5b2QrOXRacjIwUlJXU3YvbzBVd1F6QU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VnWURWUjBUQVFIL0JBZ3dCZ0VCL3dJQkFqQWRCZ05WSFE0RUZnUVU5TllZbG9ibkFHNGMwL3FqeHlIL2xxL3d6K1F3Q2dZSUtvWkl6ajBFQXdNRGFBQXdaUUl4QUxaTFo4QmdSWHpLeExNTU45VklsTytlNGhyQm5OQmdGN3R6N0hucm93djJOZXRaRXJJQUNLRnltQmx2V0R2dE1BSXdaTytraTZzc1ExYnNabzk4TzhtRUFmMk5aN2lpQ2dERFUwVndqZWNvNnp5ZWgwekJUczkvN2dWNkFITlE1M3hEIgogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfSwKICAgICAgInZhbGlkRm9yIjogewogICAgICAgICJzdGFydCI6ICIyMDIzLTA0LTE0VDAwOjAwOjAwLjAwMFoiCiAgICAgIH0KICAgIH0KICBdCn0K","registry.npmjs.org%2Fkeys.json":"ewogICAgImtleXMiOiBbCiAgICAgICAgewogICAgICAgICAgICAia2V5SWQiOiAiU0hBMjU2OmpsM2J3c3d1ODBQampva0NnaDBvMnc1YzJVNExoUUFFNTdnajljejFrekEiLAogICAgICAgICAgICAia2V5VXNhZ2UiOiAibnBtOnNpZ25hdHVyZXMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIxOTk5LTAxLTAxVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9LAogICAgICAgIHsKICAgICAgICAgICAgImtleUlkIjogIlNIQTI1NjpqbDNid3N3dTgwUGpqb2tDZ2gwbzJ3NWMyVTRMaFFBRTU3Z2o5Y3oxa3pBIiwKICAgICAgICAgICAgImtleVVzYWdlIjogIm5wbTphdHRlc3RhdGlvbnMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIyMDIyLTEyLTAxVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICBdCn0K"}}} "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DSSESignatureContent = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); class DSSESignatureContent { constructor(env) { this.env = env; } compareDigest(digest) { return core_1.crypto.bufferEqual(digest, core_1.crypto.digest('sha256', this.env.payload)); } compareSignature(signature) { return core_1.crypto.bufferEqual(signature, this.signature); } verifySignature(key) { return core_1.crypto.verify(this.preAuthEncoding, key, this.signature); } get signature() { return this.env.signatures.length > 0 ? this.env.signatures[0].sig : Buffer.from(''); } // DSSE Pre-Authentication Encoding get preAuthEncoding() { return core_1.dsse.preAuthEncoding(this.env.payloadType, this.env.payload); } } exports.DSSESignatureContent = DSSESignatureContent; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toSignedEntity = toSignedEntity; exports.signatureContent = signatureContent; const core_1 = require("@sigstore/core"); const dsse_1 = require("./dsse"); const message_1 = require("./message"); function toSignedEntity(bundle, artifact) { const { tlogEntries, timestampVerificationData } = bundle.verificationMaterial; const timestamps = []; for (const entry of tlogEntries) { timestamps.push({ $case: 'transparency-log', tlogEntry: entry, }); } for (const ts of timestampVerificationData?.rfc3161Timestamps ?? []) { timestamps.push({ $case: 'timestamp-authority', timestamp: core_1.RFC3161Timestamp.parse(ts.signedTimestamp), }); } return { signature: signatureContent(bundle, artifact), key: key(bundle), tlogEntries, timestamps, }; } function signatureContent(bundle, artifact) { switch (bundle.content.$case) { case 'dsseEnvelope': return new dsse_1.DSSESignatureContent(bundle.content.dsseEnvelope); case 'messageSignature': return new message_1.MessageSignatureContent(bundle.content.messageSignature, artifact); } } function key(bundle) { switch (bundle.verificationMaterial.content.$case) { case 'publicKey': return { $case: 'public-key', hint: bundle.verificationMaterial.content.publicKey.hint, }; case 'x509CertificateChain': return { $case: 'certificate', certificate: core_1.X509Certificate.parse(bundle.verificationMaterial.content.x509CertificateChain .certificates[0].rawBytes), }; case 'certificate': return { $case: 'certificate', certificate: core_1.X509Certificate.parse(bundle.verificationMaterial.content.certificate.rawBytes), }; } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MessageSignatureContent = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); class MessageSignatureContent { constructor(messageSignature, artifact) { this.signature = messageSignature.signature; this.messageDigest = messageSignature.messageDigest.digest; this.artifact = artifact; } compareSignature(signature) { return core_1.crypto.bufferEqual(signature, this.signature); } compareDigest(digest) { return core_1.crypto.bufferEqual(digest, this.messageDigest); } verifySignature(key) { return core_1.crypto.verify(this.artifact, key, this.signature); } } exports.MessageSignatureContent = MessageSignatureContent; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PolicyError = exports.VerificationError = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ class BaseError extends Error { constructor({ code, message, cause, }) { super(message); this.code = code; this.cause = cause; this.name = this.constructor.name; } } class VerificationError extends BaseError { } exports.VerificationError = VerificationError; class PolicyError extends BaseError { } exports.PolicyError = PolicyError; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Verifier = exports.toTrustMaterial = exports.VerificationError = exports.PolicyError = exports.toSignedEntity = void 0; /* istanbul ignore file */ /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ var bundle_1 = require("./bundle"); Object.defineProperty(exports, "toSignedEntity", { enumerable: true, get: function () { return bundle_1.toSignedEntity; } }); var error_1 = require("./error"); Object.defineProperty(exports, "PolicyError", { enumerable: true, get: function () { return error_1.PolicyError; } }); Object.defineProperty(exports, "VerificationError", { enumerable: true, get: function () { return error_1.VerificationError; } }); var trust_1 = require("./trust"); Object.defineProperty(exports, "toTrustMaterial", { enumerable: true, get: function () { return trust_1.toTrustMaterial; } }); var verifier_1 = require("./verifier"); Object.defineProperty(exports, "Verifier", { enumerable: true, get: function () { return verifier_1.Verifier; } }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CertificateChainVerifier = void 0; exports.verifyCertificateChain = verifyCertificateChain; const error_1 = require("../error"); const trust_1 = require("../trust"); function verifyCertificateChain(leaf, certificateAuthorities) { // Filter list of trusted CAs to those which are valid for the given // leaf certificate. const cas = (0, trust_1.filterCertAuthorities)(certificateAuthorities, { start: leaf.notBefore, end: leaf.notAfter, }); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ let error; for (const ca of cas) { try { const verifier = new CertificateChainVerifier({ trustedCerts: ca.certChain, untrustedCert: leaf, }); return verifier.verify(); } catch (err) { error = err; } } // If we failed to verify the certificate chain for all of the trusted // CAs, throw the last error we encountered. throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'Failed to verify certificate chain', cause: error, }); } class CertificateChainVerifier { constructor(opts) { this.untrustedCert = opts.untrustedCert; this.trustedCerts = opts.trustedCerts; this.localCerts = dedupeCertificates([ ...opts.trustedCerts, opts.untrustedCert, ]); } verify() { // Construct certificate path from leaf to root const certificatePath = this.sort(); // Perform validation checks on each certificate in the path this.checkPath(certificatePath); // Return verified certificate path return certificatePath; } sort() { const leafCert = this.untrustedCert; // Construct all possible paths from the leaf let paths = this.buildPaths(leafCert); // Filter for paths which contain a trusted certificate paths = paths.filter((path) => path.some((cert) => this.trustedCerts.includes(cert))); if (paths.length === 0) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'no trusted certificate path found', }); } // Find the shortest of possible paths /* istanbul ignore next */ const path = paths.reduce((prev, curr) => prev.length < curr.length ? prev : curr); // Construct chain from shortest path // Removes the last certificate in the path, which will be a second copy // of the root certificate given that the root is self-signed. return [leafCert, ...path].slice(0, -1); } // Recursively build all possible paths from the leaf to the root buildPaths(certificate) { const paths = []; const issuers = this.findIssuer(certificate); if (issuers.length === 0) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'no valid certificate path found', }); } for (let i = 0; i < issuers.length; i++) { const issuer = issuers[i]; // Base case - issuer is self if (issuer.equals(certificate)) { paths.push([certificate]); continue; } // Recursively build path for the issuer const subPaths = this.buildPaths(issuer); // Construct paths by appending the issuer to each subpath for (let j = 0; j < subPaths.length; j++) { paths.push([issuer, ...subPaths[j]]); } } return paths; } // Return all possible issuers for the given certificate findIssuer(certificate) { let issuers = []; let keyIdentifier; // Exit early if the certificate is self-signed if (certificate.subject.equals(certificate.issuer)) { if (certificate.verify()) { return [certificate]; } } // If the certificate has an authority key identifier, use that // to find the issuer if (certificate.extAuthorityKeyID) { keyIdentifier = certificate.extAuthorityKeyID.keyIdentifier; // TODO: Add support for authorityCertIssuer/authorityCertSerialNumber // though Fulcio doesn't appear to use these } // Find possible issuers by comparing the authorityKeyID/subjectKeyID // or issuer/subject. Potential issuers are added to the result array. this.localCerts.forEach((possibleIssuer) => { if (keyIdentifier) { if (possibleIssuer.extSubjectKeyID) { if (possibleIssuer.extSubjectKeyID.keyIdentifier.equals(keyIdentifier)) { issuers.push(possibleIssuer); } return; } } // Fallback to comparing certificate issuer and subject if // subjectKey/authorityKey extensions are not present if (possibleIssuer.subject.equals(certificate.issuer)) { issuers.push(possibleIssuer); } }); // Remove any issuers which fail to verify the certificate issuers = issuers.filter((issuer) => { try { return certificate.verify(issuer); } catch (ex) { /* istanbul ignore next - should never error */ return false; } }); return issuers; } checkPath(path) { /* istanbul ignore if */ if (path.length < 1) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'certificate chain must contain at least one certificate', }); } // Ensure that all certificates beyond the leaf are CAs const validCAs = path.slice(1).every((cert) => cert.isCA); if (!validCAs) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'intermediate certificate is not a CA', }); } // Certificate's issuer must match the subject of the next certificate // in the chain for (let i = path.length - 2; i >= 0; i--) { /* istanbul ignore if */ if (!path[i].issuer.equals(path[i + 1].subject)) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'incorrect certificate name chaining', }); } } // Check pathlength constraints for (let i = 0; i < path.length; i++) { const cert = path[i]; // If the certificate is a CA, check the path length if (cert.extBasicConstraints?.isCA) { const pathLength = cert.extBasicConstraints.pathLenConstraint; // The path length, if set, indicates how many intermediate // certificates (NOT including the leaf) are allowed to follow. The // pathLength constraint of any intermediate CA certificate MUST be // greater than or equal to it's own depth in the chain (with an // adjustment for the leaf certificate) if (pathLength !== undefined && pathLength < i - 1) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'path length constraint exceeded', }); } } } } } exports.CertificateChainVerifier = CertificateChainVerifier; // Remove duplicate certificates from the array function dedupeCertificates(certs) { for (let i = 0; i < certs.length; i++) { for (let j = i + 1; j < certs.length; j++) { if (certs[i].equals(certs[j])) { certs.splice(j, 1); j--; } } } return certs; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyPublicKey = verifyPublicKey; exports.verifyCertificate = verifyCertificate; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); const error_1 = require("../error"); const certificate_1 = require("./certificate"); const sct_1 = require("./sct"); const OID_FULCIO_ISSUER_V1 = '1.3.6.1.4.1.57264.1.1'; const OID_FULCIO_ISSUER_V2 = '1.3.6.1.4.1.57264.1.8'; function verifyPublicKey(hint, timestamps, trustMaterial) { const key = trustMaterial.publicKey(hint); timestamps.forEach((timestamp) => { if (!key.validFor(timestamp)) { throw new error_1.VerificationError({ code: 'PUBLIC_KEY_ERROR', message: `Public key is not valid for timestamp: ${timestamp.toISOString()}`, }); } }); return { key: key.publicKey }; } function verifyCertificate(leaf, timestamps, trustMaterial) { // Check that leaf certificate chains to a trusted CA const path = (0, certificate_1.verifyCertificateChain)(leaf, trustMaterial.certificateAuthorities); // Check that ALL certificates are valid for ALL of the timestamps const validForDate = timestamps.every((timestamp) => path.every((cert) => cert.validForDate(timestamp))); if (!validForDate) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'certificate is not valid or expired at the specified date', }); } return { scts: (0, sct_1.verifySCTs)(path[0], path[1], trustMaterial.ctlogs), signer: getSigner(path[0]), }; } function getSigner(cert) { let issuer; const issuerExtension = cert.extension(OID_FULCIO_ISSUER_V2); /* istanbul ignore next */ if (issuerExtension) { issuer = issuerExtension.valueObj.subs?.[0]?.value.toString('ascii'); } else { issuer = cert.extension(OID_FULCIO_ISSUER_V1)?.value.toString('ascii'); } const identity = { extensions: { issuer }, subjectAlternativeName: cert.subjectAltName, }; return { key: core_1.crypto.createPublicKey(cert.publicKey), identity, }; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySCTs = verifySCTs; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); const error_1 = require("../error"); const trust_1 = require("../trust"); function verifySCTs(cert, issuer, ctlogs) { let extSCT; // Verifying the SCT requires that we remove the SCT extension and // re-encode the TBS structure to DER -- this value is part of the data // over which the signature is calculated. Since this is a destructive action // we create a copy of the certificate so we can remove the SCT extension // without affecting the original certificate. const clone = cert.clone(); // Intentionally not using the findExtension method here because we want to // remove the the SCT extension from the certificate before calculating the // PreCert structure for (let i = 0; i < clone.extensions.length; i++) { const ext = clone.extensions[i]; if (ext.subs[0].toOID() === core_1.EXTENSION_OID_SCT) { extSCT = new core_1.X509SCTExtension(ext); // Remove the extension from the certificate clone.extensions.splice(i, 1); break; } } // No SCT extension found to verify if (!extSCT) { return []; } // Found an SCT extension but it has no SCTs /* istanbul ignore if -- too difficult to fabricate test case for this */ if (extSCT.signedCertificateTimestamps.length === 0) { return []; } // Construct the PreCert structure // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 const preCert = new core_1.ByteStream(); // Calculate hash of the issuer's public key const issuerId = core_1.crypto.digest('sha256', issuer.publicKey); preCert.appendView(issuerId); // Re-encodes the certificate to DER after removing the SCT extension const tbs = clone.tbsCertificate.toDER(); preCert.appendUint24(tbs.length); preCert.appendView(tbs); // Calculate and return the verification results for each SCT return extSCT.signedCertificateTimestamps.map((sct) => { // Find the ctlog instance that corresponds to the SCT's logID const validCTLogs = (0, trust_1.filterTLogAuthorities)(ctlogs, { logID: sct.logID, targetDate: sct.datetime, }); // See if the SCT is valid for any of the CT logs const verified = validCTLogs.some((log) => sct.verify(preCert.buffer, log.publicKey)); if (!verified) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'SCT verification failed', }); } return sct.logID; }); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySubjectAlternativeName = verifySubjectAlternativeName; exports.verifyExtensions = verifyExtensions; const error_1 = require("./error"); function verifySubjectAlternativeName(policyIdentity, signerIdentity) { if (signerIdentity === undefined || !signerIdentity.match(policyIdentity)) { throw new error_1.PolicyError({ code: 'UNTRUSTED_SIGNER_ERROR', message: `certificate identity error - expected ${policyIdentity}, got ${signerIdentity}`, }); } } function verifyExtensions(policyExtensions, signerExtensions = {}) { let key; for (key in policyExtensions) { if (signerExtensions[key] !== policyExtensions[key]) { throw new error_1.PolicyError({ code: 'UNTRUSTED_SIGNER_ERROR', message: `invalid certificate extension - expected ${key}=${policyExtensions[key]}, got ${key}=${signerExtensions[key]}`, }); } } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyCheckpoint = verifyCheckpoint; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); const error_1 = require("../error"); const trust_1 = require("../trust"); // Separator between the note and the signatures in a checkpoint const CHECKPOINT_SEPARATOR = '\n\n'; // Checkpoint signatures are of the following form: // "– \n" // where: // - the prefix is an emdash (U+2014). // - gives a human-readable representation of the signing ID. // - is the first 4 bytes of the SHA256 hash of the // associated public key followed by the signature bytes. const SIGNATURE_REGEX = /\u2014 (\S+) (\S+)\n/g; // Verifies the checkpoint value in the given tlog entry. There are two steps // to the verification: // 1. Verify that all signatures in the checkpoint can be verified against a // trusted public key // 2. Verify that the root hash in the checkpoint matches the root hash in the // inclusion proof // See: https://github.com/transparency-dev/formats/blob/main/log/README.md function verifyCheckpoint(entry, tlogs) { // Filter tlog instances to just those which were valid at the time of the // entry const validTLogs = (0, trust_1.filterTLogAuthorities)(tlogs, { targetDate: new Date(Number(entry.integratedTime) * 1000), }); const inclusionProof = entry.inclusionProof; const signedNote = SignedNote.fromString(inclusionProof.checkpoint.envelope); const checkpoint = LogCheckpoint.fromString(signedNote.note); // Verify that the signatures in the checkpoint are all valid if (!verifySignedNote(signedNote, validTLogs)) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'invalid checkpoint signature', }); } // Verify that the root hash from the checkpoint matches the root hash in the // inclusion proof if (!core_1.crypto.bufferEqual(checkpoint.logHash, inclusionProof.rootHash)) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'root hash mismatch', }); } } // Verifies the signatures in the SignedNote. For each signature, the // corresponding transparency log is looked up by the key hint and the // signature is verified against the public key in the transparency log. // Throws an error if any of the signatures are invalid. function verifySignedNote(signedNote, tlogs) { const data = Buffer.from(signedNote.note, 'utf-8'); return signedNote.signatures.every((signature) => { // Find the transparency log instance with the matching key hint const tlog = tlogs.find((tlog) => core_1.crypto.bufferEqual(tlog.logID.subarray(0, 4), signature.keyHint)); if (!tlog) { return false; } return core_1.crypto.verify(data, tlog.publicKey, signature.signature); }); } // SignedNote represents a signed note from a transparency log checkpoint. Consists // of a body (or note) and one more signatures calculated over the body. See // https://github.com/transparency-dev/formats/blob/main/log/README.md#signed-envelope class SignedNote { constructor(note, signatures) { this.note = note; this.signatures = signatures; } // Deserialize a SignedNote from a string static fromString(envelope) { if (!envelope.includes(CHECKPOINT_SEPARATOR)) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'missing checkpoint separator', }); } // Split the note into the header and the data portions at the separator const split = envelope.indexOf(CHECKPOINT_SEPARATOR); const header = envelope.slice(0, split + 1); const data = envelope.slice(split + CHECKPOINT_SEPARATOR.length); // Find all the signature lines in the data portion const matches = data.matchAll(SIGNATURE_REGEX); // Parse each of the matched signature lines into the name and signature. // The first four bytes of the signature are the key hint (should match the // first four bytes of the log ID), and the rest is the signature itself. const signatures = Array.from(matches, (match) => { const [, name, signature] = match; const sigBytes = Buffer.from(signature, 'base64'); if (sigBytes.length < 5) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'malformed checkpoint signature', }); } return { name, keyHint: sigBytes.subarray(0, 4), signature: sigBytes.subarray(4), }; }); if (signatures.length === 0) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'no signatures found in checkpoint', }); } return new SignedNote(header, signatures); } } // LogCheckpoint represents a transparency log checkpoint. Consists of the // following: // - origin: the name of the transparency log // - logSize: the size of the log at the time of the checkpoint // - logHash: the root hash of the log at the time of the checkpoint // - rest: the rest of the checkpoint body, which is a list of log entries // See: // https://github.com/transparency-dev/formats/blob/main/log/README.md#checkpoint-body class LogCheckpoint { constructor(origin, logSize, logHash, rest) { this.origin = origin; this.logSize = logSize; this.logHash = logHash; this.rest = rest; } static fromString(note) { const lines = note.trimEnd().split('\n'); if (lines.length < 3) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'too few lines in checkpoint header', }); } const origin = lines[0]; const logSize = BigInt(lines[1]); const rootHash = Buffer.from(lines[2], 'base64'); const rest = lines.slice(3); return new LogCheckpoint(origin, logSize, rootHash, rest); } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyTSATimestamp = verifyTSATimestamp; exports.verifyTLogTimestamp = verifyTLogTimestamp; const error_1 = require("../error"); const checkpoint_1 = require("./checkpoint"); const merkle_1 = require("./merkle"); const set_1 = require("./set"); const tsa_1 = require("./tsa"); function verifyTSATimestamp(timestamp, data, timestampAuthorities) { (0, tsa_1.verifyRFC3161Timestamp)(timestamp, data, timestampAuthorities); return { type: 'timestamp-authority', logID: timestamp.signerSerialNumber, timestamp: timestamp.signingTime, }; } function verifyTLogTimestamp(entry, tlogAuthorities) { let inclusionVerified = false; if (isTLogEntryWithInclusionPromise(entry)) { (0, set_1.verifyTLogSET)(entry, tlogAuthorities); inclusionVerified = true; } if (isTLogEntryWithInclusionProof(entry)) { (0, merkle_1.verifyMerkleInclusion)(entry); (0, checkpoint_1.verifyCheckpoint)(entry, tlogAuthorities); inclusionVerified = true; } if (!inclusionVerified) { throw new error_1.VerificationError({ code: 'TLOG_MISSING_INCLUSION_ERROR', message: 'inclusion could not be verified', }); } return { type: 'transparency-log', logID: entry.logId.keyId, timestamp: new Date(Number(entry.integratedTime) * 1000), }; } function isTLogEntryWithInclusionPromise(entry) { return entry.inclusionPromise !== undefined; } function isTLogEntryWithInclusionProof(entry) { return entry.inclusionProof !== undefined; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyMerkleInclusion = verifyMerkleInclusion; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); const error_1 = require("../error"); const RFC6962_LEAF_HASH_PREFIX = Buffer.from([0x00]); const RFC6962_NODE_HASH_PREFIX = Buffer.from([0x01]); function verifyMerkleInclusion(entry) { const inclusionProof = entry.inclusionProof; const logIndex = BigInt(inclusionProof.logIndex); const treeSize = BigInt(inclusionProof.treeSize); if (logIndex < 0n || logIndex >= treeSize) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: `invalid index: ${logIndex}`, }); } // Figure out which subset of hashes corresponds to the inner and border // nodes const { inner, border } = decompInclProof(logIndex, treeSize); if (inclusionProof.hashes.length !== inner + border) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'invalid hash count', }); } const innerHashes = inclusionProof.hashes.slice(0, inner); const borderHashes = inclusionProof.hashes.slice(inner); // The entry's hash is the leaf hash const leafHash = hashLeaf(entry.canonicalizedBody); // Chain the hashes belonging to the inner and border portions const calculatedHash = chainBorderRight(chainInner(leafHash, innerHashes, logIndex), borderHashes); // Calculated hash should match the root hash in the inclusion proof if (!core_1.crypto.bufferEqual(calculatedHash, inclusionProof.rootHash)) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROOF_ERROR', message: 'calculated root hash does not match inclusion proof', }); } } // Breaks down inclusion proof for a leaf at the specified index in a tree of // the specified size. The split point is where paths to the index leaf and // the (size - 1) leaf diverge. Returns lengths of the bottom and upper proof // parts. function decompInclProof(index, size) { const inner = innerProofSize(index, size); const border = onesCount(index >> BigInt(inner)); return { inner, border }; } // Computes a subtree hash for a node on or below the tree's right border. // Assumes the provided proof hashes are ordered from lower to higher levels // and seed is the initial hash of the node specified by the index. function chainInner(seed, hashes, index) { return hashes.reduce((acc, h, i) => { if ((index >> BigInt(i)) & BigInt(1)) { return hashChildren(h, acc); } else { return hashChildren(acc, h); } }, seed); } // Computes a subtree hash for nodes along the tree's right border. function chainBorderRight(seed, hashes) { return hashes.reduce((acc, h) => hashChildren(h, acc), seed); } function innerProofSize(index, size) { return bitLength(index ^ (size - BigInt(1))); } // Counts the number of ones in the binary representation of the given number. // https://en.wikipedia.org/wiki/Hamming_weight function onesCount(num) { return num.toString(2).split('1').length - 1; } // Returns the number of bits necessary to represent an integer in binary. function bitLength(n) { if (n === 0n) { return 0; } return n.toString(2).length; } // Hashing logic according to RFC6962. // https://datatracker.ietf.org/doc/html/rfc6962#section-2 function hashChildren(left, right) { return core_1.crypto.digest('sha256', RFC6962_NODE_HASH_PREFIX, left, right); } function hashLeaf(leaf) { return core_1.crypto.digest('sha256', RFC6962_LEAF_HASH_PREFIX, leaf); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyTLogSET = verifyTLogSET; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); const error_1 = require("../error"); const trust_1 = require("../trust"); // Verifies the SET for the given entry against the list of trusted // transparency logs. Returns true if the SET can be verified against at least // one of the trusted logs; otherwise, returns false. function verifyTLogSET(entry, tlogs) { // Filter the list of tlog instances to only those which might be able to // verify the SET const validTLogs = (0, trust_1.filterTLogAuthorities)(tlogs, { logID: entry.logId.keyId, targetDate: new Date(Number(entry.integratedTime) * 1000), }); // Check to see if we can verify the SET against any of the valid tlogs const verified = validTLogs.some((tlog) => { // Re-create the original Rekor verification payload const payload = toVerificationPayload(entry); // Canonicalize the payload and turn into a buffer for verification const data = Buffer.from(core_1.json.canonicalize(payload), 'utf8'); // Extract the SET from the tlog entry const signature = entry.inclusionPromise.signedEntryTimestamp; return core_1.crypto.verify(data, tlog.publicKey, signature); }); if (!verified) { throw new error_1.VerificationError({ code: 'TLOG_INCLUSION_PROMISE_ERROR', message: 'inclusion promise could not be verified', }); } } // Returns a properly formatted "VerificationPayload" for one of the // transaction log entires in the given bundle which can be used for SET // verification. function toVerificationPayload(entry) { const { integratedTime, logIndex, logId, canonicalizedBody } = entry; return { body: canonicalizedBody.toString('base64'), integratedTime: Number(integratedTime), logIndex: Number(logIndex), logID: logId.keyId.toString('hex'), }; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyRFC3161Timestamp = verifyRFC3161Timestamp; const core_1 = require("@sigstore/core"); const error_1 = require("../error"); const certificate_1 = require("../key/certificate"); const trust_1 = require("../trust"); function verifyRFC3161Timestamp(timestamp, data, timestampAuthorities) { const signingTime = timestamp.signingTime; // Filter for CAs which were valid at the time of signing timestampAuthorities = (0, trust_1.filterCertAuthorities)(timestampAuthorities, { start: signingTime, end: signingTime, }); // Filter for CAs which match serial and issuer embedded in the timestamp timestampAuthorities = filterCAsBySerialAndIssuer(timestampAuthorities, { serialNumber: timestamp.signerSerialNumber, issuer: timestamp.signerIssuer, }); // Check that we can verify the timestamp with AT LEAST ONE of the remaining // CAs const verified = timestampAuthorities.some((ca) => { try { verifyTimestampForCA(timestamp, data, ca); return true; } catch (e) { return false; } }); if (!verified) { throw new error_1.VerificationError({ code: 'TIMESTAMP_ERROR', message: 'timestamp could not be verified', }); } } function verifyTimestampForCA(timestamp, data, ca) { const [leaf, ...cas] = ca.certChain; const signingKey = core_1.crypto.createPublicKey(leaf.publicKey); const signingTime = timestamp.signingTime; // Verify the certificate chain for the provided CA try { new certificate_1.CertificateChainVerifier({ untrustedCert: leaf, trustedCerts: cas, }).verify(); } catch (e) { throw new error_1.VerificationError({ code: 'TIMESTAMP_ERROR', message: 'invalid certificate chain', }); } // Check that all of the CA certs were valid at the time of signing const validAtSigningTime = ca.certChain.every((cert) => cert.validForDate(signingTime)); if (!validAtSigningTime) { throw new error_1.VerificationError({ code: 'TIMESTAMP_ERROR', message: 'timestamp was signed with an expired certificate', }); } // Check that the signing certificate's key can be used to verify the // timestamp signature. timestamp.verify(data, signingKey); } // Filters the list of CAs to those which have a leaf signing certificate which // matches the given serial number and issuer. function filterCAsBySerialAndIssuer(timestampAuthorities, criteria) { return timestampAuthorities.filter((ca) => ca.certChain.length > 0 && core_1.crypto.bufferEqual(ca.certChain[0].serialNumber, criteria.serialNumber) && core_1.crypto.bufferEqual(ca.certChain[0].issuer, criteria.issuer)); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyDSSETLogBody = verifyDSSETLogBody; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("../error"); // Compare the given intoto tlog entry to the given bundle function verifyDSSETLogBody(tlogEntry, content) { switch (tlogEntry.apiVersion) { case '0.0.1': return verifyDSSE001TLogBody(tlogEntry, content); default: throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: `unsupported dsse version: ${tlogEntry.apiVersion}`, }); } } // Compare the given dsse v0.0.1 tlog entry to the given DSSE envelope. function verifyDSSE001TLogBody(tlogEntry, content) { // Ensure the bundle's DSSE only contains a single signature if (tlogEntry.spec.signatures?.length !== 1) { throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: 'signature count mismatch', }); } const tlogSig = tlogEntry.spec.signatures[0].signature; // Ensure that the signature in the bundle's DSSE matches tlog entry if (!content.compareSignature(Buffer.from(tlogSig, 'base64'))) throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: 'tlog entry signature mismatch', }); // Ensure the digest of the bundle's DSSE payload matches the digest in the // tlog entry const tlogHash = tlogEntry.spec.payloadHash?.value || ''; if (!content.compareDigest(Buffer.from(tlogHash, 'hex'))) { throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: 'DSSE payload hash mismatch', }); } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyHashedRekordTLogBody = verifyHashedRekordTLogBody; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("../error"); // Compare the given hashedrekord tlog entry to the given bundle function verifyHashedRekordTLogBody(tlogEntry, content) { switch (tlogEntry.apiVersion) { case '0.0.1': return verifyHashedrekord001TLogBody(tlogEntry, content); default: throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: `unsupported hashedrekord version: ${tlogEntry.apiVersion}`, }); } } // Compare the given hashedrekord v0.0.1 tlog entry to the given message // signature function verifyHashedrekord001TLogBody(tlogEntry, content) { // Ensure that the bundles message signature matches the tlog entry const tlogSig = tlogEntry.spec.signature.content || ''; if (!content.compareSignature(Buffer.from(tlogSig, 'base64'))) { throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: 'signature mismatch', }); } // Ensure that the bundle's message digest matches the tlog entry const tlogDigest = tlogEntry.spec.data.hash?.value || ''; if (!content.compareDigest(Buffer.from(tlogDigest, 'hex'))) { throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: 'digest mismatch', }); } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyTLogBody = verifyTLogBody; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("../error"); const dsse_1 = require("./dsse"); const hashedrekord_1 = require("./hashedrekord"); const intoto_1 = require("./intoto"); // Verifies that the given tlog entry matches the supplied signature content. function verifyTLogBody(entry, sigContent) { const { kind, version } = entry.kindVersion; const body = JSON.parse(entry.canonicalizedBody.toString('utf8')); if (kind !== body.kind || version !== body.apiVersion) { throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: `kind/version mismatch - expected: ${kind}/${version}, received: ${body.kind}/${body.apiVersion}`, }); } switch (body.kind) { case 'dsse': return (0, dsse_1.verifyDSSETLogBody)(body, sigContent); case 'intoto': return (0, intoto_1.verifyIntotoTLogBody)(body, sigContent); case 'hashedrekord': return (0, hashedrekord_1.verifyHashedRekordTLogBody)(body, sigContent); /* istanbul ignore next */ default: throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: `unsupported kind: ${kind}`, }); } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyIntotoTLogBody = verifyIntotoTLogBody; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const error_1 = require("../error"); // Compare the given intoto tlog entry to the given bundle function verifyIntotoTLogBody(tlogEntry, content) { switch (tlogEntry.apiVersion) { case '0.0.2': return verifyIntoto002TLogBody(tlogEntry, content); default: throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: `unsupported intoto version: ${tlogEntry.apiVersion}`, }); } } // Compare the given intoto v0.0.2 tlog entry to the given DSSE envelope. function verifyIntoto002TLogBody(tlogEntry, content) { // Ensure the bundle's DSSE contains a single signature if (tlogEntry.spec.content.envelope.signatures?.length !== 1) { throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: 'signature count mismatch', }); } // Signature is double-base64-encoded in the tlog entry const tlogSig = base64Decode(tlogEntry.spec.content.envelope.signatures[0].sig); // Ensure that the signature in the bundle's DSSE matches tlog entry if (!content.compareSignature(Buffer.from(tlogSig, 'base64'))) { throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: 'tlog entry signature mismatch', }); } // Ensure the digest of the bundle's DSSE payload matches the digest in the // tlog entry const tlogHash = tlogEntry.spec.content.payloadHash?.value || ''; if (!content.compareDigest(Buffer.from(tlogHash, 'hex'))) { throw new error_1.VerificationError({ code: 'TLOG_BODY_ERROR', message: 'DSSE payload hash mismatch', }); } } function base64Decode(str) { return Buffer.from(str, 'base64').toString('utf-8'); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.filterCertAuthorities = filterCertAuthorities; exports.filterTLogAuthorities = filterTLogAuthorities; function filterCertAuthorities(certAuthorities, criteria) { return certAuthorities.filter((ca) => { return (ca.validFor.start <= criteria.start && ca.validFor.end >= criteria.end); }); } // Filter the list of tlog instances to only those which match the given log // ID and have public keys which are valid for the given integrated time. function filterTLogAuthorities(tlogAuthorities, criteria) { return tlogAuthorities.filter((tlog) => { // If we're filtering by log ID and the log IDs don't match, we can't use // this tlog if (criteria.logID && !tlog.logID.equals(criteria.logID)) { return false; } // Check that the integrated time is within the validFor range return (tlog.validFor.start <= criteria.targetDate && criteria.targetDate <= tlog.validFor.end); }); } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.filterTLogAuthorities = exports.filterCertAuthorities = void 0; exports.toTrustMaterial = toTrustMaterial; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const core_1 = require("@sigstore/core"); const protobuf_specs_1 = require("@sigstore/protobuf-specs"); const error_1 = require("../error"); const BEGINNING_OF_TIME = new Date(0); const END_OF_TIME = new Date(8640000000000000); var filter_1 = require("./filter"); Object.defineProperty(exports, "filterCertAuthorities", { enumerable: true, get: function () { return filter_1.filterCertAuthorities; } }); Object.defineProperty(exports, "filterTLogAuthorities", { enumerable: true, get: function () { return filter_1.filterTLogAuthorities; } }); function toTrustMaterial(root, keys) { const keyFinder = typeof keys === 'function' ? keys : keyLocator(keys); return { certificateAuthorities: root.certificateAuthorities.map(createCertAuthority), timestampAuthorities: root.timestampAuthorities.map(createCertAuthority), tlogs: root.tlogs.map(createTLogAuthority), ctlogs: root.ctlogs.map(createTLogAuthority), publicKey: keyFinder, }; } function createTLogAuthority(tlogInstance) { const keyDetails = tlogInstance.publicKey.keyDetails; const keyType = keyDetails === protobuf_specs_1.PublicKeyDetails.PKCS1_RSA_PKCS1V5 || keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V5 || keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256 || keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256 || keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256 ? 'pkcs1' : 'spki'; return { logID: tlogInstance.logId.keyId, publicKey: core_1.crypto.createPublicKey(tlogInstance.publicKey.rawBytes, keyType), validFor: { start: tlogInstance.publicKey.validFor?.start || BEGINNING_OF_TIME, end: tlogInstance.publicKey.validFor?.end || END_OF_TIME, }, }; } function createCertAuthority(ca) { /* istanbul ignore next */ return { certChain: ca.certChain.certificates.map((cert) => { return core_1.X509Certificate.parse(cert.rawBytes); }), validFor: { start: ca.validFor?.start || BEGINNING_OF_TIME, end: ca.validFor?.end || END_OF_TIME, }, }; } function keyLocator(keys) { return (hint) => { const key = (keys || {})[hint]; if (!key) { throw new error_1.VerificationError({ code: 'PUBLIC_KEY_ERROR', message: `key not found: ${hint}`, }); } return { publicKey: core_1.crypto.createPublicKey(key.rawBytes), validFor: (date) => { /* istanbul ignore next */ return ((key.validFor?.start || BEGINNING_OF_TIME) <= date && (key.validFor?.end || END_OF_TIME) >= date); }, }; }; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Verifier = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (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-2.0 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. */ const util_1 = require("util"); const error_1 = require("./error"); const key_1 = require("./key"); const policy_1 = require("./policy"); const timestamp_1 = require("./timestamp"); const tlog_1 = require("./tlog"); class Verifier { constructor(trustMaterial, options = {}) { this.trustMaterial = trustMaterial; this.options = { ctlogThreshold: options.ctlogThreshold ?? 1, tlogThreshold: options.tlogThreshold ?? 1, tsaThreshold: options.tsaThreshold ?? 0, }; } verify(entity, policy) { const timestamps = this.verifyTimestamps(entity); const signer = this.verifySigningKey(entity, timestamps); this.verifyTLogs(entity); this.verifySignature(entity, signer); if (policy) { this.verifyPolicy(policy, signer.identity || {}); } return signer; } // Checks that all of the timestamps in the entity are valid and returns them verifyTimestamps(entity) { let tlogCount = 0; let tsaCount = 0; const timestamps = entity.timestamps.map((timestamp) => { switch (timestamp.$case) { case 'timestamp-authority': tsaCount++; return (0, timestamp_1.verifyTSATimestamp)(timestamp.timestamp, entity.signature.signature, this.trustMaterial.timestampAuthorities); case 'transparency-log': tlogCount++; return (0, timestamp_1.verifyTLogTimestamp)(timestamp.tlogEntry, this.trustMaterial.tlogs); } }); // Check for duplicate timestamps if (containsDupes(timestamps)) { throw new error_1.VerificationError({ code: 'TIMESTAMP_ERROR', message: 'duplicate timestamp', }); } if (tlogCount < this.options.tlogThreshold) { throw new error_1.VerificationError({ code: 'TIMESTAMP_ERROR', message: `expected ${this.options.tlogThreshold} tlog timestamps, got ${tlogCount}`, }); } if (tsaCount < this.options.tsaThreshold) { throw new error_1.VerificationError({ code: 'TIMESTAMP_ERROR', message: `expected ${this.options.tsaThreshold} tsa timestamps, got ${tsaCount}`, }); } return timestamps.map((t) => t.timestamp); } // Checks that the signing key is valid for all of the the supplied timestamps // and returns the signer. verifySigningKey({ key }, timestamps) { switch (key.$case) { case 'public-key': { return (0, key_1.verifyPublicKey)(key.hint, timestamps, this.trustMaterial); } case 'certificate': { const result = (0, key_1.verifyCertificate)(key.certificate, timestamps, this.trustMaterial); /* istanbul ignore next - no fixture */ if (containsDupes(result.scts)) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: 'duplicate SCT', }); } if (result.scts.length < this.options.ctlogThreshold) { throw new error_1.VerificationError({ code: 'CERTIFICATE_ERROR', message: `expected ${this.options.ctlogThreshold} SCTs, got ${result.scts.length}`, }); } return result.signer; } } } // Checks that the tlog entries are valid for the supplied content verifyTLogs({ signature: content, tlogEntries }) { tlogEntries.forEach((entry) => (0, tlog_1.verifyTLogBody)(entry, content)); } // Checks that the signature is valid for the supplied content verifySignature(entity, signer) { if (!entity.signature.verifySignature(signer.key)) { throw new error_1.VerificationError({ code: 'SIGNATURE_ERROR', message: 'signature verification failed', }); } } verifyPolicy(policy, identity) { // Check the subject alternative name of the signer matches the policy if (policy.subjectAlternativeName) { (0, policy_1.verifySubjectAlternativeName)(policy.subjectAlternativeName, identity.subjectAlternativeName); } // Check that the extensions of the signer match the policy if (policy.extensions) { (0, policy_1.verifyExtensions)(policy.extensions, identity.extensions); } } } exports.Verifier = Verifier; // Checks for duplicate items in the array. Objects are compared using // deep equality. function containsDupes(arr) { for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if ((0, util_1.isDeepStrictEqual)(arr[i], arr[j])) { return true; } } } return false; } { "name": "@sigstore/verify", "version": "2.0.0", "description": "Verification of Sigstore signatures", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "clean": "shx rm -rf dist *.tsbuildinfo", "build": "tsc --build", "test": "jest" }, "files": [ "dist" ], "author": "bdehamer@github.com", "license": "Apache-2.0", "repository": { "type": "git", "url": "git+https://github.com/sigstore/sigstore-js.git" }, "bugs": { "url": "https://github.com/sigstore/sigstore-js/issues" }, "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/verify#readme", "publishConfig": { "provenance": true }, "dependencies": { "@sigstore/protobuf-specs": "^0.3.2", "@sigstore/bundle": "^3.0.0", "@sigstore/core": "^2.0.0" }, "engines": { "node": "^18.17.0 || >=20.5.0" } } MIT License Copyright (c) 2022 GitHub and the TUF Contributors 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. const COMMA = ','; const COLON = ':'; const LEFT_SQUARE_BRACKET = '['; const RIGHT_SQUARE_BRACKET = ']'; const LEFT_CURLY_BRACKET = '{'; const RIGHT_CURLY_BRACKET = '}'; // Recursively encodes the supplied object according to the canonical JSON form // as specified at http://wiki.laptop.org/go/Canonical_JSON. It's a restricted // dialect of JSON in which keys are lexically sorted, floats are not allowed, // and only double quotes and backslashes are escaped. function canonicalize(object) { const buffer = []; if (typeof object === 'string') { buffer.push(canonicalizeString(object)); } else if (typeof object === 'boolean') { buffer.push(JSON.stringify(object)); } else if (Number.isInteger(object)) { buffer.push(JSON.stringify(object)); } else if (object === null) { buffer.push(JSON.stringify(object)); } else if (Array.isArray(object)) { buffer.push(LEFT_SQUARE_BRACKET); let first = true; object.forEach((element) => { if (!first) { buffer.push(COMMA); } first = false; buffer.push(canonicalize(element)); }); buffer.push(RIGHT_SQUARE_BRACKET); } else if (typeof object === 'object') { buffer.push(LEFT_CURLY_BRACKET); let first = true; Object.keys(object) .sort() .forEach((property) => { if (!first) { buffer.push(COMMA); } first = false; buffer.push(canonicalizeString(property)); buffer.push(COLON); buffer.push(canonicalize(object[property])); }); buffer.push(RIGHT_CURLY_BRACKET); } else { throw new TypeError('cannot encode ' + object.toString()); } return buffer.join(''); } // String canonicalization consists of escaping backslash (\) and double // quote (") characters and wrapping the resulting string in double quotes. function canonicalizeString(string) { const escapedString = string.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); return '"' + escapedString + '"'; } module.exports = { canonicalize, }; { "name": "@tufjs/canonical-json", "version": "2.0.0", "description": "OLPC JSON canonicalization", "main": "lib/index.js", "typings": "lib/index.d.ts", "license": "MIT", "keywords": [ "json", "canonical", "canonicalize", "canonicalization", "crypto", "signature", "olpc" ], "author": "bdehamer@github.com", "repository": { "type": "git", "url": "git+https://github.com/theupdateframework/tuf-js.git" }, "homepage": "https://github.com/theupdateframework/tuf-js/tree/main/packages/canonical-json#readme", "bugs": { "url": "https://github.com/theupdateframework/tuf-js/issues" }, "files": [ "lib/" ], "scripts": { "test": "jest" }, "engines": { "node": "^16.14.0 || >=18.0.0" } } MIT License Copyright (c) 2022 GitHub and the TUF Contributors 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. "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Signed = exports.MetadataKind = void 0; exports.isMetadataKind = isMetadataKind; const util_1 = __importDefault(require("util")); const error_1 = require("./error"); const utils_1 = require("./utils"); const SPECIFICATION_VERSION = ['1', '0', '31']; var MetadataKind; (function (MetadataKind) { MetadataKind["Root"] = "root"; MetadataKind["Timestamp"] = "timestamp"; MetadataKind["Snapshot"] = "snapshot"; MetadataKind["Targets"] = "targets"; })(MetadataKind || (exports.MetadataKind = MetadataKind = {})); function isMetadataKind(value) { return (typeof value === 'string' && Object.values(MetadataKind).includes(value)); } /*** * A base class for the signed part of TUF metadata. * * Objects with base class Signed are usually included in a ``Metadata`` object * on the signed attribute. This class provides attributes and methods that * are common for all TUF metadata types (roles). */ class Signed { constructor(options) { this.specVersion = options.specVersion || SPECIFICATION_VERSION.join('.'); const specList = this.specVersion.split('.'); if (!(specList.length === 2 || specList.length === 3) || !specList.every((item) => isNumeric(item))) { throw new error_1.ValueError('Failed to parse specVersion'); } // major version must match if (specList[0] != SPECIFICATION_VERSION[0]) { throw new error_1.ValueError('Unsupported specVersion'); } this.expires = options.expires; this.version = options.version; this.unrecognizedFields = options.unrecognizedFields || {}; } equals(other) { if (!(other instanceof Signed)) { return false; } return (this.specVersion === other.specVersion && this.expires === other.expires && this.version === other.version && util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); } isExpired(referenceTime) { if (!referenceTime) { referenceTime = new Date(); } return referenceTime >= new Date(this.expires); } static commonFieldsFromJSON(data) { const { spec_version, expires, version, ...rest } = data; if (!utils_1.guard.isDefined(spec_version)) { throw new error_1.ValueError('spec_version is not defined'); } else if (typeof spec_version !== 'string') { throw new TypeError('spec_version must be a string'); } if (!utils_1.guard.isDefined(expires)) { throw new error_1.ValueError('expires is not defined'); } else if (!(typeof expires === 'string')) { throw new TypeError('expires must be a string'); } if (!utils_1.guard.isDefined(version)) { throw new error_1.ValueError('version is not defined'); } else if (!(typeof version === 'number')) { throw new TypeError('version must be a number'); } return { specVersion: spec_version, expires, version, unrecognizedFields: rest, }; } } exports.Signed = Signed; function isNumeric(str) { return !isNaN(Number(str)); } "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Delegations = void 0; const util_1 = __importDefault(require("util")); const error_1 = require("./error"); const key_1 = require("./key"); const role_1 = require("./role"); const utils_1 = require("./utils"); /** * A container object storing information about all delegations. * * Targets roles that are trusted to provide signed metadata files * describing targets with designated pathnames and/or further delegations. */ class Delegations { constructor(options) { this.keys = options.keys; this.unrecognizedFields = options.unrecognizedFields || {}; if (options.roles) { if (Object.keys(options.roles).some((roleName) => role_1.TOP_LEVEL_ROLE_NAMES.includes(roleName))) { throw new error_1.ValueError('Delegated role name conflicts with top-level role name'); } } this.succinctRoles = options.succinctRoles; this.roles = options.roles; } equals(other) { if (!(other instanceof Delegations)) { return false; } return (util_1.default.isDeepStrictEqual(this.keys, other.keys) && util_1.default.isDeepStrictEqual(this.roles, other.roles) && util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields) && util_1.default.isDeepStrictEqual(this.succinctRoles, other.succinctRoles)); } *rolesForTarget(targetPath) { if (this.roles) { for (const role of Object.values(this.roles)) { if (role.isDelegatedPath(targetPath)) { yield { role: role.name, terminating: role.terminating }; } } } else if (this.succinctRoles) { yield { role: this.succinctRoles.getRoleForTarget(targetPath), terminating: true, }; } } toJSON() { const json = { keys: keysToJSON(this.keys), ...this.unrecognizedFields, }; if (this.roles) { json.roles = rolesToJSON(this.roles); } else if (this.succinctRoles) { json.succinct_roles = this.succinctRoles.toJSON(); } return json; } static fromJSON(data) { const { keys, roles, succinct_roles, ...unrecognizedFields } = data; let succinctRoles; if (utils_1.guard.isObject(succinct_roles)) { succinctRoles = role_1.SuccinctRoles.fromJSON(succinct_roles); } return new Delegations({ keys: keysFromJSON(keys), roles: rolesFromJSON(roles), unrecognizedFields, succinctRoles, }); } } exports.Delegations = Delegations; function keysToJSON(keys) { return Object.entries(keys).reduce((acc, [keyId, key]) => ({ ...acc, [keyId]: key.toJSON(), }), {}); } function rolesToJSON(roles) { return Object.values(roles).map((role) => role.toJSON()); } function keysFromJSON(data) { if (!utils_1.guard.isObjectRecord(data)) { throw new TypeError('keys is malformed'); } return Object.entries(data).reduce((acc, [keyID, keyData]) => ({ ...acc, [keyID]: key_1.Key.fromJSON(keyID, keyData), }), {}); } function rolesFromJSON(data) { let roleMap; if (utils_1.guard.isDefined(data)) { if (!utils_1.guard.isObjectArray(data)) { throw new TypeError('roles is malformed'); } roleMap = data.reduce((acc, role) => { const delegatedRole = role_1.DelegatedRole.fromJSON(role); return { ...acc, [delegatedRole.name]: delegatedRole, }; }, {}); } return roleMap; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnsupportedAlgorithmError = exports.CryptoError = exports.LengthOrHashMismatchError = exports.UnsignedMetadataError = exports.RepositoryError = exports.ValueError = void 0; // An error about insufficient values class ValueError extends Error { } exports.ValueError = ValueError; // An error with a repository's state, such as a missing file. // It covers all exceptions that come from the repository side when // looking from the perspective of users of metadata API or ngclient. class RepositoryError extends Error { } exports.RepositoryError = RepositoryError; // An error about metadata object with insufficient threshold of signatures. class UnsignedMetadataError extends RepositoryError { } exports.UnsignedMetadataError = UnsignedMetadataError; // An error while checking the length and hash values of an object. class LengthOrHashMismatchError extends RepositoryError { } exports.LengthOrHashMismatchError = LengthOrHashMismatchError; class CryptoError extends Error { } exports.CryptoError = CryptoError; class UnsupportedAlgorithmError extends CryptoError { } exports.UnsupportedAlgorithmError = UnsupportedAlgorithmError; "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TargetFile = exports.MetaFile = void 0; const crypto_1 = __importDefault(require("crypto")); const util_1 = __importDefault(require("util")); const error_1 = require("./error"); const utils_1 = require("./utils"); // A container with information about a particular metadata file. // // This class is used for Timestamp and Snapshot metadata. class MetaFile { constructor(opts) { if (opts.version <= 0) { throw new error_1.ValueError('Metafile version must be at least 1'); } if (opts.length !== undefined) { validateLength(opts.length); } this.version = opts.version; this.length = opts.length; this.hashes = opts.hashes; this.unrecognizedFields = opts.unrecognizedFields || {}; } equals(other) { if (!(other instanceof MetaFile)) { return false; } return (this.version === other.version && this.length === other.length && util_1.default.isDeepStrictEqual(this.hashes, other.hashes) && util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); } verify(data) { // Verifies that the given data matches the expected length. if (this.length !== undefined) { if (data.length !== this.length) { throw new error_1.LengthOrHashMismatchError(`Expected length ${this.length} but got ${data.length}`); } } // Verifies that the given data matches the supplied hashes. if (this.hashes) { Object.entries(this.hashes).forEach(([key, value]) => { let hash; try { hash = crypto_1.default.createHash(key); } catch (e) { throw new error_1.LengthOrHashMismatchError(`Hash algorithm ${key} not supported`); } const observedHash = hash.update(data).digest('hex'); if (observedHash !== value) { throw new error_1.LengthOrHashMismatchError(`Expected hash ${value} but got ${observedHash}`); } }); } } toJSON() { const json = { version: this.version, ...this.unrecognizedFields, }; if (this.length !== undefined) { json.length = this.length; } if (this.hashes) { json.hashes = this.hashes; } return json; } static fromJSON(data) { const { version, length, hashes, ...rest } = data; if (typeof version !== 'number') { throw new TypeError('version must be a number'); } if (utils_1.guard.isDefined(length) && typeof length !== 'number') { throw new TypeError('length must be a number'); } if (utils_1.guard.isDefined(hashes) && !utils_1.guard.isStringRecord(hashes)) { throw new TypeError('hashes must be string keys and values'); } return new MetaFile({ version, length, hashes, unrecognizedFields: rest, }); } } exports.MetaFile = MetaFile; // Container for info about a particular target file. // // This class is used for Target metadata. class TargetFile { constructor(opts) { validateLength(opts.length); this.length = opts.length; this.path = opts.path; this.hashes = opts.hashes; this.unrecognizedFields = opts.unrecognizedFields || {}; } get custom() { const custom = this.unrecognizedFields['custom']; if (!custom || Array.isArray(custom) || !(typeof custom === 'object')) { return {}; } return custom; } equals(other) { if (!(other instanceof TargetFile)) { return false; } return (this.length === other.length && this.path === other.path && util_1.default.isDeepStrictEqual(this.hashes, other.hashes) && util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); } async verify(stream) { let observedLength = 0; // Create a digest for each hash algorithm const digests = Object.keys(this.hashes).reduce((acc, key) => { try { acc[key] = crypto_1.default.createHash(key); } catch (e) { throw new error_1.LengthOrHashMismatchError(`Hash algorithm ${key} not supported`); } return acc; }, {}); // Read stream chunk by chunk for await (const chunk of stream) { // Keep running tally of stream length observedLength += chunk.length; // Append chunk to each digest Object.values(digests).forEach((digest) => { digest.update(chunk); }); } // Verify length matches expected value if (observedLength !== this.length) { throw new error_1.LengthOrHashMismatchError(`Expected length ${this.length} but got ${observedLength}`); } // Verify each digest matches expected value Object.entries(digests).forEach(([key, value]) => { const expected = this.hashes[key]; const actual = value.digest('hex'); if (actual !== expected) { throw new error_1.LengthOrHashMismatchError(`Expected hash ${expected} but got ${actual}`); } }); } toJSON() { return { length: this.length, hashes: this.hashes, ...this.unrecognizedFields, }; } static fromJSON(path, data) { const { length, hashes, ...rest } = data; if (typeof length !== 'number') { throw new TypeError('length must be a number'); } if (!utils_1.guard.isStringRecord(hashes)) { throw new TypeError('hashes must have string keys and values'); } return new TargetFile({ length, path, hashes, unrecognizedFields: rest, }); } } exports.TargetFile = TargetFile; // Check that supplied length if valid function validateLength(length) { if (length < 0) { throw new error_1.ValueError('Length must be at least 0'); } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Timestamp = exports.Targets = exports.Snapshot = exports.Signature = exports.Root = exports.Metadata = exports.Key = exports.TargetFile = exports.MetaFile = exports.ValueError = exports.MetadataKind = void 0; var base_1 = require("./base"); Object.defineProperty(exports, "MetadataKind", { enumerable: true, get: function () { return base_1.MetadataKind; } }); var error_1 = require("./error"); Object.defineProperty(exports, "ValueError", { enumerable: true, get: function () { return error_1.ValueError; } }); var file_1 = require("./file"); Object.defineProperty(exports, "MetaFile", { enumerable: true, get: function () { return file_1.MetaFile; } }); Object.defineProperty(exports, "TargetFile", { enumerable: true, get: function () { return file_1.TargetFile; } }); var key_1 = require("./key"); Object.defineProperty(exports, "Key", { enumerable: true, get: function () { return key_1.Key; } }); var metadata_1 = require("./metadata"); Object.defineProperty(exports, "Metadata", { enumerable: true, get: function () { return metadata_1.Metadata; } }); var root_1 = require("./root"); Object.defineProperty(exports, "Root", { enumerable: true, get: function () { return root_1.Root; } }); var signature_1 = require("./signature"); Object.defineProperty(exports, "Signature", { enumerable: true, get: function () { return signature_1.Signature; } }); var snapshot_1 = require("./snapshot"); Object.defineProperty(exports, "Snapshot", { enumerable: true, get: function () { return snapshot_1.Snapshot; } }); var targets_1 = require("./targets"); Object.defineProperty(exports, "Targets", { enumerable: true, get: function () { return targets_1.Targets; } }); var timestamp_1 = require("./timestamp"); Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp_1.Timestamp; } }); "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Key = void 0; const util_1 = __importDefault(require("util")); const error_1 = require("./error"); const utils_1 = require("./utils"); const key_1 = require("./utils/key"); // A container class representing the public portion of a Key. class Key { constructor(options) { const { keyID, keyType, scheme, keyVal, unrecognizedFields } = options; this.keyID = keyID; this.keyType = keyType; this.scheme = scheme; this.keyVal = keyVal; this.unrecognizedFields = unrecognizedFields || {}; } // Verifies the that the metadata.signatures contains a signature made with // this key and is correctly signed. verifySignature(metadata) { const signature = metadata.signatures[this.keyID]; if (!signature) throw new error_1.UnsignedMetadataError('no signature for key found in metadata'); if (!this.keyVal.public) throw new error_1.UnsignedMetadataError('no public key found'); const publicKey = (0, key_1.getPublicKey)({ keyType: this.keyType, scheme: this.scheme, keyVal: this.keyVal.public, }); const signedData = metadata.signed.toJSON(); try { if (!utils_1.crypto.verifySignature(signedData, publicKey, signature.sig)) { throw new error_1.UnsignedMetadataError(`failed to verify ${this.keyID} signature`); } } catch (error) { if (error instanceof error_1.UnsignedMetadataError) { throw error; } throw new error_1.UnsignedMetadataError(`failed to verify ${this.keyID} signature`); } } equals(other) { if (!(other instanceof Key)) { return false; } return (this.keyID === other.keyID && this.keyType === other.keyType && this.scheme === other.scheme && util_1.default.isDeepStrictEqual(this.keyVal, other.keyVal) && util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); } toJSON() { return { keytype: this.keyType, scheme: this.scheme, keyval: this.keyVal, ...this.unrecognizedFields, }; } static fromJSON(keyID, data) { const { keytype, scheme, keyval, ...rest } = data; if (typeof keytype !== 'string') { throw new TypeError('keytype must be a string'); } if (typeof scheme !== 'string') { throw new TypeError('scheme must be a string'); } if (!utils_1.guard.isStringRecord(keyval)) { throw new TypeError('keyval must be a string record'); } return new Key({ keyID, keyType: keytype, scheme, keyVal: keyval, unrecognizedFields: rest, }); } } exports.Key = Key; "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Metadata = void 0; const canonical_json_1 = require("@tufjs/canonical-json"); const util_1 = __importDefault(require("util")); const base_1 = require("./base"); const error_1 = require("./error"); const root_1 = require("./root"); const signature_1 = require("./signature"); const snapshot_1 = require("./snapshot"); const targets_1 = require("./targets"); const timestamp_1 = require("./timestamp"); const utils_1 = require("./utils"); /*** * A container for signed TUF metadata. * * Provides methods to convert to and from json, read and write to and * from JSON and to create and verify metadata signatures. * * ``Metadata[T]`` is a generic container type where T can be any one type of * [``Root``, ``Timestamp``, ``Snapshot``, ``Targets``]. The purpose of this * is to allow static type checking of the signed attribute in code using * Metadata:: * * root_md = Metadata[Root].fromJSON("root.json") * # root_md type is now Metadata[Root]. This means signed and its * # attributes like consistent_snapshot are now statically typed and the * # types can be verified by static type checkers and shown by IDEs * * Using a type constraint is not required but not doing so means T is not a * specific type so static typing cannot happen. Note that the type constraint * ``[Root]`` is not validated at runtime (as pure annotations are not available * then). * * Apart from ``expires`` all of the arguments to the inner constructors have * reasonable default values for new metadata. */ class Metadata { constructor(signed, signatures, unrecognizedFields) { this.signed = signed; this.signatures = signatures || {}; this.unrecognizedFields = unrecognizedFields || {}; } sign(signer, append = true) { const bytes = Buffer.from((0, canonical_json_1.canonicalize)(this.signed.toJSON())); const signature = signer(bytes); if (!append) { this.signatures = {}; } this.signatures[signature.keyID] = signature; } verifyDelegate(delegatedRole, delegatedMetadata) { let role; let keys = {}; switch (this.signed.type) { case base_1.MetadataKind.Root: keys = this.signed.keys; role = this.signed.roles[delegatedRole]; break; case base_1.MetadataKind.Targets: if (!this.signed.delegations) { throw new error_1.ValueError(`No delegations found for ${delegatedRole}`); } keys = this.signed.delegations.keys; if (this.signed.delegations.roles) { role = this.signed.delegations.roles[delegatedRole]; } else if (this.signed.delegations.succinctRoles) { if (this.signed.delegations.succinctRoles.isDelegatedRole(delegatedRole)) { role = this.signed.delegations.succinctRoles; } } break; default: throw new TypeError('invalid metadata type'); } if (!role) { throw new error_1.ValueError(`no delegation found for ${delegatedRole}`); } const signingKeys = new Set(); role.keyIDs.forEach((keyID) => { const key = keys[keyID]; // If we dont' have the key, continue checking other keys if (!key) { return; } try { key.verifySignature(delegatedMetadata); signingKeys.add(key.keyID); } catch (error) { // continue } }); if (signingKeys.size < role.threshold) { throw new error_1.UnsignedMetadataError(`${delegatedRole} was signed by ${signingKeys.size}/${role.threshold} keys`); } } equals(other) { if (!(other instanceof Metadata)) { return false; } return (this.signed.equals(other.signed) && util_1.default.isDeepStrictEqual(this.signatures, other.signatures) && util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); } toJSON() { const signatures = Object.values(this.signatures).map((signature) => { return signature.toJSON(); }); return { signatures, signed: this.signed.toJSON(), ...this.unrecognizedFields, }; } static fromJSON(type, data) { const { signed, signatures, ...rest } = data; if (!utils_1.guard.isDefined(signed) || !utils_1.guard.isObject(signed)) { throw new TypeError('signed is not defined'); } if (type !== signed._type) { throw new error_1.ValueError(`expected '${type}', got ${signed['_type']}`); } if (!utils_1.guard.isObjectArray(signatures)) { throw new TypeError('signatures is not an array'); } let signedObj; switch (type) { case base_1.MetadataKind.Root: signedObj = root_1.Root.fromJSON(signed); break; case base_1.MetadataKind.Timestamp: signedObj = timestamp_1.Timestamp.fromJSON(signed); break; case base_1.MetadataKind.Snapshot: signedObj = snapshot_1.Snapshot.fromJSON(signed); break; case base_1.MetadataKind.Targets: signedObj = targets_1.Targets.fromJSON(signed); break; default: throw new TypeError('invalid metadata type'); } const sigMap = {}; // Ensure that each signature is unique signatures.forEach((sigData) => { const sig = signature_1.Signature.fromJSON(sigData); if (sigMap[sig.keyID]) { throw new error_1.ValueError(`multiple signatures found for keyid: ${sig.keyID}`); } sigMap[sig.keyID] = sig; }); return new Metadata(signedObj, sigMap, rest); } } exports.Metadata = Metadata; "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SuccinctRoles = exports.DelegatedRole = exports.Role = exports.TOP_LEVEL_ROLE_NAMES = void 0; const crypto_1 = __importDefault(require("crypto")); const minimatch_1 = require("minimatch"); const util_1 = __importDefault(require("util")); const error_1 = require("./error"); const utils_1 = require("./utils"); exports.TOP_LEVEL_ROLE_NAMES = [ 'root', 'targets', 'snapshot', 'timestamp', ]; /** * Container that defines which keys are required to sign roles metadata. * * Role defines how many keys are required to successfully sign the roles * metadata, and which keys are accepted. */ class Role { constructor(options) { const { keyIDs, threshold, unrecognizedFields } = options; if (hasDuplicates(keyIDs)) { throw new error_1.ValueError('duplicate key IDs found'); } if (threshold < 1) { throw new error_1.ValueError('threshold must be at least 1'); } this.keyIDs = keyIDs; this.threshold = threshold; this.unrecognizedFields = unrecognizedFields || {}; } equals(other) { if (!(other instanceof Role)) { return false; } return (this.threshold === other.threshold && util_1.default.isDeepStrictEqual(this.keyIDs, other.keyIDs) && util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); } toJSON() { return { keyids: this.keyIDs, threshold: this.threshold, ...this.unrecognizedFields, }; } static fromJSON(data) { const { keyids, threshold, ...rest } = data; if (!utils_1.guard.isStringArray(keyids)) { throw new TypeError('keyids must be an array'); } if (typeof threshold !== 'number') { throw new TypeError('threshold must be a number'); } return new Role({ keyIDs: keyids, threshold, unrecognizedFields: rest, }); } } exports.Role = Role; function hasDuplicates(array) { return new Set(array).size !== array.length; } /** * A container with information about a delegated role. * * A delegation can happen in two ways: * - ``paths`` is set: delegates targets matching any path pattern in ``paths`` * - ``pathHashPrefixes`` is set: delegates targets whose target path hash * starts with any of the prefixes in ``pathHashPrefixes`` * * ``paths`` and ``pathHashPrefixes`` are mutually exclusive: both cannot be * set, at least one of them must be set. */ class DelegatedRole extends Role { constructor(opts) { super(opts); const { name, terminating, paths, pathHashPrefixes } = opts; this.name = name; this.terminating = terminating; if (opts.paths && opts.pathHashPrefixes) { throw new error_1.ValueError('paths and pathHashPrefixes are mutually exclusive'); } this.paths = paths; this.pathHashPrefixes = pathHashPrefixes; } equals(other) { if (!(other instanceof DelegatedRole)) { return false; } return (super.equals(other) && this.name === other.name && this.terminating === other.terminating && util_1.default.isDeepStrictEqual(this.paths, other.paths) && util_1.default.isDeepStrictEqual(this.pathHashPrefixes, other.pathHashPrefixes)); } isDelegatedPath(targetFilepath) { if (this.paths) { return this.paths.some((pathPattern) => isTargetInPathPattern(targetFilepath, pathPattern)); } if (this.pathHashPrefixes) { const hasher = crypto_1.default.createHash('sha256'); const pathHash = hasher.update(targetFilepath).digest('hex'); return this.pathHashPrefixes.some((pathHashPrefix) => pathHash.startsWith(pathHashPrefix)); } return false; } toJSON() { const json = { ...super.toJSON(), name: this.name, terminating: this.terminating, }; if (this.paths) { json.paths = this.paths; } if (this.pathHashPrefixes) { json.path_hash_prefixes = this.pathHashPrefixes; } return json; } static fromJSON(data) { const { keyids, threshold, name, terminating, paths, path_hash_prefixes, ...rest } = data; if (!utils_1.guard.isStringArray(keyids)) { throw new TypeError('keyids must be an array of strings'); } if (typeof threshold !== 'number') { throw new TypeError('threshold must be a number'); } if (typeof name !== 'string') { throw new TypeError('name must be a string'); } if (typeof terminating !== 'boolean') { throw new TypeError('terminating must be a boolean'); } if (utils_1.guard.isDefined(paths) && !utils_1.guard.isStringArray(paths)) { throw new TypeError('paths must be an array of strings'); } if (utils_1.guard.isDefined(path_hash_prefixes) && !utils_1.guard.isStringArray(path_hash_prefixes)) { throw new TypeError('path_hash_prefixes must be an array of strings'); } return new DelegatedRole({ keyIDs: keyids, threshold, name, terminating, paths, pathHashPrefixes: path_hash_prefixes, unrecognizedFields: rest, }); } } exports.DelegatedRole = DelegatedRole; // JS version of Ruby's Array#zip const zip = (a, b) => a.map((k, i) => [k, b[i]]); function isTargetInPathPattern(target, pattern) { const targetParts = target.split('/'); const patternParts = pattern.split('/'); if (patternParts.length != targetParts.length) { return false; } return zip(targetParts, patternParts).every(([targetPart, patternPart]) => (0, minimatch_1.minimatch)(targetPart, patternPart)); } /** * Succinctly defines a hash bin delegation graph. * * A ``SuccinctRoles`` object describes a delegation graph that covers all * targets, distributing them uniformly over the delegated roles (i.e. bins) * in the graph. * * The total number of bins is 2 to the power of the passed ``bit_length``. * * Bin names are the concatenation of the passed ``name_prefix`` and a * zero-padded hex representation of the bin index separated by a hyphen. * * The passed ``keyids`` and ``threshold`` is used for each bin, and each bin * is 'terminating'. * * For details: https://github.com/theupdateframework/taps/blob/master/tap15.md */ class SuccinctRoles extends Role { constructor(opts) { super(opts); const { bitLength, namePrefix } = opts; if (bitLength <= 0 || bitLength > 32) { throw new error_1.ValueError('bitLength must be between 1 and 32'); } this.bitLength = bitLength; this.namePrefix = namePrefix; // Calculate the suffix_len value based on the total number of bins in // hex. If bit_length = 10 then number_of_bins = 1024 or bin names will // have a suffix between "000" and "3ff" in hex and suffix_len will be 3 // meaning the third bin will have a suffix of "003". this.numberOfBins = Math.pow(2, bitLength); // suffix_len is calculated based on "number_of_bins - 1" as the name // of the last bin contains the number "number_of_bins -1" as a suffix. this.suffixLen = (this.numberOfBins - 1).toString(16).length; } equals(other) { if (!(other instanceof SuccinctRoles)) { return false; } return (super.equals(other) && this.bitLength === other.bitLength && this.namePrefix === other.namePrefix); } /*** * Calculates the name of the delegated role responsible for 'target_filepath'. * * The target at path ''target_filepath' is assigned to a bin by casting * the left-most 'bit_length' of bits of the file path hash digest to * int, using it as bin index between 0 and '2**bit_length - 1'. * * Args: * target_filepath: URL path to a target file, relative to a base * targets URL. */ getRoleForTarget(targetFilepath) { const hasher = crypto_1.default.createHash('sha256'); const hasherBuffer = hasher.update(targetFilepath).digest(); // can't ever need more than 4 bytes (32 bits). const hashBytes = hasherBuffer.subarray(0, 4); // Right shift hash bytes, so that we only have the leftmost // bit_length bits that we care about. const shiftValue = 32 - this.bitLength; const binNumber = hashBytes.readUInt32BE() >>> shiftValue; // Add zero padding if necessary and cast to hex the suffix. const suffix = binNumber.toString(16).padStart(this.suffixLen, '0'); return `${this.namePrefix}-${suffix}`; } *getRoles() { for (let i = 0; i < this.numberOfBins; i++) { const suffix = i.toString(16).padStart(this.suffixLen, '0'); yield `${this.namePrefix}-${suffix}`; } } /*** * Determines whether the given ``role_name`` is in one of * the delegated roles that ``SuccinctRoles`` represents. * * Args: * role_name: The name of the role to check against. */ isDelegatedRole(roleName) { const desiredPrefix = this.namePrefix + '-'; if (!roleName.startsWith(desiredPrefix)) { return false; } const suffix = roleName.slice(desiredPrefix.length, roleName.length); if (suffix.length != this.suffixLen) { return false; } // make sure the suffix is a hex string if (!suffix.match(/^[0-9a-fA-F]+$/)) { return false; } const num = parseInt(suffix, 16); return 0 <= num && num < this.numberOfBins; } toJSON() { const json = { ...super.toJSON(), bit_length: this.bitLength, name_prefix: this.namePrefix, }; return json; } static fromJSON(data) { const { keyids, threshold, bit_length, name_prefix, ...rest } = data; if (!utils_1.guard.isStringArray(keyids)) { throw new TypeError('keyids must be an array of strings'); } if (typeof threshold !== 'number') { throw new TypeError('threshold must be a number'); } if (typeof bit_length !== 'number') { throw new TypeError('bit_length must be a number'); } if (typeof name_prefix !== 'string') { throw new TypeError('name_prefix must be a string'); } return new SuccinctRoles({ keyIDs: keyids, threshold, bitLength: bit_length, namePrefix: name_prefix, unrecognizedFields: rest, }); } } exports.SuccinctRoles = SuccinctRoles; "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Root = void 0; const util_1 = __importDefault(require("util")); const base_1 = require("./base"); const error_1 = require("./error"); const key_1 = require("./key"); const role_1 = require("./role"); const utils_1 = require("./utils"); /** * A container for the signed part of root metadata. * * The top-level role and metadata file signed by the root keys. * This role specifies trusted keys for all other top-level roles, which may further delegate trust. */ class Root extends base_1.Signed { constructor(options) { super(options); this.type = base_1.MetadataKind.Root; this.keys = options.keys || {}; this.consistentSnapshot = options.consistentSnapshot ?? true; if (!options.roles) { this.roles = role_1.TOP_LEVEL_ROLE_NAMES.reduce((acc, role) => ({ ...acc, [role]: new role_1.Role({ keyIDs: [], threshold: 1 }), }), {}); } else { const roleNames = new Set(Object.keys(options.roles)); if (!role_1.TOP_LEVEL_ROLE_NAMES.every((role) => roleNames.has(role))) { throw new error_1.ValueError('missing top-level role'); } this.roles = options.roles; } } addKey(key, role) { if (!this.roles[role]) { throw new error_1.ValueError(`role ${role} does not exist`); } if (!this.roles[role].keyIDs.includes(key.keyID)) { this.roles[role].keyIDs.push(key.keyID); } this.keys[key.keyID] = key; } equals(other) { if (!(other instanceof Root)) { return false; } return (super.equals(other) && this.consistentSnapshot === other.consistentSnapshot && util_1.default.isDeepStrictEqual(this.keys, other.keys) && util_1.default.isDeepStrictEqual(this.roles, other.roles)); } toJSON() { return { _type: this.type, spec_version: this.specVersion, version: this.version, expires: this.expires, keys: keysToJSON(this.keys), roles: rolesToJSON(this.roles), consistent_snapshot: this.consistentSnapshot, ...this.unrecognizedFields, }; } static fromJSON(data) { const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); const { keys, roles, consistent_snapshot, ...rest } = unrecognizedFields; if (typeof consistent_snapshot !== 'boolean') { throw new TypeError('consistent_snapshot must be a boolean'); } return new Root({ ...commonFields, keys: keysFromJSON(keys), roles: rolesFromJSON(roles), consistentSnapshot: consistent_snapshot, unrecognizedFields: rest, }); } } exports.Root = Root; function keysToJSON(keys) { return Object.entries(keys).reduce((acc, [keyID, key]) => ({ ...acc, [keyID]: key.toJSON() }), {}); } function rolesToJSON(roles) { return Object.entries(roles).reduce((acc, [roleName, role]) => ({ ...acc, [roleName]: role.toJSON() }), {}); } function keysFromJSON(data) { let keys; if (utils_1.guard.isDefined(data)) { if (!utils_1.guard.isObjectRecord(data)) { throw new TypeError('keys must be an object'); } keys = Object.entries(data).reduce((acc, [keyID, keyData]) => ({ ...acc, [keyID]: key_1.Key.fromJSON(keyID, keyData), }), {}); } return keys; } function rolesFromJSON(data) { let roles; if (utils_1.guard.isDefined(data)) { if (!utils_1.guard.isObjectRecord(data)) { throw new TypeError('roles must be an object'); } roles = Object.entries(data).reduce((acc, [roleName, roleData]) => ({ ...acc, [roleName]: role_1.Role.fromJSON(roleData), }), {}); } return roles; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Signature = void 0; /** * A container class containing information about a signature. * * Contains a signature and the keyid uniquely identifying the key used * to generate the signature. * * Provide a `fromJSON` method to create a Signature from a JSON object. */ class Signature { constructor(options) { const { keyID, sig } = options; this.keyID = keyID; this.sig = sig; } toJSON() { return { keyid: this.keyID, sig: this.sig, }; } static fromJSON(data) { const { keyid, sig } = data; if (typeof keyid !== 'string') { throw new TypeError('keyid must be a string'); } if (typeof sig !== 'string') { throw new TypeError('sig must be a string'); } return new Signature({ keyID: keyid, sig: sig, }); } } exports.Signature = Signature; "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Snapshot = void 0; const util_1 = __importDefault(require("util")); const base_1 = require("./base"); const file_1 = require("./file"); const utils_1 = require("./utils"); /** * A container for the signed part of snapshot metadata. * * Snapshot contains information about all target Metadata files. * A top-level role that specifies the latest versions of all targets metadata files, * and hence the latest versions of all targets (including any dependencies between them) on the repository. */ class Snapshot extends base_1.Signed { constructor(opts) { super(opts); this.type = base_1.MetadataKind.Snapshot; this.meta = opts.meta || { 'targets.json': new file_1.MetaFile({ version: 1 }) }; } equals(other) { if (!(other instanceof Snapshot)) { return false; } return super.equals(other) && util_1.default.isDeepStrictEqual(this.meta, other.meta); } toJSON() { return { _type: this.type, meta: metaToJSON(this.meta), spec_version: this.specVersion, version: this.version, expires: this.expires, ...this.unrecognizedFields, }; } static fromJSON(data) { const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); const { meta, ...rest } = unrecognizedFields; return new Snapshot({ ...commonFields, meta: metaFromJSON(meta), unrecognizedFields: rest, }); } } exports.Snapshot = Snapshot; function metaToJSON(meta) { return Object.entries(meta).reduce((acc, [path, metadata]) => ({ ...acc, [path]: metadata.toJSON(), }), {}); } function metaFromJSON(data) { let meta; if (utils_1.guard.isDefined(data)) { if (!utils_1.guard.isObjectRecord(data)) { throw new TypeError('meta field is malformed'); } else { meta = Object.entries(data).reduce((acc, [path, metadata]) => ({ ...acc, [path]: file_1.MetaFile.fromJSON(metadata), }), {}); } } return meta; } "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Targets = void 0; const util_1 = __importDefault(require("util")); const base_1 = require("./base"); const delegations_1 = require("./delegations"); const file_1 = require("./file"); const utils_1 = require("./utils"); // Container for the signed part of targets metadata. // // Targets contains verifying information about target files and also delegates // responsible to other Targets roles. class Targets extends base_1.Signed { constructor(options) { super(options); this.type = base_1.MetadataKind.Targets; this.targets = options.targets || {}; this.delegations = options.delegations; } addTarget(target) { this.targets[target.path] = target; } equals(other) { if (!(other instanceof Targets)) { return false; } return (super.equals(other) && util_1.default.isDeepStrictEqual(this.targets, other.targets) && util_1.default.isDeepStrictEqual(this.delegations, other.delegations)); } toJSON() { const json = { _type: this.type, spec_version: this.specVersion, version: this.version, expires: this.expires, targets: targetsToJSON(this.targets), ...this.unrecognizedFields, }; if (this.delegations) { json.delegations = this.delegations.toJSON(); } return json; } static fromJSON(data) { const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); const { targets, delegations, ...rest } = unrecognizedFields; return new Targets({ ...commonFields, targets: targetsFromJSON(targets), delegations: delegationsFromJSON(delegations), unrecognizedFields: rest, }); } } exports.Targets = Targets; function targetsToJSON(targets) { return Object.entries(targets).reduce((acc, [path, target]) => ({ ...acc, [path]: target.toJSON(), }), {}); } function targetsFromJSON(data) { let targets; if (utils_1.guard.isDefined(data)) { if (!utils_1.guard.isObjectRecord(data)) { throw new TypeError('targets must be an object'); } else { targets = Object.entries(data).reduce((acc, [path, target]) => ({ ...acc, [path]: file_1.TargetFile.fromJSON(path, target), }), {}); } } return targets; } function delegationsFromJSON(data) { let delegations; if (utils_1.guard.isDefined(data)) { if (!utils_1.guard.isObject(data)) { throw new TypeError('delegations must be an object'); } else { delegations = delegations_1.Delegations.fromJSON(data); } } return delegations; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Timestamp = void 0; const base_1 = require("./base"); const file_1 = require("./file"); const utils_1 = require("./utils"); /** * A container for the signed part of timestamp metadata. * * A top-level that specifies the latest version of the snapshot role metadata file, * and hence the latest versions of all metadata and targets on the repository. */ class Timestamp extends base_1.Signed { constructor(options) { super(options); this.type = base_1.MetadataKind.Timestamp; this.snapshotMeta = options.snapshotMeta || new file_1.MetaFile({ version: 1 }); } equals(other) { if (!(other instanceof Timestamp)) { return false; } return super.equals(other) && this.snapshotMeta.equals(other.snapshotMeta); } toJSON() { return { _type: this.type, spec_version: this.specVersion, version: this.version, expires: this.expires, meta: { 'snapshot.json': this.snapshotMeta.toJSON() }, ...this.unrecognizedFields, }; } static fromJSON(data) { const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); const { meta, ...rest } = unrecognizedFields; return new Timestamp({ ...commonFields, snapshotMeta: snapshotMetaFromJSON(meta), unrecognizedFields: rest, }); } } exports.Timestamp = Timestamp; function snapshotMetaFromJSON(data) { let snapshotMeta; if (utils_1.guard.isDefined(data)) { const snapshotData = data['snapshot.json']; if (!utils_1.guard.isDefined(snapshotData) || !utils_1.guard.isObject(snapshotData)) { throw new TypeError('missing snapshot.json in meta'); } else { snapshotMeta = file_1.MetaFile.fromJSON(snapshotData); } } return snapshotMeta; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isDefined = isDefined; exports.isObject = isObject; exports.isStringArray = isStringArray; exports.isObjectArray = isObjectArray; exports.isStringRecord = isStringRecord; exports.isObjectRecord = isObjectRecord; function isDefined(val) { return val !== undefined; } function isObject(value) { return typeof value === 'object' && value !== null; } function isStringArray(value) { return Array.isArray(value) && value.every((v) => typeof v === 'string'); } function isObjectArray(value) { return Array.isArray(value) && value.every(isObject); } function isStringRecord(value) { return (typeof value === 'object' && value !== null && Object.keys(value).every((k) => typeof k === 'string') && Object.values(value).every((v) => typeof v === 'string')); } function isObjectRecord(value) { return (typeof value === 'object' && value !== null && Object.keys(value).every((k) => typeof k === 'string') && Object.values(value).every((v) => typeof v === 'object' && v !== null)); } "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.crypto = exports.guard = void 0; exports.guard = __importStar(require("./guard")); exports.crypto = __importStar(require("./verify")); "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getPublicKey = getPublicKey; const crypto_1 = __importDefault(require("crypto")); const error_1 = require("../error"); const oid_1 = require("./oid"); const ASN1_TAG_SEQUENCE = 0x30; const ANS1_TAG_BIT_STRING = 0x03; const NULL_BYTE = 0x00; const OID_EDDSA = '1.3.101.112'; const OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1'; const OID_EC_CURVE_P256V1 = '1.2.840.10045.3.1.7'; const PEM_HEADER = '-----BEGIN PUBLIC KEY-----'; function getPublicKey(keyInfo) { switch (keyInfo.keyType) { case 'rsa': return getRSAPublicKey(keyInfo); case 'ed25519': return getED25519PublicKey(keyInfo); case 'ecdsa': case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': return getECDCSAPublicKey(keyInfo); default: throw new error_1.UnsupportedAlgorithmError(`Unsupported key type: ${keyInfo.keyType}`); } } function getRSAPublicKey(keyInfo) { // Only support PEM-encoded RSA keys if (!keyInfo.keyVal.startsWith(PEM_HEADER)) { throw new error_1.CryptoError('Invalid key format'); } const key = crypto_1.default.createPublicKey(keyInfo.keyVal); switch (keyInfo.scheme) { case 'rsassa-pss-sha256': return { key: key, padding: crypto_1.default.constants.RSA_PKCS1_PSS_PADDING, }; default: throw new error_1.UnsupportedAlgorithmError(`Unsupported RSA scheme: ${keyInfo.scheme}`); } } function getED25519PublicKey(keyInfo) { let key; // If key is already PEM-encoded we can just parse it if (keyInfo.keyVal.startsWith(PEM_HEADER)) { key = crypto_1.default.createPublicKey(keyInfo.keyVal); } else { // If key is not PEM-encoded it had better be hex if (!isHex(keyInfo.keyVal)) { throw new error_1.CryptoError('Invalid key format'); } key = crypto_1.default.createPublicKey({ key: ed25519.hexToDER(keyInfo.keyVal), format: 'der', type: 'spki', }); } return { key }; } function getECDCSAPublicKey(keyInfo) { let key; // If key is already PEM-encoded we can just parse it if (keyInfo.keyVal.startsWith(PEM_HEADER)) { key = crypto_1.default.createPublicKey(keyInfo.keyVal); } else { // If key is not PEM-encoded it had better be hex if (!isHex(keyInfo.keyVal)) { throw new error_1.CryptoError('Invalid key format'); } key = crypto_1.default.createPublicKey({ key: ecdsa.hexToDER(keyInfo.keyVal), format: 'der', type: 'spki', }); } return { key }; } const ed25519 = { // Translates a hex key into a crypto KeyObject // https://keygen.sh/blog/how-to-use-hexadecimal-ed25519-keys-in-node/ hexToDER: (hex) => { const key = Buffer.from(hex, 'hex'); const oid = (0, oid_1.encodeOIDString)(OID_EDDSA); // Create a byte sequence containing the OID and key const elements = Buffer.concat([ Buffer.concat([ Buffer.from([ASN1_TAG_SEQUENCE]), Buffer.from([oid.length]), oid, ]), Buffer.concat([ Buffer.from([ANS1_TAG_BIT_STRING]), Buffer.from([key.length + 1]), Buffer.from([NULL_BYTE]), key, ]), ]); // Wrap up by creating a sequence of elements const der = Buffer.concat([ Buffer.from([ASN1_TAG_SEQUENCE]), Buffer.from([elements.length]), elements, ]); return der; }, }; const ecdsa = { hexToDER: (hex) => { const key = Buffer.from(hex, 'hex'); const bitString = Buffer.concat([ Buffer.from([ANS1_TAG_BIT_STRING]), Buffer.from([key.length + 1]), Buffer.from([NULL_BYTE]), key, ]); const oids = Buffer.concat([ (0, oid_1.encodeOIDString)(OID_EC_PUBLIC_KEY), (0, oid_1.encodeOIDString)(OID_EC_CURVE_P256V1), ]); const oidSequence = Buffer.concat([ Buffer.from([ASN1_TAG_SEQUENCE]), Buffer.from([oids.length]), oids, ]); // Wrap up by creating a sequence of elements const der = Buffer.concat([ Buffer.from([ASN1_TAG_SEQUENCE]), Buffer.from([oidSequence.length + bitString.length]), oidSequence, bitString, ]); return der; }, }; const isHex = (key) => /^[0-9a-fA-F]+$/.test(key); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.encodeOIDString = encodeOIDString; const ANS1_TAG_OID = 0x06; function encodeOIDString(oid) { const parts = oid.split('.'); // The first two subidentifiers are encoded into the first byte const first = parseInt(parts[0], 10) * 40 + parseInt(parts[1], 10); const rest = []; parts.slice(2).forEach((part) => { const bytes = encodeVariableLengthInteger(parseInt(part, 10)); rest.push(...bytes); }); const der = Buffer.from([first, ...rest]); return Buffer.from([ANS1_TAG_OID, der.length, ...der]); } function encodeVariableLengthInteger(value) { const bytes = []; let mask = 0x00; while (value > 0) { bytes.unshift((value & 0x7f) | mask); value >>= 7; mask = 0x80; } return bytes; } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySignature = void 0; const canonical_json_1 = require("@tufjs/canonical-json"); const crypto_1 = __importDefault(require("crypto")); const verifySignature = (metaDataSignedData, key, signature) => { const canonicalData = Buffer.from((0, canonical_json_1.canonicalize)(metaDataSignedData)); return crypto_1.default.verify(undefined, canonicalData, key, Buffer.from(signature, 'hex')); }; exports.verifySignature = verifySignature; { "name": "@tufjs/models", "version": "3.0.1", "description": "TUF metadata models", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ "dist" ], "scripts": { "build": "tsc --build", "clean": "rm -rf dist && rm tsconfig.tsbuildinfo", "test": "jest" }, "repository": { "type": "git", "url": "git+https://github.com/theupdateframework/tuf-js.git" }, "keywords": [ "tuf", "security", "update" ], "author": "bdehamer@github.com", "license": "MIT", "bugs": { "url": "https://github.com/theupdateframework/tuf-js/issues" }, "homepage": "https://github.com/theupdateframework/tuf-js/tree/main/packages/models#readme", "dependencies": { "@tufjs/canonical-json": "2.0.0", "minimatch": "^9.0.5" }, "engines": { "node": "^18.17.0 || >=20.5.0" } } This software is dual-licensed under the ISC and MIT licenses. You may use this software under EITHER of the following licenses. ---------- The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------- Copyright Isaac Z. Schlueter and Contributors All rights reserved. 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. module.exports = abbrev function abbrev (...args) { let list = args.length === 1 || Array.isArray(args[0]) ? args[0] : args for (let i = 0, l = list.length; i < l; i++) { list[i] = typeof list[i] === 'string' ? list[i] : String(list[i]) } // sort them lexicographically, so that they're next to their nearest kin list = list.sort(lexSort) // walk through each, seeing how much it has in common with the next and previous const abbrevs = {} let prev = '' for (let ii = 0, ll = list.length; ii < ll; ii++) { const current = list[ii] const next = list[ii + 1] || '' let nextMatches = true let prevMatches = true if (current === next) { continue } let j = 0 const cl = current.length for (; j < cl; j++) { const curChar = current.charAt(j) nextMatches = nextMatches && curChar === next.charAt(j) prevMatches = prevMatches && curChar === prev.charAt(j) if (!nextMatches && !prevMatches) { j++ break } } prev = current if (j === cl) { abbrevs[current] = current continue } for (let a = current.slice(0, j); j <= cl; j++) { abbrevs[a] = current a += current.charAt(j) } } return abbrevs } function lexSort (a, b) { return a === b ? 0 : a > b ? 1 : -1 } { "name": "abbrev", "version": "3.0.0", "description": "Like ruby's abbrev module, but in js", "author": "GitHub Inc.", "main": "lib/index.js", "scripts": { "test": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/abbrev-js.git" }, "license": "ISC", "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.3.0" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "files": [ "bin/", "lib/" ], "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true } } (The MIT License) Copyright (c) 2013 Nathan Rajlich 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."use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.req = exports.json = exports.toBuffer = void 0; const http = __importStar(require("http")); const https = __importStar(require("https")); async function toBuffer(stream) { let length = 0; const chunks = []; for await (const chunk of stream) { length += chunk.length; chunks.push(chunk); } return Buffer.concat(chunks, length); } exports.toBuffer = toBuffer; // eslint-disable-next-line @typescript-eslint/no-explicit-any async function json(stream) { const buf = await toBuffer(stream); const str = buf.toString('utf8'); try { return JSON.parse(str); } catch (_err) { const err = _err; err.message += ` (input: ${str})`; throw err; } } exports.json = json; function req(url, opts = {}) { const href = typeof url === 'string' ? url : url.href; const req = (href.startsWith('https:') ? https : http).request(url, opts); const promise = new Promise((resolve, reject) => { req .once('response', resolve) .once('error', reject) .end(); }); req.then = promise.then.bind(promise); return req; } exports.req = req; //# sourceMappingURL=helpers.js.map"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Agent = void 0; const net = __importStar(require("net")); const http = __importStar(require("http")); const https_1 = require("https"); __exportStar(require("./helpers"), exports); const INTERNAL = Symbol('AgentBaseInternalState'); class Agent extends http.Agent { constructor(opts) { super(opts); this[INTERNAL] = {}; } /** * Determine whether this is an `http` or `https` request. */ isSecureEndpoint(options) { if (options) { // First check the `secureEndpoint` property explicitly, since this // means that a parent `Agent` is "passing through" to this instance. // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof options.secureEndpoint === 'boolean') { return options.secureEndpoint; } // If no explicit `secure` endpoint, check if `protocol` property is // set. This will usually be the case since using a full string URL // or `URL` instance should be the most common usage. if (typeof options.protocol === 'string') { return options.protocol === 'https:'; } } // Finally, if no `protocol` property was set, then fall back to // checking the stack trace of the current call stack, and try to // detect the "https" module. const { stack } = new Error(); if (typeof stack !== 'string') return false; return stack .split('\n') .some((l) => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); } // In order to support async signatures in `connect()` and Node's native // connection pooling in `http.Agent`, the array of sockets for each origin // has to be updated synchronously. This is so the length of the array is // accurate when `addRequest()` is next called. We achieve this by creating a // fake socket and adding it to `sockets[origin]` and incrementing // `totalSocketCount`. incrementSockets(name) { // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no // need to create a fake socket because Node.js native connection pooling // will never be invoked. if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { return null; } // All instances of `sockets` are expected TypeScript errors. The // alternative is to add it as a private property of this class but that // will break TypeScript subclassing. if (!this.sockets[name]) { // @ts-expect-error `sockets` is readonly in `@types/node` this.sockets[name] = []; } const fakeSocket = new net.Socket({ writable: false }); this.sockets[name].push(fakeSocket); // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` this.totalSocketCount++; return fakeSocket; } decrementSockets(name, socket) { if (!this.sockets[name] || socket === null) { return; } const sockets = this.sockets[name]; const index = sockets.indexOf(socket); if (index !== -1) { sockets.splice(index, 1); // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` this.totalSocketCount--; if (sockets.length === 0) { // @ts-expect-error `sockets` is readonly in `@types/node` delete this.sockets[name]; } } } // In order to properly update the socket pool, we need to call `getName()` on // the core `https.Agent` if it is a secureEndpoint. getName(options) { const secureEndpoint = typeof options.secureEndpoint === 'boolean' ? options.secureEndpoint : this.isSecureEndpoint(options); if (secureEndpoint) { // @ts-expect-error `getName()` isn't defined in `@types/node` return https_1.Agent.prototype.getName.call(this, options); } // @ts-expect-error `getName()` isn't defined in `@types/node` return super.getName(options); } createSocket(req, options, cb) { const connectOpts = { ...options, secureEndpoint: this.isSecureEndpoint(options), }; const name = this.getName(connectOpts); const fakeSocket = this.incrementSockets(name); Promise.resolve() .then(() => this.connect(req, connectOpts)) .then((socket) => { this.decrementSockets(name, fakeSocket); if (socket instanceof http.Agent) { try { // @ts-expect-error `addRequest()` isn't defined in `@types/node` return socket.addRequest(req, connectOpts); } catch (err) { return cb(err); } } this[INTERNAL].currentSocket = socket; // @ts-expect-error `createSocket()` isn't defined in `@types/node` super.createSocket(req, options, cb); }, (err) => { this.decrementSockets(name, fakeSocket); cb(err); }); } createConnection() { const socket = this[INTERNAL].currentSocket; this[INTERNAL].currentSocket = undefined; if (!socket) { throw new Error('No socket was returned in the `connect()` function'); } return socket; } get defaultPort() { return (this[INTERNAL].defaultPort ?? (this.protocol === 'https:' ? 443 : 80)); } set defaultPort(v) { if (this[INTERNAL]) { this[INTERNAL].defaultPort = v; } } get protocol() { return (this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? 'https:' : 'http:')); } set protocol(v) { if (this[INTERNAL]) { this[INTERNAL].protocol = v; } } } exports.Agent = Agent; //# sourceMappingURL=index.js.map{ "name": "agent-base", "version": "7.1.3", "description": "Turn a function into an `http.Agent` instance", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist" ], "repository": { "type": "git", "url": "https://github.com/TooTallNate/proxy-agents.git", "directory": "packages/agent-base" }, "keywords": [ "http", "agent", "base", "barebones", "https" ], "author": "Nathan Rajlich (http://n8.io/)", "license": "MIT", "devDependencies": { "@types/debug": "^4.1.7", "@types/jest": "^29.5.1", "@types/node": "^14.18.45", "@types/semver": "^7.3.13", "@types/ws": "^6.0.4", "async-listen": "^3.0.0", "jest": "^29.5.0", "ts-jest": "^29.1.0", "typescript": "^5.0.4", "ws": "^5.2.4", "tsconfig": "0.0.0" }, "engines": { "node": ">= 14" }, "scripts": { "build": "tsc", "test": "jest --env node --verbose --bail", "lint": "eslint . --ext .ts", "pack": "node ../../scripts/pack.mjs" } }'use strict'; module.exports = ({onlyFirst = false} = {}) => { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; MIT License Copyright (c) Sindre Sorhus (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. { "name": "ansi-regex", "version": "5.0.1", "description": "Regular expression for matching ANSI escape codes", "license": "MIT", "repository": "chalk/ansi-regex", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "devDependencies": { "ava": "^2.4.0", "tsd": "^0.9.0", "xo": "^0.25.3" } } const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], gray: [90, 39], // Alias of `blackBright` grey: [90, 39], // Alias of `blackBright` redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgGray: [100, 49], // Alias of `bgBlackBright` bgGrey: [100, 49], // Alias of `bgBlackBright` bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], }, }; export const modifierNames = Object.keys(styles.modifier); export const foregroundColorNames = Object.keys(styles.color); export const backgroundColorNames = Object.keys(styles.bgColor); export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; function assembleStyles() { const codes = new Map(); for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m`, }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false, }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false, }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js Object.defineProperties(styles, { rgbToAnsi256: { value: (red, green, blue) => { // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round(((red - 8) / 247) * 24) + 232; } return 16 + (36 * Math.round(red / 255 * 5)) + (6 * Math.round(green / 255 * 5)) + Math.round(blue / 255 * 5); }, enumerable: false, }, hexToRgb: { value: hex => { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF, /* eslint-enable no-bitwise */ ]; }, enumerable: false, }, hexToAnsi256: { value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false, }, ansi256ToAnsi: { value: code => { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = (((code - 232) * 10) + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = (remainder % 6) / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } // eslint-disable-next-line no-bitwise let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false, }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false, }, hexToAnsi: { value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false, }, }); return styles; } const ansiStyles = assembleStyles(); export default ansiStyles; MIT License Copyright (c) Sindre Sorhus (https://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. { "name": "ansi-styles", "version": "6.2.1", "description": "ANSI escape codes for styling strings in the terminal", "license": "MIT", "repository": "chalk/ansi-styles", "funding": "https://github.com/chalk/ansi-styles?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd", "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "devDependencies": { "ava": "^3.15.0", "svg-term-cli": "^2.1.1", "tsd": "^0.19.0", "xo": "^0.47.0" } } Copyright (c) 2015, Rebecca Turner Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' module.exports = validate function isArguments (thingy) { return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') } const types = { '*': {label: 'any', check: () => true}, A: {label: 'array', check: _ => Array.isArray(_) || isArguments(_)}, S: {label: 'string', check: _ => typeof _ === 'string'}, N: {label: 'number', check: _ => typeof _ === 'number'}, F: {label: 'function', check: _ => typeof _ === 'function'}, O: {label: 'object', check: _ => typeof _ === 'object' && _ != null && !types.A.check(_) && !types.E.check(_)}, B: {label: 'boolean', check: _ => typeof _ === 'boolean'}, E: {label: 'error', check: _ => _ instanceof Error}, Z: {label: 'null', check: _ => _ == null} } function addSchema (schema, arity) { const group = arity[schema.length] = arity[schema.length] || [] if (group.indexOf(schema) === -1) group.push(schema) } function validate (rawSchemas, args) { if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') if (!args) throw missingRequiredArg(1, 'args') if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) if (!types.A.check(args)) throw invalidType(1, ['array'], args) const schemas = rawSchemas.split('|') const arity = {} schemas.forEach(schema => { for (let ii = 0; ii < schema.length; ++ii) { const type = schema[ii] if (!types[type]) throw unknownType(ii, type) } if (/E.*E/.test(schema)) throw moreThanOneError(schema) addSchema(schema, arity) if (/E/.test(schema)) { addSchema(schema.replace(/E.*$/, 'E'), arity) addSchema(schema.replace(/E/, 'Z'), arity) if (schema.length === 1) addSchema('', arity) } }) let matching = arity[args.length] if (!matching) { throw wrongNumberOfArgs(Object.keys(arity), args.length) } for (let ii = 0; ii < args.length; ++ii) { let newMatching = matching.filter(schema => { const type = schema[ii] const typeCheck = types[type].check return typeCheck(args[ii]) }) if (!newMatching.length) { const labels = matching.map(_ => types[_[ii]].label).filter(_ => _ != null) throw invalidType(ii, labels, args[ii]) } matching = newMatching } } function missingRequiredArg (num) { return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) } function unknownType (num, type) { return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) } function invalidType (num, expectedTypes, value) { let valueType Object.keys(types).forEach(typeCode => { if (types[typeCode].check(value)) valueType = types[typeCode].label }) return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + englishList(expectedTypes) + ' but got ' + valueType) } function englishList (list) { return list.join(', ').replace(/, ([^,]+)$/, ' or $1') } function wrongNumberOfArgs (expected, got) { const english = englishList(expected) const args = expected.every(ex => ex.length === 1) ? 'argument' : 'arguments' return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) } function moreThanOneError (schema) { return newException('ETOOMANYERRORTYPES', 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') } function newException (code, msg) { const err = new Error(msg) err.code = code /* istanbul ignore else */ if (Error.captureStackTrace) Error.captureStackTrace(err, validate) return err } { "name": "aproba", "version": "2.0.0", "description": "A ridiculously light-weight argument validator (now browser friendly)", "main": "index.js", "directories": { "test": "test" }, "dependencies": {}, "devDependencies": { "standard": "^11.0.1", "tap": "^12.0.1" }, "files": [ "index.js" ], "scripts": { "pretest": "standard", "test": "tap --100 -J test/*.js" }, "repository": { "type": "git", "url": "https://github.com/iarna/aproba" }, "keywords": [ "argument", "validate" ], "author": "Rebecca Turner ", "license": "ISC", "bugs": { "url": "https://github.com/iarna/aproba/issues" }, "homepage": "https://github.com/iarna/aproba" } This software is released under the MIT license: 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. var archy = require('../'); var s = archy({ label : 'beep', nodes : [ 'ity', { label : 'boop', nodes : [ { label : 'o_O', nodes : [ { label : 'oh', nodes : [ 'hello', 'puny' ] }, 'human' ] }, 'party\ntime!' ] } ] }); console.log(s); var archy = require('../'); var s = archy({ label : 'beep\none\ntwo', nodes : [ 'ity', { label : 'boop', nodes : [ { label : 'o_O\nwheee', nodes : [ { label : 'oh', nodes : [ 'hello', 'puny\nmeat' ] }, 'creature' ] }, 'party\ntime!' ] } ] }); console.log(s); module.exports = function archy (obj, prefix, opts) { if (prefix === undefined) prefix = ''; if (!opts) opts = {}; var chr = function (s) { var chars = { '│' : '|', '└' : '`', '├' : '+', '─' : '-', '┬' : '-' }; return opts.unicode === false ? chars[s] : s; }; if (typeof obj === 'string') obj = { label : obj }; var nodes = obj.nodes || []; var lines = (obj.label || '').split('\n'); var splitter = '\n' + prefix + (nodes.length ? chr('│') : ' ') + ' '; return prefix + lines.join(splitter) + '\n' + nodes.map(function (node, ix) { var last = ix === nodes.length - 1; var more = node.nodes && node.nodes.length; var prefix_ = prefix + (last ? ' ' : chr('│')) + ' '; return prefix + (last ? chr('└') : chr('├')) + chr('─') + (more ? chr('┬') : chr('─')) + ' ' + archy(node, prefix_, opts).slice(prefix.length + 2) ; }).join('') ; }; { "name" : "archy", "version" : "1.0.0", "description" : "render nested hierarchies `npm ls` style with unicode pipes", "main" : "index.js", "devDependencies" : { "tap" : "~0.3.3", "tape" : "~0.1.1" }, "scripts" : { "test" : "tap test" }, "testling" : { "files" : "test/*.js", "browsers" : { "iexplore" : [ "6.0", "7.0", "8.0", "9.0" ], "chrome" : [ "20.0" ], "firefox" : [ "10.0", "15.0" ], "safari" : [ "5.1" ], "opera" : [ "12.0" ] } }, "repository" : { "type" : "git", "url" : "http://github.com/substack/node-archy.git" }, "keywords" : [ "hierarchy", "npm ls", "unicode", "pretty", "print" ], "author" : { "name" : "James Halliday", "email" : "mail@substack.net", "url" : "http://substack.net" }, "license" : "MIT" } var test = require('tape'); var archy = require('../'); test('beep', function (t) { var s = archy({ label : 'beep', nodes : [ 'ity', { label : 'boop', nodes : [ { label : 'o_O', nodes : [ { label : 'oh', nodes : [ 'hello', 'puny' ] }, 'human' ] }, 'party!' ] } ] }); t.equal(s, [ 'beep', '├── ity', '└─┬ boop', ' ├─┬ o_O', ' │ ├─┬ oh', ' │ │ ├── hello', ' │ │ └── puny', ' │ └── human', ' └── party!', '' ].join('\n')); t.end(); }); var test = require('tape'); var archy = require('../'); test('multi-line', function (t) { var s = archy({ label : 'beep\none\ntwo', nodes : [ 'ity', { label : 'boop', nodes : [ { label : 'o_O\nwheee', nodes : [ { label : 'oh', nodes : [ 'hello', 'puny\nmeat' ] }, 'creature' ] }, 'party\ntime!' ] } ] }); t.equal(s, [ 'beep', '│ one', '│ two', '├── ity', '└─┬ boop', ' ├─┬ o_O', ' │ │ wheee', ' │ ├─┬ oh', ' │ │ ├── hello', ' │ │ └── puny', ' │ │ meat', ' │ └── creature', ' └── party', ' time!', '' ].join('\n')); t.end(); }); var test = require('tape'); var archy = require('../'); test('beep', function (t) { var s = archy({ label : 'beep', nodes : [ 'ity', { label : 'boop', nodes : [ { label : 'o_O', nodes : [ { label : 'oh', nodes : [ 'hello', 'puny' ] }, 'human' ] }, 'party!' ] } ] }, '', { unicode : false }); t.equal(s, [ 'beep', '+-- ity', '`-- boop', ' +-- o_O', ' | +-- oh', ' | | +-- hello', ' | | `-- puny', ' | `-- human', ' `-- party!', '' ].join('\n')); t.end(); }); (MIT) Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. 'use strict'; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { if(a===b) { return [ai, bi]; } begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } { "name": "balanced-match", "description": "Match balanced character pairs, like \"{\" and \"}\"", "version": "1.0.2", "repository": { "type": "git", "url": "git://github.com/juliangruber/balanced-match.git" }, "homepage": "https://github.com/juliangruber/balanced-match", "main": "index.js", "scripts": { "test": "tape test/test.js", "bench": "matcha test/bench.js" }, "devDependencies": { "matcha": "^0.7.0", "tape": "^4.6.0" }, "keywords": [ "match", "regexp", "test", "balanced", "parse" ], "author": { "name": "Julian Gruber", "email": "mail@juliangruber.com", "url": "http://juliangruber.com" }, "license": "MIT", "testling": { "files": "test/*.js", "browsers": [ "ie/8..latest", "firefox/20..latest", "firefox/nightly", "chrome/25..latest", "chrome/canary", "opera/12..latest", "opera/next", "safari/5.1..latest", "ipad/6.0..latest", "iphone/6.0..latest", "android-browser/4.2..latest" ] } } The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const isWindows = require('./is-windows.js') const getPrefix = require('./get-prefix.js') const getNodeModules = require('./get-node-modules.js') const { dirname } = require('path') module.exports = ({ top, path }) => !top ? getNodeModules(path) + '/.bin' : isWindows ? getPrefix(path) : dirname(getPrefix(path)) + '/bin' // check to see if a bin is allowed to be overwritten // either rejects or resolves to nothing. return value not relevant. const isWindows = require('./is-windows.js') const binTarget = require('./bin-target.js') const { resolve, dirname } = require('path') const readCmdShim = require('read-cmd-shim') const { readlink } = require('fs/promises') const checkBin = async ({ bin, path, top, global, force }) => { // always ok to clobber when forced // always ok to clobber local bins, or when forced if (force || !global || !top) { return } // ok, need to make sure, then const target = resolve(binTarget({ path, top }), bin) path = resolve(path) return isWindows ? checkShim({ target, path }) : checkLink({ target, path }) } // only enoent is allowed. anything else is a problem. const handleReadLinkError = async ({ er, target }) => er.code === 'ENOENT' ? null : failEEXIST({ target }) const checkLink = async ({ target, path }) => { const current = await readlink(target) .catch(er => handleReadLinkError({ er, target })) if (!current) { return } const resolved = resolve(dirname(target), current) if (resolved.toLowerCase().indexOf(path.toLowerCase()) !== 0) { return failEEXIST({ target }) } } const handleReadCmdShimError = ({ er, target }) => er.code === 'ENOENT' ? null : failEEXIST({ target }) const failEEXIST = ({ target }) => Promise.reject(Object.assign(new Error('EEXIST: file already exists'), { path: target, code: 'EEXIST', })) const checkShim = async ({ target, path }) => { const shims = [ target, target + '.cmd', target + '.ps1', ] await Promise.all(shims.map(async shim => { const current = await readCmdShim(shim) .catch(er => handleReadCmdShimError({ er, target: shim })) if (!current) { return } const resolved = resolve(dirname(shim), current.replace(/\\/g, '/')) if (resolved.toLowerCase().indexOf(path.toLowerCase()) !== 0) { return failEEXIST({ target: shim }) } })) } module.exports = checkBin const checkBin = require('./check-bin.js') const normalize = require('npm-normalize-package-bin') const checkBins = async ({ pkg, path, top, global, force }) => { // always ok to clobber when forced // always ok to clobber local bins, or when forced if (force || !global || !top) { return } pkg = normalize(pkg) if (!pkg.bin) { return } await Promise.all(Object.keys(pkg.bin) .map(bin => checkBin({ bin, path, top, global, force }))) } module.exports = checkBins // make sure that bins are executable, and that they don't have // windows line-endings on the hashbang line. const { chmod, open, readFile, } = require('fs/promises') const execMode = 0o777 & (~process.umask()) const writeFileAtomic = require('write-file-atomic') const isWindowsHashBang = buf => buf[0] === '#'.charCodeAt(0) && buf[1] === '!'.charCodeAt(0) && /^#![^\n]+\r\n/.test(buf.toString()) const isWindowsHashbangFile = file => { const FALSE = () => false return open(file, 'r').then(fh => { const buf = Buffer.alloc(2048) return fh.read(buf, 0, 2048, 0) .then( () => { const isWHB = isWindowsHashBang(buf) return fh.close().then(() => isWHB, () => isWHB) }, // don't leak FD if read() fails () => fh.close().then(FALSE, FALSE) ) }, FALSE) } const dos2Unix = file => readFile(file, 'utf8').then(content => writeFileAtomic(file, content.replace(/^(#![^\n]+)\r\n/, '$1\n'))) const fixBin = (file, mode = execMode) => chmod(file, mode) .then(() => isWindowsHashbangFile(file)) .then(isWHB => isWHB ? dos2Unix(file) : null) module.exports = fixBin // we know it's global and/or not top, so the path has to be // {prefix}/node_modules/{name}. Can't rely on pkg.name, because // it might be installed as an alias. const { dirname, basename } = require('path') // this gets called a lot and can't change, so memoize it const memo = new Map() module.exports = path => { if (memo.has(path)) { return memo.get(path) } const scopeOrNm = dirname(path) const nm = basename(scopeOrNm) === 'node_modules' ? scopeOrNm : dirname(scopeOrNm) memo.set(path, nm) return nm } // get all the paths that are (or might be) installed for a given pkg // There's no guarantee that all of these will be installed, but if they // are present, then we can assume that they're associated. const binTarget = require('./bin-target.js') const manTarget = require('./man-target.js') const { resolve, basename, extname } = require('path') const isWindows = require('./is-windows.js') module.exports = ({ path, pkg, global, top }) => { if (top && !global) { return [] } const binSet = [] const binTarg = binTarget({ path, top }) if (pkg.bin) { for (const bin of Object.keys(pkg.bin)) { const b = resolve(binTarg, bin) binSet.push(b) if (isWindows) { binSet.push(b + '.cmd') binSet.push(b + '.ps1') } } } const manTarg = manTarget({ path, top }) const manSet = [] if (manTarg && pkg.man && Array.isArray(pkg.man) && pkg.man.length) { for (const man of pkg.man) { if (!/.\.[0-9]+(\.gz)?$/.test(man)) { return binSet } const section = extname(basename(man, '.gz')).slice(1) const base = basename(man) manSet.push(resolve(manTarg, 'man' + section, base)) } } return manSet.length ? [...binSet, ...manSet] : binSet } const { dirname } = require('path') const getNodeModules = require('./get-node-modules.js') module.exports = path => dirname(getNodeModules(path)) const linkBins = require('./link-bins.js') const linkMans = require('./link-mans.js') const binLinks = opts => { const { path, pkg, force, global, top } = opts // global top pkgs on windows get bins installed in {prefix}, and no mans // // unix global top pkgs get their bins installed in {prefix}/bin, // and mans in {prefix}/share/man // // non-top pkgs get their bins installed in {prefix}/node_modules/.bin, // and do not install mans // // non-global top pkgs don't have any bins or mans linked. From here on // out, if it's top, we know that it's global, so no need to pass that // option further down the stack. if (top && !global) { return Promise.resolve() } return Promise.all([ // allow clobbering within the local node_modules/.bin folder. // only global bins are protected in this way, or else it is // yet another vector for excessive dependency conflicts. linkBins({ path, pkg, top, force: force || !top }), linkMans({ path, pkg, top, force }), ]) } const shimBin = require('./shim-bin.js') const linkGently = require('./link-gently.js') const resetSeen = () => { shimBin.resetSeen() linkGently.resetSeen() } const checkBins = require('./check-bins.js') const getPaths = require('./get-paths.js') module.exports = Object.assign(binLinks, { checkBins, resetSeen, getPaths, }) const platform = process.env.__TESTING_BIN_LINKS_PLATFORM__ || process.platform module.exports = platform === 'win32' const linkGently = require('./link-gently.js') const fixBin = require('./fix-bin.js') // linking bins is simple. just symlink, and if we linked it, fix the bin up const linkBin = ({ path, to, from, absFrom, force }) => linkGently({ path, to, from, absFrom, force }) .then(linked => linked && fixBin(absFrom)) module.exports = linkBin const isWindows = require('./is-windows.js') const binTarget = require('./bin-target.js') const { dirname, resolve, relative } = require('path') const linkBin = isWindows ? require('./shim-bin.js') : require('./link-bin.js') const normalize = require('npm-normalize-package-bin') const linkBins = ({ path, pkg, top, force }) => { pkg = normalize(pkg) if (!pkg.bin) { return Promise.resolve([]) } const promises = [] const target = binTarget({ path, top }) for (const [key, val] of Object.entries(pkg.bin)) { const to = resolve(target, key) const absFrom = resolve(path, val) const from = relative(dirname(to), absFrom) promises.push(linkBin({ path, from, to, absFrom, force })) } return Promise.all(promises) } module.exports = linkBins // if the thing isn't there, skip it // if there's a non-symlink there already, eexist // if there's a symlink already, pointing somewhere else, eexist // if there's a symlink already, pointing into our pkg, remove it first // then create the symlink const { resolve, dirname } = require('path') const { lstat, mkdir, readlink, rm, symlink } = require('fs/promises') const { log } = require('proc-log') const throwSignificant = er => { if (er.code === 'ENOENT') { return } if (er.code === 'EACCES') { log.warn('error adding file', er.message) return } throw er } const rmOpts = { recursive: true, force: true, } // even in --force mode, we never create a link over a link we've // already created. you can have multiple packages in a tree trying // to contend for the same bin, or the same manpage listed multiple times, // which creates a race condition and nondeterminism. const seen = new Set() const SKIP = Symbol('skip - missing or already installed') const CLOBBER = Symbol('clobber - ours or in forceful mode') const linkGently = async ({ path, to, from, absFrom, force }) => { if (seen.has(to)) { return false } seen.add(to) // if the script or manpage isn't there, just ignore it. // this arguably *should* be an install error of some sort, // or at least a warning, but npm has always behaved this // way in the past, so it'd be a breaking change return Promise.all([ lstat(absFrom).catch(throwSignificant), lstat(to).catch(throwSignificant), ]).then(([stFrom, stTo]) => { // not present in package, skip it if (!stFrom) { return SKIP } // exists! maybe clobber if we can if (stTo) { if (!stTo.isSymbolicLink()) { return force && rm(to, rmOpts).then(() => CLOBBER) } return readlink(to).then(target => { if (target === from) { return SKIP } // skip it, already set up like we want it. target = resolve(dirname(to), target) if (target.indexOf(path) === 0 || force) { return rm(to, rmOpts).then(() => CLOBBER) } // neither skip nor clobber return false }) } else { // doesn't exist, dir might not either return mkdir(dirname(to), { recursive: true }) } }) .then(skipOrClobber => { if (skipOrClobber === SKIP) { return false } return symlink(from, to, 'file').catch(er => { if (skipOrClobber === CLOBBER || force) { return rm(to, rmOpts).then(() => symlink(from, to, 'file')) } throw er }).then(() => true) }) } const resetSeen = () => { for (const p of seen) { seen.delete(p) } } module.exports = Object.assign(linkGently, { resetSeen }) const { dirname, relative, join, resolve, basename } = require('path') const linkGently = require('./link-gently.js') const manTarget = require('./man-target.js') const linkMans = async ({ path, pkg, top, force }) => { const target = manTarget({ path, top }) if (!target || !Array.isArray(pkg?.man) || !pkg.man.length) { return [] } const links = [] // `new Set` to filter out duplicates for (let man of new Set(pkg.man)) { if (!man || typeof man !== 'string') { continue } // break any links to c:\\blah or /foo/blah or ../blah man = join('/', man).replace(/\\|:/g, '/').slice(1) const parseMan = man.match(/\.([0-9]+)(\.gz)?$/) if (!parseMan) { throw Object.assign(new Error('invalid man entry name\n' + 'Man files must end with a number, ' + 'and optionally a .gz suffix if they are compressed.' ), { code: 'EBADMAN', path, pkgid: pkg._id, man, }) } const section = parseMan[1] const base = basename(man) const absFrom = resolve(path, man) /* istanbul ignore if - that unpossible */ if (absFrom.indexOf(path) !== 0) { throw Object.assign(new Error('invalid man entry'), { code: 'EBADMAN', path, pkgid: pkg._id, man, }) } const to = resolve(target, 'man' + section, base) const from = relative(dirname(to), absFrom) links.push(linkGently({ from, to, path, absFrom, force })) } return Promise.all(links) } module.exports = linkMans const isWindows = require('./is-windows.js') const getPrefix = require('./get-prefix.js') const { dirname } = require('path') module.exports = ({ top, path }) => !top || isWindows ? null : dirname(getPrefix(path)) + '/share/man' const { resolve, dirname } = require('path') const { lstat } = require('fs/promises') const throwNonEnoent = er => { if (er.code !== 'ENOENT') { throw er } } const cmdShim = require('cmd-shim') const readCmdShim = require('read-cmd-shim') const fixBin = require('./fix-bin.js') // even in --force mode, we never create a shim over a shim we've // already created. you can have multiple packages in a tree trying // to contend for the same bin, which creates a race condition and // nondeterminism. const seen = new Set() const failEEXIST = ({ to, from }) => Promise.reject(Object.assign(new Error('EEXIST: file already exists'), { path: to, dest: from, code: 'EEXIST', })) const handleReadCmdShimError = ({ er, from, to }) => er.code === 'ENOENT' ? null : er.code === 'ENOTASHIM' ? failEEXIST({ from, to }) : Promise.reject(er) const SKIP = Symbol('skip - missing or already installed') const shimBin = ({ path, to, from, absFrom, force }) => { const shims = [ to, to + '.cmd', to + '.ps1', ] for (const shim of shims) { if (seen.has(shim)) { return true } seen.add(shim) } return Promise.all([ ...shims, absFrom, ].map(f => lstat(f).catch(throwNonEnoent))).then((stats) => { const [, , , stFrom] = stats if (!stFrom) { return SKIP } if (force) { return false } return Promise.all(shims.map((s, i) => [s, stats[i]]).map(([s, st]) => { if (!st) { return false } return readCmdShim(s) .then(target => { target = resolve(dirname(to), target) if (target.indexOf(resolve(path)) !== 0) { return failEEXIST({ from, to, path }) } return false }, er => handleReadCmdShimError({ er, from, to })) })) }) .then(skip => skip !== SKIP && doShim(absFrom, to)) } const doShim = (absFrom, to) => cmdShim(absFrom, to).then(() => fixBin(absFrom)) const resetSeen = () => { for (const p of seen) { seen.delete(p) } } module.exports = Object.assign(shimBin, { resetSeen }) { "name": "bin-links", "version": "5.0.0", "description": "JavaScript package binary linker", "main": "./lib/index.js", "scripts": { "snap": "tap", "test": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/bin-links.git" }, "keywords": [ "npm", "link", "bins" ], "license": "ISC", "dependencies": { "cmd-shim": "^7.0.0", "npm-normalize-package-bin": "^4.0.0", "proc-log": "^5.0.0", "read-cmd-shim": "^5.0.0", "write-file-atomic": "^6.0.0" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "require-inject": "^1.4.4", "tap": "^16.0.1" }, "tap": { "check-coverage": true, "coverage-map": "map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "files": [ "bin/", "lib/" ], "engines": { "node": "^18.17.0 || >=20.5.0" }, "author": "GitHub Inc.", "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "windowsCI": false, "version": "4.23.3", "publish": true } } [ "3dm", "3ds", "3g2", "3gp", "7z", "a", "aac", "adp", "afdesign", "afphoto", "afpub", "ai", "aif", "aiff", "alz", "ape", "apk", "appimage", "ar", "arj", "asf", "au", "avi", "bak", "baml", "bh", "bin", "bk", "bmp", "btif", "bz2", "bzip2", "cab", "caf", "cgm", "class", "cmx", "cpio", "cr2", "cur", "dat", "dcm", "deb", "dex", "djvu", "dll", "dmg", "dng", "doc", "docm", "docx", "dot", "dotm", "dra", "DS_Store", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", "flatpak", "fli", "flv", "fpx", "fst", "fvt", "g3", "gh", "gif", "graffle", "gz", "gzip", "h261", "h263", "h264", "icns", "ico", "ief", "img", "ipa", "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "key", "ktx", "lha", "lib", "lvp", "lz", "lzh", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", "mdi", "mht", "mid", "midi", "mj2", "mka", "mkv", "mmr", "mng", "mobi", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "mxu", "nef", "npx", "numbers", "nupkg", "o", "odp", "ods", "odt", "oga", "ogg", "ogv", "otf", "ott", "pages", "pbm", "pcx", "pdb", "pdf", "pea", "pgm", "pic", "png", "pnm", "pot", "potm", "potx", "ppa", "ppam", "ppm", "pps", "ppsm", "ppsx", "ppt", "pptm", "pptx", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "resources", "rgb", "rip", "rlc", "rmf", "rmvb", "rpm", "rtf", "rz", "s3m", "s7z", "scpt", "sgi", "shar", "snap", "sil", "sketch", "slk", "smv", "snk", "so", "stl", "suo", "sub", "swf", "tar", "tbz", "tbz2", "tga", "tgz", "thmx", "tif", "tiff", "tlz", "ttc", "ttf", "txz", "udf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", "webm", "webp", "whl", "wim", "wm", "wma", "wmv", "wmx", "woff", "woff2", "wrm", "wvx", "xbm", "xif", "xla", "xlam", "xls", "xlsb", "xlsm", "xlsx", "xlt", "xltm", "xltx", "xm", "xmind", "xpi", "xpm", "xwd", "xz", "z", "zip", "zipx" ] import binaryExtensions from './binary-extensions.json' with {type: 'json'}; export default binaryExtensions; MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Copyright (c) Paul Miller (https://paulmillr.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. { "name": "binary-extensions", "version": "3.0.0", "description": "List of binary file extensions", "license": "MIT", "repository": "sindresorhus/binary-extensions", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18.20" }, "scripts": { "//test": "xo && ava && tsd", "test": "ava && tsd" }, "files": [ "index.js", "index.d.ts", "binary-extensions.json" ], "keywords": [ "binary", "extensions", "extension", "file", "json", "list", "array" ], "devDependencies": { "ava": "^6.1.2", "tsd": "^0.31.0", "xo": "^0.58.0" } } MIT License Copyright (c) 2013 Julian Gruber 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. var balanced = require('balanced-match'); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m) return [str]; // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; if (/\$$/.test(m.pre)) { for (var k = 0; k < post.length; k++) { var expansion = pre+ '{' + m.body + '}' + post[k]; expansions.push(expansion); } } else { var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = []; for (var j = 0; j < n.length; j++) { N.push.apply(N, expand(n[j], false)); } } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } } return expansions; } { "name": "brace-expansion", "description": "Brace expansion as known from sh/bash", "version": "2.0.1", "repository": { "type": "git", "url": "git://github.com/juliangruber/brace-expansion.git" }, "homepage": "https://github.com/juliangruber/brace-expansion", "main": "index.js", "scripts": { "test": "tape test/*.js", "gentest": "bash test/generate.sh", "bench": "matcha test/perf/bench.js" }, "dependencies": { "balanced-match": "^1.0.0" }, "devDependencies": { "@c4312/matcha": "^1.3.1", "tape": "^4.6.0" }, "keywords": [], "author": { "name": "Julian Gruber", "email": "mail@juliangruber.com", "url": "http://juliangruber.com" }, "license": "MIT", "testling": { "files": "test/*.js", "browsers": [ "ie/8..latest", "firefox/20..latest", "firefox/nightly", "chrome/25..latest", "chrome/canary", "opera/12..latest", "opera/next", "safari/5.1..latest", "ipad/6.0..latest", "iphone/6.0..latest", "android-browser/4.2..latest" ] } } ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' const contentVer = require('../../package.json')['cache-version'].content const hashToSegments = require('../util/hash-to-segments') const path = require('path') const ssri = require('ssri') // Current format of content file path: // // sha512-BaSE64Hex= -> // ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee // module.exports = contentPath function contentPath (cache, integrity) { const sri = ssri.parse(integrity, { single: true }) // contentPath is the *strongest* algo given return path.join( contentDir(cache), sri.algorithm, ...hashToSegments(sri.hexDigest()) ) } module.exports.contentDir = contentDir function contentDir (cache) { return path.join(cache, `content-v${contentVer}`) } 'use strict' const fs = require('fs/promises') const fsm = require('fs-minipass') const ssri = require('ssri') const contentPath = require('./path') const Pipeline = require('minipass-pipeline') module.exports = read const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024 async function read (cache, integrity, opts = {}) { const { size } = opts const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { // get size const stat = size ? { size } : await fs.stat(cpath) return { stat, cpath, sri } }) if (stat.size > MAX_SINGLE_READ_SIZE) { return readPipeline(cpath, stat.size, sri, new Pipeline()).concat() } const data = await fs.readFile(cpath, { encoding: null }) if (stat.size !== data.length) { throw sizeError(stat.size, data.length) } if (!ssri.checkData(data, sri)) { throw integrityError(sri, cpath) } return data } const readPipeline = (cpath, size, sri, stream) => { stream.push( new fsm.ReadStream(cpath, { size, readSize: MAX_SINGLE_READ_SIZE, }), ssri.integrityStream({ integrity: sri, size, }) ) return stream } module.exports.stream = readStream module.exports.readStream = readStream function readStream (cache, integrity, opts = {}) { const { size } = opts const stream = new Pipeline() // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { // get size const stat = size ? { size } : await fs.stat(cpath) return { stat, cpath, sri } }) return readPipeline(cpath, stat.size, sri, stream) }).catch(err => stream.emit('error', err)) return stream } module.exports.copy = copy function copy (cache, integrity, dest) { return withContentSri(cache, integrity, (cpath) => { return fs.copyFile(cpath, dest) }) } module.exports.hasContent = hasContent async function hasContent (cache, integrity) { if (!integrity) { return false } try { return await withContentSri(cache, integrity, async (cpath, sri) => { const stat = await fs.stat(cpath) return { size: stat.size, sri, stat } }) } catch (err) { if (err.code === 'ENOENT') { return false } if (err.code === 'EPERM') { /* istanbul ignore else */ if (process.platform !== 'win32') { throw err } else { return false } } } } async function withContentSri (cache, integrity, fn) { const sri = ssri.parse(integrity) // If `integrity` has multiple entries, pick the first digest // with available local data. const algo = sri.pickAlgorithm() const digests = sri[algo] if (digests.length <= 1) { const cpath = contentPath(cache, digests[0]) return fn(cpath, digests[0]) } else { // Can't use race here because a generic error can happen before // a ENOENT error, and can happen before a valid result const results = await Promise.all(digests.map(async (meta) => { try { return await withContentSri(cache, meta, fn) } catch (err) { if (err.code === 'ENOENT') { return Object.assign( new Error('No matching content found for ' + sri.toString()), { code: 'ENOENT' } ) } return err } })) // Return the first non error if it is found const result = results.find((r) => !(r instanceof Error)) if (result) { return result } // Throw the No matching content found error const enoentError = results.find((r) => r.code === 'ENOENT') if (enoentError) { throw enoentError } // Throw generic error throw results.find((r) => r instanceof Error) } } function sizeError (expected, found) { /* eslint-disable-next-line max-len */ const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) err.expected = expected err.found = found err.code = 'EBADSIZE' return err } function integrityError (sri, path) { const err = new Error(`Integrity verification failed for ${sri} (${path})`) err.code = 'EINTEGRITY' err.sri = sri err.path = path return err } 'use strict' const fs = require('fs/promises') const contentPath = require('./path') const { hasContent } = require('./read') module.exports = rm async function rm (cache, integrity) { const content = await hasContent(cache, integrity) // ~pretty~ sure we can't end up with a content lacking sri, but be safe if (content && content.sri) { await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true }) return true } else { return false } } 'use strict' const events = require('events') const contentPath = require('./path') const fs = require('fs/promises') const { moveFile } = require('@npmcli/fs') const { Minipass } = require('minipass') const Pipeline = require('minipass-pipeline') const Flush = require('minipass-flush') const path = require('path') const ssri = require('ssri') const uniqueFilename = require('unique-filename') const fsm = require('fs-minipass') module.exports = write // Cache of move operations in process so we don't duplicate const moveOperations = new Map() async function write (cache, data, opts = {}) { const { algorithms, size, integrity } = opts if (typeof size === 'number' && data.length !== size) { throw sizeError(size, data.length) } const sri = ssri.fromData(data, algorithms ? { algorithms } : {}) if (integrity && !ssri.checkData(data, integrity, opts)) { throw checksumError(integrity, sri) } for (const algo in sri) { const tmp = await makeTmp(cache, opts) const hash = sri[algo].toString() try { await fs.writeFile(tmp.target, data, { flag: 'wx' }) await moveToDestination(tmp, cache, hash, opts) } finally { if (!tmp.moved) { await fs.rm(tmp.target, { recursive: true, force: true }) } } } return { integrity: sri, size: data.length } } module.exports.stream = writeStream // writes proxied to the 'inputStream' that is passed to the Promise // 'end' is deferred until content is handled. class CacacheWriteStream extends Flush { constructor (cache, opts) { super() this.opts = opts this.cache = cache this.inputStream = new Minipass() this.inputStream.on('error', er => this.emit('error', er)) this.inputStream.on('drain', () => this.emit('drain')) this.handleContentP = null } write (chunk, encoding, cb) { if (!this.handleContentP) { this.handleContentP = handleContent( this.inputStream, this.cache, this.opts ) this.handleContentP.catch(error => this.emit('error', error)) } return this.inputStream.write(chunk, encoding, cb) } flush (cb) { this.inputStream.end(() => { if (!this.handleContentP) { const e = new Error('Cache input stream was empty') e.code = 'ENODATA' // empty streams are probably emitting end right away. // defer this one tick by rejecting a promise on it. return Promise.reject(e).catch(cb) } // eslint-disable-next-line promise/catch-or-return this.handleContentP.then( (res) => { res.integrity && this.emit('integrity', res.integrity) // eslint-disable-next-line promise/always-return res.size !== null && this.emit('size', res.size) cb() }, (er) => cb(er) ) }) } } function writeStream (cache, opts = {}) { return new CacacheWriteStream(cache, opts) } async function handleContent (inputStream, cache, opts) { const tmp = await makeTmp(cache, opts) try { const res = await pipeToTmp(inputStream, cache, tmp.target, opts) await moveToDestination( tmp, cache, res.integrity, opts ) return res } finally { if (!tmp.moved) { await fs.rm(tmp.target, { recursive: true, force: true }) } } } async function pipeToTmp (inputStream, cache, tmpTarget, opts) { const outStream = new fsm.WriteStream(tmpTarget, { flags: 'wx', }) if (opts.integrityEmitter) { // we need to create these all simultaneously since they can fire in any order const [integrity, size] = await Promise.all([ events.once(opts.integrityEmitter, 'integrity').then(res => res[0]), events.once(opts.integrityEmitter, 'size').then(res => res[0]), new Pipeline(inputStream, outStream).promise(), ]) return { integrity, size } } let integrity let size const hashStream = ssri.integrityStream({ integrity: opts.integrity, algorithms: opts.algorithms, size: opts.size, }) hashStream.on('integrity', i => { integrity = i }) hashStream.on('size', s => { size = s }) const pipeline = new Pipeline(inputStream, hashStream, outStream) await pipeline.promise() return { integrity, size } } async function makeTmp (cache, opts) { const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) await fs.mkdir(path.dirname(tmpTarget), { recursive: true }) return { target: tmpTarget, moved: false, } } async function moveToDestination (tmp, cache, sri) { const destination = contentPath(cache, sri) const destDir = path.dirname(destination) if (moveOperations.has(destination)) { return moveOperations.get(destination) } moveOperations.set( destination, fs.mkdir(destDir, { recursive: true }) .then(async () => { await moveFile(tmp.target, destination, { overwrite: false }) tmp.moved = true return tmp.moved }) .catch(err => { if (!err.message.startsWith('The destination file exists')) { throw Object.assign(err, { code: 'EEXIST' }) } }).finally(() => { moveOperations.delete(destination) }) ) return moveOperations.get(destination) } function sizeError (expected, found) { /* eslint-disable-next-line max-len */ const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) err.expected = expected err.found = found err.code = 'EBADSIZE' return err } function checksumError (expected, found) { const err = new Error(`Integrity check failed: Wanted: ${expected} Found: ${found}`) err.code = 'EINTEGRITY' err.expected = expected err.found = found return err } 'use strict' const crypto = require('crypto') const { appendFile, mkdir, readFile, readdir, rm, writeFile, } = require('fs/promises') const { Minipass } = require('minipass') const path = require('path') const ssri = require('ssri') const uniqueFilename = require('unique-filename') const contentPath = require('./content/path') const hashToSegments = require('./util/hash-to-segments') const indexV = require('../package.json')['cache-version'].index const { moveFile } = require('@npmcli/fs') const lsStreamConcurrency = 5 module.exports.NotFoundError = class NotFoundError extends Error { constructor (cache, key) { super(`No cache entry for ${key} found in ${cache}`) this.code = 'ENOENT' this.cache = cache this.key = key } } module.exports.compact = compact async function compact (cache, key, matchFn, opts = {}) { const bucket = bucketPath(cache, key) const entries = await bucketEntries(bucket) const newEntries = [] // we loop backwards because the bottom-most result is the newest // since we add new entries with appendFile for (let i = entries.length - 1; i >= 0; --i) { const entry = entries[i] // a null integrity could mean either a delete was appended // or the user has simply stored an index that does not map // to any content. we determine if the user wants to keep the // null integrity based on the validateEntry function passed in options. // if the integrity is null and no validateEntry is provided, we break // as we consider the null integrity to be a deletion of everything // that came before it. if (entry.integrity === null && !opts.validateEntry) { break } // if this entry is valid, and it is either the first entry or // the newEntries array doesn't already include an entry that // matches this one based on the provided matchFn, then we add // it to the beginning of our list if ((!opts.validateEntry || opts.validateEntry(entry) === true) && (newEntries.length === 0 || !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) { newEntries.unshift(entry) } } const newIndex = '\n' + newEntries.map((entry) => { const stringified = JSON.stringify(entry) const hash = hashEntry(stringified) return `${hash}\t${stringified}` }).join('\n') const setup = async () => { const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) await mkdir(path.dirname(target), { recursive: true }) return { target, moved: false, } } const teardown = async (tmp) => { if (!tmp.moved) { return rm(tmp.target, { recursive: true, force: true }) } } const write = async (tmp) => { await writeFile(tmp.target, newIndex, { flag: 'wx' }) await mkdir(path.dirname(bucket), { recursive: true }) // we use @npmcli/move-file directly here because we // want to overwrite the existing file await moveFile(tmp.target, bucket) tmp.moved = true } // write the file atomically const tmp = await setup() try { await write(tmp) } finally { await teardown(tmp) } // we reverse the list we generated such that the newest // entries come first in order to make looping through them easier // the true passed to formatEntry tells it to keep null // integrity values, if they made it this far it's because // validateEntry returned true, and as such we should return it return newEntries.reverse().map((entry) => formatEntry(cache, entry, true)) } module.exports.insert = insert async function insert (cache, key, integrity, opts = {}) { const { metadata, size, time } = opts const bucket = bucketPath(cache, key) const entry = { key, integrity: integrity && ssri.stringify(integrity), time: time || Date.now(), size, metadata, } try { await mkdir(path.dirname(bucket), { recursive: true }) const stringified = JSON.stringify(entry) // NOTE - Cleverness ahoy! // // This works because it's tremendously unlikely for an entry to corrupt // another while still preserving the string length of the JSON in // question. So, we just slap the length in there and verify it on read. // // Thanks to @isaacs for the whiteboarding session that ended up with // this. await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`) } catch (err) { if (err.code === 'ENOENT') { return undefined } throw err } return formatEntry(cache, entry) } module.exports.find = find async function find (cache, key) { const bucket = bucketPath(cache, key) try { const entries = await bucketEntries(bucket) return entries.reduce((latest, next) => { if (next && next.key === key) { return formatEntry(cache, next) } else { return latest } }, null) } catch (err) { if (err.code === 'ENOENT') { return null } else { throw err } } } module.exports.delete = del function del (cache, key, opts = {}) { if (!opts.removeFully) { return insert(cache, key, null, opts) } const bucket = bucketPath(cache, key) return rm(bucket, { recursive: true, force: true }) } module.exports.lsStream = lsStream function lsStream (cache) { const indexDir = bucketDir(cache) const stream = new Minipass({ objectMode: true }) // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const { default: pMap } = await import('p-map') const buckets = await readdirOrEmpty(indexDir) await pMap(buckets, async (bucket) => { const bucketPath = path.join(indexDir, bucket) const subbuckets = await readdirOrEmpty(bucketPath) await pMap(subbuckets, async (subbucket) => { const subbucketPath = path.join(bucketPath, subbucket) // "/cachename//./*" const subbucketEntries = await readdirOrEmpty(subbucketPath) await pMap(subbucketEntries, async (entry) => { const entryPath = path.join(subbucketPath, entry) try { const entries = await bucketEntries(entryPath) // using a Map here prevents duplicate keys from showing up // twice, I guess? const reduced = entries.reduce((acc, entry) => { acc.set(entry.key, entry) return acc }, new Map()) // reduced is a map of key => entry for (const entry of reduced.values()) { const formatted = formatEntry(cache, entry) if (formatted) { stream.write(formatted) } } } catch (err) { if (err.code === 'ENOENT') { return undefined } throw err } }, { concurrency: lsStreamConcurrency }) }, { concurrency: lsStreamConcurrency }) }, { concurrency: lsStreamConcurrency }) stream.end() return stream }).catch(err => stream.emit('error', err)) return stream } module.exports.ls = ls async function ls (cache) { const entries = await lsStream(cache).collect() return entries.reduce((acc, xs) => { acc[xs.key] = xs return acc }, {}) } module.exports.bucketEntries = bucketEntries async function bucketEntries (bucket, filter) { const data = await readFile(bucket, 'utf8') return _bucketEntries(data, filter) } function _bucketEntries (data) { const entries = [] data.split('\n').forEach((entry) => { if (!entry) { return } const pieces = entry.split('\t') if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) { // Hash is no good! Corruption or malice? Doesn't matter! // EJECT EJECT return } let obj try { obj = JSON.parse(pieces[1]) } catch (_) { // eslint-ignore-next-line no-empty-block } // coverage disabled here, no need to test with an entry that parses to something falsey // istanbul ignore else if (obj) { entries.push(obj) } }) return entries } module.exports.bucketDir = bucketDir function bucketDir (cache) { return path.join(cache, `index-v${indexV}`) } module.exports.bucketPath = bucketPath function bucketPath (cache, key) { const hashed = hashKey(key) return path.join.apply( path, [bucketDir(cache)].concat(hashToSegments(hashed)) ) } module.exports.hashKey = hashKey function hashKey (key) { return hash(key, 'sha256') } module.exports.hashEntry = hashEntry function hashEntry (str) { return hash(str, 'sha1') } function hash (str, digest) { return crypto .createHash(digest) .update(str) .digest('hex') } function formatEntry (cache, entry, keepAll) { // Treat null digests as deletions. They'll shadow any previous entries. if (!entry.integrity && !keepAll) { return null } return { key: entry.key, integrity: entry.integrity, path: entry.integrity ? contentPath(cache, entry.integrity) : undefined, size: entry.size, time: entry.time, metadata: entry.metadata, } } function readdirOrEmpty (dir) { return readdir(dir).catch((err) => { if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { return [] } throw err }) } 'use strict' const Collect = require('minipass-collect') const { Minipass } = require('minipass') const Pipeline = require('minipass-pipeline') const index = require('./entry-index') const memo = require('./memoization') const read = require('./content/read') async function getData (cache, key, opts = {}) { const { integrity, memoize, size } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return { metadata: memoized.entry.metadata, data: memoized.data, integrity: memoized.entry.integrity, size: memoized.entry.size, } } const entry = await index.find(cache, key, opts) if (!entry) { throw new index.NotFoundError(cache, key) } const data = await read(cache, entry.integrity, { integrity, size }) if (memoize) { memo.put(cache, entry, data, opts) } return { data, metadata: entry.metadata, size: entry.size, integrity: entry.integrity, } } module.exports = getData async function getDataByDigest (cache, key, opts = {}) { const { integrity, memoize, size } = opts const memoized = memo.get.byDigest(cache, key, opts) if (memoized && memoize !== false) { return memoized } const res = await read(cache, key, { integrity, size }) if (memoize) { memo.put.byDigest(cache, key, res, opts) } return res } module.exports.byDigest = getDataByDigest const getMemoizedStream = (memoized) => { const stream = new Minipass() stream.on('newListener', function (ev, cb) { ev === 'metadata' && cb(memoized.entry.metadata) ev === 'integrity' && cb(memoized.entry.integrity) ev === 'size' && cb(memoized.entry.size) }) stream.end(memoized.data) return stream } function getStream (cache, key, opts = {}) { const { memoize, size } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return getMemoizedStream(memoized) } const stream = new Pipeline() // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const entry = await index.find(cache, key) if (!entry) { throw new index.NotFoundError(cache, key) } stream.emit('metadata', entry.metadata) stream.emit('integrity', entry.integrity) stream.emit('size', entry.size) stream.on('newListener', function (ev, cb) { ev === 'metadata' && cb(entry.metadata) ev === 'integrity' && cb(entry.integrity) ev === 'size' && cb(entry.size) }) const src = read.readStream( cache, entry.integrity, { ...opts, size: typeof size !== 'number' ? entry.size : size } ) if (memoize) { const memoStream = new Collect.PassThrough() memoStream.on('collect', data => memo.put(cache, entry, data, opts)) stream.unshift(memoStream) } stream.unshift(src) return stream }).catch((err) => stream.emit('error', err)) return stream } module.exports.stream = getStream function getStreamDigest (cache, integrity, opts = {}) { const { memoize } = opts const memoized = memo.get.byDigest(cache, integrity, opts) if (memoized && memoize !== false) { const stream = new Minipass() stream.end(memoized) return stream } else { const stream = read.readStream(cache, integrity, opts) if (!memoize) { return stream } const memoStream = new Collect.PassThrough() memoStream.on('collect', data => memo.put.byDigest( cache, integrity, data, opts )) return new Pipeline(stream, memoStream) } } module.exports.stream.byDigest = getStreamDigest function info (cache, key, opts = {}) { const { memoize } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return Promise.resolve(memoized.entry) } else { return index.find(cache, key) } } module.exports.info = info async function copy (cache, key, dest, opts = {}) { const entry = await index.find(cache, key, opts) if (!entry) { throw new index.NotFoundError(cache, key) } await read.copy(cache, entry.integrity, dest, opts) return { metadata: entry.metadata, size: entry.size, integrity: entry.integrity, } } module.exports.copy = copy async function copyByDigest (cache, key, dest, opts = {}) { await read.copy(cache, key, dest, opts) return key } module.exports.copy.byDigest = copyByDigest module.exports.hasContent = read.hasContent 'use strict' const get = require('./get.js') const put = require('./put.js') const rm = require('./rm.js') const verify = require('./verify.js') const { clearMemoized } = require('./memoization.js') const tmp = require('./util/tmp.js') const index = require('./entry-index.js') module.exports.index = {} module.exports.index.compact = index.compact module.exports.index.insert = index.insert module.exports.ls = index.ls module.exports.ls.stream = index.lsStream module.exports.get = get module.exports.get.byDigest = get.byDigest module.exports.get.stream = get.stream module.exports.get.stream.byDigest = get.stream.byDigest module.exports.get.copy = get.copy module.exports.get.copy.byDigest = get.copy.byDigest module.exports.get.info = get.info module.exports.get.hasContent = get.hasContent module.exports.put = put module.exports.put.stream = put.stream module.exports.rm = rm.entry module.exports.rm.all = rm.all module.exports.rm.entry = module.exports.rm module.exports.rm.content = rm.content module.exports.clearMemoized = clearMemoized module.exports.tmp = {} module.exports.tmp.mkdir = tmp.mkdir module.exports.tmp.withTmp = tmp.withTmp module.exports.verify = verify module.exports.verify.lastRun = verify.lastRun 'use strict' const { LRUCache } = require('lru-cache') const MEMOIZED = new LRUCache({ max: 500, maxSize: 50 * 1024 * 1024, // 50MB ttl: 3 * 60 * 1000, // 3 minutes sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length, }) module.exports.clearMemoized = clearMemoized function clearMemoized () { const old = {} MEMOIZED.forEach((v, k) => { old[k] = v }) MEMOIZED.clear() return old } module.exports.put = put function put (cache, entry, data, opts) { pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) putDigest(cache, entry.integrity, data, opts) } module.exports.put.byDigest = putDigest function putDigest (cache, integrity, data, opts) { pickMem(opts).set(`digest:${cache}:${integrity}`, data) } module.exports.get = get function get (cache, key, opts) { return pickMem(opts).get(`key:${cache}:${key}`) } module.exports.get.byDigest = getDigest function getDigest (cache, integrity, opts) { return pickMem(opts).get(`digest:${cache}:${integrity}`) } class ObjProxy { constructor (obj) { this.obj = obj } get (key) { return this.obj[key] } set (key, val) { this.obj[key] = val } } function pickMem (opts) { if (!opts || !opts.memoize) { return MEMOIZED } else if (opts.memoize.get && opts.memoize.set) { return opts.memoize } else if (typeof opts.memoize === 'object') { return new ObjProxy(opts.memoize) } else { return MEMOIZED } } 'use strict' const index = require('./entry-index') const memo = require('./memoization') const write = require('./content/write') const Flush = require('minipass-flush') const { PassThrough } = require('minipass-collect') const Pipeline = require('minipass-pipeline') const putOpts = (opts) => ({ algorithms: ['sha512'], ...opts, }) module.exports = putData async function putData (cache, key, data, opts = {}) { const { memoize } = opts opts = putOpts(opts) const res = await write(cache, data, opts) const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size }) if (memoize) { memo.put(cache, entry, data, opts) } return res.integrity } module.exports.stream = putStream function putStream (cache, key, opts = {}) { const { memoize } = opts opts = putOpts(opts) let integrity let size let error let memoData const pipeline = new Pipeline() // first item in the pipeline is the memoizer, because we need // that to end first and get the collected data. if (memoize) { const memoizer = new PassThrough().on('collect', data => { memoData = data }) pipeline.push(memoizer) } // contentStream is a write-only, not a passthrough // no data comes out of it. const contentStream = write.stream(cache, opts) .on('integrity', (int) => { integrity = int }) .on('size', (s) => { size = s }) .on('error', (err) => { error = err }) pipeline.push(contentStream) // last but not least, we write the index and emit hash and size, // and memoize if we're doing that pipeline.push(new Flush({ async flush () { if (!error) { const entry = await index.insert(cache, key, integrity, { ...opts, size }) if (memoize && memoData) { memo.put(cache, entry, memoData, opts) } pipeline.emit('integrity', integrity) pipeline.emit('size', size) } }, })) return pipeline } 'use strict' const { rm } = require('fs/promises') const glob = require('./util/glob.js') const index = require('./entry-index') const memo = require('./memoization') const path = require('path') const rmContent = require('./content/rm') module.exports = entry module.exports.entry = entry function entry (cache, key, opts) { memo.clearMemoized() return index.delete(cache, key, opts) } module.exports.content = content function content (cache, integrity) { memo.clearMemoized() return rmContent(cache, integrity) } module.exports.all = all async function all (cache) { memo.clearMemoized() const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true }) return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true }))) } 'use strict' const { glob } = require('glob') const path = require('path') const globify = (pattern) => pattern.split(path.win32.sep).join(path.posix.sep) module.exports = (path, options) => glob(globify(path), options) 'use strict' module.exports = hashToSegments function hashToSegments (hash) { return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)] } 'use strict' const { withTempDir } = require('@npmcli/fs') const fs = require('fs/promises') const path = require('path') module.exports.mkdir = mktmpdir async function mktmpdir (cache, opts = {}) { const { tmpPrefix } = opts const tmpDir = path.join(cache, 'tmp') await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' }) // do not use path.join(), it drops the trailing / if tmpPrefix is unset const target = `${tmpDir}${path.sep}${tmpPrefix || ''}` return fs.mkdtemp(target, { owner: 'inherit' }) } module.exports.withTmp = withTmp function withTmp (cache, opts, cb) { if (!cb) { cb = opts opts = {} } return withTempDir(path.join(cache, 'tmp'), cb, opts) } 'use strict' const { mkdir, readFile, rm, stat, truncate, writeFile, } = require('fs/promises') const contentPath = require('./content/path') const fsm = require('fs-minipass') const glob = require('./util/glob.js') const index = require('./entry-index') const path = require('path') const ssri = require('ssri') const hasOwnProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key) const verifyOpts = (opts) => ({ concurrency: 20, log: { silly () {} }, ...opts, }) module.exports = verify async function verify (cache, opts) { opts = verifyOpts(opts) opts.log.silly('verify', 'verifying cache at', cache) const steps = [ markStartTime, fixPerms, garbageCollect, rebuildIndex, cleanTmp, writeVerifile, markEndTime, ] const stats = {} for (const step of steps) { const label = step.name const start = new Date() const s = await step(cache, opts) if (s) { Object.keys(s).forEach((k) => { stats[k] = s[k] }) } const end = new Date() if (!stats.runTime) { stats.runTime = {} } stats.runTime[label] = end - start } stats.runTime.total = stats.endTime - stats.startTime opts.log.silly( 'verify', 'verification finished for', cache, 'in', `${stats.runTime.total}ms` ) return stats } async function markStartTime () { return { startTime: new Date() } } async function markEndTime () { return { endTime: new Date() } } async function fixPerms (cache, opts) { opts.log.silly('verify', 'fixing cache permissions') await mkdir(cache, { recursive: true }) return null } // Implements a naive mark-and-sweep tracing garbage collector. // // The algorithm is basically as follows: // 1. Read (and filter) all index entries ("pointers") // 2. Mark each integrity value as "live" // 3. Read entire filesystem tree in `content-vX/` dir // 4. If content is live, verify its checksum and delete it if it fails // 5. If content is not marked as live, rm it. // async function garbageCollect (cache, opts) { opts.log.silly('verify', 'garbage collecting content') const { default: pMap } = await import('p-map') const indexStream = index.lsStream(cache) const liveContent = new Set() indexStream.on('data', (entry) => { if (opts.filter && !opts.filter(entry)) { return } // integrity is stringified, re-parse it so we can get each hash const integrity = ssri.parse(entry.integrity) for (const algo in integrity) { liveContent.add(integrity[algo].toString()) } }) await new Promise((resolve, reject) => { indexStream.on('end', resolve).on('error', reject) }) const contentDir = contentPath.contentDir(cache) const files = await glob(path.join(contentDir, '**'), { follow: false, nodir: true, nosort: true, }) const stats = { verifiedContent: 0, reclaimedCount: 0, reclaimedSize: 0, badContentCount: 0, keptSize: 0, } await pMap( files, async (f) => { const split = f.split(/[/\\]/) const digest = split.slice(split.length - 3).join('') const algo = split[split.length - 4] const integrity = ssri.fromHex(digest, algo) if (liveContent.has(integrity.toString())) { const info = await verifyContent(f, integrity) if (!info.valid) { stats.reclaimedCount++ stats.badContentCount++ stats.reclaimedSize += info.size } else { stats.verifiedContent++ stats.keptSize += info.size } } else { // No entries refer to this content. We can delete. stats.reclaimedCount++ const s = await stat(f) await rm(f, { recursive: true, force: true }) stats.reclaimedSize += s.size } return stats }, { concurrency: opts.concurrency } ) return stats } async function verifyContent (filepath, sri) { const contentInfo = {} try { const { size } = await stat(filepath) contentInfo.size = size contentInfo.valid = true await ssri.checkStream(new fsm.ReadStream(filepath), sri) } catch (err) { if (err.code === 'ENOENT') { return { size: 0, valid: false } } if (err.code !== 'EINTEGRITY') { throw err } await rm(filepath, { recursive: true, force: true }) contentInfo.valid = false } return contentInfo } async function rebuildIndex (cache, opts) { opts.log.silly('verify', 'rebuilding index') const { default: pMap } = await import('p-map') const entries = await index.ls(cache) const stats = { missingContent: 0, rejectedEntries: 0, totalEntries: 0, } const buckets = {} for (const k in entries) { /* istanbul ignore else */ if (hasOwnProperty(entries, k)) { const hashed = index.hashKey(k) const entry = entries[k] const excluded = opts.filter && !opts.filter(entry) excluded && stats.rejectedEntries++ if (buckets[hashed] && !excluded) { buckets[hashed].push(entry) } else if (buckets[hashed] && excluded) { // skip } else if (excluded) { buckets[hashed] = [] buckets[hashed]._path = index.bucketPath(cache, k) } else { buckets[hashed] = [entry] buckets[hashed]._path = index.bucketPath(cache, k) } } } await pMap( Object.keys(buckets), (key) => { return rebuildBucket(cache, buckets[key], stats, opts) }, { concurrency: opts.concurrency } ) return stats } async function rebuildBucket (cache, bucket, stats) { await truncate(bucket._path) // This needs to be serialized because cacache explicitly // lets very racy bucket conflicts clobber each other. for (const entry of bucket) { const content = contentPath(cache, entry.integrity) try { await stat(content) await index.insert(cache, entry.key, entry.integrity, { metadata: entry.metadata, size: entry.size, time: entry.time, }) stats.totalEntries++ } catch (err) { if (err.code === 'ENOENT') { stats.rejectedEntries++ stats.missingContent++ } else { throw err } } } } function cleanTmp (cache, opts) { opts.log.silly('verify', 'cleaning tmp directory') return rm(path.join(cache, 'tmp'), { recursive: true, force: true }) } async function writeVerifile (cache, opts) { const verifile = path.join(cache, '_lastverified') opts.log.silly('verify', 'writing verifile to ' + verifile) return writeFile(verifile, `${Date.now()}`) } module.exports.lastRun = lastRun async function lastRun (cache) { const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' }) return new Date(+data) } All packages under `src/` are licensed according to the terms in their respective `LICENSE` or `LICENSE.md` files. The remainder of this project is licensed under the Blue Oak Model License, as follows: ----- # Blue Oak Model License Version 1.0.0 ## Purpose This license gives everyone as much permission to work with this software as possible, while protecting contributors from liability. ## Acceptance In order to receive this license, you must agree to its rules. The rules of this license are both obligations under that agreement and conditions to your license. You must not do anything with this software that triggers a rule that you cannot or will not follow. ## Copyright Each contributor licenses you to do everything with this software that would otherwise infringe that contributor's copyright in it. ## Notices You must ensure that everyone who gets a copy of any part of this software from you, with or without changes, also gets the text of this license or a link to . ## Excuse If anyone notifies you in writing that you have not complied with [Notices](#notices), you can keep your license by taking all practical steps to comply within 30 days after the notice. If you do not do so, your license ends immediately. ## Patent Each contributor licenses you to do everything with this software that would otherwise infringe any patent claims they can license or become able to license. ## Reliability No contributor can revoke this license. ## No Liability ***As far as the law allows, this software comes as is, without any warranty or condition, and no contributor will be liable to anyone for any damages related to this software or this license, under any kind of legal claim.*** "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.chownrSync = exports.chownr = void 0; const node_fs_1 = __importDefault(require("node:fs")); const node_path_1 = __importDefault(require("node:path")); const lchownSync = (path, uid, gid) => { try { return node_fs_1.default.lchownSync(path, uid, gid); } catch (er) { if (er?.code !== 'ENOENT') throw er; } }; const chown = (cpath, uid, gid, cb) => { node_fs_1.default.lchown(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er?.code !== 'ENOENT' ? er : null); }); }; const chownrKid = (p, child, uid, gid, cb) => { if (child.isDirectory()) { (0, exports.chownr)(node_path_1.default.resolve(p, child.name), uid, gid, (er) => { if (er) return cb(er); const cpath = node_path_1.default.resolve(p, child.name); chown(cpath, uid, gid, cb); }); } else { const cpath = node_path_1.default.resolve(p, child.name); chown(cpath, uid, gid, cb); } }; const chownr = (p, uid, gid, cb) => { node_fs_1.default.readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb(); else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er); } if (er || !children.length) return chown(p, uid, gid, cb); let len = children.length; let errState = null; const then = (er) => { /* c8 ignore start */ if (errState) return; /* c8 ignore stop */ if (er) return cb((errState = er)); if (--len === 0) return chown(p, uid, gid, cb); }; for (const child of children) { chownrKid(p, child, uid, gid, then); } }); }; exports.chownr = chownr; const chownrKidSync = (p, child, uid, gid) => { if (child.isDirectory()) (0, exports.chownrSync)(node_path_1.default.resolve(p, child.name), uid, gid); lchownSync(node_path_1.default.resolve(p, child.name), uid, gid); }; const chownrSync = (p, uid, gid) => { let children; try { children = node_fs_1.default.readdirSync(p, { withFileTypes: true }); } catch (er) { const e = er; if (e?.code === 'ENOENT') return; else if (e?.code === 'ENOTDIR' || e?.code === 'ENOTSUP') return lchownSync(p, uid, gid); else throw e; } for (const child of children) { chownrKidSync(p, child, uid, gid); } return lchownSync(p, uid, gid); }; exports.chownrSync = chownrSync; //# sourceMappingURL=index.js.map{ "type": "commonjs" } import fs from 'node:fs'; import path from 'node:path'; const lchownSync = (path, uid, gid) => { try { return fs.lchownSync(path, uid, gid); } catch (er) { if (er?.code !== 'ENOENT') throw er; } }; const chown = (cpath, uid, gid, cb) => { fs.lchown(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er?.code !== 'ENOENT' ? er : null); }); }; const chownrKid = (p, child, uid, gid, cb) => { if (child.isDirectory()) { chownr(path.resolve(p, child.name), uid, gid, (er) => { if (er) return cb(er); const cpath = path.resolve(p, child.name); chown(cpath, uid, gid, cb); }); } else { const cpath = path.resolve(p, child.name); chown(cpath, uid, gid, cb); } }; export const chownr = (p, uid, gid, cb) => { fs.readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb(); else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er); } if (er || !children.length) return chown(p, uid, gid, cb); let len = children.length; let errState = null; const then = (er) => { /* c8 ignore start */ if (errState) return; /* c8 ignore stop */ if (er) return cb((errState = er)); if (--len === 0) return chown(p, uid, gid, cb); }; for (const child of children) { chownrKid(p, child, uid, gid, then); } }); }; const chownrKidSync = (p, child, uid, gid) => { if (child.isDirectory()) chownrSync(path.resolve(p, child.name), uid, gid); lchownSync(path.resolve(p, child.name), uid, gid); }; export const chownrSync = (p, uid, gid) => { let children; try { children = fs.readdirSync(p, { withFileTypes: true }); } catch (er) { const e = er; if (e?.code === 'ENOENT') return; else if (e?.code === 'ENOTDIR' || e?.code === 'ENOTSUP') return lchownSync(p, uid, gid); else throw e; } for (const child of children) { chownrKidSync(p, child, uid, gid); } return lchownSync(p, uid, gid); }; //# sourceMappingURL=index.js.map{ "type": "module" } { "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "name": "chownr", "description": "like `chown -R`", "version": "3.0.0", "repository": { "type": "git", "url": "git://github.com/isaacs/chownr.git" }, "files": [ "dist" ], "devDependencies": { "@types/node": "^20.12.5", "mkdirp": "^3.0.1", "prettier": "^3.2.5", "rimraf": "^5.0.5", "tap": "^18.7.2", "tshy": "^1.13.1", "typedoc": "^0.25.12" }, "scripts": { "prepare": "tshy", "pretest": "npm run prepare", "test": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "format": "prettier --write . --loglevel warn", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "license": "BlueOak-1.0.0", "engines": { "node": ">=18" }, "tshy": { "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", "type": "module", "prettier": { "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" } } Minizlib was created by Isaac Z. Schlueter. It is a derivative work of the Node.js project. """ Copyright (c) 2017-2023 Isaac Z. Schlueter and Contributors Copyright (c) 2017-2023 Node.js contributors. All rights reserved. Copyright (c) 2017-2023 Joyent, Inc. and other Node contributors. All rights reserved. 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. """ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.constants = void 0; // Update with any zlib constants that are added or changed in the future. // Node v6 didn't export this, so we just hard code the version and rely // on all the other hard-coded values from zlib v4736. When node v6 // support drops, we can just export the realZlibConstants object. const zlib_1 = __importDefault(require("zlib")); /* c8 ignore start */ const realZlibConstants = zlib_1.default.constants || { ZLIB_VERNUM: 4736 }; /* c8 ignore stop */ exports.constants = Object.freeze(Object.assign(Object.create(null), { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8, BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity, Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1, BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1, BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3, BROTLI_MODE_GENERIC: 0, BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0, BROTLI_MIN_QUALITY: 0, BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11, BROTLI_MIN_WINDOW_BITS: 10, BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30, BROTLI_DEFAULT_WINDOW: 22, BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24, BROTLI_PARAM_MODE: 0, BROTLI_PARAM_QUALITY: 1, BROTLI_PARAM_LGWIN: 2, BROTLI_PARAM_LGBLOCK: 3, BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6, BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8, BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1, BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1, BROTLI_DECODER_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, BROTLI_DECODER_ERROR_UNREACHABLE: -31, }, realZlibConstants)); //# sourceMappingURL=constants.js.map"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BrotliDecompress = exports.BrotliCompress = exports.Brotli = exports.Unzip = exports.InflateRaw = exports.DeflateRaw = exports.Gunzip = exports.Gzip = exports.Inflate = exports.Deflate = exports.Zlib = exports.ZlibError = exports.constants = void 0; const assert_1 = __importDefault(require("assert")); const buffer_1 = require("buffer"); const minipass_1 = require("minipass"); const zlib_1 = __importDefault(require("zlib")); const constants_js_1 = require("./constants.js"); var constants_js_2 = require("./constants.js"); Object.defineProperty(exports, "constants", { enumerable: true, get: function () { return constants_js_2.constants; } }); const OriginalBufferConcat = buffer_1.Buffer.concat; const _superWrite = Symbol('_superWrite'); class ZlibError extends Error { code; errno; constructor(err) { super('zlib: ' + err.message); this.code = err.code; this.errno = err.errno; /* c8 ignore next */ if (!this.code) this.code = 'ZLIB_ERROR'; this.message = 'zlib: ' + err.message; Error.captureStackTrace(this, this.constructor); } get name() { return 'ZlibError'; } } exports.ZlibError = ZlibError; // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. const _flushFlag = Symbol('flushFlag'); class ZlibBase extends minipass_1.Minipass { #sawError = false; #ended = false; #flushFlag; #finishFlushFlag; #fullFlushFlag; #handle; #onError; get sawError() { return this.#sawError; } get handle() { return this.#handle; } /* c8 ignore start */ get flushFlag() { return this.#flushFlag; } /* c8 ignore stop */ constructor(opts, mode) { if (!opts || typeof opts !== 'object') throw new TypeError('invalid options for ZlibBase constructor'); //@ts-ignore super(opts); /* c8 ignore start */ this.#flushFlag = opts.flush ?? 0; this.#finishFlushFlag = opts.finishFlush ?? 0; this.#fullFlushFlag = opts.fullFlushFlag ?? 0; /* c8 ignore stop */ // this will throw if any options are invalid for the class selected try { // @types/node doesn't know that it exports the classes, but they're there //@ts-ignore this.#handle = new zlib_1.default[mode](opts); } catch (er) { // make sure that all errors get decorated properly throw new ZlibError(er); } this.#onError = err => { // no sense raising multiple errors, since we abort on the first one. if (this.#sawError) return; this.#sawError = true; // there is no way to cleanly recover. // continuing only obscures problems. this.close(); this.emit('error', err); }; this.#handle?.on('error', er => this.#onError(new ZlibError(er))); this.once('end', () => this.close); } close() { if (this.#handle) { this.#handle.close(); this.#handle = undefined; this.emit('close'); } } reset() { if (!this.#sawError) { (0, assert_1.default)(this.#handle, 'zlib binding closed'); //@ts-ignore return this.#handle.reset?.(); } } flush(flushFlag) { if (this.ended) return; if (typeof flushFlag !== 'number') flushFlag = this.#fullFlushFlag; this.write(Object.assign(buffer_1.Buffer.alloc(0), { [_flushFlag]: flushFlag })); } end(chunk, encoding, cb) { /* c8 ignore start */ if (typeof chunk === 'function') { cb = chunk; encoding = undefined; chunk = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } /* c8 ignore stop */ if (chunk) { if (encoding) this.write(chunk, encoding); else this.write(chunk); } this.flush(this.#finishFlushFlag); this.#ended = true; return super.end(cb); } get ended() { return this.#ended; } // overridden in the gzip classes to do portable writes [_superWrite](data) { return super.write(data); } write(chunk, encoding, cb) { // process the chunk using the sync process // then super.write() all the outputted chunks if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8'); if (typeof chunk === 'string') chunk = buffer_1.Buffer.from(chunk, encoding); if (this.#sawError) return; (0, assert_1.default)(this.#handle, 'zlib binding closed'); // _processChunk tries to .close() the native handle after it's done, so we // intercept that by temporarily making it a no-op. // diving into the node:zlib internals a bit here const nativeHandle = this.#handle ._handle; const originalNativeClose = nativeHandle.close; nativeHandle.close = () => { }; const originalClose = this.#handle.close; this.#handle.close = () => { }; // It also calls `Buffer.concat()` at the end, which may be convenient // for some, but which we are not interested in as it slows us down. buffer_1.Buffer.concat = args => args; let result = undefined; try { const flushFlag = typeof chunk[_flushFlag] === 'number' ? chunk[_flushFlag] : this.#flushFlag; result = this.#handle._processChunk(chunk, flushFlag); // if we don't throw, reset it back how it was buffer_1.Buffer.concat = OriginalBufferConcat; } catch (err) { // or if we do, put Buffer.concat() back before we emit error // Error events call into user code, which may call Buffer.concat() buffer_1.Buffer.concat = OriginalBufferConcat; this.#onError(new ZlibError(err)); } finally { if (this.#handle) { // Core zlib resets `_handle` to null after attempting to close the // native handle. Our no-op handler prevented actual closure, but we // need to restore the `._handle` property. ; this.#handle._handle = nativeHandle; nativeHandle.close = originalNativeClose; this.#handle.close = originalClose; // `_processChunk()` adds an 'error' listener. If we don't remove it // after each call, these handlers start piling up. this.#handle.removeAllListeners('error'); // make sure OUR error listener is still attached tho } } if (this.#handle) this.#handle.on('error', er => this.#onError(new ZlibError(er))); let writeReturn; if (result) { if (Array.isArray(result) && result.length > 0) { const r = result[0]; // The first buffer is always `handle._outBuffer`, which would be // re-used for later invocations; so, we always have to copy that one. writeReturn = this[_superWrite](buffer_1.Buffer.from(r)); for (let i = 1; i < result.length; i++) { writeReturn = this[_superWrite](result[i]); } } else { // either a single Buffer or an empty array writeReturn = this[_superWrite](buffer_1.Buffer.from(result)); } } if (cb) cb(); return writeReturn; } } class Zlib extends ZlibBase { #level; #strategy; constructor(opts, mode) { opts = opts || {}; opts.flush = opts.flush || constants_js_1.constants.Z_NO_FLUSH; opts.finishFlush = opts.finishFlush || constants_js_1.constants.Z_FINISH; opts.fullFlushFlag = constants_js_1.constants.Z_FULL_FLUSH; super(opts, mode); this.#level = opts.level; this.#strategy = opts.strategy; } params(level, strategy) { if (this.sawError) return; if (!this.handle) throw new Error('cannot switch params when binding is closed'); // no way to test this without also not supporting params at all /* c8 ignore start */ if (!this.handle.params) throw new Error('not supported in this implementation'); /* c8 ignore stop */ if (this.#level !== level || this.#strategy !== strategy) { this.flush(constants_js_1.constants.Z_SYNC_FLUSH); (0, assert_1.default)(this.handle, 'zlib binding closed'); // .params() calls .flush(), but the latter is always async in the // core zlib. We override .flush() temporarily to intercept that and // flush synchronously. const origFlush = this.handle.flush; this.handle.flush = (flushFlag, cb) => { /* c8 ignore start */ if (typeof flushFlag === 'function') { cb = flushFlag; flushFlag = this.flushFlag; } /* c8 ignore stop */ this.flush(flushFlag); cb?.(); }; try { ; this.handle.params(level, strategy); } finally { this.handle.flush = origFlush; } /* c8 ignore start */ if (this.handle) { this.#level = level; this.#strategy = strategy; } /* c8 ignore stop */ } } } exports.Zlib = Zlib; // minimal 2-byte header class Deflate extends Zlib { constructor(opts) { super(opts, 'Deflate'); } } exports.Deflate = Deflate; class Inflate extends Zlib { constructor(opts) { super(opts, 'Inflate'); } } exports.Inflate = Inflate; class Gzip extends Zlib { #portable; constructor(opts) { super(opts, 'Gzip'); this.#portable = opts && !!opts.portable; } [_superWrite](data) { if (!this.#portable) return super[_superWrite](data); // we'll always get the header emitted in one first chunk // overwrite the OS indicator byte with 0xFF this.#portable = false; data[9] = 255; return super[_superWrite](data); } } exports.Gzip = Gzip; class Gunzip extends Zlib { constructor(opts) { super(opts, 'Gunzip'); } } exports.Gunzip = Gunzip; // raw - no header class DeflateRaw extends Zlib { constructor(opts) { super(opts, 'DeflateRaw'); } } exports.DeflateRaw = DeflateRaw; class InflateRaw extends Zlib { constructor(opts) { super(opts, 'InflateRaw'); } } exports.InflateRaw = InflateRaw; // auto-detect header. class Unzip extends Zlib { constructor(opts) { super(opts, 'Unzip'); } } exports.Unzip = Unzip; class Brotli extends ZlibBase { constructor(opts, mode) { opts = opts || {}; opts.flush = opts.flush || constants_js_1.constants.BROTLI_OPERATION_PROCESS; opts.finishFlush = opts.finishFlush || constants_js_1.constants.BROTLI_OPERATION_FINISH; opts.fullFlushFlag = constants_js_1.constants.BROTLI_OPERATION_FLUSH; super(opts, mode); } } exports.Brotli = Brotli; class BrotliCompress extends Brotli { constructor(opts) { super(opts, 'BrotliCompress'); } } exports.BrotliCompress = BrotliCompress; class BrotliDecompress extends Brotli { constructor(opts) { super(opts, 'BrotliDecompress'); } } exports.BrotliDecompress = BrotliDecompress; //# sourceMappingURL=index.js.map{ "type": "commonjs" } // Update with any zlib constants that are added or changed in the future. // Node v6 didn't export this, so we just hard code the version and rely // on all the other hard-coded values from zlib v4736. When node v6 // support drops, we can just export the realZlibConstants object. import realZlib from 'zlib'; /* c8 ignore start */ const realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 }; /* c8 ignore stop */ export const constants = Object.freeze(Object.assign(Object.create(null), { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8, BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity, Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1, BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1, BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3, BROTLI_MODE_GENERIC: 0, BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0, BROTLI_MIN_QUALITY: 0, BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11, BROTLI_MIN_WINDOW_BITS: 10, BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30, BROTLI_DEFAULT_WINDOW: 22, BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24, BROTLI_PARAM_MODE: 0, BROTLI_PARAM_QUALITY: 1, BROTLI_PARAM_LGWIN: 2, BROTLI_PARAM_LGBLOCK: 3, BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6, BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8, BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1, BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1, BROTLI_DECODER_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, BROTLI_DECODER_ERROR_UNREACHABLE: -31, }, realZlibConstants)); //# sourceMappingURL=constants.js.mapimport assert from 'assert'; import { Buffer } from 'buffer'; import { Minipass } from 'minipass'; import realZlib from 'zlib'; import { constants } from './constants.js'; export { constants } from './constants.js'; const OriginalBufferConcat = Buffer.concat; const _superWrite = Symbol('_superWrite'); export class ZlibError extends Error { code; errno; constructor(err) { super('zlib: ' + err.message); this.code = err.code; this.errno = err.errno; /* c8 ignore next */ if (!this.code) this.code = 'ZLIB_ERROR'; this.message = 'zlib: ' + err.message; Error.captureStackTrace(this, this.constructor); } get name() { return 'ZlibError'; } } // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. const _flushFlag = Symbol('flushFlag'); class ZlibBase extends Minipass { #sawError = false; #ended = false; #flushFlag; #finishFlushFlag; #fullFlushFlag; #handle; #onError; get sawError() { return this.#sawError; } get handle() { return this.#handle; } /* c8 ignore start */ get flushFlag() { return this.#flushFlag; } /* c8 ignore stop */ constructor(opts, mode) { if (!opts || typeof opts !== 'object') throw new TypeError('invalid options for ZlibBase constructor'); //@ts-ignore super(opts); /* c8 ignore start */ this.#flushFlag = opts.flush ?? 0; this.#finishFlushFlag = opts.finishFlush ?? 0; this.#fullFlushFlag = opts.fullFlushFlag ?? 0; /* c8 ignore stop */ // this will throw if any options are invalid for the class selected try { // @types/node doesn't know that it exports the classes, but they're there //@ts-ignore this.#handle = new realZlib[mode](opts); } catch (er) { // make sure that all errors get decorated properly throw new ZlibError(er); } this.#onError = err => { // no sense raising multiple errors, since we abort on the first one. if (this.#sawError) return; this.#sawError = true; // there is no way to cleanly recover. // continuing only obscures problems. this.close(); this.emit('error', err); }; this.#handle?.on('error', er => this.#onError(new ZlibError(er))); this.once('end', () => this.close); } close() { if (this.#handle) { this.#handle.close(); this.#handle = undefined; this.emit('close'); } } reset() { if (!this.#sawError) { assert(this.#handle, 'zlib binding closed'); //@ts-ignore return this.#handle.reset?.(); } } flush(flushFlag) { if (this.ended) return; if (typeof flushFlag !== 'number') flushFlag = this.#fullFlushFlag; this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })); } end(chunk, encoding, cb) { /* c8 ignore start */ if (typeof chunk === 'function') { cb = chunk; encoding = undefined; chunk = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } /* c8 ignore stop */ if (chunk) { if (encoding) this.write(chunk, encoding); else this.write(chunk); } this.flush(this.#finishFlushFlag); this.#ended = true; return super.end(cb); } get ended() { return this.#ended; } // overridden in the gzip classes to do portable writes [_superWrite](data) { return super.write(data); } write(chunk, encoding, cb) { // process the chunk using the sync process // then super.write() all the outputted chunks if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8'); if (typeof chunk === 'string') chunk = Buffer.from(chunk, encoding); if (this.#sawError) return; assert(this.#handle, 'zlib binding closed'); // _processChunk tries to .close() the native handle after it's done, so we // intercept that by temporarily making it a no-op. // diving into the node:zlib internals a bit here const nativeHandle = this.#handle ._handle; const originalNativeClose = nativeHandle.close; nativeHandle.close = () => { }; const originalClose = this.#handle.close; this.#handle.close = () => { }; // It also calls `Buffer.concat()` at the end, which may be convenient // for some, but which we are not interested in as it slows us down. Buffer.concat = args => args; let result = undefined; try { const flushFlag = typeof chunk[_flushFlag] === 'number' ? chunk[_flushFlag] : this.#flushFlag; result = this.#handle._processChunk(chunk, flushFlag); // if we don't throw, reset it back how it was Buffer.concat = OriginalBufferConcat; } catch (err) { // or if we do, put Buffer.concat() back before we emit error // Error events call into user code, which may call Buffer.concat() Buffer.concat = OriginalBufferConcat; this.#onError(new ZlibError(err)); } finally { if (this.#handle) { // Core zlib resets `_handle` to null after attempting to close the // native handle. Our no-op handler prevented actual closure, but we // need to restore the `._handle` property. ; this.#handle._handle = nativeHandle; nativeHandle.close = originalNativeClose; this.#handle.close = originalClose; // `_processChunk()` adds an 'error' listener. If we don't remove it // after each call, these handlers start piling up. this.#handle.removeAllListeners('error'); // make sure OUR error listener is still attached tho } } if (this.#handle) this.#handle.on('error', er => this.#onError(new ZlibError(er))); let writeReturn; if (result) { if (Array.isArray(result) && result.length > 0) { const r = result[0]; // The first buffer is always `handle._outBuffer`, which would be // re-used for later invocations; so, we always have to copy that one. writeReturn = this[_superWrite](Buffer.from(r)); for (let i = 1; i < result.length; i++) { writeReturn = this[_superWrite](result[i]); } } else { // either a single Buffer or an empty array writeReturn = this[_superWrite](Buffer.from(result)); } } if (cb) cb(); return writeReturn; } } export class Zlib extends ZlibBase { #level; #strategy; constructor(opts, mode) { opts = opts || {}; opts.flush = opts.flush || constants.Z_NO_FLUSH; opts.finishFlush = opts.finishFlush || constants.Z_FINISH; opts.fullFlushFlag = constants.Z_FULL_FLUSH; super(opts, mode); this.#level = opts.level; this.#strategy = opts.strategy; } params(level, strategy) { if (this.sawError) return; if (!this.handle) throw new Error('cannot switch params when binding is closed'); // no way to test this without also not supporting params at all /* c8 ignore start */ if (!this.handle.params) throw new Error('not supported in this implementation'); /* c8 ignore stop */ if (this.#level !== level || this.#strategy !== strategy) { this.flush(constants.Z_SYNC_FLUSH); assert(this.handle, 'zlib binding closed'); // .params() calls .flush(), but the latter is always async in the // core zlib. We override .flush() temporarily to intercept that and // flush synchronously. const origFlush = this.handle.flush; this.handle.flush = (flushFlag, cb) => { /* c8 ignore start */ if (typeof flushFlag === 'function') { cb = flushFlag; flushFlag = this.flushFlag; } /* c8 ignore stop */ this.flush(flushFlag); cb?.(); }; try { ; this.handle.params(level, strategy); } finally { this.handle.flush = origFlush; } /* c8 ignore start */ if (this.handle) { this.#level = level; this.#strategy = strategy; } /* c8 ignore stop */ } } } // minimal 2-byte header export class Deflate extends Zlib { constructor(opts) { super(opts, 'Deflate'); } } export class Inflate extends Zlib { constructor(opts) { super(opts, 'Inflate'); } } export class Gzip extends Zlib { #portable; constructor(opts) { super(opts, 'Gzip'); this.#portable = opts && !!opts.portable; } [_superWrite](data) { if (!this.#portable) return super[_superWrite](data); // we'll always get the header emitted in one first chunk // overwrite the OS indicator byte with 0xFF this.#portable = false; data[9] = 255; return super[_superWrite](data); } } export class Gunzip extends Zlib { constructor(opts) { super(opts, 'Gunzip'); } } // raw - no header export class DeflateRaw extends Zlib { constructor(opts) { super(opts, 'DeflateRaw'); } } export class InflateRaw extends Zlib { constructor(opts) { super(opts, 'InflateRaw'); } } // auto-detect header. export class Unzip extends Zlib { constructor(opts) { super(opts, 'Unzip'); } } export class Brotli extends ZlibBase { constructor(opts, mode) { opts = opts || {}; opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS; opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH; opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH; super(opts, mode); } } export class BrotliCompress extends Brotli { constructor(opts) { super(opts, 'BrotliCompress'); } } export class BrotliDecompress extends Brotli { constructor(opts) { super(opts, 'BrotliDecompress'); } } //# sourceMappingURL=index.js.map{ "type": "module" } { "name": "minizlib", "version": "3.0.1", "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.", "main": "./dist/commonjs/index.js", "dependencies": { "minipass": "^7.0.4", "rimraf": "^5.0.5" }, "scripts": { "prepare": "tshy", "pretest": "npm run prepare", "test": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "format": "prettier --write . --loglevel warn", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minizlib.git" }, "keywords": [ "zlib", "gzip", "gunzip", "deflate", "inflate", "compression", "zip", "unzip" ], "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "license": "MIT", "devDependencies": { "@types/node": "^20.11.29", "mkdirp": "^3.0.1", "tap": "^18.7.1", "tshy": "^1.12.0", "typedoc": "^0.25.12" }, "files": [ "dist" ], "engines": { "node": ">= 18" }, "tshy": { "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "types": "./dist/commonjs/index.d.ts", "type": "module", "prettier": { "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" } } Copyright (c) 2011-2023 James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me) This project is free software released under the MIT license: 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. { "name": "mkdirp", "description": "Recursively mkdir, like `mkdir -p`", "version": "3.0.1", "keywords": [ "mkdir", "directory", "make dir", "make", "dir", "recursive", "native" ], "bin": "./dist/cjs/src/bin.js", "main": "./dist/cjs/src/index.js", "module": "./dist/mjs/index.js", "types": "./dist/mjs/index.d.ts", "exports": { ".": { "import": { "types": "./dist/mjs/index.d.ts", "default": "./dist/mjs/index.js" }, "require": { "types": "./dist/cjs/src/index.d.ts", "default": "./dist/cjs/src/index.js" } } }, "files": [ "dist" ], "scripts": { "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "preprepare": "rm -rf dist", "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json", "postprepare": "bash fixup.sh", "pretest": "npm run prepare", "presnap": "npm run prepare", "test": "c8 tap", "snap": "c8 tap", "format": "prettier --write . --loglevel warn", "benchmark": "node benchmark/index.js", "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" }, "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "devDependencies": { "@types/brace-expansion": "^1.1.0", "@types/node": "^18.11.9", "@types/tap": "^15.0.7", "c8": "^7.12.0", "eslint-config-prettier": "^8.6.0", "prettier": "^2.8.2", "tap": "^16.3.3", "ts-node": "^10.9.1", "typedoc": "^0.23.21", "typescript": "^4.9.3" }, "tap": { "coverage": false, "node-arg": [ "--no-warnings", "--loader", "ts-node/esm" ], "ts": false }, "funding": { "url": "https://github.com/sponsors/isaacs" }, "repository": { "type": "git", "url": "https://github.com/isaacs/node-mkdirp.git" }, "license": "MIT", "engines": { "node": ">=10" } } #!/usr/bin/env node export {}; //# sourceMappingURL=bin.d.ts.map{"version":3,"file":"bin.d.ts","sourceRoot":"","sources":["../../../src/bin.ts"],"names":[],"mappings":""}#!/usr/bin/env node "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const package_json_1 = require("../package.json"); const usage = () => ` usage: mkdirp [DIR1,DIR2..] {OPTIONS} Create each supplied directory including any necessary parent directories that don't yet exist. If the directory already exists, do nothing. OPTIONS are: -m If a directory needs to be created, set the mode as an octal --mode= permission string. -v --version Print the mkdirp version number -h --help Print this helpful banner -p --print Print the first directories created for each path provided --manual Use manual implementation, even if native is available `; const dirs = []; const opts = {}; let doPrint = false; let dashdash = false; let manual = false; for (const arg of process.argv.slice(2)) { if (dashdash) dirs.push(arg); else if (arg === '--') dashdash = true; else if (arg === '--manual') manual = true; else if (/^-h/.test(arg) || /^--help/.test(arg)) { console.log(usage()); process.exit(0); } else if (arg === '-v' || arg === '--version') { console.log(package_json_1.version); process.exit(0); } else if (arg === '-p' || arg === '--print') { doPrint = true; } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) { // these don't get covered in CI, but work locally // weird because the tests below show as passing in the output. /* c8 ignore start */ const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8); if (isNaN(mode)) { console.error(`invalid mode argument: ${arg}\nMust be an octal number.`); process.exit(1); } /* c8 ignore stop */ opts.mode = mode; } else dirs.push(arg); } const index_js_1 = require("./index.js"); const impl = manual ? index_js_1.mkdirp.manual : index_js_1.mkdirp; if (dirs.length === 0) { console.error(usage()); } // these don't get covered in CI, but work locally /* c8 ignore start */ Promise.all(dirs.map(dir => impl(dir, opts))) .then(made => (doPrint ? made.forEach(m => m && console.log(m)) : null)) .catch(er => { console.error(er.message); if (er.code) console.error(' code: ' + er.code); process.exit(1); }); /* c8 ignore stop */ //# sourceMappingURL=bin.js.map{"version":3,"file":"bin.js","sourceRoot":"","sources":["../../../src/bin.ts"],"names":[],"mappings":";;;AAEA,kDAAyC;AAGzC,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC;;;;;;;;;;;;;;;;;;;;CAoBnB,CAAA;AAED,MAAM,IAAI,GAAa,EAAE,CAAA;AACzB,MAAM,IAAI,GAAkB,EAAE,CAAA;AAC9B,IAAI,OAAO,GAAY,KAAK,CAAA;AAC5B,IAAI,QAAQ,GAAG,KAAK,CAAA;AACpB,IAAI,MAAM,GAAG,KAAK,CAAA;AAClB,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IACvC,IAAI,QAAQ;QAAE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;SACvB,IAAI,GAAG,KAAK,IAAI;QAAE,QAAQ,GAAG,IAAI,CAAA;SACjC,IAAI,GAAG,KAAK,UAAU;QAAE,MAAM,GAAG,IAAI,CAAA;SACrC,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAC/C,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;QACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;KAChB;SAAM,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,WAAW,EAAE;QAC9C,OAAO,CAAC,GAAG,CAAC,sBAAO,CAAC,CAAA;QACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;KAChB;SAAM,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS,EAAE;QAC5C,OAAO,GAAG,IAAI,CAAA;KACf;SAAM,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAClD,kDAAkD;QAClD,+DAA+D;QAC/D,qBAAqB;QACrB,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;QAC1D,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE;YACf,OAAO,CAAC,KAAK,CAAC,0BAA0B,GAAG,4BAA4B,CAAC,CAAA;YACxE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;SAChB;QACD,oBAAoB;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;KACjB;;QAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;CACtB;AAED,yCAAmC;AACnC,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,iBAAM,CAAC,MAAM,CAAC,CAAC,CAAC,iBAAM,CAAA;AAC5C,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAA;CACvB;AAED,kDAAkD;AAClD,qBAAqB;AACrB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;KAC1C,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;KACvE,KAAK,CAAC,EAAE,CAAC,EAAE;IACV,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,CAAA;IACzB,IAAI,EAAE,CAAC,IAAI;QAAE,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,EAAE,CAAC,IAAI,CAAC,CAAA;IAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC,CAAC,CAAA;AACJ,oBAAoB","sourcesContent":["#!/usr/bin/env node\n\nimport { version } from '../package.json'\nimport { MkdirpOptions } from './opts-arg.js'\n\nconst usage = () => `\nusage: mkdirp [DIR1,DIR2..] {OPTIONS}\n\n Create each supplied directory including any necessary parent directories\n that don't yet exist.\n\n If the directory already exists, do nothing.\n\nOPTIONS are:\n\n -m If a directory needs to be created, set the mode as an octal\n --mode= permission string.\n\n -v --version Print the mkdirp version number\n\n -h --help Print this helpful banner\n\n -p --print Print the first directories created for each path provided\n\n --manual Use manual implementation, even if native is available\n`\n\nconst dirs: string[] = []\nconst opts: MkdirpOptions = {}\nlet doPrint: boolean = false\nlet dashdash = false\nlet manual = false\nfor (const arg of process.argv.slice(2)) {\n if (dashdash) dirs.push(arg)\n else if (arg === '--') dashdash = true\n else if (arg === '--manual') manual = true\n else if (/^-h/.test(arg) || /^--help/.test(arg)) {\n console.log(usage())\n process.exit(0)\n } else if (arg === '-v' || arg === '--version') {\n console.log(version)\n process.exit(0)\n } else if (arg === '-p' || arg === '--print') {\n doPrint = true\n } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) {\n // these don't get covered in CI, but work locally\n // weird because the tests below show as passing in the output.\n /* c8 ignore start */\n const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8)\n if (isNaN(mode)) {\n console.error(`invalid mode argument: ${arg}\\nMust be an octal number.`)\n process.exit(1)\n }\n /* c8 ignore stop */\n opts.mode = mode\n } else dirs.push(arg)\n}\n\nimport { mkdirp } from './index.js'\nconst impl = manual ? mkdirp.manual : mkdirp\nif (dirs.length === 0) {\n console.error(usage())\n}\n\n// these don't get covered in CI, but work locally\n/* c8 ignore start */\nPromise.all(dirs.map(dir => impl(dir, opts)))\n .then(made => (doPrint ? made.forEach(m => m && console.log(m)) : null))\n .catch(er => {\n console.error(er.message)\n if (er.code) console.error(' code: ' + er.code)\n process.exit(1)\n })\n/* c8 ignore stop */\n"]}import { MkdirpOptionsResolved } from './opts-arg.js'; export declare const findMade: (opts: MkdirpOptionsResolved, parent: string, path?: string) => Promise; export declare const findMadeSync: (opts: MkdirpOptionsResolved, parent: string, path?: string) => undefined | string; //# sourceMappingURL=find-made.d.ts.map{"version":3,"file":"find-made.d.ts","sourceRoot":"","sources":["../../../src/find-made.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAA;AAErD,eAAO,MAAM,QAAQ,SACb,qBAAqB,UACnB,MAAM,SACP,MAAM,KACZ,QAAQ,SAAS,GAAG,MAAM,CAe5B,CAAA;AAED,eAAO,MAAM,YAAY,SACjB,qBAAqB,UACnB,MAAM,SACP,MAAM,KACZ,SAAS,GAAG,MAad,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.findMadeSync = exports.findMade = void 0; const path_1 = require("path"); const findMade = async (opts, parent, path) => { // we never want the 'made' return value to be a root directory if (path === parent) { return; } return opts.statAsync(parent).then(st => (st.isDirectory() ? path : undefined), // will fail later // will fail later er => { const fer = er; return fer && fer.code === 'ENOENT' ? (0, exports.findMade)(opts, (0, path_1.dirname)(parent), parent) : undefined; }); }; exports.findMade = findMade; const findMadeSync = (opts, parent, path) => { if (path === parent) { return undefined; } try { return opts.statSync(parent).isDirectory() ? path : undefined; } catch (er) { const fer = er; return fer && fer.code === 'ENOENT' ? (0, exports.findMadeSync)(opts, (0, path_1.dirname)(parent), parent) : undefined; } }; exports.findMadeSync = findMadeSync; //# sourceMappingURL=find-made.js.map{"version":3,"file":"find-made.js","sourceRoot":"","sources":["../../../src/find-made.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAGvB,MAAM,QAAQ,GAAG,KAAK,EAC3B,IAA2B,EAC3B,MAAc,EACd,IAAa,EACgB,EAAE;IAC/B,+DAA+D;IAC/D,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAM;KACP;IAED,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,CAChC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,kBAAkB;IAC/D,AAD6C,kBAAkB;IAC/D,EAAE,CAAC,EAAE;QACH,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ;YACjC,CAAC,CAAC,IAAA,gBAAQ,EAAC,IAAI,EAAE,IAAA,cAAO,EAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YACzC,CAAC,CAAC,SAAS,CAAA;IACf,CAAC,CACF,CAAA;AACH,CAAC,CAAA;AAnBY,QAAA,QAAQ,YAmBpB;AAEM,MAAM,YAAY,GAAG,CAC1B,IAA2B,EAC3B,MAAc,EACd,IAAa,EACO,EAAE;IACtB,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAO,SAAS,CAAA;KACjB;IAED,IAAI;QACF,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;KAC9D;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ;YACjC,CAAC,CAAC,IAAA,oBAAY,EAAC,IAAI,EAAE,IAAA,cAAO,EAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YAC7C,CAAC,CAAC,SAAS,CAAA;KACd;AACH,CAAC,CAAA;AAjBY,QAAA,YAAY,gBAiBxB","sourcesContent":["import { dirname } from 'path'\nimport { MkdirpOptionsResolved } from './opts-arg.js'\n\nexport const findMade = async (\n opts: MkdirpOptionsResolved,\n parent: string,\n path?: string\n): Promise => {\n // we never want the 'made' return value to be a root directory\n if (path === parent) {\n return\n }\n\n return opts.statAsync(parent).then(\n st => (st.isDirectory() ? path : undefined), // will fail later\n er => {\n const fer = er as NodeJS.ErrnoException\n return fer && fer.code === 'ENOENT'\n ? findMade(opts, dirname(parent), parent)\n : undefined\n }\n )\n}\n\nexport const findMadeSync = (\n opts: MkdirpOptionsResolved,\n parent: string,\n path?: string\n): undefined | string => {\n if (path === parent) {\n return undefined\n }\n\n try {\n return opts.statSync(parent).isDirectory() ? path : undefined\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n return fer && fer.code === 'ENOENT'\n ? findMadeSync(opts, dirname(parent), parent)\n : undefined\n }\n}\n"]}import { MkdirpOptions } from './opts-arg.js'; export { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'; export { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'; export { useNative, useNativeSync } from './use-native.js'; export declare const mkdirpSync: (path: string, opts?: MkdirpOptions) => string | void; export declare const sync: (path: string, opts?: MkdirpOptions) => string | void; export declare const manual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; }; export declare const manualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; export declare const native: ((path: string, options?: MkdirpOptions | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; }; export declare const nativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; export declare const mkdirp: ((path: string, opts?: MkdirpOptions) => Promise) & { mkdirpSync: (path: string, opts?: MkdirpOptions) => string | void; mkdirpNative: ((path: string, options?: MkdirpOptions | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; }; mkdirpNativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; mkdirpManual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; }; mkdirpManualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; sync: (path: string, opts?: MkdirpOptions) => string | void; native: ((path: string, options?: MkdirpOptions | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; }; nativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; manual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; }; manualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; useNative: ((opts?: MkdirpOptions | undefined) => boolean) & { sync: (opts?: MkdirpOptions | undefined) => boolean; }; useNativeSync: (opts?: MkdirpOptions | undefined) => boolean; }; //# sourceMappingURL=index.d.ts.map{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAItD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAG1D,eAAO,MAAM,UAAU,SAAU,MAAM,SAAS,aAAa,kBAM5D,CAAA;AAED,eAAO,MAAM,IAAI,SARgB,MAAM,SAAS,aAAa,kBAQ/B,CAAA;AAC9B,eAAO,MAAM,MAAM;;CAAe,CAAA;AAClC,eAAO,MAAM,UAAU,oHAAmB,CAAA;AAC1C,eAAO,MAAM,MAAM;;CAAe,CAAA;AAClC,eAAO,MAAM,UAAU,kFAAmB,CAAA;AAC1C,eAAO,MAAM,MAAM,UACJ,MAAM,SAAS,aAAa;uBAdV,MAAM,SAAS,aAAa;;;;;;;;;iBAA5B,MAAM,SAAS,aAAa;;;;;;;;;;;;;CAoC5D,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mkdirp = exports.nativeSync = exports.native = exports.manualSync = exports.manual = exports.sync = exports.mkdirpSync = exports.useNativeSync = exports.useNative = exports.mkdirpNativeSync = exports.mkdirpNative = exports.mkdirpManualSync = exports.mkdirpManual = void 0; const mkdirp_manual_js_1 = require("./mkdirp-manual.js"); const mkdirp_native_js_1 = require("./mkdirp-native.js"); const opts_arg_js_1 = require("./opts-arg.js"); const path_arg_js_1 = require("./path-arg.js"); const use_native_js_1 = require("./use-native.js"); /* c8 ignore start */ var mkdirp_manual_js_2 = require("./mkdirp-manual.js"); Object.defineProperty(exports, "mkdirpManual", { enumerable: true, get: function () { return mkdirp_manual_js_2.mkdirpManual; } }); Object.defineProperty(exports, "mkdirpManualSync", { enumerable: true, get: function () { return mkdirp_manual_js_2.mkdirpManualSync; } }); var mkdirp_native_js_2 = require("./mkdirp-native.js"); Object.defineProperty(exports, "mkdirpNative", { enumerable: true, get: function () { return mkdirp_native_js_2.mkdirpNative; } }); Object.defineProperty(exports, "mkdirpNativeSync", { enumerable: true, get: function () { return mkdirp_native_js_2.mkdirpNativeSync; } }); var use_native_js_2 = require("./use-native.js"); Object.defineProperty(exports, "useNative", { enumerable: true, get: function () { return use_native_js_2.useNative; } }); Object.defineProperty(exports, "useNativeSync", { enumerable: true, get: function () { return use_native_js_2.useNativeSync; } }); /* c8 ignore stop */ const mkdirpSync = (path, opts) => { path = (0, path_arg_js_1.pathArg)(path); const resolved = (0, opts_arg_js_1.optsArg)(opts); return (0, use_native_js_1.useNativeSync)(resolved) ? (0, mkdirp_native_js_1.mkdirpNativeSync)(path, resolved) : (0, mkdirp_manual_js_1.mkdirpManualSync)(path, resolved); }; exports.mkdirpSync = mkdirpSync; exports.sync = exports.mkdirpSync; exports.manual = mkdirp_manual_js_1.mkdirpManual; exports.manualSync = mkdirp_manual_js_1.mkdirpManualSync; exports.native = mkdirp_native_js_1.mkdirpNative; exports.nativeSync = mkdirp_native_js_1.mkdirpNativeSync; exports.mkdirp = Object.assign(async (path, opts) => { path = (0, path_arg_js_1.pathArg)(path); const resolved = (0, opts_arg_js_1.optsArg)(opts); return (0, use_native_js_1.useNative)(resolved) ? (0, mkdirp_native_js_1.mkdirpNative)(path, resolved) : (0, mkdirp_manual_js_1.mkdirpManual)(path, resolved); }, { mkdirpSync: exports.mkdirpSync, mkdirpNative: mkdirp_native_js_1.mkdirpNative, mkdirpNativeSync: mkdirp_native_js_1.mkdirpNativeSync, mkdirpManual: mkdirp_manual_js_1.mkdirpManual, mkdirpManualSync: mkdirp_manual_js_1.mkdirpManualSync, sync: exports.mkdirpSync, native: mkdirp_native_js_1.mkdirpNative, nativeSync: mkdirp_native_js_1.mkdirpNativeSync, manual: mkdirp_manual_js_1.mkdirpManual, manualSync: mkdirp_manual_js_1.mkdirpManualSync, useNative: use_native_js_1.useNative, useNativeSync: use_native_js_1.useNativeSync, }); //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":";;;AAAA,yDAAmE;AACnE,yDAAmE;AACnE,+CAAsD;AACtD,+CAAuC;AACvC,mDAA0D;AAC1D,qBAAqB;AACrB,uDAAmE;AAA1D,gHAAA,YAAY,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AACvC,uDAAmE;AAA1D,gHAAA,YAAY,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AACvC,iDAA0D;AAAjD,0GAAA,SAAS,OAAA;AAAE,8GAAA,aAAa,OAAA;AACjC,oBAAoB;AAEb,MAAM,UAAU,GAAG,CAAC,IAAY,EAAE,IAAoB,EAAE,EAAE;IAC/D,IAAI,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAA;IACpB,MAAM,QAAQ,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAA;IAC9B,OAAO,IAAA,6BAAa,EAAC,QAAQ,CAAC;QAC5B,CAAC,CAAC,IAAA,mCAAgB,EAAC,IAAI,EAAE,QAAQ,CAAC;QAClC,CAAC,CAAC,IAAA,mCAAgB,EAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AACtC,CAAC,CAAA;AANY,QAAA,UAAU,cAMtB;AAEY,QAAA,IAAI,GAAG,kBAAU,CAAA;AACjB,QAAA,MAAM,GAAG,+BAAY,CAAA;AACrB,QAAA,UAAU,GAAG,mCAAgB,CAAA;AAC7B,QAAA,MAAM,GAAG,+BAAY,CAAA;AACrB,QAAA,UAAU,GAAG,mCAAgB,CAAA;AAC7B,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CACjC,KAAK,EAAE,IAAY,EAAE,IAAoB,EAAE,EAAE;IAC3C,IAAI,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAA;IACpB,MAAM,QAAQ,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAA;IAC9B,OAAO,IAAA,yBAAS,EAAC,QAAQ,CAAC;QACxB,CAAC,CAAC,IAAA,+BAAY,EAAC,IAAI,EAAE,QAAQ,CAAC;QAC9B,CAAC,CAAC,IAAA,+BAAY,EAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AAClC,CAAC,EACD;IACE,UAAU,EAAV,kBAAU;IACV,YAAY,EAAZ,+BAAY;IACZ,gBAAgB,EAAhB,mCAAgB;IAChB,YAAY,EAAZ,+BAAY;IACZ,gBAAgB,EAAhB,mCAAgB;IAEhB,IAAI,EAAE,kBAAU;IAChB,MAAM,EAAE,+BAAY;IACpB,UAAU,EAAE,mCAAgB;IAC5B,MAAM,EAAE,+BAAY;IACpB,UAAU,EAAE,mCAAgB;IAC5B,SAAS,EAAT,yBAAS;IACT,aAAa,EAAb,6BAAa;CACd,CACF,CAAA","sourcesContent":["import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nimport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\nimport { pathArg } from './path-arg.js'\nimport { useNative, useNativeSync } from './use-native.js'\n/* c8 ignore start */\nexport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nexport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'\nexport { useNative, useNativeSync } from './use-native.js'\n/* c8 ignore stop */\n\nexport const mkdirpSync = (path: string, opts?: MkdirpOptions) => {\n path = pathArg(path)\n const resolved = optsArg(opts)\n return useNativeSync(resolved)\n ? mkdirpNativeSync(path, resolved)\n : mkdirpManualSync(path, resolved)\n}\n\nexport const sync = mkdirpSync\nexport const manual = mkdirpManual\nexport const manualSync = mkdirpManualSync\nexport const native = mkdirpNative\nexport const nativeSync = mkdirpNativeSync\nexport const mkdirp = Object.assign(\n async (path: string, opts?: MkdirpOptions) => {\n path = pathArg(path)\n const resolved = optsArg(opts)\n return useNative(resolved)\n ? mkdirpNative(path, resolved)\n : mkdirpManual(path, resolved)\n },\n {\n mkdirpSync,\n mkdirpNative,\n mkdirpNativeSync,\n mkdirpManual,\n mkdirpManualSync,\n\n sync: mkdirpSync,\n native: mkdirpNative,\n nativeSync: mkdirpNativeSync,\n manual: mkdirpManual,\n manualSync: mkdirpManualSync,\n useNative,\n useNativeSync,\n }\n)\n"]}import { MkdirpOptions } from './opts-arg.js'; export declare const mkdirpManualSync: (path: string, options?: MkdirpOptions, made?: string | undefined | void) => string | undefined | void; export declare const mkdirpManual: ((path: string, options?: MkdirpOptions, made?: string | undefined | void) => Promise) & { sync: (path: string, options?: MkdirpOptions, made?: string | undefined | void) => string | undefined | void; }; //# sourceMappingURL=mkdirp-manual.d.ts.map{"version":3,"file":"mkdirp-manual.d.ts","sourceRoot":"","sources":["../../../src/mkdirp-manual.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAEtD,eAAO,MAAM,gBAAgB,SACrB,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,MAAM,GAAG,SAAS,GAAG,IAmCvB,CAAA;AAED,eAAO,MAAM,YAAY,UAEf,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;iBA7C/B,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,MAAM,GAAG,SAAS,GAAG,IAAI;CAqF3B,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mkdirpManual = exports.mkdirpManualSync = void 0; const path_1 = require("path"); const opts_arg_js_1 = require("./opts-arg.js"); const mkdirpManualSync = (path, options, made) => { const parent = (0, path_1.dirname)(path); const opts = { ...(0, opts_arg_js_1.optsArg)(options), recursive: false }; if (parent === path) { try { return opts.mkdirSync(path, opts); } catch (er) { // swallowed by recursive implementation on posix systems // any other error is a failure const fer = er; if (fer && fer.code !== 'EISDIR') { throw er; } return; } } try { opts.mkdirSync(path, opts); return made || path; } catch (er) { const fer = er; if (fer && fer.code === 'ENOENT') { return (0, exports.mkdirpManualSync)(path, opts, (0, exports.mkdirpManualSync)(parent, opts, made)); } if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') { throw er; } try { if (!opts.statSync(path).isDirectory()) throw er; } catch (_) { throw er; } } }; exports.mkdirpManualSync = mkdirpManualSync; exports.mkdirpManual = Object.assign(async (path, options, made) => { const opts = (0, opts_arg_js_1.optsArg)(options); opts.recursive = false; const parent = (0, path_1.dirname)(path); if (parent === path) { return opts.mkdirAsync(path, opts).catch(er => { // swallowed by recursive implementation on posix systems // any other error is a failure const fer = er; if (fer && fer.code !== 'EISDIR') { throw er; } }); } return opts.mkdirAsync(path, opts).then(() => made || path, async (er) => { const fer = er; if (fer && fer.code === 'ENOENT') { return (0, exports.mkdirpManual)(parent, opts).then((made) => (0, exports.mkdirpManual)(path, opts, made)); } if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') { throw er; } return opts.statAsync(path).then(st => { if (st.isDirectory()) { return made; } else { throw er; } }, () => { throw er; }); }); }, { sync: exports.mkdirpManualSync }); //# sourceMappingURL=mkdirp-manual.js.map{"version":3,"file":"mkdirp-manual.js","sourceRoot":"","sources":["../../../src/mkdirp-manual.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAC9B,+CAAsD;AAE/C,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAuB,EACvB,IAAgC,EACL,EAAE;IAC7B,MAAM,MAAM,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,IAAI,GAAG,EAAE,GAAG,IAAA,qBAAO,EAAC,OAAO,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,CAAA;IAEtD,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,IAAI;YACF,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAClC;QAAC,OAAO,EAAE,EAAE;YACX,yDAAyD;YACzD,+BAA+B;YAC/B,MAAM,GAAG,GAAG,EAA2B,CAAA;YACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAChC,MAAM,EAAE,CAAA;aACT;YACD,OAAM;SACP;KACF;IAED,IAAI;QACF,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAO,IAAI,IAAI,IAAI,CAAA;KACpB;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,IAAA,wBAAgB,EAAC,IAAI,EAAE,IAAI,EAAE,IAAA,wBAAgB,EAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;SAC1E;QACD,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE;YAC/D,MAAM,EAAE,CAAA;SACT;QACD,IAAI;YACF,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE;gBAAE,MAAM,EAAE,CAAA;SACjD;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,EAAE,CAAA;SACT;KACF;AACH,CAAC,CAAA;AAvCY,QAAA,gBAAgB,oBAuC5B;AAEY,QAAA,YAAY,GAAG,MAAM,CAAC,MAAM,CACvC,KAAK,EACH,IAAY,EACZ,OAAuB,EACvB,IAAgC,EACI,EAAE;IACtC,MAAM,IAAI,GAAG,IAAA,qBAAO,EAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAA;IACtB,MAAM,MAAM,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE;YAC5C,yDAAyD;YACzD,+BAA+B;YAC/B,MAAM,GAAG,GAAG,EAA2B,CAAA;YACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAChC,MAAM,EAAE,CAAA;aACT;QACH,CAAC,CAAC,CAAA;KACH;IAED,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CACrC,GAAG,EAAE,CAAC,IAAI,IAAI,IAAI,EAClB,KAAK,EAAC,EAAE,EAAC,EAAE;QACT,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,IAAA,oBAAY,EAAC,MAAM,EAAE,IAAI,CAAC,CAAC,IAAI,CACpC,CAAC,IAAgC,EAAE,EAAE,CAAC,IAAA,oBAAY,EAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CACrE,CAAA;SACF;QACD,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE;YACxD,MAAM,EAAE,CAAA;SACT;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,CAC9B,EAAE,CAAC,EAAE;YACH,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE;gBACpB,OAAO,IAAI,CAAA;aACZ;iBAAM;gBACL,MAAM,EAAE,CAAA;aACT;QACH,CAAC,EACD,GAAG,EAAE;YACH,MAAM,EAAE,CAAA;QACV,CAAC,CACF,CAAA;IACH,CAAC,CACF,CAAA;AACH,CAAC,EACD,EAAE,IAAI,EAAE,wBAAgB,EAAE,CAC3B,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nexport const mkdirpManualSync = (\n path: string,\n options?: MkdirpOptions,\n made?: string | undefined | void\n): string | undefined | void => {\n const parent = dirname(path)\n const opts = { ...optsArg(options), recursive: false }\n\n if (parent === path) {\n try {\n return opts.mkdirSync(path, opts)\n } catch (er) {\n // swallowed by recursive implementation on posix systems\n // any other error is a failure\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code !== 'EISDIR') {\n throw er\n }\n return\n }\n }\n\n try {\n opts.mkdirSync(path, opts)\n return made || path\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made))\n }\n if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') {\n throw er\n }\n try {\n if (!opts.statSync(path).isDirectory()) throw er\n } catch (_) {\n throw er\n }\n }\n}\n\nexport const mkdirpManual = Object.assign(\n async (\n path: string,\n options?: MkdirpOptions,\n made?: string | undefined | void\n ): Promise => {\n const opts = optsArg(options)\n opts.recursive = false\n const parent = dirname(path)\n if (parent === path) {\n return opts.mkdirAsync(path, opts).catch(er => {\n // swallowed by recursive implementation on posix systems\n // any other error is a failure\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code !== 'EISDIR') {\n throw er\n }\n })\n }\n\n return opts.mkdirAsync(path, opts).then(\n () => made || path,\n async er => {\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManual(parent, opts).then(\n (made?: string | undefined | void) => mkdirpManual(path, opts, made)\n )\n }\n if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') {\n throw er\n }\n return opts.statAsync(path).then(\n st => {\n if (st.isDirectory()) {\n return made\n } else {\n throw er\n }\n },\n () => {\n throw er\n }\n )\n }\n )\n },\n { sync: mkdirpManualSync }\n)\n"]}import { MkdirpOptions } from './opts-arg.js'; export declare const mkdirpNativeSync: (path: string, options?: MkdirpOptions) => string | void | undefined; export declare const mkdirpNative: ((path: string, options?: MkdirpOptions) => Promise) & { sync: (path: string, options?: MkdirpOptions) => string | void | undefined; }; //# sourceMappingURL=mkdirp-native.d.ts.map{"version":3,"file":"mkdirp-native.d.ts","sourceRoot":"","sources":["../../../src/mkdirp-native.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAEtD,eAAO,MAAM,gBAAgB,SACrB,MAAM,YACF,aAAa,KACtB,MAAM,GAAG,IAAI,GAAG,SAoBlB,CAAA;AAED,eAAO,MAAM,YAAY,UAEf,MAAM,YACF,aAAa,KACtB,QAAQ,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;iBA5B/B,MAAM,YACF,aAAa,KACtB,MAAM,GAAG,IAAI,GAAG,SAAS;CAgD3B,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mkdirpNative = exports.mkdirpNativeSync = void 0; const path_1 = require("path"); const find_made_js_1 = require("./find-made.js"); const mkdirp_manual_js_1 = require("./mkdirp-manual.js"); const opts_arg_js_1 = require("./opts-arg.js"); const mkdirpNativeSync = (path, options) => { const opts = (0, opts_arg_js_1.optsArg)(options); opts.recursive = true; const parent = (0, path_1.dirname)(path); if (parent === path) { return opts.mkdirSync(path, opts); } const made = (0, find_made_js_1.findMadeSync)(opts, path); try { opts.mkdirSync(path, opts); return made; } catch (er) { const fer = er; if (fer && fer.code === 'ENOENT') { return (0, mkdirp_manual_js_1.mkdirpManualSync)(path, opts); } else { throw er; } } }; exports.mkdirpNativeSync = mkdirpNativeSync; exports.mkdirpNative = Object.assign(async (path, options) => { const opts = { ...(0, opts_arg_js_1.optsArg)(options), recursive: true }; const parent = (0, path_1.dirname)(path); if (parent === path) { return await opts.mkdirAsync(path, opts); } return (0, find_made_js_1.findMade)(opts, path).then((made) => opts .mkdirAsync(path, opts) .then(m => made || m) .catch(er => { const fer = er; if (fer && fer.code === 'ENOENT') { return (0, mkdirp_manual_js_1.mkdirpManual)(path, opts); } else { throw er; } })); }, { sync: exports.mkdirpNativeSync }); //# sourceMappingURL=mkdirp-native.js.map{"version":3,"file":"mkdirp-native.js","sourceRoot":"","sources":["../../../src/mkdirp-native.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAC9B,iDAAuD;AACvD,yDAAmE;AACnE,+CAAsD;AAE/C,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAuB,EACI,EAAE;IAC7B,MAAM,IAAI,GAAG,IAAA,qBAAO,EAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;IACrB,MAAM,MAAM,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;KAClC;IAED,MAAM,IAAI,GAAG,IAAA,2BAAY,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACrC,IAAI;QACF,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAO,IAAI,CAAA;KACZ;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,IAAA,mCAAgB,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SACpC;aAAM;YACL,MAAM,EAAE,CAAA;SACT;KACF;AACH,CAAC,CAAA;AAvBY,QAAA,gBAAgB,oBAuB5B;AAEY,QAAA,YAAY,GAAG,MAAM,CAAC,MAAM,CACvC,KAAK,EACH,IAAY,EACZ,OAAuB,EACa,EAAE;IACtC,MAAM,IAAI,GAAG,EAAE,GAAG,IAAA,qBAAO,EAAC,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAA;IACrD,MAAM,MAAM,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;KACzC;IAED,OAAO,IAAA,uBAAQ,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAyB,EAAE,EAAE,CAC7D,IAAI;SACD,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;SACtB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC;SACpB,KAAK,CAAC,EAAE,CAAC,EAAE;QACV,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAChC;aAAM;YACL,MAAM,EAAE,CAAA;SACT;IACH,CAAC,CAAC,CACL,CAAA;AACH,CAAC,EACD,EAAE,IAAI,EAAE,wBAAgB,EAAE,CAC3B,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { findMade, findMadeSync } from './find-made.js'\nimport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nexport const mkdirpNativeSync = (\n path: string,\n options?: MkdirpOptions\n): string | void | undefined => {\n const opts = optsArg(options)\n opts.recursive = true\n const parent = dirname(path)\n if (parent === path) {\n return opts.mkdirSync(path, opts)\n }\n\n const made = findMadeSync(opts, path)\n try {\n opts.mkdirSync(path, opts)\n return made\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManualSync(path, opts)\n } else {\n throw er\n }\n }\n}\n\nexport const mkdirpNative = Object.assign(\n async (\n path: string,\n options?: MkdirpOptions\n ): Promise => {\n const opts = { ...optsArg(options), recursive: true }\n const parent = dirname(path)\n if (parent === path) {\n return await opts.mkdirAsync(path, opts)\n }\n\n return findMade(opts, path).then((made?: string | undefined) =>\n opts\n .mkdirAsync(path, opts)\n .then(m => made || m)\n .catch(er => {\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManual(path, opts)\n } else {\n throw er\n }\n })\n )\n },\n { sync: mkdirpNativeSync }\n)\n"]}/// /// import { MakeDirectoryOptions, Stats } from 'fs'; export interface FsProvider { stat?: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any; mkdir?: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any; statSync?: (path: string) => Stats; mkdirSync?: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }) => string | undefined; } interface Options extends FsProvider { mode?: number | string; fs?: FsProvider; mkdirAsync?: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }) => Promise; statAsync?: (path: string) => Promise; } export type MkdirpOptions = Options | number | string; export interface MkdirpOptionsResolved { mode: number; fs: FsProvider; mkdirAsync: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }) => Promise; statAsync: (path: string) => Promise; stat: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any; mkdir: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any; statSync: (path: string) => Stats; mkdirSync: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }) => string | undefined; recursive?: boolean; } export declare const optsArg: (opts?: MkdirpOptions) => MkdirpOptionsResolved; export {}; //# sourceMappingURL=opts-arg.d.ts.map{"version":3,"file":"opts-arg.d.ts","sourceRoot":"","sources":["../../../src/opts-arg.ts"],"names":[],"mappings":";;AAAA,OAAO,EACL,oBAAoB,EAIpB,KAAK,EAEN,MAAM,IAAI,CAAA;AAEX,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,EAAE,CACL,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK,GAAG,KAC/D,GAAG,CAAA;IACR,KAAK,CAAC,EAAE,CACN,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,EACpD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,KAChE,GAAG,CAAA;IACR,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IAClC,SAAS,CAAC,EAAE,CACV,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,MAAM,GAAG,SAAS,CAAA;CACxB;AAED,UAAU,OAAQ,SAAQ,UAAU;IAClC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IACtB,EAAE,CAAC,EAAE,UAAU,CAAA;IACf,UAAU,CAAC,EAAE,CACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAA;CAC7C;AAED,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAA;AAErD,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,EAAE,EAAE,UAAU,CAAA;IACd,UAAU,EAAE,CACV,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChC,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAA;IAC3C,IAAI,EAAE,CACJ,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK,GAAG,KAC/D,GAAG,CAAA;IACR,KAAK,EAAE,CACL,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,EACpD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,KAChE,GAAG,CAAA;IACR,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IACjC,SAAS,EAAE,CACT,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,MAAM,GAAG,SAAS,CAAA;IACvB,SAAS,CAAC,EAAE,OAAO,CAAA;CACpB;AAED,eAAO,MAAM,OAAO,UAAW,aAAa,KAAG,qBA2C9C,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.optsArg = void 0; const fs_1 = require("fs"); const optsArg = (opts) => { if (!opts) { opts = { mode: 0o777 }; } else if (typeof opts === 'object') { opts = { mode: 0o777, ...opts }; } else if (typeof opts === 'number') { opts = { mode: opts }; } else if (typeof opts === 'string') { opts = { mode: parseInt(opts, 8) }; } else { throw new TypeError('invalid options argument'); } const resolved = opts; const optsFs = opts.fs || {}; opts.mkdir = opts.mkdir || optsFs.mkdir || fs_1.mkdir; opts.mkdirAsync = opts.mkdirAsync ? opts.mkdirAsync : async (path, options) => { return new Promise((res, rej) => resolved.mkdir(path, options, (er, made) => er ? rej(er) : res(made))); }; opts.stat = opts.stat || optsFs.stat || fs_1.stat; opts.statAsync = opts.statAsync ? opts.statAsync : async (path) => new Promise((res, rej) => resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats)))); opts.statSync = opts.statSync || optsFs.statSync || fs_1.statSync; opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || fs_1.mkdirSync; return resolved; }; exports.optsArg = optsArg; //# sourceMappingURL=opts-arg.js.map{"version":3,"file":"opts-arg.js","sourceRoot":"","sources":["../../../src/opts-arg.ts"],"names":[],"mappings":";;;AAAA,2BAOW;AAwDJ,MAAM,OAAO,GAAG,CAAC,IAAoB,EAAyB,EAAE;IACrE,IAAI,CAAC,IAAI,EAAE;QACT,IAAI,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;KACvB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,CAAA;KAChC;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;KACtB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,CAAA;KACnC;SAAM;QACL,MAAM,IAAI,SAAS,CAAC,0BAA0B,CAAC,CAAA;KAChD;IAED,MAAM,QAAQ,GAAG,IAA6B,CAAA;IAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,EAAE,IAAI,EAAE,CAAA;IAE5B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,IAAI,UAAK,CAAA;IAEhD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU;QAC/B,CAAC,CAAC,IAAI,CAAC,UAAU;QACjB,CAAC,CAAC,KAAK,EACH,IAAY,EACZ,OAAuD,EAC1B,EAAE;YAC/B,OAAO,IAAI,OAAO,CAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAClD,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CACzC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CACzB,CACF,CAAA;QACH,CAAC,CAAA;IAEL,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,SAAI,CAAA;IAC5C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS;QAC7B,CAAC,CAAC,IAAI,CAAC,SAAS;QAChB,CAAC,CAAC,KAAK,EAAE,IAAY,EAAE,EAAE,CACrB,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CACnE,CAAA;IAEP,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,MAAM,CAAC,QAAQ,IAAI,aAAQ,CAAA;IAC5D,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC,SAAS,IAAI,cAAS,CAAA;IAEhE,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA;AA3CY,QAAA,OAAO,WA2CnB","sourcesContent":["import {\n MakeDirectoryOptions,\n mkdir,\n mkdirSync,\n stat,\n Stats,\n statSync,\n} from 'fs'\n\nexport interface FsProvider {\n stat?: (\n path: string,\n callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any\n ) => any\n mkdir?: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean },\n callback: (err: NodeJS.ErrnoException | null, made?: string) => any\n ) => any\n statSync?: (path: string) => Stats\n mkdirSync?: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean }\n ) => string | undefined\n}\n\ninterface Options extends FsProvider {\n mode?: number | string\n fs?: FsProvider\n mkdirAsync?: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean }\n ) => Promise\n statAsync?: (path: string) => Promise\n}\n\nexport type MkdirpOptions = Options | number | string\n\nexport interface MkdirpOptionsResolved {\n mode: number\n fs: FsProvider\n mkdirAsync: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean }\n ) => Promise\n statAsync: (path: string) => Promise\n stat: (\n path: string,\n callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any\n ) => any\n mkdir: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean },\n callback: (err: NodeJS.ErrnoException | null, made?: string) => any\n ) => any\n statSync: (path: string) => Stats\n mkdirSync: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean }\n ) => string | undefined\n recursive?: boolean\n}\n\nexport const optsArg = (opts?: MkdirpOptions): MkdirpOptionsResolved => {\n if (!opts) {\n opts = { mode: 0o777 }\n } else if (typeof opts === 'object') {\n opts = { mode: 0o777, ...opts }\n } else if (typeof opts === 'number') {\n opts = { mode: opts }\n } else if (typeof opts === 'string') {\n opts = { mode: parseInt(opts, 8) }\n } else {\n throw new TypeError('invalid options argument')\n }\n\n const resolved = opts as MkdirpOptionsResolved\n const optsFs = opts.fs || {}\n\n opts.mkdir = opts.mkdir || optsFs.mkdir || mkdir\n\n opts.mkdirAsync = opts.mkdirAsync\n ? opts.mkdirAsync\n : async (\n path: string,\n options: MakeDirectoryOptions & { recursive?: boolean }\n ): Promise => {\n return new Promise((res, rej) =>\n resolved.mkdir(path, options, (er, made) =>\n er ? rej(er) : res(made)\n )\n )\n }\n\n opts.stat = opts.stat || optsFs.stat || stat\n opts.statAsync = opts.statAsync\n ? opts.statAsync\n : async (path: string) =>\n new Promise((res, rej) =>\n resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats)))\n )\n\n opts.statSync = opts.statSync || optsFs.statSync || statSync\n opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || mkdirSync\n\n return resolved\n}\n"]}export declare const pathArg: (path: string) => string; //# sourceMappingURL=path-arg.d.ts.map{"version":3,"file":"path-arg.d.ts","sourceRoot":"","sources":["../../../src/path-arg.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,SAAU,MAAM,WAyBnC,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.pathArg = void 0; const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform; const path_1 = require("path"); const pathArg = (path) => { if (/\0/.test(path)) { // simulate same failure that node raises throw Object.assign(new TypeError('path must be a string without null bytes'), { path, code: 'ERR_INVALID_ARG_VALUE', }); } path = (0, path_1.resolve)(path); if (platform === 'win32') { const badWinChars = /[*|"<>?:]/; const { root } = (0, path_1.parse)(path); if (badWinChars.test(path.substring(root.length))) { throw Object.assign(new Error('Illegal characters in path.'), { path, code: 'EINVAL', }); } } return path; }; exports.pathArg = pathArg; //# sourceMappingURL=path-arg.js.map{"version":3,"file":"path-arg.js","sourceRoot":"","sources":["../../../src/path-arg.ts"],"names":[],"mappings":";;;AAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,2BAA2B,IAAI,OAAO,CAAC,QAAQ,CAAA;AAC5E,+BAAqC;AAC9B,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,EAAE;IACtC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QACnB,yCAAyC;QACzC,MAAM,MAAM,CAAC,MAAM,CACjB,IAAI,SAAS,CAAC,0CAA0C,CAAC,EACzD;YACE,IAAI;YACJ,IAAI,EAAE,uBAAuB;SAC9B,CACF,CAAA;KACF;IAED,IAAI,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IACpB,IAAI,QAAQ,KAAK,OAAO,EAAE;QACxB,MAAM,WAAW,GAAG,WAAW,CAAA;QAC/B,MAAM,EAAE,IAAI,EAAE,GAAG,IAAA,YAAK,EAAC,IAAI,CAAC,CAAA;QAC5B,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE;YACjD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,EAAE;gBAC5D,IAAI;gBACJ,IAAI,EAAE,QAAQ;aACf,CAAC,CAAA;SACH;KACF;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAzBY,QAAA,OAAO,WAyBnB","sourcesContent":["const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform\nimport { parse, resolve } from 'path'\nexport const pathArg = (path: string) => {\n if (/\\0/.test(path)) {\n // simulate same failure that node raises\n throw Object.assign(\n new TypeError('path must be a string without null bytes'),\n {\n path,\n code: 'ERR_INVALID_ARG_VALUE',\n }\n )\n }\n\n path = resolve(path)\n if (platform === 'win32') {\n const badWinChars = /[*|\"<>?:]/\n const { root } = parse(path)\n if (badWinChars.test(path.substring(root.length))) {\n throw Object.assign(new Error('Illegal characters in path.'), {\n path,\n code: 'EINVAL',\n })\n }\n }\n\n return path\n}\n"]}import { MkdirpOptions } from './opts-arg.js'; export declare const useNativeSync: (opts?: MkdirpOptions) => boolean; export declare const useNative: ((opts?: MkdirpOptions) => boolean) & { sync: (opts?: MkdirpOptions) => boolean; }; //# sourceMappingURL=use-native.d.ts.map{"version":3,"file":"use-native.d.ts","sourceRoot":"","sources":["../../../src/use-native.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAMtD,eAAO,MAAM,aAAa,UAEd,aAAa,YAA0C,CAAA;AAEnE,eAAO,MAAM,SAAS,WAGR,aAAa;kBALf,aAAa;CASxB,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useNative = exports.useNativeSync = void 0; const fs_1 = require("fs"); const opts_arg_js_1 = require("./opts-arg.js"); const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version; const versArr = version.replace(/^v/, '').split('.'); const hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12); exports.useNativeSync = !hasNative ? () => false : (opts) => (0, opts_arg_js_1.optsArg)(opts).mkdirSync === fs_1.mkdirSync; exports.useNative = Object.assign(!hasNative ? () => false : (opts) => (0, opts_arg_js_1.optsArg)(opts).mkdir === fs_1.mkdir, { sync: exports.useNativeSync, }); //# sourceMappingURL=use-native.js.map{"version":3,"file":"use-native.js","sourceRoot":"","sources":["../../../src/use-native.ts"],"names":[],"mappings":";;;AAAA,2BAAqC;AACrC,+CAAsD;AAEtD,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,IAAI,OAAO,CAAC,OAAO,CAAA;AAC9E,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AACpD,MAAM,SAAS,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;AAElE,QAAA,aAAa,GAAG,CAAC,SAAS;IACrC,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,CAAC,IAAoB,EAAE,EAAE,CAAC,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAC,SAAS,KAAK,cAAS,CAAA;AAEtD,QAAA,SAAS,GAAG,MAAM,CAAC,MAAM,CACpC,CAAC,SAAS;IACR,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,CAAC,IAAoB,EAAE,EAAE,CAAC,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAC,KAAK,KAAK,UAAK,EAC3D;IACE,IAAI,EAAE,qBAAa;CACpB,CACF,CAAA","sourcesContent":["import { mkdir, mkdirSync } from 'fs'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nconst version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version\nconst versArr = version.replace(/^v/, '').split('.')\nconst hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12)\n\nexport const useNativeSync = !hasNative\n ? () => false\n : (opts?: MkdirpOptions) => optsArg(opts).mkdirSync === mkdirSync\n\nexport const useNative = Object.assign(\n !hasNative\n ? () => false\n : (opts?: MkdirpOptions) => optsArg(opts).mkdir === mkdir,\n {\n sync: useNativeSync,\n }\n)\n"]}import { MkdirpOptionsResolved } from './opts-arg.js'; export declare const findMade: (opts: MkdirpOptionsResolved, parent: string, path?: string) => Promise; export declare const findMadeSync: (opts: MkdirpOptionsResolved, parent: string, path?: string) => undefined | string; //# sourceMappingURL=find-made.d.ts.map{"version":3,"file":"find-made.d.ts","sourceRoot":"","sources":["../../src/find-made.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAA;AAErD,eAAO,MAAM,QAAQ,SACb,qBAAqB,UACnB,MAAM,SACP,MAAM,KACZ,QAAQ,SAAS,GAAG,MAAM,CAe5B,CAAA;AAED,eAAO,MAAM,YAAY,SACjB,qBAAqB,UACnB,MAAM,SACP,MAAM,KACZ,SAAS,GAAG,MAad,CAAA"}import { dirname } from 'path'; export const findMade = async (opts, parent, path) => { // we never want the 'made' return value to be a root directory if (path === parent) { return; } return opts.statAsync(parent).then(st => (st.isDirectory() ? path : undefined), // will fail later // will fail later er => { const fer = er; return fer && fer.code === 'ENOENT' ? findMade(opts, dirname(parent), parent) : undefined; }); }; export const findMadeSync = (opts, parent, path) => { if (path === parent) { return undefined; } try { return opts.statSync(parent).isDirectory() ? path : undefined; } catch (er) { const fer = er; return fer && fer.code === 'ENOENT' ? findMadeSync(opts, dirname(parent), parent) : undefined; } }; //# sourceMappingURL=find-made.js.map{"version":3,"file":"find-made.js","sourceRoot":"","sources":["../../src/find-made.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAG9B,MAAM,CAAC,MAAM,QAAQ,GAAG,KAAK,EAC3B,IAA2B,EAC3B,MAAc,EACd,IAAa,EACgB,EAAE;IAC/B,+DAA+D;IAC/D,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAM;KACP;IAED,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,CAChC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,kBAAkB;IAC/D,AAD6C,kBAAkB;IAC/D,EAAE,CAAC,EAAE;QACH,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ;YACjC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YACzC,CAAC,CAAC,SAAS,CAAA;IACf,CAAC,CACF,CAAA;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,CAC1B,IAA2B,EAC3B,MAAc,EACd,IAAa,EACO,EAAE;IACtB,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAO,SAAS,CAAA;KACjB;IAED,IAAI;QACF,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;KAC9D;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ;YACjC,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YAC7C,CAAC,CAAC,SAAS,CAAA;KACd;AACH,CAAC,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { MkdirpOptionsResolved } from './opts-arg.js'\n\nexport const findMade = async (\n opts: MkdirpOptionsResolved,\n parent: string,\n path?: string\n): Promise => {\n // we never want the 'made' return value to be a root directory\n if (path === parent) {\n return\n }\n\n return opts.statAsync(parent).then(\n st => (st.isDirectory() ? path : undefined), // will fail later\n er => {\n const fer = er as NodeJS.ErrnoException\n return fer && fer.code === 'ENOENT'\n ? findMade(opts, dirname(parent), parent)\n : undefined\n }\n )\n}\n\nexport const findMadeSync = (\n opts: MkdirpOptionsResolved,\n parent: string,\n path?: string\n): undefined | string => {\n if (path === parent) {\n return undefined\n }\n\n try {\n return opts.statSync(parent).isDirectory() ? path : undefined\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n return fer && fer.code === 'ENOENT'\n ? findMadeSync(opts, dirname(parent), parent)\n : undefined\n }\n}\n"]}import { MkdirpOptions } from './opts-arg.js'; export { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'; export { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'; export { useNative, useNativeSync } from './use-native.js'; export declare const mkdirpSync: (path: string, opts?: MkdirpOptions) => string | void; export declare const sync: (path: string, opts?: MkdirpOptions) => string | void; export declare const manual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; }; export declare const manualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; export declare const native: ((path: string, options?: MkdirpOptions | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; }; export declare const nativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; export declare const mkdirp: ((path: string, opts?: MkdirpOptions) => Promise) & { mkdirpSync: (path: string, opts?: MkdirpOptions) => string | void; mkdirpNative: ((path: string, options?: MkdirpOptions | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; }; mkdirpNativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; mkdirpManual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; }; mkdirpManualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; sync: (path: string, opts?: MkdirpOptions) => string | void; native: ((path: string, options?: MkdirpOptions | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; }; nativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined; manual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & { sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; }; manualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined; useNative: ((opts?: MkdirpOptions | undefined) => boolean) & { sync: (opts?: MkdirpOptions | undefined) => boolean; }; useNativeSync: (opts?: MkdirpOptions | undefined) => boolean; }; //# sourceMappingURL=index.d.ts.map{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAItD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAG1D,eAAO,MAAM,UAAU,SAAU,MAAM,SAAS,aAAa,kBAM5D,CAAA;AAED,eAAO,MAAM,IAAI,SARgB,MAAM,SAAS,aAAa,kBAQ/B,CAAA;AAC9B,eAAO,MAAM,MAAM;;CAAe,CAAA;AAClC,eAAO,MAAM,UAAU,oHAAmB,CAAA;AAC1C,eAAO,MAAM,MAAM;;CAAe,CAAA;AAClC,eAAO,MAAM,UAAU,kFAAmB,CAAA;AAC1C,eAAO,MAAM,MAAM,UACJ,MAAM,SAAS,aAAa;uBAdV,MAAM,SAAS,aAAa;;;;;;;;;iBAA5B,MAAM,SAAS,aAAa;;;;;;;;;;;;;CAoC5D,CAAA"}import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'; import { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'; import { optsArg } from './opts-arg.js'; import { pathArg } from './path-arg.js'; import { useNative, useNativeSync } from './use-native.js'; /* c8 ignore start */ export { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'; export { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'; export { useNative, useNativeSync } from './use-native.js'; /* c8 ignore stop */ export const mkdirpSync = (path, opts) => { path = pathArg(path); const resolved = optsArg(opts); return useNativeSync(resolved) ? mkdirpNativeSync(path, resolved) : mkdirpManualSync(path, resolved); }; export const sync = mkdirpSync; export const manual = mkdirpManual; export const manualSync = mkdirpManualSync; export const native = mkdirpNative; export const nativeSync = mkdirpNativeSync; export const mkdirp = Object.assign(async (path, opts) => { path = pathArg(path); const resolved = optsArg(opts); return useNative(resolved) ? mkdirpNative(path, resolved) : mkdirpManual(path, resolved); }, { mkdirpSync, mkdirpNative, mkdirpNativeSync, mkdirpManual, mkdirpManualSync, sync: mkdirpSync, native: mkdirpNative, nativeSync: mkdirpNativeSync, manual: mkdirpManual, manualSync: mkdirpManualSync, useNative, useNativeSync, }); //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAiB,OAAO,EAAE,MAAM,eAAe,CAAA;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAA;AACvC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC1D,qBAAqB;AACrB,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC1D,oBAAoB;AAEpB,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,IAAY,EAAE,IAAoB,EAAE,EAAE;IAC/D,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACpB,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9B,OAAO,aAAa,CAAC,QAAQ,CAAC;QAC5B,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC;QAClC,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AACtC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,IAAI,GAAG,UAAU,CAAA;AAC9B,MAAM,CAAC,MAAM,MAAM,GAAG,YAAY,CAAA;AAClC,MAAM,CAAC,MAAM,UAAU,GAAG,gBAAgB,CAAA;AAC1C,MAAM,CAAC,MAAM,MAAM,GAAG,YAAY,CAAA;AAClC,MAAM,CAAC,MAAM,UAAU,GAAG,gBAAgB,CAAA;AAC1C,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CACjC,KAAK,EAAE,IAAY,EAAE,IAAoB,EAAE,EAAE;IAC3C,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACpB,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9B,OAAO,SAAS,CAAC,QAAQ,CAAC;QACxB,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC;QAC9B,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AAClC,CAAC,EACD;IACE,UAAU;IACV,YAAY;IACZ,gBAAgB;IAChB,YAAY;IACZ,gBAAgB;IAEhB,IAAI,EAAE,UAAU;IAChB,MAAM,EAAE,YAAY;IACpB,UAAU,EAAE,gBAAgB;IAC5B,MAAM,EAAE,YAAY;IACpB,UAAU,EAAE,gBAAgB;IAC5B,SAAS;IACT,aAAa;CACd,CACF,CAAA","sourcesContent":["import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nimport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\nimport { pathArg } from './path-arg.js'\nimport { useNative, useNativeSync } from './use-native.js'\n/* c8 ignore start */\nexport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nexport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'\nexport { useNative, useNativeSync } from './use-native.js'\n/* c8 ignore stop */\n\nexport const mkdirpSync = (path: string, opts?: MkdirpOptions) => {\n path = pathArg(path)\n const resolved = optsArg(opts)\n return useNativeSync(resolved)\n ? mkdirpNativeSync(path, resolved)\n : mkdirpManualSync(path, resolved)\n}\n\nexport const sync = mkdirpSync\nexport const manual = mkdirpManual\nexport const manualSync = mkdirpManualSync\nexport const native = mkdirpNative\nexport const nativeSync = mkdirpNativeSync\nexport const mkdirp = Object.assign(\n async (path: string, opts?: MkdirpOptions) => {\n path = pathArg(path)\n const resolved = optsArg(opts)\n return useNative(resolved)\n ? mkdirpNative(path, resolved)\n : mkdirpManual(path, resolved)\n },\n {\n mkdirpSync,\n mkdirpNative,\n mkdirpNativeSync,\n mkdirpManual,\n mkdirpManualSync,\n\n sync: mkdirpSync,\n native: mkdirpNative,\n nativeSync: mkdirpNativeSync,\n manual: mkdirpManual,\n manualSync: mkdirpManualSync,\n useNative,\n useNativeSync,\n }\n)\n"]}import { MkdirpOptions } from './opts-arg.js'; export declare const mkdirpManualSync: (path: string, options?: MkdirpOptions, made?: string | undefined | void) => string | undefined | void; export declare const mkdirpManual: ((path: string, options?: MkdirpOptions, made?: string | undefined | void) => Promise) & { sync: (path: string, options?: MkdirpOptions, made?: string | undefined | void) => string | undefined | void; }; //# sourceMappingURL=mkdirp-manual.d.ts.map{"version":3,"file":"mkdirp-manual.d.ts","sourceRoot":"","sources":["../../src/mkdirp-manual.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAEtD,eAAO,MAAM,gBAAgB,SACrB,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,MAAM,GAAG,SAAS,GAAG,IAmCvB,CAAA;AAED,eAAO,MAAM,YAAY,UAEf,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;iBA7C/B,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,MAAM,GAAG,SAAS,GAAG,IAAI;CAqF3B,CAAA"}import { dirname } from 'path'; import { optsArg } from './opts-arg.js'; export const mkdirpManualSync = (path, options, made) => { const parent = dirname(path); const opts = { ...optsArg(options), recursive: false }; if (parent === path) { try { return opts.mkdirSync(path, opts); } catch (er) { // swallowed by recursive implementation on posix systems // any other error is a failure const fer = er; if (fer && fer.code !== 'EISDIR') { throw er; } return; } } try { opts.mkdirSync(path, opts); return made || path; } catch (er) { const fer = er; if (fer && fer.code === 'ENOENT') { return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)); } if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') { throw er; } try { if (!opts.statSync(path).isDirectory()) throw er; } catch (_) { throw er; } } }; export const mkdirpManual = Object.assign(async (path, options, made) => { const opts = optsArg(options); opts.recursive = false; const parent = dirname(path); if (parent === path) { return opts.mkdirAsync(path, opts).catch(er => { // swallowed by recursive implementation on posix systems // any other error is a failure const fer = er; if (fer && fer.code !== 'EISDIR') { throw er; } }); } return opts.mkdirAsync(path, opts).then(() => made || path, async (er) => { const fer = er; if (fer && fer.code === 'ENOENT') { return mkdirpManual(parent, opts).then((made) => mkdirpManual(path, opts, made)); } if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') { throw er; } return opts.statAsync(path).then(st => { if (st.isDirectory()) { return made; } else { throw er; } }, () => { throw er; }); }); }, { sync: mkdirpManualSync }); //# sourceMappingURL=mkdirp-manual.js.map{"version":3,"file":"mkdirp-manual.js","sourceRoot":"","sources":["../../src/mkdirp-manual.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAC9B,OAAO,EAAiB,OAAO,EAAE,MAAM,eAAe,CAAA;AAEtD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAuB,EACvB,IAAgC,EACL,EAAE;IAC7B,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,CAAA;IAEtD,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,IAAI;YACF,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAClC;QAAC,OAAO,EAAE,EAAE;YACX,yDAAyD;YACzD,+BAA+B;YAC/B,MAAM,GAAG,GAAG,EAA2B,CAAA;YACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAChC,MAAM,EAAE,CAAA;aACT;YACD,OAAM;SACP;KACF;IAED,IAAI;QACF,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAO,IAAI,IAAI,IAAI,CAAA;KACpB;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,gBAAgB,CAAC,IAAI,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;SAC1E;QACD,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE;YAC/D,MAAM,EAAE,CAAA;SACT;QACD,IAAI;YACF,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE;gBAAE,MAAM,EAAE,CAAA;SACjD;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,EAAE,CAAA;SACT;KACF;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CACvC,KAAK,EACH,IAAY,EACZ,OAAuB,EACvB,IAAgC,EACI,EAAE;IACtC,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAA;IACtB,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE;YAC5C,yDAAyD;YACzD,+BAA+B;YAC/B,MAAM,GAAG,GAAG,EAA2B,CAAA;YACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAChC,MAAM,EAAE,CAAA;aACT;QACH,CAAC,CAAC,CAAA;KACH;IAED,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CACrC,GAAG,EAAE,CAAC,IAAI,IAAI,IAAI,EAClB,KAAK,EAAC,EAAE,EAAC,EAAE;QACT,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,IAAI,CACpC,CAAC,IAAgC,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CACrE,CAAA;SACF;QACD,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE;YACxD,MAAM,EAAE,CAAA;SACT;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,CAC9B,EAAE,CAAC,EAAE;YACH,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE;gBACpB,OAAO,IAAI,CAAA;aACZ;iBAAM;gBACL,MAAM,EAAE,CAAA;aACT;QACH,CAAC,EACD,GAAG,EAAE;YACH,MAAM,EAAE,CAAA;QACV,CAAC,CACF,CAAA;IACH,CAAC,CACF,CAAA;AACH,CAAC,EACD,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAC3B,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nexport const mkdirpManualSync = (\n path: string,\n options?: MkdirpOptions,\n made?: string | undefined | void\n): string | undefined | void => {\n const parent = dirname(path)\n const opts = { ...optsArg(options), recursive: false }\n\n if (parent === path) {\n try {\n return opts.mkdirSync(path, opts)\n } catch (er) {\n // swallowed by recursive implementation on posix systems\n // any other error is a failure\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code !== 'EISDIR') {\n throw er\n }\n return\n }\n }\n\n try {\n opts.mkdirSync(path, opts)\n return made || path\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made))\n }\n if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') {\n throw er\n }\n try {\n if (!opts.statSync(path).isDirectory()) throw er\n } catch (_) {\n throw er\n }\n }\n}\n\nexport const mkdirpManual = Object.assign(\n async (\n path: string,\n options?: MkdirpOptions,\n made?: string | undefined | void\n ): Promise => {\n const opts = optsArg(options)\n opts.recursive = false\n const parent = dirname(path)\n if (parent === path) {\n return opts.mkdirAsync(path, opts).catch(er => {\n // swallowed by recursive implementation on posix systems\n // any other error is a failure\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code !== 'EISDIR') {\n throw er\n }\n })\n }\n\n return opts.mkdirAsync(path, opts).then(\n () => made || path,\n async er => {\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManual(parent, opts).then(\n (made?: string | undefined | void) => mkdirpManual(path, opts, made)\n )\n }\n if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') {\n throw er\n }\n return opts.statAsync(path).then(\n st => {\n if (st.isDirectory()) {\n return made\n } else {\n throw er\n }\n },\n () => {\n throw er\n }\n )\n }\n )\n },\n { sync: mkdirpManualSync }\n)\n"]}import { MkdirpOptions } from './opts-arg.js'; export declare const mkdirpNativeSync: (path: string, options?: MkdirpOptions) => string | void | undefined; export declare const mkdirpNative: ((path: string, options?: MkdirpOptions) => Promise) & { sync: (path: string, options?: MkdirpOptions) => string | void | undefined; }; //# sourceMappingURL=mkdirp-native.d.ts.map{"version":3,"file":"mkdirp-native.d.ts","sourceRoot":"","sources":["../../src/mkdirp-native.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAEtD,eAAO,MAAM,gBAAgB,SACrB,MAAM,YACF,aAAa,KACtB,MAAM,GAAG,IAAI,GAAG,SAoBlB,CAAA;AAED,eAAO,MAAM,YAAY,UAEf,MAAM,YACF,aAAa,KACtB,QAAQ,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;iBA5B/B,MAAM,YACF,aAAa,KACtB,MAAM,GAAG,IAAI,GAAG,SAAS;CAgD3B,CAAA"}import { dirname } from 'path'; import { findMade, findMadeSync } from './find-made.js'; import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'; import { optsArg } from './opts-arg.js'; export const mkdirpNativeSync = (path, options) => { const opts = optsArg(options); opts.recursive = true; const parent = dirname(path); if (parent === path) { return opts.mkdirSync(path, opts); } const made = findMadeSync(opts, path); try { opts.mkdirSync(path, opts); return made; } catch (er) { const fer = er; if (fer && fer.code === 'ENOENT') { return mkdirpManualSync(path, opts); } else { throw er; } } }; export const mkdirpNative = Object.assign(async (path, options) => { const opts = { ...optsArg(options), recursive: true }; const parent = dirname(path); if (parent === path) { return await opts.mkdirAsync(path, opts); } return findMade(opts, path).then((made) => opts .mkdirAsync(path, opts) .then(m => made || m) .catch(er => { const fer = er; if (fer && fer.code === 'ENOENT') { return mkdirpManual(path, opts); } else { throw er; } })); }, { sync: mkdirpNativeSync }); //# sourceMappingURL=mkdirp-native.js.map{"version":3,"file":"mkdirp-native.js","sourceRoot":"","sources":["../../src/mkdirp-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAC9B,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AACvD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAiB,OAAO,EAAE,MAAM,eAAe,CAAA;AAEtD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAuB,EACI,EAAE;IAC7B,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;IACrB,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;KAClC;IAED,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACrC,IAAI;QACF,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAO,IAAI,CAAA;KACZ;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SACpC;aAAM;YACL,MAAM,EAAE,CAAA;SACT;KACF;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CACvC,KAAK,EACH,IAAY,EACZ,OAAuB,EACa,EAAE;IACtC,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAA;IACrD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;KACzC;IAED,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAyB,EAAE,EAAE,CAC7D,IAAI;SACD,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;SACtB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC;SACpB,KAAK,CAAC,EAAE,CAAC,EAAE;QACV,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAChC;aAAM;YACL,MAAM,EAAE,CAAA;SACT;IACH,CAAC,CAAC,CACL,CAAA;AACH,CAAC,EACD,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAC3B,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { findMade, findMadeSync } from './find-made.js'\nimport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nexport const mkdirpNativeSync = (\n path: string,\n options?: MkdirpOptions\n): string | void | undefined => {\n const opts = optsArg(options)\n opts.recursive = true\n const parent = dirname(path)\n if (parent === path) {\n return opts.mkdirSync(path, opts)\n }\n\n const made = findMadeSync(opts, path)\n try {\n opts.mkdirSync(path, opts)\n return made\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManualSync(path, opts)\n } else {\n throw er\n }\n }\n}\n\nexport const mkdirpNative = Object.assign(\n async (\n path: string,\n options?: MkdirpOptions\n ): Promise => {\n const opts = { ...optsArg(options), recursive: true }\n const parent = dirname(path)\n if (parent === path) {\n return await opts.mkdirAsync(path, opts)\n }\n\n return findMade(opts, path).then((made?: string | undefined) =>\n opts\n .mkdirAsync(path, opts)\n .then(m => made || m)\n .catch(er => {\n const fer = er as NodeJS.ErrnoException\n if (fer && fer.code === 'ENOENT') {\n return mkdirpManual(path, opts)\n } else {\n throw er\n }\n })\n )\n },\n { sync: mkdirpNativeSync }\n)\n"]}/// /// import { MakeDirectoryOptions, Stats } from 'fs'; export interface FsProvider { stat?: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any; mkdir?: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any; statSync?: (path: string) => Stats; mkdirSync?: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }) => string | undefined; } interface Options extends FsProvider { mode?: number | string; fs?: FsProvider; mkdirAsync?: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }) => Promise; statAsync?: (path: string) => Promise; } export type MkdirpOptions = Options | number | string; export interface MkdirpOptionsResolved { mode: number; fs: FsProvider; mkdirAsync: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }) => Promise; statAsync: (path: string) => Promise; stat: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any; mkdir: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any; statSync: (path: string) => Stats; mkdirSync: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean; }) => string | undefined; recursive?: boolean; } export declare const optsArg: (opts?: MkdirpOptions) => MkdirpOptionsResolved; export {}; //# sourceMappingURL=opts-arg.d.ts.map{"version":3,"file":"opts-arg.d.ts","sourceRoot":"","sources":["../../src/opts-arg.ts"],"names":[],"mappings":";;AAAA,OAAO,EACL,oBAAoB,EAIpB,KAAK,EAEN,MAAM,IAAI,CAAA;AAEX,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,EAAE,CACL,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK,GAAG,KAC/D,GAAG,CAAA;IACR,KAAK,CAAC,EAAE,CACN,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,EACpD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,KAChE,GAAG,CAAA;IACR,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IAClC,SAAS,CAAC,EAAE,CACV,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,MAAM,GAAG,SAAS,CAAA;CACxB;AAED,UAAU,OAAQ,SAAQ,UAAU;IAClC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IACtB,EAAE,CAAC,EAAE,UAAU,CAAA;IACf,UAAU,CAAC,EAAE,CACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAA;CAC7C;AAED,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAA;AAErD,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,EAAE,EAAE,UAAU,CAAA;IACd,UAAU,EAAE,CACV,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChC,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAA;IAC3C,IAAI,EAAE,CACJ,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK,GAAG,KAC/D,GAAG,CAAA;IACR,KAAK,EAAE,CACL,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,EACpD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,KAChE,GAAG,CAAA;IACR,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IACjC,SAAS,EAAE,CACT,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,MAAM,GAAG,SAAS,CAAA;IACvB,SAAS,CAAC,EAAE,OAAO,CAAA;CACpB;AAED,eAAO,MAAM,OAAO,UAAW,aAAa,KAAG,qBA2C9C,CAAA"}import { mkdir, mkdirSync, stat, statSync, } from 'fs'; export const optsArg = (opts) => { if (!opts) { opts = { mode: 0o777 }; } else if (typeof opts === 'object') { opts = { mode: 0o777, ...opts }; } else if (typeof opts === 'number') { opts = { mode: opts }; } else if (typeof opts === 'string') { opts = { mode: parseInt(opts, 8) }; } else { throw new TypeError('invalid options argument'); } const resolved = opts; const optsFs = opts.fs || {}; opts.mkdir = opts.mkdir || optsFs.mkdir || mkdir; opts.mkdirAsync = opts.mkdirAsync ? opts.mkdirAsync : async (path, options) => { return new Promise((res, rej) => resolved.mkdir(path, options, (er, made) => er ? rej(er) : res(made))); }; opts.stat = opts.stat || optsFs.stat || stat; opts.statAsync = opts.statAsync ? opts.statAsync : async (path) => new Promise((res, rej) => resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats)))); opts.statSync = opts.statSync || optsFs.statSync || statSync; opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || mkdirSync; return resolved; }; //# sourceMappingURL=opts-arg.js.map{"version":3,"file":"opts-arg.js","sourceRoot":"","sources":["../../src/opts-arg.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,EACL,SAAS,EACT,IAAI,EAEJ,QAAQ,GACT,MAAM,IAAI,CAAA;AAwDX,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAoB,EAAyB,EAAE;IACrE,IAAI,CAAC,IAAI,EAAE;QACT,IAAI,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;KACvB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,CAAA;KAChC;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;KACtB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,CAAA;KACnC;SAAM;QACL,MAAM,IAAI,SAAS,CAAC,0BAA0B,CAAC,CAAA;KAChD;IAED,MAAM,QAAQ,GAAG,IAA6B,CAAA;IAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,EAAE,IAAI,EAAE,CAAA;IAE5B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,IAAI,KAAK,CAAA;IAEhD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU;QAC/B,CAAC,CAAC,IAAI,CAAC,UAAU;QACjB,CAAC,CAAC,KAAK,EACH,IAAY,EACZ,OAAuD,EAC1B,EAAE;YAC/B,OAAO,IAAI,OAAO,CAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAClD,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CACzC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CACzB,CACF,CAAA;QACH,CAAC,CAAA;IAEL,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,IAAI,CAAA;IAC5C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS;QAC7B,CAAC,CAAC,IAAI,CAAC,SAAS;QAChB,CAAC,CAAC,KAAK,EAAE,IAAY,EAAE,EAAE,CACrB,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CACnE,CAAA;IAEP,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,MAAM,CAAC,QAAQ,IAAI,QAAQ,CAAA;IAC5D,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC,SAAS,IAAI,SAAS,CAAA;IAEhE,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA","sourcesContent":["import {\n MakeDirectoryOptions,\n mkdir,\n mkdirSync,\n stat,\n Stats,\n statSync,\n} from 'fs'\n\nexport interface FsProvider {\n stat?: (\n path: string,\n callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any\n ) => any\n mkdir?: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean },\n callback: (err: NodeJS.ErrnoException | null, made?: string) => any\n ) => any\n statSync?: (path: string) => Stats\n mkdirSync?: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean }\n ) => string | undefined\n}\n\ninterface Options extends FsProvider {\n mode?: number | string\n fs?: FsProvider\n mkdirAsync?: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean }\n ) => Promise\n statAsync?: (path: string) => Promise\n}\n\nexport type MkdirpOptions = Options | number | string\n\nexport interface MkdirpOptionsResolved {\n mode: number\n fs: FsProvider\n mkdirAsync: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean }\n ) => Promise\n statAsync: (path: string) => Promise\n stat: (\n path: string,\n callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any\n ) => any\n mkdir: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean },\n callback: (err: NodeJS.ErrnoException | null, made?: string) => any\n ) => any\n statSync: (path: string) => Stats\n mkdirSync: (\n path: string,\n opts: MakeDirectoryOptions & { recursive?: boolean }\n ) => string | undefined\n recursive?: boolean\n}\n\nexport const optsArg = (opts?: MkdirpOptions): MkdirpOptionsResolved => {\n if (!opts) {\n opts = { mode: 0o777 }\n } else if (typeof opts === 'object') {\n opts = { mode: 0o777, ...opts }\n } else if (typeof opts === 'number') {\n opts = { mode: opts }\n } else if (typeof opts === 'string') {\n opts = { mode: parseInt(opts, 8) }\n } else {\n throw new TypeError('invalid options argument')\n }\n\n const resolved = opts as MkdirpOptionsResolved\n const optsFs = opts.fs || {}\n\n opts.mkdir = opts.mkdir || optsFs.mkdir || mkdir\n\n opts.mkdirAsync = opts.mkdirAsync\n ? opts.mkdirAsync\n : async (\n path: string,\n options: MakeDirectoryOptions & { recursive?: boolean }\n ): Promise => {\n return new Promise((res, rej) =>\n resolved.mkdir(path, options, (er, made) =>\n er ? rej(er) : res(made)\n )\n )\n }\n\n opts.stat = opts.stat || optsFs.stat || stat\n opts.statAsync = opts.statAsync\n ? opts.statAsync\n : async (path: string) =>\n new Promise((res, rej) =>\n resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats)))\n )\n\n opts.statSync = opts.statSync || optsFs.statSync || statSync\n opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || mkdirSync\n\n return resolved\n}\n"]}{ "type": "module" } export declare const pathArg: (path: string) => string; //# sourceMappingURL=path-arg.d.ts.map{"version":3,"file":"path-arg.d.ts","sourceRoot":"","sources":["../../src/path-arg.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,SAAU,MAAM,WAyBnC,CAAA"}const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform; import { parse, resolve } from 'path'; export const pathArg = (path) => { if (/\0/.test(path)) { // simulate same failure that node raises throw Object.assign(new TypeError('path must be a string without null bytes'), { path, code: 'ERR_INVALID_ARG_VALUE', }); } path = resolve(path); if (platform === 'win32') { const badWinChars = /[*|"<>?:]/; const { root } = parse(path); if (badWinChars.test(path.substring(root.length))) { throw Object.assign(new Error('Illegal characters in path.'), { path, code: 'EINVAL', }); } } return path; }; //# sourceMappingURL=path-arg.js.map{"version":3,"file":"path-arg.js","sourceRoot":"","sources":["../../src/path-arg.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,2BAA2B,IAAI,OAAO,CAAC,QAAQ,CAAA;AAC5E,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AACrC,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,EAAE;IACtC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QACnB,yCAAyC;QACzC,MAAM,MAAM,CAAC,MAAM,CACjB,IAAI,SAAS,CAAC,0CAA0C,CAAC,EACzD;YACE,IAAI;YACJ,IAAI,EAAE,uBAAuB;SAC9B,CACF,CAAA;KACF;IAED,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACpB,IAAI,QAAQ,KAAK,OAAO,EAAE;QACxB,MAAM,WAAW,GAAG,WAAW,CAAA;QAC/B,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,CAAA;QAC5B,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE;YACjD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,EAAE;gBAC5D,IAAI;gBACJ,IAAI,EAAE,QAAQ;aACf,CAAC,CAAA;SACH;KACF;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA","sourcesContent":["const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform\nimport { parse, resolve } from 'path'\nexport const pathArg = (path: string) => {\n if (/\\0/.test(path)) {\n // simulate same failure that node raises\n throw Object.assign(\n new TypeError('path must be a string without null bytes'),\n {\n path,\n code: 'ERR_INVALID_ARG_VALUE',\n }\n )\n }\n\n path = resolve(path)\n if (platform === 'win32') {\n const badWinChars = /[*|\"<>?:]/\n const { root } = parse(path)\n if (badWinChars.test(path.substring(root.length))) {\n throw Object.assign(new Error('Illegal characters in path.'), {\n path,\n code: 'EINVAL',\n })\n }\n }\n\n return path\n}\n"]}import { MkdirpOptions } from './opts-arg.js'; export declare const useNativeSync: (opts?: MkdirpOptions) => boolean; export declare const useNative: ((opts?: MkdirpOptions) => boolean) & { sync: (opts?: MkdirpOptions) => boolean; }; //# sourceMappingURL=use-native.d.ts.map{"version":3,"file":"use-native.d.ts","sourceRoot":"","sources":["../../src/use-native.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAMtD,eAAO,MAAM,aAAa,UAEd,aAAa,YAA0C,CAAA;AAEnE,eAAO,MAAM,SAAS,WAGR,aAAa;kBALf,aAAa;CASxB,CAAA"}import { mkdir, mkdirSync } from 'fs'; import { optsArg } from './opts-arg.js'; const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version; const versArr = version.replace(/^v/, '').split('.'); const hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12); export const useNativeSync = !hasNative ? () => false : (opts) => optsArg(opts).mkdirSync === mkdirSync; export const useNative = Object.assign(!hasNative ? () => false : (opts) => optsArg(opts).mkdir === mkdir, { sync: useNativeSync, }); //# sourceMappingURL=use-native.js.map{"version":3,"file":"use-native.js","sourceRoot":"","sources":["../../src/use-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAA;AACrC,OAAO,EAAiB,OAAO,EAAE,MAAM,eAAe,CAAA;AAEtD,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,IAAI,OAAO,CAAC,OAAO,CAAA;AAC9E,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AACpD,MAAM,SAAS,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;AAE/E,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,SAAS;IACrC,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,CAAC,IAAoB,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,KAAK,SAAS,CAAA;AAEnE,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CACpC,CAAC,SAAS;IACR,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,CAAC,IAAoB,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,KAAK,KAAK,EAC3D;IACE,IAAI,EAAE,aAAa;CACpB,CACF,CAAA","sourcesContent":["import { mkdir, mkdirSync } from 'fs'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nconst version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version\nconst versArr = version.replace(/^v/, '').split('.')\nconst hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12)\n\nexport const useNativeSync = !hasNative\n ? () => false\n : (opts?: MkdirpOptions) => optsArg(opts).mkdirSync === mkdirSync\n\nexport const useNative = Object.assign(\n !hasNative\n ? () => false\n : (opts?: MkdirpOptions) => optsArg(opts).mkdir === mkdir,\n {\n sync: useNativeSync,\n }\n)\n"]}{ "name": "mkdirp", "description": "Recursively mkdir, like `mkdir -p`", "version": "3.0.1", "keywords": [ "mkdir", "directory", "make dir", "make", "dir", "recursive", "native" ], "bin": "./dist/cjs/src/bin.js", "main": "./dist/cjs/src/index.js", "module": "./dist/mjs/index.js", "types": "./dist/mjs/index.d.ts", "exports": { ".": { "import": { "types": "./dist/mjs/index.d.ts", "default": "./dist/mjs/index.js" }, "require": { "types": "./dist/cjs/src/index.d.ts", "default": "./dist/cjs/src/index.js" } } }, "files": [ "dist" ], "scripts": { "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "preprepare": "rm -rf dist", "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json", "postprepare": "bash fixup.sh", "pretest": "npm run prepare", "presnap": "npm run prepare", "test": "c8 tap", "snap": "c8 tap", "format": "prettier --write . --loglevel warn", "benchmark": "node benchmark/index.js", "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" }, "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "devDependencies": { "@types/brace-expansion": "^1.1.0", "@types/node": "^18.11.9", "@types/tap": "^15.0.7", "c8": "^7.12.0", "eslint-config-prettier": "^8.6.0", "prettier": "^2.8.2", "tap": "^16.3.3", "ts-node": "^10.9.1", "typedoc": "^0.23.21", "typescript": "^4.9.3" }, "tap": { "coverage": false, "node-arg": [ "--no-warnings", "--loader", "ts-node/esm" ], "ts": false }, "funding": { "url": "https://github.com/sponsors/isaacs" }, "repository": { "type": "git", "url": "https://github.com/isaacs/node-mkdirp.git" }, "license": "MIT", "engines": { "node": ">=10" } } # mkdirp Like `mkdir -p`, but in Node.js! Now with a modern API and no\* bugs! \* may contain some bugs # example ## pow.js ```js // hybrid module, import or require() both work import { mkdirp } from 'mkdirp' // or: const { mkdirp } = require('mkdirp') // return value is a Promise resolving to the first directory created mkdirp('/tmp/foo/bar/baz').then(made => console.log(`made directories, starting with ${made}`) ) ``` Output (where `/tmp/foo` already exists) ``` made directories, starting with /tmp/foo/bar ``` Or, if you don't have time to wait around for promises: ```js import { mkdirp } from 'mkdirp' // return value is the first directory created const made = mkdirp.sync('/tmp/foo/bar/baz') console.log(`made directories, starting with ${made}`) ``` And now /tmp/foo/bar/baz exists, huzzah! # methods ```js import { mkdirp } from 'mkdirp' ``` ## `mkdirp(dir: string, opts?: MkdirpOptions) => Promise` Create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a string or number, it will be treated as the `opts.mode`. If `opts.mode` isn't specified, it defaults to `0o777`. Promise resolves to first directory `made` that had to be created, or `undefined` if everything already exists. Promise rejects if any errors are encountered. Note that, in the case of promise rejection, some directories _may_ have been created, as recursive directory creation is not an atomic operation. You can optionally pass in an alternate `fs` implementation by passing in `opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)` and `opts.fs.stat(path, cb)`. You can also override just one or the other of `mkdir` and `stat` by passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that only overrides one of these. ## `mkdirp.sync(dir: string, opts: MkdirpOptions) => string|undefined` Synchronously create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a string or number, it will be treated as the `opts.mode`. If `opts.mode` isn't specified, it defaults to `0o777`. Returns the first directory that had to be created, or undefined if everything already exists. You can optionally pass in an alternate `fs` implementation by passing in `opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and `opts.fs.statSync(path)`. You can also override just one or the other of `mkdirSync` and `statSync` by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs` option that only overrides one of these. ## `mkdirp.manual`, `mkdirp.manualSync` Use the manual implementation (not the native one). This is the default when the native implementation is not available or the stat/mkdir implementation is overridden. ## `mkdirp.native`, `mkdirp.nativeSync` Use the native implementation (not the manual one). This is the default when the native implementation is available and stat/mkdir are not overridden. # implementation On Node.js v10.12.0 and above, use the native `fs.mkdir(p, {recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been overridden by an option. ## native implementation - If the path is a root directory, then pass it to the underlying implementation and return the result/error. (In this case, it'll either succeed or fail, but we aren't actually creating any dirs.) - Walk up the path statting each directory, to find the first path that will be created, `made`. - Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`) - If error, raise it to the caller. - Return `made`. ## manual implementation - Call underlying `fs.mkdir` implementation, with `recursive: false` - If error: - If path is a root directory, raise to the caller and do not handle it - If ENOENT, mkdirp parent dir, store result as `made` - stat(path) - If error, raise original `mkdir` error - If directory, return `made` - Else, raise original `mkdir` error - else - return `undefined` if a root dir, or `made` if set, or `path` ## windows vs unix caveat On Windows file systems, attempts to create a root directory (ie, a drive letter or root UNC path) will fail. If the root directory exists, then it will fail with `EPERM`. If the root directory does not exist, then it will fail with `ENOENT`. On posix file systems, attempts to create a root directory (in recursive mode) will succeed silently, as it is treated like just another directory that already exists. (In non-recursive mode, of course, it fails with `EEXIST`.) In order to preserve this system-specific behavior (and because it's not as if we can create the parent of a root directory anyway), attempts to create a root directory are passed directly to the `fs` implementation, and any errors encountered are not handled. ## native error caveat The native implementation (as of at least Node.js v13.4.0) does not provide appropriate errors in some cases (see [nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and [nodejs/node#28015](https://github.com/nodejs/node/issues/28015)). In order to work around this issue, the native implementation will fall back to the manual implementation if an `ENOENT` error is encountered. # choosing a recursive mkdir implementation There are a few to choose from! Use the one that suits your needs best :D ## use `fs.mkdir(path, {recursive: true}, cb)` if: - You wish to optimize performance even at the expense of other factors. - You don't need to know the first dir created. - You are ok with getting `ENOENT` as the error when some other problem is the actual cause. - You can limit your platforms to Node.js v10.12 and above. - You're ok with using callbacks instead of promises. - You don't need/want a CLI. - You don't need to override the `fs` methods in use. ## use this module (mkdirp 1.x or 2.x) if: - You need to know the first directory that was created. - You wish to use the native implementation if available, but fall back when it's not. - You prefer promise-returning APIs to callback-taking APIs. - You want more useful error messages than the native recursive mkdir provides (at least as of Node.js v13.4), and are ok with re-trying on `ENOENT` to achieve this. - You need (or at least, are ok with) a CLI. - You need to override the `fs` methods in use. ## use [`make-dir`](http://npm.im/make-dir) if: - You do not need to know the first dir created (and wish to save a few `stat` calls when using the native implementation for this reason). - You wish to use the native implementation if available, but fall back when it's not. - You prefer promise-returning APIs to callback-taking APIs. - You are ok with occasionally getting `ENOENT` errors for failures that are actually related to something other than a missing file system entry. - You don't need/want a CLI. - You need to override the `fs` methods in use. ## use mkdirp 0.x if: - You need to know the first directory that was created. - You need (or at least, are ok with) a CLI. - You need to override the `fs` methods in use. - You're ok with using callbacks instead of promises. - You are not running on Windows, where the root-level ENOENT errors can lead to infinite regress. - You think vinyl just sounds warmer and richer for some weird reason. - You are supporting truly ancient Node.js versions, before even the advent of a `Promise` language primitive. (Please don't. You deserve better.) # cli This package also ships with a `mkdirp` command. ``` $ mkdirp -h usage: mkdirp [DIR1,DIR2..] {OPTIONS} Create each supplied directory including any necessary parent directories that don't yet exist. If the directory already exists, do nothing. OPTIONS are: -m If a directory needs to be created, set the mode as an octal --mode= permission string. -v --version Print the mkdirp version number -h --help Print this helpful banner -p --print Print the first directories created for each path provided --manual Use manual implementation, even if native is available ``` # install With [npm](http://npmjs.org) do: ``` npm install mkdirp ``` to get the library locally, or ``` npm install -g mkdirp ``` to get the command everywhere, or ``` npx mkdirp ... ``` to run the command without installing it globally. # platform support This module works on node v8, but only v10 and above are officially supported, as Node v8 reached its LTS end of life 2020-01-01, which is in the past, as of this writing. # license MIT The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.create = void 0; const fs_minipass_1 = require("@isaacs/fs-minipass"); const node_path_1 = __importDefault(require("node:path")); const list_js_1 = require("./list.js"); const make_command_js_1 = require("./make-command.js"); const pack_js_1 = require("./pack.js"); const createFileSync = (opt, files) => { const p = new pack_js_1.PackSync(opt); const stream = new fs_minipass_1.WriteStreamSync(opt.file, { mode: opt.mode || 0o666, }); p.pipe(stream); addFilesSync(p, files); }; const createFile = (opt, files) => { const p = new pack_js_1.Pack(opt); const stream = new fs_minipass_1.WriteStream(opt.file, { mode: opt.mode || 0o666, }); p.pipe(stream); const promise = new Promise((res, rej) => { stream.on('error', rej); stream.on('close', res); p.on('error', rej); }); addFilesAsync(p, files); return promise; }; const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { (0, list_js_1.list)({ file: node_path_1.default.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onReadEntry: entry => p.add(entry), }); } else { p.add(file); } }); p.end(); }; const addFilesAsync = async (p, files) => { for (let i = 0; i < files.length; i++) { const file = String(files[i]); if (file.charAt(0) === '@') { await (0, list_js_1.list)({ file: node_path_1.default.resolve(String(p.cwd), file.slice(1)), noResume: true, onReadEntry: entry => { p.add(entry); }, }); } else { p.add(file); } } p.end(); }; const createSync = (opt, files) => { const p = new pack_js_1.PackSync(opt); addFilesSync(p, files); return p; }; const createAsync = (opt, files) => { const p = new pack_js_1.Pack(opt); addFilesAsync(p, files); return p; }; exports.create = (0, make_command_js_1.makeCommand)(createFileSync, createFile, createSync, createAsync, (_opt, files) => { if (!files?.length) { throw new TypeError('no paths specified to add to archive'); } }); //# sourceMappingURL=create.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CwdError = void 0; class CwdError extends Error { path; code; syscall = 'chdir'; constructor(path, code) { super(`${code}: Cannot cd into '${path}'`); this.path = path; this.code = code; } get name() { return 'CwdError'; } } exports.CwdError = CwdError; //# sourceMappingURL=cwd-error.js.map"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.extract = void 0; // tar -x const fsm = __importStar(require("@isaacs/fs-minipass")); const node_fs_1 = __importDefault(require("node:fs")); const list_js_1 = require("./list.js"); const make_command_js_1 = require("./make-command.js"); const unpack_js_1 = require("./unpack.js"); const extractFileSync = (opt) => { const u = new unpack_js_1.UnpackSync(opt); const file = opt.file; const stat = node_fs_1.default.statSync(file); // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation const readSize = opt.maxReadSize || 16 * 1024 * 1024; const stream = new fsm.ReadStreamSync(file, { readSize: readSize, size: stat.size, }); stream.pipe(u); }; const extractFile = (opt, _) => { const u = new unpack_js_1.Unpack(opt); const readSize = opt.maxReadSize || 16 * 1024 * 1024; const file = opt.file; const p = new Promise((resolve, reject) => { u.on('error', reject); u.on('close', resolve); // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation node_fs_1.default.stat(file, (er, stat) => { if (er) { reject(er); } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }); stream.on('error', reject); stream.pipe(u); } }); }); return p; }; exports.extract = (0, make_command_js_1.makeCommand)(extractFileSync, extractFile, opt => new unpack_js_1.UnpackSync(opt), opt => new unpack_js_1.Unpack(opt), (opt, files) => { if (files?.length) (0, list_js_1.filesFilter)(opt, files); }); //# sourceMappingURL=extract.js.map"use strict"; // Get the appropriate flag to use for creating files // We use fmap on Windows platforms for files less than // 512kb. This is a fairly low limit, but avoids making // things slower in some cases. Since most of what this // library is used for is extracting tarballs of many // relatively small files in npm packages and the like, // it can be a big boost on Windows platforms. var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getWriteFlag = void 0; const fs_1 = __importDefault(require("fs")); const platform = process.env.__FAKE_PLATFORM__ || process.platform; const isWindows = platform === 'win32'; /* c8 ignore start */ const { O_CREAT, O_TRUNC, O_WRONLY } = fs_1.default.constants; const UV_FS_O_FILEMAP = Number(process.env.__FAKE_FS_O_FILENAME__) || fs_1.default.constants.UV_FS_O_FILEMAP || 0; /* c8 ignore stop */ const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP; const fMapLimit = 512 * 1024; const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY; exports.getWriteFlag = !fMapEnabled ? () => 'w' : (size) => (size < fMapLimit ? fMapFlag : 'w'); //# sourceMappingURL=get-write-flag.js.map"use strict"; // parse a 512-byte header block to a data object, or vice-versa // encode returns `true` if a pax extended header is needed, because // the data could not be faithfully encoded in a simple header. // (Also, check header.needPax to see if it needs a pax header.) var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Header = void 0; const node_path_1 = require("node:path"); const large = __importStar(require("./large-numbers.js")); const types = __importStar(require("./types.js")); class Header { cksumValid = false; needPax = false; nullBlock = false; block; path; mode; uid; gid; size; cksum; #type = 'Unsupported'; linkpath; uname; gname; devmaj = 0; devmin = 0; atime; ctime; mtime; charset; comment; constructor(data, off = 0, ex, gex) { if (Buffer.isBuffer(data)) { this.decode(data, off || 0, ex, gex); } else if (data) { this.#slurp(data); } } decode(buf, off, ex, gex) { if (!off) { off = 0; } if (!buf || !(buf.length >= off + 512)) { throw new Error('need 512 bytes for header'); } this.path = decString(buf, off, 100); this.mode = decNumber(buf, off + 100, 8); this.uid = decNumber(buf, off + 108, 8); this.gid = decNumber(buf, off + 116, 8); this.size = decNumber(buf, off + 124, 12); this.mtime = decDate(buf, off + 136, 12); this.cksum = decNumber(buf, off + 148, 12); // if we have extended or global extended headers, apply them now // See https://github.com/npm/node-tar/pull/187 // Apply global before local, so it overrides if (gex) this.#slurp(gex, true); if (ex) this.#slurp(ex); // old tar versions marked dirs as a file with a trailing / const t = decString(buf, off + 156, 1); if (types.isCode(t)) { this.#type = t || '0'; } if (this.#type === '0' && this.path.slice(-1) === '/') { this.#type = '5'; } // tar implementations sometimes incorrectly put the stat(dir).size // as the size in the tarball, even though Directory entries are // not able to have any body at all. In the very rare chance that // it actually DOES have a body, we weren't going to do anything with // it anyway, and it'll just be a warning about an invalid header. if (this.#type === '5') { this.size = 0; } this.linkpath = decString(buf, off + 157, 100); if (buf.subarray(off + 257, off + 265).toString() === 'ustar\u000000') { this.uname = decString(buf, off + 265, 32); this.gname = decString(buf, off + 297, 32); /* c8 ignore start */ this.devmaj = decNumber(buf, off + 329, 8) ?? 0; this.devmin = decNumber(buf, off + 337, 8) ?? 0; /* c8 ignore stop */ if (buf[off + 475] !== 0) { // definitely a prefix, definitely >130 chars. const prefix = decString(buf, off + 345, 155); this.path = prefix + '/' + this.path; } else { const prefix = decString(buf, off + 345, 130); if (prefix) { this.path = prefix + '/' + this.path; } this.atime = decDate(buf, off + 476, 12); this.ctime = decDate(buf, off + 488, 12); } } let sum = 8 * 0x20; for (let i = off; i < off + 148; i++) { sum += buf[i]; } for (let i = off + 156; i < off + 512; i++) { sum += buf[i]; } this.cksumValid = sum === this.cksum; if (this.cksum === undefined && sum === 8 * 0x20) { this.nullBlock = true; } } #slurp(ex, gex = false) { Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. Also, any // null/undefined values are ignored. return !(v === null || v === undefined || (k === 'path' && gex) || (k === 'linkpath' && gex) || k === 'global'); }))); } encode(buf, off = 0) { if (!buf) { buf = this.block = Buffer.alloc(512); } if (this.#type === 'Unsupported') { this.#type = '0'; } if (!(buf.length >= off + 512)) { throw new Error('need 512 bytes for header'); } const prefixSize = this.ctime || this.atime ? 130 : 155; const split = splitPrefix(this.path || '', prefixSize); const path = split[0]; const prefix = split[1]; this.needPax = !!split[2]; this.needPax = encString(buf, off, 100, path) || this.needPax; this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax; this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax; this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax; this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax; this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax; buf[off + 156] = this.#type.charCodeAt(0); this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax; buf.write('ustar\u000000', off + 257, 8); this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax; this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax; this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax; this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax; this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax; if (buf[off + 475] !== 0) { this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax; } else { this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax; this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax; this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax; } let sum = 8 * 0x20; for (let i = off; i < off + 148; i++) { sum += buf[i]; } for (let i = off + 156; i < off + 512; i++) { sum += buf[i]; } this.cksum = sum; encNumber(buf, off + 148, 8, this.cksum); this.cksumValid = true; return this.needPax; } get type() { return (this.#type === 'Unsupported' ? this.#type : types.name.get(this.#type)); } get typeKey() { return this.#type; } set type(type) { const c = String(types.code.get(type)); if (types.isCode(c) || c === 'Unsupported') { this.#type = c; } else if (types.isCode(type)) { this.#type = type; } else { throw new TypeError('invalid entry type: ' + type); } } } exports.Header = Header; const splitPrefix = (p, prefixSize) => { const pathSize = 100; let pp = p; let prefix = ''; let ret = undefined; const root = node_path_1.posix.parse(p).root || '.'; if (Buffer.byteLength(pp) < pathSize) { ret = [pp, prefix, false]; } else { // first set prefix to the dir, and path to the base prefix = node_path_1.posix.dirname(pp); pp = node_path_1.posix.basename(pp); do { if (Buffer.byteLength(pp) <= pathSize && Buffer.byteLength(prefix) <= prefixSize) { // both fit! ret = [pp, prefix, false]; } else if (Buffer.byteLength(pp) > pathSize && Buffer.byteLength(prefix) <= prefixSize) { // prefix fits in prefix, but path doesn't fit in path ret = [pp.slice(0, pathSize - 1), prefix, true]; } else { // make path take a bit from prefix pp = node_path_1.posix.join(node_path_1.posix.basename(prefix), pp); prefix = node_path_1.posix.dirname(prefix); } } while (prefix !== root && ret === undefined); // at this point, found no resolution, just truncate if (!ret) { ret = [p.slice(0, pathSize - 1), '', true]; } } return ret; }; const decString = (buf, off, size) => buf .subarray(off, off + size) .toString('utf8') .replace(/\0.*/, ''); const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size)); const numToDate = (num) => num === undefined ? undefined : new Date(num * 1000); const decNumber = (buf, off, size) => Number(buf[off]) & 0x80 ? large.parse(buf.subarray(off, off + size)) : decSmallNumber(buf, off, size); const nanUndef = (value) => (isNaN(value) ? undefined : value); const decSmallNumber = (buf, off, size) => nanUndef(parseInt(buf .subarray(off, off + size) .toString('utf8') .replace(/\0.*$/, '') .trim(), 8)); // the maximum encodable as a null-terminated octal, by field size const MAXNUM = { 12: 0o77777777777, 8: 0o7777777, }; const encNumber = (buf, off, size, num) => num === undefined ? false : num > MAXNUM[size] || num < 0 ? (large.encode(num, buf.subarray(off, off + size)), true) : (encSmallNumber(buf, off, size, num), false); const encSmallNumber = (buf, off, size, num) => buf.write(octalString(num, size), off, size, 'ascii'); const octalString = (num, size) => padOctal(Math.floor(num).toString(8), size); const padOctal = (str, size) => (str.length === size - 1 ? str : new Array(size - str.length - 1).join('0') + str + ' ') + '\0'; const encDate = (buf, off, size, date) => date === undefined ? false : (encNumber(buf, off, size, date.getTime() / 1000)); // enough to fill the longest string we've got const NULLS = new Array(156).join('\0'); // pad with nulls, return true if it's longer or non-ascii const encString = (buf, off, size, str) => str === undefined ? false : ((buf.write(str + NULLS, off, size, 'utf8'), str.length !== Buffer.byteLength(str) || str.length > size)); //# sourceMappingURL=header.js.map"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.u = exports.types = exports.r = exports.t = exports.x = exports.c = void 0; __exportStar(require("./create.js"), exports); var create_js_1 = require("./create.js"); Object.defineProperty(exports, "c", { enumerable: true, get: function () { return create_js_1.create; } }); __exportStar(require("./extract.js"), exports); var extract_js_1 = require("./extract.js"); Object.defineProperty(exports, "x", { enumerable: true, get: function () { return extract_js_1.extract; } }); __exportStar(require("./header.js"), exports); __exportStar(require("./list.js"), exports); var list_js_1 = require("./list.js"); Object.defineProperty(exports, "t", { enumerable: true, get: function () { return list_js_1.list; } }); // classes __exportStar(require("./pack.js"), exports); __exportStar(require("./parse.js"), exports); __exportStar(require("./pax.js"), exports); __exportStar(require("./read-entry.js"), exports); __exportStar(require("./replace.js"), exports); var replace_js_1 = require("./replace.js"); Object.defineProperty(exports, "r", { enumerable: true, get: function () { return replace_js_1.replace; } }); exports.types = __importStar(require("./types.js")); __exportStar(require("./unpack.js"), exports); __exportStar(require("./update.js"), exports); var update_js_1 = require("./update.js"); Object.defineProperty(exports, "u", { enumerable: true, get: function () { return update_js_1.update; } }); __exportStar(require("./write-entry.js"), exports); //# sourceMappingURL=index.js.map"use strict"; // Tar can encode large and negative numbers using a leading byte of // 0xff for negative, and 0x80 for positive. Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = exports.encode = void 0; const encode = (num, buf) => { if (!Number.isSafeInteger(num)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('cannot encode number outside of javascript safe integer range'); } else if (num < 0) { encodeNegative(num, buf); } else { encodePositive(num, buf); } return buf; }; exports.encode = encode; const encodePositive = (num, buf) => { buf[0] = 0x80; for (var i = buf.length; i > 1; i--) { buf[i - 1] = num & 0xff; num = Math.floor(num / 0x100); } }; const encodeNegative = (num, buf) => { buf[0] = 0xff; var flipped = false; num = num * -1; for (var i = buf.length; i > 1; i--) { var byte = num & 0xff; num = Math.floor(num / 0x100); if (flipped) { buf[i - 1] = onesComp(byte); } else if (byte === 0) { buf[i - 1] = 0; } else { flipped = true; buf[i - 1] = twosComp(byte); } } }; const parse = (buf) => { const pre = buf[0]; const value = pre === 0x80 ? pos(buf.subarray(1, buf.length)) : pre === 0xff ? twos(buf) : null; if (value === null) { throw Error('invalid base256 encoding'); } if (!Number.isSafeInteger(value)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('parsed number outside of javascript safe integer range'); } return value; }; exports.parse = parse; const twos = (buf) => { var len = buf.length; var sum = 0; var flipped = false; for (var i = len - 1; i > -1; i--) { var byte = Number(buf[i]); var f; if (flipped) { f = onesComp(byte); } else if (byte === 0) { f = byte; } else { flipped = true; f = twosComp(byte); } if (f !== 0) { sum -= f * Math.pow(256, len - i - 1); } } return sum; }; const pos = (buf) => { var len = buf.length; var sum = 0; for (var i = len - 1; i > -1; i--) { var byte = Number(buf[i]); if (byte !== 0) { sum += byte * Math.pow(256, len - i - 1); } } return sum; }; const onesComp = (byte) => (0xff ^ byte) & 0xff; const twosComp = (byte) => ((0xff ^ byte) + 1) & 0xff; //# sourceMappingURL=large-numbers.js.map"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.list = exports.filesFilter = void 0; // tar -t const fsm = __importStar(require("@isaacs/fs-minipass")); const node_fs_1 = __importDefault(require("node:fs")); const path_1 = require("path"); const make_command_js_1 = require("./make-command.js"); const parse_js_1 = require("./parse.js"); const strip_trailing_slashes_js_1 = require("./strip-trailing-slashes.js"); const onReadEntryFunction = (opt) => { const onReadEntry = opt.onReadEntry; opt.onReadEntry = onReadEntry ? e => { onReadEntry(e); e.resume(); } : e => e.resume(); }; // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [(0, strip_trailing_slashes_js_1.stripTrailingSlashes)(f), true])); const filter = opt.filter; const mapHas = (file, r = '') => { const root = r || (0, path_1.parse)(file).root || '.'; let ret; if (file === root) ret = false; else { const m = map.get(file); if (m !== undefined) { ret = m; } else { ret = mapHas((0, path_1.dirname)(file), root); } } map.set(file, ret); return ret; }; opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas((0, strip_trailing_slashes_js_1.stripTrailingSlashes)(file)) : file => mapHas((0, strip_trailing_slashes_js_1.stripTrailingSlashes)(file)); }; exports.filesFilter = filesFilter; const listFileSync = (opt) => { const p = new parse_js_1.Parser(opt); const file = opt.file; let fd; try { const stat = node_fs_1.default.statSync(file); const readSize = opt.maxReadSize || 16 * 1024 * 1024; if (stat.size < readSize) { p.end(node_fs_1.default.readFileSync(file)); } else { let pos = 0; const buf = Buffer.allocUnsafe(readSize); fd = node_fs_1.default.openSync(file, 'r'); while (pos < stat.size) { const bytesRead = node_fs_1.default.readSync(fd, buf, 0, readSize, pos); pos += bytesRead; p.write(buf.subarray(0, bytesRead)); } p.end(); } } finally { if (typeof fd === 'number') { try { node_fs_1.default.closeSync(fd); /* c8 ignore next */ } catch (er) { } } } }; const listFile = (opt, _files) => { const parse = new parse_js_1.Parser(opt); const readSize = opt.maxReadSize || 16 * 1024 * 1024; const file = opt.file; const p = new Promise((resolve, reject) => { parse.on('error', reject); parse.on('end', resolve); node_fs_1.default.stat(file, (er, stat) => { if (er) { reject(er); } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }); stream.on('error', reject); stream.pipe(parse); } }); }); return p; }; exports.list = (0, make_command_js_1.makeCommand)(listFileSync, listFile, opt => new parse_js_1.Parser(opt), opt => new parse_js_1.Parser(opt), (opt, files) => { if (files?.length) (0, exports.filesFilter)(opt, files); if (!opt.noResume) onReadEntryFunction(opt); }); //# sourceMappingURL=list.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeCommand = void 0; const options_js_1 = require("./options.js"); const makeCommand = (syncFile, asyncFile, syncNoFile, asyncNoFile, validate) => { return Object.assign((opt_ = [], entries, cb) => { if (Array.isArray(opt_)) { entries = opt_; opt_ = {}; } if (typeof entries === 'function') { cb = entries; entries = undefined; } if (!entries) { entries = []; } else { entries = Array.from(entries); } const opt = (0, options_js_1.dealias)(opt_); validate?.(opt, entries); if ((0, options_js_1.isSyncFile)(opt)) { if (typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions'); } return syncFile(opt, entries); } else if ((0, options_js_1.isAsyncFile)(opt)) { const p = asyncFile(opt, entries); // weirdness to make TS happy const c = cb ? cb : undefined; return c ? p.then(() => c(), c) : p; } else if ((0, options_js_1.isSyncNoFile)(opt)) { if (typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions'); } return syncNoFile(opt, entries); } else if ((0, options_js_1.isAsyncNoFile)(opt)) { if (typeof cb === 'function') { throw new TypeError('callback only supported with file option'); } return asyncNoFile(opt, entries); /* c8 ignore start */ } else { throw new Error('impossible options??'); } /* c8 ignore stop */ }, { syncFile, asyncFile, syncNoFile, asyncNoFile, validate, }); }; exports.makeCommand = makeCommand; //# sourceMappingURL=make-command.js.map"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.mkdirSync = exports.mkdir = void 0; const chownr_1 = require("chownr"); const fs_1 = __importDefault(require("fs")); const mkdirp_1 = require("mkdirp"); const node_path_1 = __importDefault(require("node:path")); const cwd_error_js_1 = require("./cwd-error.js"); const normalize_windows_path_js_1 = require("./normalize-windows-path.js"); const symlink_error_js_1 = require("./symlink-error.js"); const cGet = (cache, key) => cache.get((0, normalize_windows_path_js_1.normalizeWindowsPath)(key)); const cSet = (cache, key, val) => cache.set((0, normalize_windows_path_js_1.normalizeWindowsPath)(key), val); const checkCwd = (dir, cb) => { fs_1.default.stat(dir, (er, st) => { if (er || !st.isDirectory()) { er = new cwd_error_js_1.CwdError(dir, er?.code || 'ENOTDIR'); } cb(er); }); }; /** * Wrapper around mkdirp for tar's needs. * * The main purpose is to avoid creating directories if we know that * they already exist (and track which ones exist for this purpose), * and prevent entries from being extracted into symlinked folders, * if `preservePaths` is not set. */ const mkdir = (dir, opt, cb) => { dir = (0, normalize_windows_path_js_1.normalizeWindowsPath)(dir); // if there's any overlap between mask and mode, // then we'll need an explicit chmod /* c8 ignore next */ const umask = opt.umask ?? 0o22; const mode = opt.mode | 0o0700; const needChmod = (mode & umask) !== 0; const uid = opt.uid; const gid = opt.gid; const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid); const preserve = opt.preserve; const unlink = opt.unlink; const cache = opt.cache; const cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.cwd); const done = (er, created) => { if (er) { cb(er); } else { cSet(cache, dir, true); if (created && doChown) { (0, chownr_1.chownr)(created, uid, gid, er => done(er)); } else if (needChmod) { fs_1.default.chmod(dir, mode, cb); } else { cb(); } } }; if (cache && cGet(cache, dir) === true) { return done(); } if (dir === cwd) { return checkCwd(dir, done); } if (preserve) { return (0, mkdirp_1.mkdirp)(dir, { mode }).then(made => done(null, made ?? undefined), // oh, ts done); } const sub = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.relative(cwd, dir)); const parts = sub.split('/'); mkdir_(cwd, parts, mode, cache, unlink, cwd, undefined, done); }; exports.mkdir = mkdir; const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { if (!parts.length) { return cb(null, created); } const p = parts.shift(); const part = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(base + '/' + p)); if (cGet(cache, part)) { return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); } fs_1.default.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)); }; const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => (er) => { if (er) { fs_1.default.lstat(part, (statEr, st) => { if (statEr) { statEr.path = statEr.path && (0, normalize_windows_path_js_1.normalizeWindowsPath)(statEr.path); cb(statEr); } else if (st.isDirectory()) { mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); } else if (unlink) { fs_1.default.unlink(part, er => { if (er) { return cb(er); } fs_1.default.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)); }); } else if (st.isSymbolicLink()) { return cb(new symlink_error_js_1.SymlinkError(part, part + '/' + parts.join('/'))); } else { cb(er); } }); } else { created = created || part; mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); } }; const checkCwdSync = (dir) => { let ok = false; let code = undefined; try { ok = fs_1.default.statSync(dir).isDirectory(); } catch (er) { code = er?.code; } finally { if (!ok) { throw new cwd_error_js_1.CwdError(dir, code ?? 'ENOTDIR'); } } }; const mkdirSync = (dir, opt) => { dir = (0, normalize_windows_path_js_1.normalizeWindowsPath)(dir); // if there's any overlap between mask and mode, // then we'll need an explicit chmod /* c8 ignore next */ const umask = opt.umask ?? 0o22; const mode = opt.mode | 0o700; const needChmod = (mode & umask) !== 0; const uid = opt.uid; const gid = opt.gid; const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid); const preserve = opt.preserve; const unlink = opt.unlink; const cache = opt.cache; const cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.cwd); const done = (created) => { cSet(cache, dir, true); if (created && doChown) { (0, chownr_1.chownrSync)(created, uid, gid); } if (needChmod) { fs_1.default.chmodSync(dir, mode); } }; if (cache && cGet(cache, dir) === true) { return done(); } if (dir === cwd) { checkCwdSync(cwd); return done(); } if (preserve) { return done((0, mkdirp_1.mkdirpSync)(dir, mode) ?? undefined); } const sub = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.relative(cwd, dir)); const parts = sub.split('/'); let created = undefined; for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) { part = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(part)); if (cGet(cache, part)) { continue; } try { fs_1.default.mkdirSync(part, mode); created = created || part; cSet(cache, part, true); } catch (er) { const st = fs_1.default.lstatSync(part); if (st.isDirectory()) { cSet(cache, part, true); continue; } else if (unlink) { fs_1.default.unlinkSync(part); fs_1.default.mkdirSync(part, mode); created = created || part; cSet(cache, part, true); continue; } else if (st.isSymbolicLink()) { return new symlink_error_js_1.SymlinkError(part, part + '/' + parts.join('/')); } } } return done(created); }; exports.mkdirSync = mkdirSync; //# sourceMappingURL=mkdir.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.modeFix = void 0; const modeFix = (mode, isDir, portable) => { mode &= 0o7777; // in portable mode, use the minimum reasonable umask // if this system creates files with 0o664 by default // (as some linux distros do), then we'll write the // archive with 0o644 instead. Also, don't ever create // a file that is not readable/writable by the owner. if (portable) { mode = (mode | 0o600) & ~0o22; } // if dirs are readable, then they should be listable if (isDir) { if (mode & 0o400) { mode |= 0o100; } if (mode & 0o40) { mode |= 0o10; } if (mode & 0o4) { mode |= 0o1; } } return mode; }; exports.modeFix = modeFix; //# sourceMappingURL=mode-fix.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.normalizeUnicode = void 0; // warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. const normalizeCache = Object.create(null); const { hasOwnProperty } = Object.prototype; const normalizeUnicode = (s) => { if (!hasOwnProperty.call(normalizeCache, s)) { normalizeCache[s] = s.normalize('NFD'); } return normalizeCache[s]; }; exports.normalizeUnicode = normalizeUnicode; //# sourceMappingURL=normalize-unicode.js.map"use strict"; // on windows, either \ or / are valid directory separators. // on unix, \ is a valid character in filenames. // so, on windows, and only on windows, we replace all \ chars with /, // so that we can use / as our one and only directory separator char. Object.defineProperty(exports, "__esModule", { value: true }); exports.normalizeWindowsPath = void 0; const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; exports.normalizeWindowsPath = platform !== 'win32' ? (p) => p : (p) => p && p.replace(/\\/g, '/'); //# sourceMappingURL=normalize-windows-path.js.map"use strict"; // turn tar(1) style args like `C` into the more verbose things like `cwd` Object.defineProperty(exports, "__esModule", { value: true }); exports.dealias = exports.isNoFile = exports.isFile = exports.isAsync = exports.isSync = exports.isAsyncNoFile = exports.isSyncNoFile = exports.isAsyncFile = exports.isSyncFile = void 0; const argmap = new Map([ ['C', 'cwd'], ['f', 'file'], ['z', 'gzip'], ['P', 'preservePaths'], ['U', 'unlink'], ['strip-components', 'strip'], ['stripComponents', 'strip'], ['keep-newer', 'newer'], ['keepNewer', 'newer'], ['keep-newer-files', 'newer'], ['keepNewerFiles', 'newer'], ['k', 'keep'], ['keep-existing', 'keep'], ['keepExisting', 'keep'], ['m', 'noMtime'], ['no-mtime', 'noMtime'], ['p', 'preserveOwner'], ['L', 'follow'], ['h', 'follow'], ['onentry', 'onReadEntry'], ]); const isSyncFile = (o) => !!o.sync && !!o.file; exports.isSyncFile = isSyncFile; const isAsyncFile = (o) => !o.sync && !!o.file; exports.isAsyncFile = isAsyncFile; const isSyncNoFile = (o) => !!o.sync && !o.file; exports.isSyncNoFile = isSyncNoFile; const isAsyncNoFile = (o) => !o.sync && !o.file; exports.isAsyncNoFile = isAsyncNoFile; const isSync = (o) => !!o.sync; exports.isSync = isSync; const isAsync = (o) => !o.sync; exports.isAsync = isAsync; const isFile = (o) => !!o.file; exports.isFile = isFile; const isNoFile = (o) => !o.file; exports.isNoFile = isNoFile; const dealiasKey = (k) => { const d = argmap.get(k); if (d) return d; return k; }; const dealias = (opt = {}) => { if (!opt) return {}; const result = {}; for (const [key, v] of Object.entries(opt)) { // TS doesn't know that aliases are going to always be the same type const k = dealiasKey(key); result[k] = v; } // affordance for deprecated noChmod -> chmod if (result.chmod === undefined && result.noChmod === false) { result.chmod = true; } delete result.noChmod; return result; }; exports.dealias = dealias; //# sourceMappingURL=options.js.map"use strict"; // A readable tar stream creator // Technically, this is a transform stream that you write paths into, // and tar format comes out of. // The `add()` method is like `write()` but returns this, // and end() return `this` as well, so you can // do `new Pack(opt).add('files').add('dir').end().pipe(output) // You could also do something like: // streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PackSync = exports.Pack = exports.PackJob = void 0; const fs_1 = __importDefault(require("fs")); const write_entry_js_1 = require("./write-entry.js"); class PackJob { path; absolute; entry; stat; readdir; pending = false; ignore = false; piped = false; constructor(path, absolute) { this.path = path || './'; this.absolute = absolute; } } exports.PackJob = PackJob; const minipass_1 = require("minipass"); const zlib = __importStar(require("minizlib")); const yallist_1 = require("yallist"); const read_entry_js_1 = require("./read-entry.js"); const warn_method_js_1 = require("./warn-method.js"); const EOF = Buffer.alloc(1024); const ONSTAT = Symbol('onStat'); const ENDED = Symbol('ended'); const QUEUE = Symbol('queue'); const CURRENT = Symbol('current'); const PROCESS = Symbol('process'); const PROCESSING = Symbol('processing'); const PROCESSJOB = Symbol('processJob'); const JOBS = Symbol('jobs'); const JOBDONE = Symbol('jobDone'); const ADDFSENTRY = Symbol('addFSEntry'); const ADDTARENTRY = Symbol('addTarEntry'); const STAT = Symbol('stat'); const READDIR = Symbol('readdir'); const ONREADDIR = Symbol('onreaddir'); const PIPE = Symbol('pipe'); const ENTRY = Symbol('entry'); const ENTRYOPT = Symbol('entryOpt'); const WRITEENTRYCLASS = Symbol('writeEntryClass'); const WRITE = Symbol('write'); const ONDRAIN = Symbol('ondrain'); const path_1 = __importDefault(require("path")); const normalize_windows_path_js_1 = require("./normalize-windows-path.js"); class Pack extends minipass_1.Minipass { opt; cwd; maxReadSize; preservePaths; strict; noPax; prefix; linkCache; statCache; file; portable; zip; readdirCache; noDirRecurse; follow; noMtime; mtime; filter; jobs; [WRITEENTRYCLASS]; onWriteEntry; [QUEUE]; [JOBS] = 0; [PROCESSING] = false; [ENDED] = false; constructor(opt = {}) { //@ts-ignore super(); this.opt = opt; this.file = opt.file || ''; this.cwd = opt.cwd || process.cwd(); this.maxReadSize = opt.maxReadSize; this.preservePaths = !!opt.preservePaths; this.strict = !!opt.strict; this.noPax = !!opt.noPax; this.prefix = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.prefix || ''); this.linkCache = opt.linkCache || new Map(); this.statCache = opt.statCache || new Map(); this.readdirCache = opt.readdirCache || new Map(); this.onWriteEntry = opt.onWriteEntry; this[WRITEENTRYCLASS] = write_entry_js_1.WriteEntry; if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn); } this.portable = !!opt.portable; if (opt.gzip || opt.brotli) { if (opt.gzip && opt.brotli) { throw new TypeError('gzip and brotli are mutually exclusive'); } if (opt.gzip) { if (typeof opt.gzip !== 'object') { opt.gzip = {}; } if (this.portable) { opt.gzip.portable = true; } this.zip = new zlib.Gzip(opt.gzip); } if (opt.brotli) { if (typeof opt.brotli !== 'object') { opt.brotli = {}; } this.zip = new zlib.BrotliCompress(opt.brotli); } /* c8 ignore next */ if (!this.zip) throw new Error('impossible'); const zip = this.zip; zip.on('data', chunk => super.write(chunk)); zip.on('end', () => super.end()); zip.on('drain', () => this[ONDRAIN]()); this.on('resume', () => zip.resume()); } else { this.on('drain', this[ONDRAIN]); } this.noDirRecurse = !!opt.noDirRecurse; this.follow = !!opt.follow; this.noMtime = !!opt.noMtime; if (opt.mtime) this.mtime = opt.mtime; this.filter = typeof opt.filter === 'function' ? opt.filter : () => true; this[QUEUE] = new yallist_1.Yallist(); this[JOBS] = 0; this.jobs = Number(opt.jobs) || 4; this[PROCESSING] = false; this[ENDED] = false; } [WRITE](chunk) { return super.write(chunk); } add(path) { this.write(path); return this; } end(path, encoding, cb) { /* c8 ignore start */ if (typeof path === 'function') { cb = path; path = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } /* c8 ignore stop */ if (path) { this.add(path); } this[ENDED] = true; this[PROCESS](); /* c8 ignore next */ if (cb) cb(); return this; } write(path) { if (this[ENDED]) { throw new Error('write after end'); } if (path instanceof read_entry_js_1.ReadEntry) { this[ADDTARENTRY](path); } else { this[ADDFSENTRY](path); } return this.flowing; } [ADDTARENTRY](p) { const absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(path_1.default.resolve(this.cwd, p.path)); // in this case, we don't have to wait for the stat if (!this.filter(p.path, p)) { p.resume(); } else { const job = new PackJob(p.path, absolute); job.entry = new write_entry_js_1.WriteEntryTar(p, this[ENTRYOPT](job)); job.entry.on('end', () => this[JOBDONE](job)); this[JOBS] += 1; this[QUEUE].push(job); } this[PROCESS](); } [ADDFSENTRY](p) { const absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(path_1.default.resolve(this.cwd, p)); this[QUEUE].push(new PackJob(p, absolute)); this[PROCESS](); } [STAT](job) { job.pending = true; this[JOBS] += 1; const stat = this.follow ? 'stat' : 'lstat'; fs_1.default[stat](job.absolute, (er, stat) => { job.pending = false; this[JOBS] -= 1; if (er) { this.emit('error', er); } else { this[ONSTAT](job, stat); } }); } [ONSTAT](job, stat) { this.statCache.set(job.absolute, stat); job.stat = stat; // now we have the stat, we can filter it. if (!this.filter(job.path, stat)) { job.ignore = true; } this[PROCESS](); } [READDIR](job) { job.pending = true; this[JOBS] += 1; fs_1.default.readdir(job.absolute, (er, entries) => { job.pending = false; this[JOBS] -= 1; if (er) { return this.emit('error', er); } this[ONREADDIR](job, entries); }); } [ONREADDIR](job, entries) { this.readdirCache.set(job.absolute, entries); job.readdir = entries; this[PROCESS](); } [PROCESS]() { if (this[PROCESSING]) { return; } this[PROCESSING] = true; for (let w = this[QUEUE].head; !!w && this[JOBS] < this.jobs; w = w.next) { this[PROCESSJOB](w.value); if (w.value.ignore) { const p = w.next; this[QUEUE].removeNode(w); w.next = p; } } this[PROCESSING] = false; if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { if (this.zip) { this.zip.end(EOF); } else { super.write(EOF); super.end(); } } } get [CURRENT]() { return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value; } [JOBDONE](_job) { this[QUEUE].shift(); this[JOBS] -= 1; this[PROCESS](); } [PROCESSJOB](job) { if (job.pending) { return; } if (job.entry) { if (job === this[CURRENT] && !job.piped) { this[PIPE](job); } return; } if (!job.stat) { const sc = this.statCache.get(job.absolute); if (sc) { this[ONSTAT](job, sc); } else { this[STAT](job); } } if (!job.stat) { return; } // filtered out! if (job.ignore) { return; } if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { const rc = this.readdirCache.get(job.absolute); if (rc) { this[ONREADDIR](job, rc); } else { this[READDIR](job); } if (!job.readdir) { return; } } // we know it doesn't have an entry, because that got checked above job.entry = this[ENTRY](job); if (!job.entry) { job.ignore = true; return; } if (job === this[CURRENT] && !job.piped) { this[PIPE](job); } } [ENTRYOPT](job) { return { onwarn: (code, msg, data) => this.warn(code, msg, data), noPax: this.noPax, cwd: this.cwd, absolute: job.absolute, preservePaths: this.preservePaths, maxReadSize: this.maxReadSize, strict: this.strict, portable: this.portable, linkCache: this.linkCache, statCache: this.statCache, noMtime: this.noMtime, mtime: this.mtime, prefix: this.prefix, onWriteEntry: this.onWriteEntry, }; } [ENTRY](job) { this[JOBS] += 1; try { const e = new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)); return e .on('end', () => this[JOBDONE](job)) .on('error', er => this.emit('error', er)); } catch (er) { this.emit('error', er); } } [ONDRAIN]() { if (this[CURRENT] && this[CURRENT].entry) { this[CURRENT].entry.resume(); } } // like .pipe() but using super, because our write() is special [PIPE](job) { job.piped = true; if (job.readdir) { job.readdir.forEach(entry => { const p = job.path; const base = p === './' ? '' : p.replace(/\/*$/, '/'); this[ADDFSENTRY](base + entry); }); } const source = job.entry; const zip = this.zip; /* c8 ignore start */ if (!source) throw new Error('cannot pipe without source'); /* c8 ignore stop */ if (zip) { source.on('data', chunk => { if (!zip.write(chunk)) { source.pause(); } }); } else { source.on('data', chunk => { if (!super.write(chunk)) { source.pause(); } }); } } pause() { if (this.zip) { this.zip.pause(); } return super.pause(); } warn(code, message, data = {}) { (0, warn_method_js_1.warnMethod)(this, code, message, data); } } exports.Pack = Pack; class PackSync extends Pack { sync = true; constructor(opt) { super(opt); this[WRITEENTRYCLASS] = write_entry_js_1.WriteEntrySync; } // pause/resume are no-ops in sync streams. pause() { } resume() { } [STAT](job) { const stat = this.follow ? 'statSync' : 'lstatSync'; this[ONSTAT](job, fs_1.default[stat](job.absolute)); } [READDIR](job) { this[ONREADDIR](job, fs_1.default.readdirSync(job.absolute)); } // gotta get it all in this tick [PIPE](job) { const source = job.entry; const zip = this.zip; if (job.readdir) { job.readdir.forEach(entry => { const p = job.path; const base = p === './' ? '' : p.replace(/\/*$/, '/'); this[ADDFSENTRY](base + entry); }); } /* c8 ignore start */ if (!source) throw new Error('Cannot pipe without source'); /* c8 ignore stop */ if (zip) { source.on('data', chunk => { zip.write(chunk); }); } else { source.on('data', chunk => { super[WRITE](chunk); }); } } } exports.PackSync = PackSync; //# sourceMappingURL=pack.js.map{ "type": "commonjs" } "use strict"; // this[BUFFER] is the remainder of a chunk if we're waiting for // the full 512 bytes of a header to come in. We will Buffer.concat() // it to the next write(), which is a mem copy, but a small one. // // this[QUEUE] is a Yallist of entries that haven't been emitted // yet this can only get filled up if the user keeps write()ing after // a write() returns false, or does a write() with more than one entry // // We don't buffer chunks, we always parse them and either create an // entry, or push it into the active entry. The ReadEntry class knows // to throw data away if .ignore=true // // Shift entry off the buffer when it emits 'end', and emit 'entry' for // the next one in the list. // // At any time, we're pushing body chunks into the entry at WRITEENTRY, // and waiting for 'end' on the entry at READENTRY // // ignored entries get .resume() called on them straight away Object.defineProperty(exports, "__esModule", { value: true }); exports.Parser = void 0; const events_1 = require("events"); const minizlib_1 = require("minizlib"); const yallist_1 = require("yallist"); const header_js_1 = require("./header.js"); const pax_js_1 = require("./pax.js"); const read_entry_js_1 = require("./read-entry.js"); const warn_method_js_1 = require("./warn-method.js"); const maxMetaEntrySize = 1024 * 1024; const gzipHeader = Buffer.from([0x1f, 0x8b]); const STATE = Symbol('state'); const WRITEENTRY = Symbol('writeEntry'); const READENTRY = Symbol('readEntry'); const NEXTENTRY = Symbol('nextEntry'); const PROCESSENTRY = Symbol('processEntry'); const EX = Symbol('extendedHeader'); const GEX = Symbol('globalExtendedHeader'); const META = Symbol('meta'); const EMITMETA = Symbol('emitMeta'); const BUFFER = Symbol('buffer'); const QUEUE = Symbol('queue'); const ENDED = Symbol('ended'); const EMITTEDEND = Symbol('emittedEnd'); const EMIT = Symbol('emit'); const UNZIP = Symbol('unzip'); const CONSUMECHUNK = Symbol('consumeChunk'); const CONSUMECHUNKSUB = Symbol('consumeChunkSub'); const CONSUMEBODY = Symbol('consumeBody'); const CONSUMEMETA = Symbol('consumeMeta'); const CONSUMEHEADER = Symbol('consumeHeader'); const CONSUMING = Symbol('consuming'); const BUFFERCONCAT = Symbol('bufferConcat'); const MAYBEEND = Symbol('maybeEnd'); const WRITING = Symbol('writing'); const ABORTED = Symbol('aborted'); const DONE = Symbol('onDone'); const SAW_VALID_ENTRY = Symbol('sawValidEntry'); const SAW_NULL_BLOCK = Symbol('sawNullBlock'); const SAW_EOF = Symbol('sawEOF'); const CLOSESTREAM = Symbol('closeStream'); const noop = () => true; class Parser extends events_1.EventEmitter { file; strict; maxMetaEntrySize; filter; brotli; writable = true; readable = false; [QUEUE] = new yallist_1.Yallist(); [BUFFER]; [READENTRY]; [WRITEENTRY]; [STATE] = 'begin'; [META] = ''; [EX]; [GEX]; [ENDED] = false; [UNZIP]; [ABORTED] = false; [SAW_VALID_ENTRY]; [SAW_NULL_BLOCK] = false; [SAW_EOF] = false; [WRITING] = false; [CONSUMING] = false; [EMITTEDEND] = false; constructor(opt = {}) { super(); this.file = opt.file || ''; // these BADARCHIVE errors can't be detected early. listen on DONE. this.on(DONE, () => { if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { // either less than 1 block of data, or all entries were invalid. // Either way, probably not even a tarball. this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format'); } }); if (opt.ondone) { this.on(DONE, opt.ondone); } else { this.on(DONE, () => { this.emit('prefinish'); this.emit('finish'); this.emit('end'); }); } this.strict = !!opt.strict; this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize; this.filter = typeof opt.filter === 'function' ? opt.filter : noop; // Unlike gzip, brotli doesn't have any magic bytes to identify it // Users need to explicitly tell us they're extracting a brotli file // Or we infer from the file extension const isTBR = opt.file && (opt.file.endsWith('.tar.br') || opt.file.endsWith('.tbr')); // if it's a tbr file it MIGHT be brotli, but we don't know until // we look at it and verify it's not a valid tar file. this.brotli = !opt.gzip && opt.brotli !== undefined ? opt.brotli : isTBR ? undefined : false; // have to set this so that streams are ok piping into it this.on('end', () => this[CLOSESTREAM]()); if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn); } if (typeof opt.onReadEntry === 'function') { this.on('entry', opt.onReadEntry); } } warn(code, message, data = {}) { (0, warn_method_js_1.warnMethod)(this, code, message, data); } [CONSUMEHEADER](chunk, position) { if (this[SAW_VALID_ENTRY] === undefined) { this[SAW_VALID_ENTRY] = false; } let header; try { header = new header_js_1.Header(chunk, position, this[EX], this[GEX]); } catch (er) { return this.warn('TAR_ENTRY_INVALID', er); } if (header.nullBlock) { if (this[SAW_NULL_BLOCK]) { this[SAW_EOF] = true; // ending an archive with no entries. pointless, but legal. if (this[STATE] === 'begin') { this[STATE] = 'header'; } this[EMIT]('eof'); } else { this[SAW_NULL_BLOCK] = true; this[EMIT]('nullBlock'); } } else { this[SAW_NULL_BLOCK] = false; if (!header.cksumValid) { this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header }); } else if (!header.path) { this.warn('TAR_ENTRY_INVALID', 'path is required', { header }); } else { const type = header.type; if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath required', { header, }); } else if (!/^(Symbolic)?Link$/.test(type) && !/^(Global)?ExtendedHeader$/.test(type) && header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', { header, }); } else { const entry = (this[WRITEENTRY] = new read_entry_js_1.ReadEntry(header, this[EX], this[GEX])); // we do this for meta & ignored entries as well, because they // are still valid tar, or else we wouldn't know to ignore them if (!this[SAW_VALID_ENTRY]) { if (entry.remain) { // this might be the one! const onend = () => { if (!entry.invalid) { this[SAW_VALID_ENTRY] = true; } }; entry.on('end', onend); } else { this[SAW_VALID_ENTRY] = true; } } if (entry.meta) { if (entry.size > this.maxMetaEntrySize) { entry.ignore = true; this[EMIT]('ignoredEntry', entry); this[STATE] = 'ignore'; entry.resume(); } else if (entry.size > 0) { this[META] = ''; entry.on('data', c => (this[META] += c)); this[STATE] = 'meta'; } } else { this[EX] = undefined; entry.ignore = entry.ignore || !this.filter(entry.path, entry); if (entry.ignore) { // probably valid, just not something we care about this[EMIT]('ignoredEntry', entry); this[STATE] = entry.remain ? 'ignore' : 'header'; entry.resume(); } else { if (entry.remain) { this[STATE] = 'body'; } else { this[STATE] = 'header'; entry.end(); } if (!this[READENTRY]) { this[QUEUE].push(entry); this[NEXTENTRY](); } else { this[QUEUE].push(entry); } } } } } } } [CLOSESTREAM]() { queueMicrotask(() => this.emit('close')); } [PROCESSENTRY](entry) { let go = true; if (!entry) { this[READENTRY] = undefined; go = false; } else if (Array.isArray(entry)) { const [ev, ...args] = entry; this.emit(ev, ...args); } else { this[READENTRY] = entry; this.emit('entry', entry); if (!entry.emittedEnd) { entry.on('end', () => this[NEXTENTRY]()); go = false; } } return go; } [NEXTENTRY]() { do { } while (this[PROCESSENTRY](this[QUEUE].shift())); if (!this[QUEUE].length) { // At this point, there's nothing in the queue, but we may have an // entry which is being consumed (readEntry). // If we don't, then we definitely can handle more data. // If we do, and either it's flowing, or it has never had any data // written to it, then it needs more. // The only other possibility is that it has returned false from a // write() call, so we wait for the next drain to continue. const re = this[READENTRY]; const drainNow = !re || re.flowing || re.size === re.remain; if (drainNow) { if (!this[WRITING]) { this.emit('drain'); } } else { re.once('drain', () => this.emit('drain')); } } } [CONSUMEBODY](chunk, position) { // write up to but no more than writeEntry.blockRemain const entry = this[WRITEENTRY]; /* c8 ignore start */ if (!entry) { throw new Error('attempt to consume body without entry??'); } const br = entry.blockRemain ?? 0; /* c8 ignore stop */ const c = br >= chunk.length && position === 0 ? chunk : chunk.subarray(position, position + br); entry.write(c); if (!entry.blockRemain) { this[STATE] = 'header'; this[WRITEENTRY] = undefined; entry.end(); } return c.length; } [CONSUMEMETA](chunk, position) { const entry = this[WRITEENTRY]; const ret = this[CONSUMEBODY](chunk, position); // if we finished, then the entry is reset if (!this[WRITEENTRY] && entry) { this[EMITMETA](entry); } return ret; } [EMIT](ev, data, extra) { if (!this[QUEUE].length && !this[READENTRY]) { this.emit(ev, data, extra); } else { this[QUEUE].push([ev, data, extra]); } } [EMITMETA](entry) { this[EMIT]('meta', this[META]); switch (entry.type) { case 'ExtendedHeader': case 'OldExtendedHeader': this[EX] = pax_js_1.Pax.parse(this[META], this[EX], false); break; case 'GlobalExtendedHeader': this[GEX] = pax_js_1.Pax.parse(this[META], this[GEX], true); break; case 'NextFileHasLongPath': case 'OldGnuLongPath': { const ex = this[EX] ?? Object.create(null); this[EX] = ex; ex.path = this[META].replace(/\0.*/, ''); break; } case 'NextFileHasLongLinkpath': { const ex = this[EX] || Object.create(null); this[EX] = ex; ex.linkpath = this[META].replace(/\0.*/, ''); break; } /* c8 ignore start */ default: throw new Error('unknown meta: ' + entry.type); /* c8 ignore stop */ } } abort(error) { this[ABORTED] = true; this.emit('abort', error); // always throws, even in non-strict mode this.warn('TAR_ABORT', error, { recoverable: false }); } write(chunk, encoding, cb) { if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, /* c8 ignore next */ typeof encoding === 'string' ? encoding : 'utf8'); } if (this[ABORTED]) { /* c8 ignore next */ cb?.(); return false; } // first write, might be gzipped const needSniff = this[UNZIP] === undefined || (this.brotli === undefined && this[UNZIP] === false); if (needSniff && chunk) { if (this[BUFFER]) { chunk = Buffer.concat([this[BUFFER], chunk]); this[BUFFER] = undefined; } if (chunk.length < gzipHeader.length) { this[BUFFER] = chunk; /* c8 ignore next */ cb?.(); return true; } // look for gzip header for (let i = 0; this[UNZIP] === undefined && i < gzipHeader.length; i++) { if (chunk[i] !== gzipHeader[i]) { this[UNZIP] = false; } } const maybeBrotli = this.brotli === undefined; if (this[UNZIP] === false && maybeBrotli) { // read the first header to see if it's a valid tar file. If so, // we can safely assume that it's not actually brotli, despite the // .tbr or .tar.br file extension. // if we ended before getting a full chunk, yes, def brotli if (chunk.length < 512) { if (this[ENDED]) { this.brotli = true; } else { this[BUFFER] = chunk; /* c8 ignore next */ cb?.(); return true; } } else { // if it's tar, it's pretty reliably not brotli, chances of // that happening are astronomical. try { new header_js_1.Header(chunk.subarray(0, 512)); this.brotli = false; } catch (_) { this.brotli = true; } } } if (this[UNZIP] === undefined || (this[UNZIP] === false && this.brotli)) { const ended = this[ENDED]; this[ENDED] = false; this[UNZIP] = this[UNZIP] === undefined ? new minizlib_1.Unzip({}) : new minizlib_1.BrotliDecompress({}); this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)); this[UNZIP].on('error', er => this.abort(er)); this[UNZIP].on('end', () => { this[ENDED] = true; this[CONSUMECHUNK](); }); this[WRITING] = true; const ret = !!this[UNZIP][ended ? 'end' : 'write'](chunk); this[WRITING] = false; cb?.(); return ret; } } this[WRITING] = true; if (this[UNZIP]) { this[UNZIP].write(chunk); } else { this[CONSUMECHUNK](chunk); } this[WRITING] = false; // return false if there's a queue, or if the current entry isn't flowing const ret = this[QUEUE].length ? false : this[READENTRY] ? this[READENTRY].flowing : true; // if we have no queue, then that means a clogged READENTRY if (!ret && !this[QUEUE].length) { this[READENTRY]?.once('drain', () => this.emit('drain')); } /* c8 ignore next */ cb?.(); return ret; } [BUFFERCONCAT](c) { if (c && !this[ABORTED]) { this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c; } } [MAYBEEND]() { if (this[ENDED] && !this[EMITTEDEND] && !this[ABORTED] && !this[CONSUMING]) { this[EMITTEDEND] = true; const entry = this[WRITEENTRY]; if (entry && entry.blockRemain) { // truncated, likely a damaged file const have = this[BUFFER] ? this[BUFFER].length : 0; this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${entry.blockRemain} more bytes, only ${have} available)`, { entry }); if (this[BUFFER]) { entry.write(this[BUFFER]); } entry.end(); } this[EMIT](DONE); } } [CONSUMECHUNK](chunk) { if (this[CONSUMING] && chunk) { this[BUFFERCONCAT](chunk); } else if (!chunk && !this[BUFFER]) { this[MAYBEEND](); } else if (chunk) { this[CONSUMING] = true; if (this[BUFFER]) { this[BUFFERCONCAT](chunk); const c = this[BUFFER]; this[BUFFER] = undefined; this[CONSUMECHUNKSUB](c); } else { this[CONSUMECHUNKSUB](chunk); } while (this[BUFFER] && this[BUFFER]?.length >= 512 && !this[ABORTED] && !this[SAW_EOF]) { const c = this[BUFFER]; this[BUFFER] = undefined; this[CONSUMECHUNKSUB](c); } this[CONSUMING] = false; } if (!this[BUFFER] || this[ENDED]) { this[MAYBEEND](); } } [CONSUMECHUNKSUB](chunk) { // we know that we are in CONSUMING mode, so anything written goes into // the buffer. Advance the position and put any remainder in the buffer. let position = 0; const length = chunk.length; while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { switch (this[STATE]) { case 'begin': case 'header': this[CONSUMEHEADER](chunk, position); position += 512; break; case 'ignore': case 'body': position += this[CONSUMEBODY](chunk, position); break; case 'meta': position += this[CONSUMEMETA](chunk, position); break; /* c8 ignore start */ default: throw new Error('invalid state: ' + this[STATE]); /* c8 ignore stop */ } } if (position < length) { if (this[BUFFER]) { this[BUFFER] = Buffer.concat([ chunk.subarray(position), this[BUFFER], ]); } else { this[BUFFER] = chunk.subarray(position); } } } end(chunk, encoding, cb) { if (typeof chunk === 'function') { cb = chunk; encoding = undefined; chunk = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } if (cb) this.once('finish', cb); if (!this[ABORTED]) { if (this[UNZIP]) { /* c8 ignore start */ if (chunk) this[UNZIP].write(chunk); /* c8 ignore stop */ this[UNZIP].end(); } else { this[ENDED] = true; if (this.brotli === undefined) chunk = chunk || Buffer.alloc(0); if (chunk) this.write(chunk); this[MAYBEEND](); } } return this; } } exports.Parser = Parser; //# sourceMappingURL=parse.js.map"use strict"; // A path exclusive reservation system // reserve([list, of, paths], fn) // When the fn is first in line for all its paths, it // is called with a cb that clears the reservation. // // Used by async unpack to avoid clobbering paths in use, // while still allowing maximal safe parallelization. Object.defineProperty(exports, "__esModule", { value: true }); exports.PathReservations = void 0; const node_path_1 = require("node:path"); const normalize_unicode_js_1 = require("./normalize-unicode.js"); const strip_trailing_slashes_js_1 = require("./strip-trailing-slashes.js"); const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; const isWindows = platform === 'win32'; // return a set of parent dirs for a given path // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d'] const getDirs = (path) => { const dirs = path .split('/') .slice(0, -1) .reduce((set, path) => { const s = set[set.length - 1]; if (s !== undefined) { path = (0, node_path_1.join)(s, path); } set.push(path || '/'); return set; }, []); return dirs; }; class PathReservations { // path => [function or Set] // A Set object means a directory reservation // A fn is a direct reservation on that path #queues = new Map(); // fn => {paths:[path,...], dirs:[path, ...]} #reservations = new Map(); // functions currently running #running = new Set(); reserve(paths, fn) { paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { // don't need normPath, because we skip this entirely for windows return (0, strip_trailing_slashes_js_1.stripTrailingSlashes)((0, node_path_1.join)((0, normalize_unicode_js_1.normalizeUnicode)(p))).toLowerCase(); }); const dirs = new Set(paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b))); this.#reservations.set(fn, { dirs, paths }); for (const p of paths) { const q = this.#queues.get(p); if (!q) { this.#queues.set(p, [fn]); } else { q.push(fn); } } for (const dir of dirs) { const q = this.#queues.get(dir); if (!q) { this.#queues.set(dir, [new Set([fn])]); } else { const l = q[q.length - 1]; if (l instanceof Set) { l.add(fn); } else { q.push(new Set([fn])); } } } return this.#run(fn); } // return the queues for each path the function cares about // fn => {paths, dirs} #getQueues(fn) { const res = this.#reservations.get(fn); /* c8 ignore start */ if (!res) { throw new Error('function does not have any path reservations'); } /* c8 ignore stop */ return { paths: res.paths.map((path) => this.#queues.get(path)), dirs: [...res.dirs].map(path => this.#queues.get(path)), }; } // check if fn is first in line for all its paths, and is // included in the first set for all its dir queues check(fn) { const { paths, dirs } = this.#getQueues(fn); return (paths.every(q => q && q[0] === fn) && dirs.every(q => q && q[0] instanceof Set && q[0].has(fn))); } // run the function if it's first in line and not already running #run(fn) { if (this.#running.has(fn) || !this.check(fn)) { return false; } this.#running.add(fn); fn(() => this.#clear(fn)); return true; } #clear(fn) { if (!this.#running.has(fn)) { return false; } const res = this.#reservations.get(fn); /* c8 ignore start */ if (!res) { throw new Error('invalid reservation'); } /* c8 ignore stop */ const { paths, dirs } = res; const next = new Set(); for (const path of paths) { const q = this.#queues.get(path); /* c8 ignore start */ if (!q || q?.[0] !== fn) { continue; } /* c8 ignore stop */ const q0 = q[1]; if (!q0) { this.#queues.delete(path); continue; } q.shift(); if (typeof q0 === 'function') { next.add(q0); } else { for (const f of q0) { next.add(f); } } } for (const dir of dirs) { const q = this.#queues.get(dir); const q0 = q?.[0]; /* c8 ignore next - type safety only */ if (!q || !(q0 instanceof Set)) continue; if (q0.size === 1 && q.length === 1) { this.#queues.delete(dir); continue; } else if (q0.size === 1) { q.shift(); // next one must be a function, // or else the Set would've been reused const n = q[0]; if (typeof n === 'function') { next.add(n); } } else { q0.delete(fn); } } this.#running.delete(fn); next.forEach(fn => this.#run(fn)); return true; } } exports.PathReservations = PathReservations; //# sourceMappingURL=path-reservations.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Pax = void 0; const node_path_1 = require("node:path"); const header_js_1 = require("./header.js"); class Pax { atime; mtime; ctime; charset; comment; gid; uid; gname; uname; linkpath; dev; ino; nlink; path; size; mode; global; constructor(obj, global = false) { this.atime = obj.atime; this.charset = obj.charset; this.comment = obj.comment; this.ctime = obj.ctime; this.dev = obj.dev; this.gid = obj.gid; this.global = global; this.gname = obj.gname; this.ino = obj.ino; this.linkpath = obj.linkpath; this.mtime = obj.mtime; this.nlink = obj.nlink; this.path = obj.path; this.size = obj.size; this.uid = obj.uid; this.uname = obj.uname; } encode() { const body = this.encodeBody(); if (body === '') { return Buffer.allocUnsafe(0); } const bodyLen = Buffer.byteLength(body); // round up to 512 bytes // add 512 for header const bufLen = 512 * Math.ceil(1 + bodyLen / 512); const buf = Buffer.allocUnsafe(bufLen); // 0-fill the header section, it might not hit every field for (let i = 0; i < 512; i++) { buf[i] = 0; } new header_js_1.Header({ // XXX split the path // then the path should be PaxHeader + basename, but less than 99, // prepend with the dirname /* c8 ignore start */ path: ('PaxHeader/' + (0, node_path_1.basename)(this.path ?? '')).slice(0, 99), /* c8 ignore stop */ mode: this.mode || 0o644, uid: this.uid, gid: this.gid, size: bodyLen, mtime: this.mtime, type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', linkpath: '', uname: this.uname || '', gname: this.gname || '', devmaj: 0, devmin: 0, atime: this.atime, ctime: this.ctime, }).encode(buf); buf.write(body, 512, bodyLen, 'utf8'); // null pad after the body for (let i = bodyLen + 512; i < buf.length; i++) { buf[i] = 0; } return buf; } encodeBody() { return (this.encodeField('path') + this.encodeField('ctime') + this.encodeField('atime') + this.encodeField('dev') + this.encodeField('ino') + this.encodeField('nlink') + this.encodeField('charset') + this.encodeField('comment') + this.encodeField('gid') + this.encodeField('gname') + this.encodeField('linkpath') + this.encodeField('mtime') + this.encodeField('size') + this.encodeField('uid') + this.encodeField('uname')); } encodeField(field) { if (this[field] === undefined) { return ''; } const r = this[field]; const v = r instanceof Date ? r.getTime() / 1000 : r; const s = ' ' + (field === 'dev' || field === 'ino' || field === 'nlink' ? 'SCHILY.' : '') + field + '=' + v + '\n'; const byteLen = Buffer.byteLength(s); // the digits includes the length of the digits in ascii base-10 // so if it's 9 characters, then adding 1 for the 9 makes it 10 // which makes it 11 chars. let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1; if (byteLen + digits >= Math.pow(10, digits)) { digits += 1; } const len = digits + byteLen; return len + s; } static parse(str, ex, g = false) { return new Pax(merge(parseKV(str), ex), g); } } exports.Pax = Pax; const merge = (a, b) => b ? Object.assign({}, b, a) : a; const parseKV = (str) => str .replace(/\n$/, '') .split('\n') .reduce(parseKVLine, Object.create(null)); const parseKVLine = (set, line) => { const n = parseInt(line, 10); // XXX Values with \n in them will fail this. // Refactor to not be a naive line-by-line parse. if (n !== Buffer.byteLength(line) + 1) { return set; } line = line.slice((n + ' ').length); const kv = line.split('='); const r = kv.shift(); if (!r) { return set; } const k = r.replace(/^SCHILY\.(dev|ino|nlink)/, '$1'); const v = kv.join('='); set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ? new Date(Number(v) * 1000) : /^[0-9]+$/.test(v) ? +v : v; return set; }; //# sourceMappingURL=pax.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ReadEntry = void 0; const minipass_1 = require("minipass"); const normalize_windows_path_js_1 = require("./normalize-windows-path.js"); class ReadEntry extends minipass_1.Minipass { extended; globalExtended; header; startBlockSize; blockRemain; remain; type; meta = false; ignore = false; path; mode; uid; gid; uname; gname; size = 0; mtime; atime; ctime; linkpath; dev; ino; nlink; invalid = false; absolute; unsupported = false; constructor(header, ex, gex) { super({}); // read entries always start life paused. this is to avoid the // situation where Minipass's auto-ending empty streams results // in an entry ending before we're ready for it. this.pause(); this.extended = ex; this.globalExtended = gex; this.header = header; /* c8 ignore start */ this.remain = header.size ?? 0; /* c8 ignore stop */ this.startBlockSize = 512 * Math.ceil(this.remain / 512); this.blockRemain = this.startBlockSize; this.type = header.type; switch (this.type) { case 'File': case 'OldFile': case 'Link': case 'SymbolicLink': case 'CharacterDevice': case 'BlockDevice': case 'Directory': case 'FIFO': case 'ContiguousFile': case 'GNUDumpDir': break; case 'NextFileHasLongLinkpath': case 'NextFileHasLongPath': case 'OldGnuLongPath': case 'GlobalExtendedHeader': case 'ExtendedHeader': case 'OldExtendedHeader': this.meta = true; break; // NOTE: gnutar and bsdtar treat unrecognized types as 'File' // it may be worth doing the same, but with a warning. default: this.ignore = true; } /* c8 ignore start */ if (!header.path) { throw new Error('no path provided for tar.ReadEntry'); } /* c8 ignore stop */ this.path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(header.path); this.mode = header.mode; if (this.mode) { this.mode = this.mode & 0o7777; } this.uid = header.uid; this.gid = header.gid; this.uname = header.uname; this.gname = header.gname; this.size = this.remain; this.mtime = header.mtime; this.atime = header.atime; this.ctime = header.ctime; /* c8 ignore start */ this.linkpath = header.linkpath ? (0, normalize_windows_path_js_1.normalizeWindowsPath)(header.linkpath) : undefined; /* c8 ignore stop */ this.uname = header.uname; this.gname = header.gname; if (ex) { this.#slurp(ex); } if (gex) { this.#slurp(gex, true); } } write(data) { const writeLen = data.length; if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate'); } const r = this.remain; const br = this.blockRemain; this.remain = Math.max(0, r - writeLen); this.blockRemain = Math.max(0, br - writeLen); if (this.ignore) { return true; } if (r >= writeLen) { return super.write(data); } // r < writeLen return super.write(data.subarray(0, r)); } #slurp(ex, gex = false) { if (ex.path) ex.path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(ex.path); if (ex.linkpath) ex.linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(ex.linkpath); Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. Also, any // null/undefined values are ignored. return !(v === null || v === undefined || (k === 'path' && gex)); }))); } } exports.ReadEntry = ReadEntry; //# sourceMappingURL=read-entry.js.map"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.replace = void 0; // tar -r const fs_minipass_1 = require("@isaacs/fs-minipass"); const node_fs_1 = __importDefault(require("node:fs")); const node_path_1 = __importDefault(require("node:path")); const header_js_1 = require("./header.js"); const list_js_1 = require("./list.js"); const make_command_js_1 = require("./make-command.js"); const options_js_1 = require("./options.js"); const pack_js_1 = require("./pack.js"); // starting at the head of the file, read a Header // If the checksum is invalid, that's our position to start writing // If it is, jump forward by the specified size (round up to 512) // and try again. // Write the new Pack stream starting there. const replaceSync = (opt, files) => { const p = new pack_js_1.PackSync(opt); let threw = true; let fd; let position; try { try { fd = node_fs_1.default.openSync(opt.file, 'r+'); } catch (er) { if (er?.code === 'ENOENT') { fd = node_fs_1.default.openSync(opt.file, 'w+'); } else { throw er; } } const st = node_fs_1.default.fstatSync(fd); const headBuf = Buffer.alloc(512); POSITION: for (position = 0; position < st.size; position += 512) { for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { bytes = node_fs_1.default.readSync(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos); if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { throw new Error('cannot append to compressed archives'); } if (!bytes) { break POSITION; } } const h = new header_js_1.Header(headBuf); if (!h.cksumValid) { break; } const entryBlockSize = 512 * Math.ceil((h.size || 0) / 512); if (position + entryBlockSize + 512 > st.size) { break; } // the 512 for the header we just parsed will be added as well // also jump ahead all the blocks for the body position += entryBlockSize; if (opt.mtimeCache && h.mtime) { opt.mtimeCache.set(String(h.path), h.mtime); } } threw = false; streamSync(opt, p, position, fd, files); } finally { if (threw) { try { node_fs_1.default.closeSync(fd); } catch (er) { } } } }; const streamSync = (opt, p, position, fd, files) => { const stream = new fs_minipass_1.WriteStreamSync(opt.file, { fd: fd, start: position, }); p.pipe(stream); addFilesSync(p, files); }; const replaceAsync = (opt, files) => { files = Array.from(files); const p = new pack_js_1.Pack(opt); const getPos = (fd, size, cb_) => { const cb = (er, pos) => { if (er) { node_fs_1.default.close(fd, _ => cb_(er)); } else { cb_(null, pos); } }; let position = 0; if (size === 0) { return cb(null, 0); } let bufPos = 0; const headBuf = Buffer.alloc(512); const onread = (er, bytes) => { if (er || typeof bytes === 'undefined') { return cb(er); } bufPos += bytes; if (bufPos < 512 && bytes) { return node_fs_1.default.read(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread); } if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { return cb(new Error('cannot append to compressed archives')); } // truncated header if (bufPos < 512) { return cb(null, position); } const h = new header_js_1.Header(headBuf); if (!h.cksumValid) { return cb(null, position); } /* c8 ignore next */ const entryBlockSize = 512 * Math.ceil((h.size ?? 0) / 512); if (position + entryBlockSize + 512 > size) { return cb(null, position); } position += entryBlockSize + 512; if (position >= size) { return cb(null, position); } if (opt.mtimeCache && h.mtime) { opt.mtimeCache.set(String(h.path), h.mtime); } bufPos = 0; node_fs_1.default.read(fd, headBuf, 0, 512, position, onread); }; node_fs_1.default.read(fd, headBuf, 0, 512, position, onread); }; const promise = new Promise((resolve, reject) => { p.on('error', reject); let flag = 'r+'; const onopen = (er, fd) => { if (er && er.code === 'ENOENT' && flag === 'r+') { flag = 'w+'; return node_fs_1.default.open(opt.file, flag, onopen); } if (er || !fd) { return reject(er); } node_fs_1.default.fstat(fd, (er, st) => { if (er) { return node_fs_1.default.close(fd, () => reject(er)); } getPos(fd, st.size, (er, position) => { if (er) { return reject(er); } const stream = new fs_minipass_1.WriteStream(opt.file, { fd: fd, start: position, }); p.pipe(stream); stream.on('error', reject); stream.on('close', resolve); addFilesAsync(p, files); }); }); }; node_fs_1.default.open(opt.file, flag, onopen); }); return promise; }; const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { (0, list_js_1.list)({ file: node_path_1.default.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onReadEntry: entry => p.add(entry), }); } else { p.add(file); } }); p.end(); }; const addFilesAsync = async (p, files) => { for (let i = 0; i < files.length; i++) { const file = String(files[i]); if (file.charAt(0) === '@') { await (0, list_js_1.list)({ file: node_path_1.default.resolve(String(p.cwd), file.slice(1)), noResume: true, onReadEntry: entry => p.add(entry), }); } else { p.add(file); } } p.end(); }; exports.replace = (0, make_command_js_1.makeCommand)(replaceSync, replaceAsync, /* c8 ignore start */ () => { throw new TypeError('file is required'); }, () => { throw new TypeError('file is required'); }, /* c8 ignore stop */ (opt, entries) => { if (!(0, options_js_1.isFile)(opt)) { throw new TypeError('file is required'); } if (opt.gzip || opt.brotli || opt.file.endsWith('.br') || opt.file.endsWith('.tbr')) { throw new TypeError('cannot append to compressed archives'); } if (!entries?.length) { throw new TypeError('no paths specified to add/replace'); } }); //# sourceMappingURL=replace.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stripAbsolutePath = void 0; // unix absolute paths are also absolute on win32, so we use this for both const node_path_1 = require("node:path"); const { isAbsolute, parse } = node_path_1.win32; // returns [root, stripped] // Note that windows will think that //x/y/z/a has a "root" of //x/y, and in // those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip / // explicitly if it's the first character. // drive-specific relative paths on Windows get their root stripped off even // though they are not absolute, so `c:../foo` becomes ['c:', '../foo'] const stripAbsolutePath = (path) => { let r = ''; let parsed = parse(path); while (isAbsolute(path) || parsed.root) { // windows will think that //x/y/z has a "root" of //x/y/ // but strip the //?/C:/ off of //?/C:/path const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ? '/' : parsed.root; path = path.slice(root.length); r += root; parsed = parse(path); } return [r, path]; }; exports.stripAbsolutePath = stripAbsolutePath; //# sourceMappingURL=strip-absolute-path.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stripTrailingSlashes = void 0; // warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. const stripTrailingSlashes = (str) => { let i = str.length - 1; let slashesStart = -1; while (i > -1 && str.charAt(i) === '/') { slashesStart = i; i--; } return slashesStart === -1 ? str : str.slice(0, slashesStart); }; exports.stripTrailingSlashes = stripTrailingSlashes; //# sourceMappingURL=strip-trailing-slashes.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SymlinkError = void 0; class SymlinkError extends Error { path; symlink; syscall = 'symlink'; code = 'TAR_SYMLINK_ERROR'; constructor(symlink, path) { super('TAR_SYMLINK_ERROR: Cannot extract through symbolic link'); this.symlink = symlink; this.path = path; } get name() { return 'SymlinkError'; } } exports.SymlinkError = SymlinkError; //# sourceMappingURL=symlink-error.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.code = exports.name = exports.isName = exports.isCode = void 0; const isCode = (c) => exports.name.has(c); exports.isCode = isCode; const isName = (c) => exports.code.has(c); exports.isName = isName; // map types from key to human-friendly name exports.name = new Map([ ['0', 'File'], // same as File ['', 'OldFile'], ['1', 'Link'], ['2', 'SymbolicLink'], // Devices and FIFOs aren't fully supported // they are parsed, but skipped when unpacking ['3', 'CharacterDevice'], ['4', 'BlockDevice'], ['5', 'Directory'], ['6', 'FIFO'], // same as File ['7', 'ContiguousFile'], // pax headers ['g', 'GlobalExtendedHeader'], ['x', 'ExtendedHeader'], // vendor-specific stuff // skip ['A', 'SolarisACL'], // like 5, but with data, which should be skipped ['D', 'GNUDumpDir'], // metadata only, skip ['I', 'Inode'], // data = link path of next file ['K', 'NextFileHasLongLinkpath'], // data = path of next file ['L', 'NextFileHasLongPath'], // skip ['M', 'ContinuationFile'], // like L ['N', 'OldGnuLongPath'], // skip ['S', 'SparseFile'], // skip ['V', 'TapeVolumeHeader'], // like x ['X', 'OldExtendedHeader'], ]); // map the other direction exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])); //# sourceMappingURL=types.js.map"use strict"; // the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. // but the path reservations are required to avoid race conditions where // parallelized unpack ops may mess with one another, due to dependencies // (like a Link depending on its target) or destructive operations (like // clobbering an fs object to create one of a different type.) var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnpackSync = exports.Unpack = void 0; const fsm = __importStar(require("@isaacs/fs-minipass")); const node_assert_1 = __importDefault(require("node:assert")); const node_crypto_1 = require("node:crypto"); const node_fs_1 = __importDefault(require("node:fs")); const node_path_1 = __importDefault(require("node:path")); const get_write_flag_js_1 = require("./get-write-flag.js"); const mkdir_js_1 = require("./mkdir.js"); const normalize_unicode_js_1 = require("./normalize-unicode.js"); const normalize_windows_path_js_1 = require("./normalize-windows-path.js"); const parse_js_1 = require("./parse.js"); const strip_absolute_path_js_1 = require("./strip-absolute-path.js"); const strip_trailing_slashes_js_1 = require("./strip-trailing-slashes.js"); const wc = __importStar(require("./winchars.js")); const path_reservations_js_1 = require("./path-reservations.js"); const ONENTRY = Symbol('onEntry'); const CHECKFS = Symbol('checkFs'); const CHECKFS2 = Symbol('checkFs2'); const PRUNECACHE = Symbol('pruneCache'); const ISREUSABLE = Symbol('isReusable'); const MAKEFS = Symbol('makeFs'); const FILE = Symbol('file'); const DIRECTORY = Symbol('directory'); const LINK = Symbol('link'); const SYMLINK = Symbol('symlink'); const HARDLINK = Symbol('hardlink'); const UNSUPPORTED = Symbol('unsupported'); const CHECKPATH = Symbol('checkPath'); const MKDIR = Symbol('mkdir'); const ONERROR = Symbol('onError'); const PENDING = Symbol('pending'); const PEND = Symbol('pend'); const UNPEND = Symbol('unpend'); const ENDED = Symbol('ended'); const MAYBECLOSE = Symbol('maybeClose'); const SKIP = Symbol('skip'); const DOCHOWN = Symbol('doChown'); const UID = Symbol('uid'); const GID = Symbol('gid'); const CHECKED_CWD = Symbol('checkedCwd'); const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; const isWindows = platform === 'win32'; const DEFAULT_MAX_DEPTH = 1024; // Unlinks on Windows are not atomic. // // This means that if you have a file entry, followed by another // file entry with an identical name, and you cannot re-use the file // (because it's a hardlink, or because unlink:true is set, or it's // Windows, which does not have useful nlink values), then the unlink // will be committed to the disk AFTER the new file has been written // over the old one, deleting the new file. // // To work around this, on Windows systems, we rename the file and then // delete the renamed file. It's a sloppy kludge, but frankly, I do not // know of a better way to do this, given windows' non-atomic unlink // semantics. // // See: https://github.com/npm/node-tar/issues/183 /* c8 ignore start */ const unlinkFile = (path, cb) => { if (!isWindows) { return node_fs_1.default.unlink(path, cb); } const name = path + '.DELETE.' + (0, node_crypto_1.randomBytes)(16).toString('hex'); node_fs_1.default.rename(path, name, er => { if (er) { return cb(er); } node_fs_1.default.unlink(name, cb); }); }; /* c8 ignore stop */ /* c8 ignore start */ const unlinkFileSync = (path) => { if (!isWindows) { return node_fs_1.default.unlinkSync(path); } const name = path + '.DELETE.' + (0, node_crypto_1.randomBytes)(16).toString('hex'); node_fs_1.default.renameSync(path, name); node_fs_1.default.unlinkSync(name); }; /* c8 ignore stop */ // this.gid, entry.gid, this.processUid const uint32 = (a, b, c) => a !== undefined && a === a >>> 0 ? a : b !== undefined && b === b >>> 0 ? b : c; // clear the cache if it's a case-insensitive unicode-squashing match. // we can't know if the current file system is case-sensitive or supports // unicode fully, so we check for similarity on the maximally compatible // representation. Err on the side of pruning, since all it's doing is // preventing lstats, and it's not the end of the world if we get a false // positive. // Note that on windows, we always drop the entire cache whenever a // symbolic link is encountered, because 8.3 filenames are impossible // to reason about, and collisions are hazards rather than just failures. const cacheKeyNormalize = (path) => (0, strip_trailing_slashes_js_1.stripTrailingSlashes)((0, normalize_windows_path_js_1.normalizeWindowsPath)((0, normalize_unicode_js_1.normalizeUnicode)(path))).toLowerCase(); // remove all cache entries matching ${abs}/** const pruneCache = (cache, abs) => { abs = cacheKeyNormalize(abs); for (const path of cache.keys()) { const pnorm = cacheKeyNormalize(path); if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) { cache.delete(path); } } }; const dropCache = (cache) => { for (const key of cache.keys()) { cache.delete(key); } }; class Unpack extends parse_js_1.Parser { [ENDED] = false; [CHECKED_CWD] = false; [PENDING] = 0; reservations = new path_reservations_js_1.PathReservations(); transform; writable = true; readable = false; dirCache; uid; gid; setOwner; preserveOwner; processGid; processUid; maxDepth; forceChown; win32; newer; keep; noMtime; preservePaths; unlink; cwd; strip; processUmask; umask; dmode; fmode; chmod; constructor(opt = {}) { opt.ondone = () => { this[ENDED] = true; this[MAYBECLOSE](); }; super(opt); this.transform = opt.transform; this.dirCache = opt.dirCache || new Map(); this.chmod = !!opt.chmod; if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { // need both or neither if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') { throw new TypeError('cannot set owner without number uid and gid'); } if (opt.preserveOwner) { throw new TypeError('cannot preserve owner in archive and also set owner explicitly'); } this.uid = opt.uid; this.gid = opt.gid; this.setOwner = true; } else { this.uid = undefined; this.gid = undefined; this.setOwner = false; } // default true for root if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') { this.preserveOwner = !!(process.getuid && process.getuid() === 0); } else { this.preserveOwner = !!opt.preserveOwner; } this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : undefined; this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : undefined; // prevent excessively deep nesting of subfolders // set to `Infinity` to remove this restriction this.maxDepth = typeof opt.maxDepth === 'number' ? opt.maxDepth : DEFAULT_MAX_DEPTH; // mostly just for testing, but useful in some cases. // Forcibly trigger a chown on every entry, no matter what this.forceChown = opt.forceChown === true; // turn > this[ONENTRY](entry)); } // a bad or damaged archive is a warning for Parser, but an error // when extracting. Mark those errors as unrecoverable, because // the Unpack contract cannot be met. warn(code, msg, data = {}) { if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') { data.recoverable = false; } return super.warn(code, msg, data); } [MAYBECLOSE]() { if (this[ENDED] && this[PENDING] === 0) { this.emit('prefinish'); this.emit('finish'); this.emit('end'); } } [CHECKPATH](entry) { const p = (0, normalize_windows_path_js_1.normalizeWindowsPath)(entry.path); const parts = p.split('/'); if (this.strip) { if (parts.length < this.strip) { return false; } if (entry.type === 'Link') { const linkparts = (0, normalize_windows_path_js_1.normalizeWindowsPath)(String(entry.linkpath)).split('/'); if (linkparts.length >= this.strip) { entry.linkpath = linkparts.slice(this.strip).join('/'); } else { return false; } } parts.splice(0, this.strip); entry.path = parts.join('/'); } if (isFinite(this.maxDepth) && parts.length > this.maxDepth) { this.warn('TAR_ENTRY_ERROR', 'path excessively deep', { entry, path: p, depth: parts.length, maxDepth: this.maxDepth, }); return false; } if (!this.preservePaths) { if (parts.includes('..') || /* c8 ignore next */ (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) { this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { entry, path: p, }); return false; } // strip off the root const [root, stripped] = (0, strip_absolute_path_js_1.stripAbsolutePath)(p); if (root) { entry.path = String(stripped); this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { entry, path: p, }); } } if (node_path_1.default.isAbsolute(entry.path)) { entry.absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(entry.path)); } else { entry.absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(this.cwd, entry.path)); } // if we somehow ended up with a path that escapes the cwd, and we are // not in preservePaths mode, then something is fishy! This should have // been prevented above, so ignore this for coverage. /* c8 ignore start - defense in depth */ if (!this.preservePaths && typeof entry.absolute === 'string' && entry.absolute.indexOf(this.cwd + '/') !== 0 && entry.absolute !== this.cwd) { this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { entry, path: (0, normalize_windows_path_js_1.normalizeWindowsPath)(entry.path), resolvedPath: entry.absolute, cwd: this.cwd, }); return false; } /* c8 ignore stop */ // an archive can set properties on the extraction directory, but it // may not replace the cwd with a different kind of thing entirely. if (entry.absolute === this.cwd && entry.type !== 'Directory' && entry.type !== 'GNUDumpDir') { return false; } // only encode : chars that aren't drive letter indicators if (this.win32) { const { root: aRoot } = node_path_1.default.win32.parse(String(entry.absolute)); entry.absolute = aRoot + wc.encode(String(entry.absolute).slice(aRoot.length)); const { root: pRoot } = node_path_1.default.win32.parse(entry.path); entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length)); } return true; } [ONENTRY](entry) { if (!this[CHECKPATH](entry)) { return entry.resume(); } node_assert_1.default.equal(typeof entry.absolute, 'string'); switch (entry.type) { case 'Directory': case 'GNUDumpDir': if (entry.mode) { entry.mode = entry.mode | 0o700; } // eslint-disable-next-line no-fallthrough case 'File': case 'OldFile': case 'ContiguousFile': case 'Link': case 'SymbolicLink': return this[CHECKFS](entry); case 'CharacterDevice': case 'BlockDevice': case 'FIFO': default: return this[UNSUPPORTED](entry); } } [ONERROR](er, entry) { // Cwd has to exist, or else nothing works. That's serious. // Other errors are warnings, which raise the error in strict // mode, but otherwise continue on. if (er.name === 'CwdError') { this.emit('error', er); } else { this.warn('TAR_ENTRY_ERROR', er, { entry }); this[UNPEND](); entry.resume(); } } [MKDIR](dir, mode, cb) { (0, mkdir_js_1.mkdir)((0, normalize_windows_path_js_1.normalizeWindowsPath)(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, }, cb); } [DOCHOWN](entry) { // in preserve owner mode, chown if the entry doesn't match process // in set owner mode, chown if setting doesn't match process return (this.forceChown || (this.preserveOwner && ((typeof entry.uid === 'number' && entry.uid !== this.processUid) || (typeof entry.gid === 'number' && entry.gid !== this.processGid))) || (typeof this.uid === 'number' && this.uid !== this.processUid) || (typeof this.gid === 'number' && this.gid !== this.processGid)); } [UID](entry) { return uint32(this.uid, entry.uid, this.processUid); } [GID](entry) { return uint32(this.gid, entry.gid, this.processGid); } [FILE](entry, fullyDone) { const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.fmode; const stream = new fsm.WriteStream(String(entry.absolute), { // slight lie, but it can be numeric flags flags: (0, get_write_flag_js_1.getWriteFlag)(entry.size), mode: mode, autoClose: false, }); stream.on('error', (er) => { if (stream.fd) { node_fs_1.default.close(stream.fd, () => { }); } // flush all the data out so that we aren't left hanging // if the error wasn't actually fatal. otherwise the parse // is blocked, and we never proceed. stream.write = () => true; this[ONERROR](er, entry); fullyDone(); }); let actions = 1; const done = (er) => { if (er) { /* c8 ignore start - we should always have a fd by now */ if (stream.fd) { node_fs_1.default.close(stream.fd, () => { }); } /* c8 ignore stop */ this[ONERROR](er, entry); fullyDone(); return; } if (--actions === 0) { if (stream.fd !== undefined) { node_fs_1.default.close(stream.fd, er => { if (er) { this[ONERROR](er, entry); } else { this[UNPEND](); } fullyDone(); }); } } }; stream.on('finish', () => { // if futimes fails, try utimes // if utimes fails, fail with the original error // same for fchown/chown const abs = String(entry.absolute); const fd = stream.fd; if (typeof fd === 'number' && entry.mtime && !this.noMtime) { actions++; const atime = entry.atime || new Date(); const mtime = entry.mtime; node_fs_1.default.futimes(fd, atime, mtime, er => er ? node_fs_1.default.utimes(abs, atime, mtime, er2 => done(er2 && er)) : done()); } if (typeof fd === 'number' && this[DOCHOWN](entry)) { actions++; const uid = this[UID](entry); const gid = this[GID](entry); if (typeof uid === 'number' && typeof gid === 'number') { node_fs_1.default.fchown(fd, uid, gid, er => er ? node_fs_1.default.chown(abs, uid, gid, er2 => done(er2 && er)) : done()); } } done(); }); const tx = this.transform ? this.transform(entry) || entry : entry; if (tx !== entry) { tx.on('error', (er) => { this[ONERROR](er, entry); fullyDone(); }); entry.pipe(tx); } tx.pipe(stream); } [DIRECTORY](entry, fullyDone) { const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.dmode; this[MKDIR](String(entry.absolute), mode, er => { if (er) { this[ONERROR](er, entry); fullyDone(); return; } let actions = 1; const done = () => { if (--actions === 0) { fullyDone(); this[UNPEND](); entry.resume(); } }; if (entry.mtime && !this.noMtime) { actions++; node_fs_1.default.utimes(String(entry.absolute), entry.atime || new Date(), entry.mtime, done); } if (this[DOCHOWN](entry)) { actions++; node_fs_1.default.chown(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)), done); } done(); }); } [UNSUPPORTED](entry) { entry.unsupported = true; this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry }); entry.resume(); } [SYMLINK](entry, done) { this[LINK](entry, String(entry.linkpath), 'symlink', done); } [HARDLINK](entry, done) { const linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(this.cwd, String(entry.linkpath))); this[LINK](entry, linkpath, 'link', done); } [PEND]() { this[PENDING]++; } [UNPEND]() { this[PENDING]--; this[MAYBECLOSE](); } [SKIP](entry) { this[UNPEND](); entry.resume(); } // Check if we can reuse an existing filesystem entry safely and // overwrite it, rather than unlinking and recreating // Windows doesn't report a useful nlink, so we just never reuse entries [ISREUSABLE](entry, st) { return (entry.type === 'File' && !this.unlink && st.isFile() && st.nlink <= 1 && !isWindows); } // check if a thing is there, and if so, try to clobber it [CHECKFS](entry) { this[PEND](); const paths = [entry.path]; if (entry.linkpath) { paths.push(entry.linkpath); } this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)); } [PRUNECACHE](entry) { // if we are not creating a directory, and the path is in the dirCache, // then that means we are about to delete the directory we created // previously, and it is no longer going to be a directory, and neither // is any of its children. // If a symbolic link is encountered, all bets are off. There is no // reasonable way to sanitize the cache in such a way we will be able to // avoid having filesystem collisions. If this happens with a non-symlink // entry, it'll just fail to unpack, but a symlink to a directory, using an // 8.3 shortname or certain unicode attacks, can evade detection and lead // to arbitrary writes to anywhere on the system. if (entry.type === 'SymbolicLink') { dropCache(this.dirCache); } else if (entry.type !== 'Directory') { pruneCache(this.dirCache, String(entry.absolute)); } } [CHECKFS2](entry, fullyDone) { this[PRUNECACHE](entry); const done = (er) => { this[PRUNECACHE](entry); fullyDone(er); }; const checkCwd = () => { this[MKDIR](this.cwd, this.dmode, er => { if (er) { this[ONERROR](er, entry); done(); return; } this[CHECKED_CWD] = true; start(); }); }; const start = () => { if (entry.absolute !== this.cwd) { const parent = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.dirname(String(entry.absolute))); if (parent !== this.cwd) { return this[MKDIR](parent, this.dmode, er => { if (er) { this[ONERROR](er, entry); done(); return; } afterMakeParent(); }); } } afterMakeParent(); }; const afterMakeParent = () => { node_fs_1.default.lstat(String(entry.absolute), (lstatEr, st) => { if (st && (this.keep || /* c8 ignore next */ (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) { this[SKIP](entry); done(); return; } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry, done); } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = this.chmod && entry.mode && (st.mode & 0o7777) !== entry.mode; const afterChmod = (er) => this[MAKEFS](er ?? null, entry, done); if (!needChmod) { return afterChmod(); } return node_fs_1.default.chmod(String(entry.absolute), Number(entry.mode), afterChmod); } // Not a dir entry, have to remove it. // NB: the only way to end up with an entry that is the cwd // itself, in such a way that == does not detect, is a // tricky windows absolute path with UNC or 8.3 parts (and // preservePaths:true, or else it will have been stripped). // In that case, the user has opted out of path protections // explicitly, so if they blow away the cwd, c'est la vie. if (entry.absolute !== this.cwd) { return node_fs_1.default.rmdir(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done)); } } // not a dir, and not reusable // don't remove if the cwd, we want that error if (entry.absolute === this.cwd) { return this[MAKEFS](null, entry, done); } unlinkFile(String(entry.absolute), er => this[MAKEFS](er ?? null, entry, done)); }); }; if (this[CHECKED_CWD]) { start(); } else { checkCwd(); } } [MAKEFS](er, entry, done) { if (er) { this[ONERROR](er, entry); done(); return; } switch (entry.type) { case 'File': case 'OldFile': case 'ContiguousFile': return this[FILE](entry, done); case 'Link': return this[HARDLINK](entry, done); case 'SymbolicLink': return this[SYMLINK](entry, done); case 'Directory': case 'GNUDumpDir': return this[DIRECTORY](entry, done); } } [LINK](entry, linkpath, link, done) { // XXX: get the type ('symlink' or 'junction') for windows node_fs_1.default[link](linkpath, String(entry.absolute), er => { if (er) { this[ONERROR](er, entry); } else { this[UNPEND](); entry.resume(); } done(); }); } } exports.Unpack = Unpack; const callSync = (fn) => { try { return [null, fn()]; } catch (er) { return [er, null]; } }; class UnpackSync extends Unpack { sync = true; [MAKEFS](er, entry) { return super[MAKEFS](er, entry, () => { }); } [CHECKFS](entry) { this[PRUNECACHE](entry); if (!this[CHECKED_CWD]) { const er = this[MKDIR](this.cwd, this.dmode); if (er) { return this[ONERROR](er, entry); } this[CHECKED_CWD] = true; } // don't bother to make the parent if the current entry is the cwd, // we've already checked it. if (entry.absolute !== this.cwd) { const parent = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.dirname(String(entry.absolute))); if (parent !== this.cwd) { const mkParent = this[MKDIR](parent, this.dmode); if (mkParent) { return this[ONERROR](mkParent, entry); } } } const [lstatEr, st] = callSync(() => node_fs_1.default.lstatSync(String(entry.absolute))); if (st && (this.keep || /* c8 ignore next */ (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) { return this[SKIP](entry); } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry); } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = this.chmod && entry.mode && (st.mode & 0o7777) !== entry.mode; const [er] = needChmod ? callSync(() => { node_fs_1.default.chmodSync(String(entry.absolute), Number(entry.mode)); }) : []; return this[MAKEFS](er, entry); } // not a dir entry, have to remove it const [er] = callSync(() => node_fs_1.default.rmdirSync(String(entry.absolute))); this[MAKEFS](er, entry); } // not a dir, and not reusable. // don't remove if it's the cwd, since we want that error. const [er] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(String(entry.absolute))); this[MAKEFS](er, entry); } [FILE](entry, done) { const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.fmode; const oner = (er) => { let closeError; try { node_fs_1.default.closeSync(fd); } catch (e) { closeError = e; } if (er || closeError) { this[ONERROR](er || closeError, entry); } done(); }; let fd; try { fd = node_fs_1.default.openSync(String(entry.absolute), (0, get_write_flag_js_1.getWriteFlag)(entry.size), mode); } catch (er) { return oner(er); } const tx = this.transform ? this.transform(entry) || entry : entry; if (tx !== entry) { tx.on('error', (er) => this[ONERROR](er, entry)); entry.pipe(tx); } tx.on('data', (chunk) => { try { node_fs_1.default.writeSync(fd, chunk, 0, chunk.length); } catch (er) { oner(er); } }); tx.on('end', () => { let er = null; // try both, falling futimes back to utimes // if either fails, handle the first error if (entry.mtime && !this.noMtime) { const atime = entry.atime || new Date(); const mtime = entry.mtime; try { node_fs_1.default.futimesSync(fd, atime, mtime); } catch (futimeser) { try { node_fs_1.default.utimesSync(String(entry.absolute), atime, mtime); } catch (utimeser) { er = futimeser; } } } if (this[DOCHOWN](entry)) { const uid = this[UID](entry); const gid = this[GID](entry); try { node_fs_1.default.fchownSync(fd, Number(uid), Number(gid)); } catch (fchowner) { try { node_fs_1.default.chownSync(String(entry.absolute), Number(uid), Number(gid)); } catch (chowner) { er = er || fchowner; } } } oner(er); }); } [DIRECTORY](entry, done) { const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.dmode; const er = this[MKDIR](String(entry.absolute), mode); if (er) { this[ONERROR](er, entry); done(); return; } if (entry.mtime && !this.noMtime) { try { node_fs_1.default.utimesSync(String(entry.absolute), entry.atime || new Date(), entry.mtime); /* c8 ignore next */ } catch (er) { } } if (this[DOCHOWN](entry)) { try { node_fs_1.default.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry))); } catch (er) { } } done(); entry.resume(); } [MKDIR](dir, mode) { try { return (0, mkdir_js_1.mkdirSync)((0, normalize_windows_path_js_1.normalizeWindowsPath)(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, }); } catch (er) { return er; } } [LINK](entry, linkpath, link, done) { const ls = `${link}Sync`; try { node_fs_1.default[ls](linkpath, String(entry.absolute)); done(); entry.resume(); } catch (er) { return this[ONERROR](er, entry); } } } exports.UnpackSync = UnpackSync; //# sourceMappingURL=unpack.js.map"use strict"; // tar -u Object.defineProperty(exports, "__esModule", { value: true }); exports.update = void 0; const make_command_js_1 = require("./make-command.js"); const replace_js_1 = require("./replace.js"); // just call tar.r with the filter and mtimeCache exports.update = (0, make_command_js_1.makeCommand)(replace_js_1.replace.syncFile, replace_js_1.replace.asyncFile, replace_js_1.replace.syncNoFile, replace_js_1.replace.asyncNoFile, (opt, entries = []) => { replace_js_1.replace.validate?.(opt, entries); mtimeFilter(opt); }); const mtimeFilter = (opt) => { const filter = opt.filter; if (!opt.mtimeCache) { opt.mtimeCache = new Map(); } opt.filter = filter ? (path, stat) => filter(path, stat) && !( /* c8 ignore start */ ((opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) > (stat.mtime ?? 0)) /* c8 ignore stop */ ) : (path, stat) => !( /* c8 ignore start */ ((opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) > (stat.mtime ?? 0)) /* c8 ignore stop */ ); }; //# sourceMappingURL=update.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.warnMethod = void 0; const warnMethod = (self, code, message, data = {}) => { if (self.file) { data.file = self.file; } if (self.cwd) { data.cwd = self.cwd; } data.code = (message instanceof Error && message.code) || code; data.tarCode = code; if (!self.strict && data.recoverable !== false) { if (message instanceof Error) { data = Object.assign(message, data); message = message.message; } self.emit('warn', code, message, data); } else if (message instanceof Error) { self.emit('error', Object.assign(message, data)); } else { self.emit('error', Object.assign(new Error(`${code}: ${message}`), data)); } }; exports.warnMethod = warnMethod; //# sourceMappingURL=warn-method.js.map"use strict"; // When writing files on Windows, translate the characters to their // 0xf000 higher-encoded versions. Object.defineProperty(exports, "__esModule", { value: true }); exports.decode = exports.encode = void 0; const raw = ['|', '<', '>', '?', ':']; const win = raw.map(char => String.fromCharCode(0xf000 + char.charCodeAt(0))); const toWin = new Map(raw.map((char, i) => [char, win[i]])); const toRaw = new Map(win.map((char, i) => [char, raw[i]])); const encode = (s) => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s); exports.encode = encode; const decode = (s) => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s); exports.decode = decode; //# sourceMappingURL=winchars.js.map"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WriteEntryTar = exports.WriteEntrySync = exports.WriteEntry = void 0; const fs_1 = __importDefault(require("fs")); const minipass_1 = require("minipass"); const path_1 = __importDefault(require("path")); const header_js_1 = require("./header.js"); const mode_fix_js_1 = require("./mode-fix.js"); const normalize_windows_path_js_1 = require("./normalize-windows-path.js"); const options_js_1 = require("./options.js"); const pax_js_1 = require("./pax.js"); const strip_absolute_path_js_1 = require("./strip-absolute-path.js"); const strip_trailing_slashes_js_1 = require("./strip-trailing-slashes.js"); const warn_method_js_1 = require("./warn-method.js"); const winchars = __importStar(require("./winchars.js")); const prefixPath = (path, prefix) => { if (!prefix) { return (0, normalize_windows_path_js_1.normalizeWindowsPath)(path); } path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(path).replace(/^\.(\/|$)/, ''); return (0, strip_trailing_slashes_js_1.stripTrailingSlashes)(prefix) + '/' + path; }; const maxReadSize = 16 * 1024 * 1024; const PROCESS = Symbol('process'); const FILE = Symbol('file'); const DIRECTORY = Symbol('directory'); const SYMLINK = Symbol('symlink'); const HARDLINK = Symbol('hardlink'); const HEADER = Symbol('header'); const READ = Symbol('read'); const LSTAT = Symbol('lstat'); const ONLSTAT = Symbol('onlstat'); const ONREAD = Symbol('onread'); const ONREADLINK = Symbol('onreadlink'); const OPENFILE = Symbol('openfile'); const ONOPENFILE = Symbol('onopenfile'); const CLOSE = Symbol('close'); const MODE = Symbol('mode'); const AWAITDRAIN = Symbol('awaitDrain'); const ONDRAIN = Symbol('ondrain'); const PREFIX = Symbol('prefix'); class WriteEntry extends minipass_1.Minipass { path; portable; myuid = (process.getuid && process.getuid()) || 0; // until node has builtin pwnam functions, this'll have to do myuser = process.env.USER || ''; maxReadSize; linkCache; statCache; preservePaths; cwd; strict; mtime; noPax; noMtime; prefix; fd; blockLen = 0; blockRemain = 0; buf; pos = 0; remain = 0; length = 0; offset = 0; win32; absolute; header; type; linkpath; stat; onWriteEntry; #hadError = false; constructor(p, opt_ = {}) { const opt = (0, options_js_1.dealias)(opt_); super(); this.path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(p); // suppress atime, ctime, uid, gid, uname, gname this.portable = !!opt.portable; this.maxReadSize = opt.maxReadSize || maxReadSize; this.linkCache = opt.linkCache || new Map(); this.statCache = opt.statCache || new Map(); this.preservePaths = !!opt.preservePaths; this.cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.cwd || process.cwd()); this.strict = !!opt.strict; this.noPax = !!opt.noPax; this.noMtime = !!opt.noMtime; this.mtime = opt.mtime; this.prefix = opt.prefix ? (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.prefix) : undefined; this.onWriteEntry = opt.onWriteEntry; if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn); } let pathWarn = false; if (!this.preservePaths) { const [root, stripped] = (0, strip_absolute_path_js_1.stripAbsolutePath)(this.path); if (root && typeof stripped === 'string') { this.path = stripped; pathWarn = root; } } this.win32 = !!opt.win32 || process.platform === 'win32'; if (this.win32) { // force the \ to / normalization, since we might not *actually* // be on windows, but want \ to be considered a path separator. this.path = winchars.decode(this.path.replace(/\\/g, '/')); p = p.replace(/\\/g, '/'); } this.absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.absolute || path_1.default.resolve(this.cwd, p)); if (this.path === '') { this.path = './'; } if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }); } const cs = this.statCache.get(this.absolute); if (cs) { this[ONLSTAT](cs); } else { this[LSTAT](); } } warn(code, message, data = {}) { return (0, warn_method_js_1.warnMethod)(this, code, message, data); } emit(ev, ...data) { if (ev === 'error') { this.#hadError = true; } return super.emit(ev, ...data); } [LSTAT]() { fs_1.default.lstat(this.absolute, (er, stat) => { if (er) { return this.emit('error', er); } this[ONLSTAT](stat); }); } [ONLSTAT](stat) { this.statCache.set(this.absolute, stat); this.stat = stat; if (!stat.isFile()) { stat.size = 0; } this.type = getType(stat); this.emit('stat', stat); this[PROCESS](); } [PROCESS]() { switch (this.type) { case 'File': return this[FILE](); case 'Directory': return this[DIRECTORY](); case 'SymbolicLink': return this[SYMLINK](); // unsupported types are ignored. default: return this.end(); } } [MODE](mode) { return (0, mode_fix_js_1.modeFix)(mode, this.type === 'Directory', this.portable); } [PREFIX](path) { return prefixPath(path, this.prefix); } [HEADER]() { /* c8 ignore start */ if (!this.stat) { throw new Error('cannot write header before stat'); } /* c8 ignore stop */ if (this.type === 'Directory' && this.portable) { this.noMtime = true; } this.onWriteEntry?.(this); this.header = new header_js_1.Header({ path: this[PREFIX](this.path), // only apply the prefix to hard links. linkpath: this.type === 'Link' && this.linkpath !== undefined ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this[MODE](this.stat.mode), uid: this.portable ? undefined : this.stat.uid, gid: this.portable ? undefined : this.stat.gid, size: this.stat.size, mtime: this.noMtime ? undefined : this.mtime || this.stat.mtime, /* c8 ignore next */ type: this.type === 'Unsupported' ? undefined : this.type, uname: this.portable ? undefined : this.stat.uid === this.myuid ? this.myuser : '', atime: this.portable ? undefined : this.stat.atime, ctime: this.portable ? undefined : this.stat.ctime, }); if (this.header.encode() && !this.noPax) { super.write(new pax_js_1.Pax({ atime: this.portable ? undefined : this.header.atime, ctime: this.portable ? undefined : this.header.ctime, gid: this.portable ? undefined : this.header.gid, mtime: this.noMtime ? undefined : (this.mtime || this.header.mtime), path: this[PREFIX](this.path), linkpath: this.type === 'Link' && this.linkpath !== undefined ? this[PREFIX](this.linkpath) : this.linkpath, size: this.header.size, uid: this.portable ? undefined : this.header.uid, uname: this.portable ? undefined : this.header.uname, dev: this.portable ? undefined : this.stat.dev, ino: this.portable ? undefined : this.stat.ino, nlink: this.portable ? undefined : this.stat.nlink, }).encode()); } const block = this.header?.block; /* c8 ignore start */ if (!block) { throw new Error('failed to encode header'); } /* c8 ignore stop */ super.write(block); } [DIRECTORY]() { /* c8 ignore start */ if (!this.stat) { throw new Error('cannot create directory entry without stat'); } /* c8 ignore stop */ if (this.path.slice(-1) !== '/') { this.path += '/'; } this.stat.size = 0; this[HEADER](); this.end(); } [SYMLINK]() { fs_1.default.readlink(this.absolute, (er, linkpath) => { if (er) { return this.emit('error', er); } this[ONREADLINK](linkpath); }); } [ONREADLINK](linkpath) { this.linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(linkpath); this[HEADER](); this.end(); } [HARDLINK](linkpath) { /* c8 ignore start */ if (!this.stat) { throw new Error('cannot create link entry without stat'); } /* c8 ignore stop */ this.type = 'Link'; this.linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(path_1.default.relative(this.cwd, linkpath)); this.stat.size = 0; this[HEADER](); this.end(); } [FILE]() { /* c8 ignore start */ if (!this.stat) { throw new Error('cannot create file entry without stat'); } /* c8 ignore stop */ if (this.stat.nlink > 1) { const linkKey = `${this.stat.dev}:${this.stat.ino}`; const linkpath = this.linkCache.get(linkKey); if (linkpath?.indexOf(this.cwd) === 0) { return this[HARDLINK](linkpath); } this.linkCache.set(linkKey, this.absolute); } this[HEADER](); if (this.stat.size === 0) { return this.end(); } this[OPENFILE](); } [OPENFILE]() { fs_1.default.open(this.absolute, 'r', (er, fd) => { if (er) { return this.emit('error', er); } this[ONOPENFILE](fd); }); } [ONOPENFILE](fd) { this.fd = fd; if (this.#hadError) { return this[CLOSE](); } /* c8 ignore start */ if (!this.stat) { throw new Error('should stat before calling onopenfile'); } /* c8 ignore start */ this.blockLen = 512 * Math.ceil(this.stat.size / 512); this.blockRemain = this.blockLen; const bufLen = Math.min(this.blockLen, this.maxReadSize); this.buf = Buffer.allocUnsafe(bufLen); this.offset = 0; this.pos = 0; this.remain = this.stat.size; this.length = this.buf.length; this[READ](); } [READ]() { const { fd, buf, offset, length, pos } = this; if (fd === undefined || buf === undefined) { throw new Error('cannot read file without first opening'); } fs_1.default.read(fd, buf, offset, length, pos, (er, bytesRead) => { if (er) { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one return this[CLOSE](() => this.emit('error', er)); } this[ONREAD](bytesRead); }); } /* c8 ignore start */ [CLOSE](cb = () => { }) { /* c8 ignore stop */ if (this.fd !== undefined) fs_1.default.close(this.fd, cb); } [ONREAD](bytesRead) { if (bytesRead <= 0 && this.remain > 0) { const er = Object.assign(new Error('encountered unexpected EOF'), { path: this.absolute, syscall: 'read', code: 'EOF', }); return this[CLOSE](() => this.emit('error', er)); } if (bytesRead > this.remain) { const er = Object.assign(new Error('did not encounter expected EOF'), { path: this.absolute, syscall: 'read', code: 'EOF', }); return this[CLOSE](() => this.emit('error', er)); } /* c8 ignore start */ if (!this.buf) { throw new Error('should have created buffer prior to reading'); } /* c8 ignore stop */ // null out the rest of the buffer, if we could fit the block padding // at the end of this loop, we've incremented bytesRead and this.remain // to be incremented up to the blockRemain level, as if we had expected // to get a null-padded file, and read it until the end. then we will // decrement both remain and blockRemain by bytesRead, and know that we // reached the expected EOF, without any null buffer to append. if (bytesRead === this.remain) { for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { this.buf[i + this.offset] = 0; bytesRead++; this.remain++; } } const chunk = this.offset === 0 && bytesRead === this.buf.length ? this.buf : this.buf.subarray(this.offset, this.offset + bytesRead); const flushed = this.write(chunk); if (!flushed) { this[AWAITDRAIN](() => this[ONDRAIN]()); } else { this[ONDRAIN](); } } [AWAITDRAIN](cb) { this.once('drain', cb); } write(chunk, encoding, cb) { /* c8 ignore start - just junk to comply with NodeJS.WritableStream */ if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8'); } /* c8 ignore stop */ if (this.blockRemain < chunk.length) { const er = Object.assign(new Error('writing more data than expected'), { path: this.absolute, }); return this.emit('error', er); } this.remain -= chunk.length; this.blockRemain -= chunk.length; this.pos += chunk.length; this.offset += chunk.length; return super.write(chunk, null, cb); } [ONDRAIN]() { if (!this.remain) { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)); } return this[CLOSE](er => er ? this.emit('error', er) : this.end()); } /* c8 ignore start */ if (!this.buf) { throw new Error('buffer lost somehow in ONDRAIN'); } /* c8 ignore stop */ if (this.offset >= this.length) { // if we only have a smaller bit left to read, alloc a smaller buffer // otherwise, keep it the same length it was before. this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)); this.offset = 0; } this.length = this.buf.length - this.offset; this[READ](); } } exports.WriteEntry = WriteEntry; class WriteEntrySync extends WriteEntry { sync = true; [LSTAT]() { this[ONLSTAT](fs_1.default.lstatSync(this.absolute)); } [SYMLINK]() { this[ONREADLINK](fs_1.default.readlinkSync(this.absolute)); } [OPENFILE]() { this[ONOPENFILE](fs_1.default.openSync(this.absolute, 'r')); } [READ]() { let threw = true; try { const { fd, buf, offset, length, pos } = this; /* c8 ignore start */ if (fd === undefined || buf === undefined) { throw new Error('fd and buf must be set in READ method'); } /* c8 ignore stop */ const bytesRead = fs_1.default.readSync(fd, buf, offset, length, pos); this[ONREAD](bytesRead); threw = false; } finally { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one if (threw) { try { this[CLOSE](() => { }); } catch (er) { } } } } [AWAITDRAIN](cb) { cb(); } /* c8 ignore start */ [CLOSE](cb = () => { }) { /* c8 ignore stop */ if (this.fd !== undefined) fs_1.default.closeSync(this.fd); cb(); } } exports.WriteEntrySync = WriteEntrySync; class WriteEntryTar extends minipass_1.Minipass { blockLen = 0; blockRemain = 0; buf = 0; pos = 0; remain = 0; length = 0; preservePaths; portable; strict; noPax; noMtime; readEntry; type; prefix; path; mode; uid; gid; uname; gname; header; mtime; atime; ctime; linkpath; size; onWriteEntry; warn(code, message, data = {}) { return (0, warn_method_js_1.warnMethod)(this, code, message, data); } constructor(readEntry, opt_ = {}) { const opt = (0, options_js_1.dealias)(opt_); super(); this.preservePaths = !!opt.preservePaths; this.portable = !!opt.portable; this.strict = !!opt.strict; this.noPax = !!opt.noPax; this.noMtime = !!opt.noMtime; this.onWriteEntry = opt.onWriteEntry; this.readEntry = readEntry; const { type } = readEntry; /* c8 ignore start */ if (type === 'Unsupported') { throw new Error('writing entry that should be ignored'); } /* c8 ignore stop */ this.type = type; if (this.type === 'Directory' && this.portable) { this.noMtime = true; } this.prefix = opt.prefix; this.path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(readEntry.path); this.mode = readEntry.mode !== undefined ? this[MODE](readEntry.mode) : undefined; this.uid = this.portable ? undefined : readEntry.uid; this.gid = this.portable ? undefined : readEntry.gid; this.uname = this.portable ? undefined : readEntry.uname; this.gname = this.portable ? undefined : readEntry.gname; this.size = readEntry.size; this.mtime = this.noMtime ? undefined : opt.mtime || readEntry.mtime; this.atime = this.portable ? undefined : readEntry.atime; this.ctime = this.portable ? undefined : readEntry.ctime; this.linkpath = readEntry.linkpath !== undefined ? (0, normalize_windows_path_js_1.normalizeWindowsPath)(readEntry.linkpath) : undefined; if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn); } let pathWarn = false; if (!this.preservePaths) { const [root, stripped] = (0, strip_absolute_path_js_1.stripAbsolutePath)(this.path); if (root && typeof stripped === 'string') { this.path = stripped; pathWarn = root; } } this.remain = readEntry.size; this.blockRemain = readEntry.startBlockSize; this.onWriteEntry?.(this); this.header = new header_js_1.Header({ path: this[PREFIX](this.path), linkpath: this.type === 'Link' && this.linkpath !== undefined ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this.mode, uid: this.portable ? undefined : this.uid, gid: this.portable ? undefined : this.gid, size: this.size, mtime: this.noMtime ? undefined : this.mtime, type: this.type, uname: this.portable ? undefined : this.uname, atime: this.portable ? undefined : this.atime, ctime: this.portable ? undefined : this.ctime, }); if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }); } if (this.header.encode() && !this.noPax) { super.write(new pax_js_1.Pax({ atime: this.portable ? undefined : this.atime, ctime: this.portable ? undefined : this.ctime, gid: this.portable ? undefined : this.gid, mtime: this.noMtime ? undefined : this.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' && this.linkpath !== undefined ? this[PREFIX](this.linkpath) : this.linkpath, size: this.size, uid: this.portable ? undefined : this.uid, uname: this.portable ? undefined : this.uname, dev: this.portable ? undefined : this.readEntry.dev, ino: this.portable ? undefined : this.readEntry.ino, nlink: this.portable ? undefined : this.readEntry.nlink, }).encode()); } const b = this.header?.block; /* c8 ignore start */ if (!b) throw new Error('failed to encode header'); /* c8 ignore stop */ super.write(b); readEntry.pipe(this); } [PREFIX](path) { return prefixPath(path, this.prefix); } [MODE](mode) { return (0, mode_fix_js_1.modeFix)(mode, this.type === 'Directory', this.portable); } write(chunk, encoding, cb) { /* c8 ignore start - just junk to comply with NodeJS.WritableStream */ if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8'); } /* c8 ignore stop */ const writeLen = chunk.length; if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate'); } this.blockRemain -= writeLen; return super.write(chunk, cb); } end(chunk, encoding, cb) { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)); } /* c8 ignore start - just junk to comply with NodeJS.WritableStream */ if (typeof chunk === 'function') { cb = chunk; encoding = undefined; chunk = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding ?? 'utf8'); } if (cb) this.once('finish', cb); chunk ? super.end(chunk, cb) : super.end(cb); /* c8 ignore stop */ return this; } } exports.WriteEntryTar = WriteEntryTar; const getType = (stat) => stat.isFile() ? 'File' : stat.isDirectory() ? 'Directory' : stat.isSymbolicLink() ? 'SymbolicLink' : 'Unsupported'; //# sourceMappingURL=write-entry.js.mapimport { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass'; import path from 'node:path'; import { list } from './list.js'; import { makeCommand } from './make-command.js'; import { Pack, PackSync } from './pack.js'; const createFileSync = (opt, files) => { const p = new PackSync(opt); const stream = new WriteStreamSync(opt.file, { mode: opt.mode || 0o666, }); p.pipe(stream); addFilesSync(p, files); }; const createFile = (opt, files) => { const p = new Pack(opt); const stream = new WriteStream(opt.file, { mode: opt.mode || 0o666, }); p.pipe(stream); const promise = new Promise((res, rej) => { stream.on('error', rej); stream.on('close', res); p.on('error', rej); }); addFilesAsync(p, files); return promise; }; const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { list({ file: path.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onReadEntry: entry => p.add(entry), }); } else { p.add(file); } }); p.end(); }; const addFilesAsync = async (p, files) => { for (let i = 0; i < files.length; i++) { const file = String(files[i]); if (file.charAt(0) === '@') { await list({ file: path.resolve(String(p.cwd), file.slice(1)), noResume: true, onReadEntry: entry => { p.add(entry); }, }); } else { p.add(file); } } p.end(); }; const createSync = (opt, files) => { const p = new PackSync(opt); addFilesSync(p, files); return p; }; const createAsync = (opt, files) => { const p = new Pack(opt); addFilesAsync(p, files); return p; }; export const create = makeCommand(createFileSync, createFile, createSync, createAsync, (_opt, files) => { if (!files?.length) { throw new TypeError('no paths specified to add to archive'); } }); //# sourceMappingURL=create.js.mapexport class CwdError extends Error { path; code; syscall = 'chdir'; constructor(path, code) { super(`${code}: Cannot cd into '${path}'`); this.path = path; this.code = code; } get name() { return 'CwdError'; } } //# sourceMappingURL=cwd-error.js.map// tar -x import * as fsm from '@isaacs/fs-minipass'; import fs from 'node:fs'; import { filesFilter } from './list.js'; import { makeCommand } from './make-command.js'; import { Unpack, UnpackSync } from './unpack.js'; const extractFileSync = (opt) => { const u = new UnpackSync(opt); const file = opt.file; const stat = fs.statSync(file); // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation const readSize = opt.maxReadSize || 16 * 1024 * 1024; const stream = new fsm.ReadStreamSync(file, { readSize: readSize, size: stat.size, }); stream.pipe(u); }; const extractFile = (opt, _) => { const u = new Unpack(opt); const readSize = opt.maxReadSize || 16 * 1024 * 1024; const file = opt.file; const p = new Promise((resolve, reject) => { u.on('error', reject); u.on('close', resolve); // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation fs.stat(file, (er, stat) => { if (er) { reject(er); } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }); stream.on('error', reject); stream.pipe(u); } }); }); return p; }; export const extract = makeCommand(extractFileSync, extractFile, opt => new UnpackSync(opt), opt => new Unpack(opt), (opt, files) => { if (files?.length) filesFilter(opt, files); }); //# sourceMappingURL=extract.js.map// Get the appropriate flag to use for creating files // We use fmap on Windows platforms for files less than // 512kb. This is a fairly low limit, but avoids making // things slower in some cases. Since most of what this // library is used for is extracting tarballs of many // relatively small files in npm packages and the like, // it can be a big boost on Windows platforms. import fs from 'fs'; const platform = process.env.__FAKE_PLATFORM__ || process.platform; const isWindows = platform === 'win32'; /* c8 ignore start */ const { O_CREAT, O_TRUNC, O_WRONLY } = fs.constants; const UV_FS_O_FILEMAP = Number(process.env.__FAKE_FS_O_FILENAME__) || fs.constants.UV_FS_O_FILEMAP || 0; /* c8 ignore stop */ const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP; const fMapLimit = 512 * 1024; const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY; export const getWriteFlag = !fMapEnabled ? () => 'w' : (size) => (size < fMapLimit ? fMapFlag : 'w'); //# sourceMappingURL=get-write-flag.js.map// parse a 512-byte header block to a data object, or vice-versa // encode returns `true` if a pax extended header is needed, because // the data could not be faithfully encoded in a simple header. // (Also, check header.needPax to see if it needs a pax header.) import { posix as pathModule } from 'node:path'; import * as large from './large-numbers.js'; import * as types from './types.js'; export class Header { cksumValid = false; needPax = false; nullBlock = false; block; path; mode; uid; gid; size; cksum; #type = 'Unsupported'; linkpath; uname; gname; devmaj = 0; devmin = 0; atime; ctime; mtime; charset; comment; constructor(data, off = 0, ex, gex) { if (Buffer.isBuffer(data)) { this.decode(data, off || 0, ex, gex); } else if (data) { this.#slurp(data); } } decode(buf, off, ex, gex) { if (!off) { off = 0; } if (!buf || !(buf.length >= off + 512)) { throw new Error('need 512 bytes for header'); } this.path = decString(buf, off, 100); this.mode = decNumber(buf, off + 100, 8); this.uid = decNumber(buf, off + 108, 8); this.gid = decNumber(buf, off + 116, 8); this.size = decNumber(buf, off + 124, 12); this.mtime = decDate(buf, off + 136, 12); this.cksum = decNumber(buf, off + 148, 12); // if we have extended or global extended headers, apply them now // See https://github.com/npm/node-tar/pull/187 // Apply global before local, so it overrides if (gex) this.#slurp(gex, true); if (ex) this.#slurp(ex); // old tar versions marked dirs as a file with a trailing / const t = decString(buf, off + 156, 1); if (types.isCode(t)) { this.#type = t || '0'; } if (this.#type === '0' && this.path.slice(-1) === '/') { this.#type = '5'; } // tar implementations sometimes incorrectly put the stat(dir).size // as the size in the tarball, even though Directory entries are // not able to have any body at all. In the very rare chance that // it actually DOES have a body, we weren't going to do anything with // it anyway, and it'll just be a warning about an invalid header. if (this.#type === '5') { this.size = 0; } this.linkpath = decString(buf, off + 157, 100); if (buf.subarray(off + 257, off + 265).toString() === 'ustar\u000000') { this.uname = decString(buf, off + 265, 32); this.gname = decString(buf, off + 297, 32); /* c8 ignore start */ this.devmaj = decNumber(buf, off + 329, 8) ?? 0; this.devmin = decNumber(buf, off + 337, 8) ?? 0; /* c8 ignore stop */ if (buf[off + 475] !== 0) { // definitely a prefix, definitely >130 chars. const prefix = decString(buf, off + 345, 155); this.path = prefix + '/' + this.path; } else { const prefix = decString(buf, off + 345, 130); if (prefix) { this.path = prefix + '/' + this.path; } this.atime = decDate(buf, off + 476, 12); this.ctime = decDate(buf, off + 488, 12); } } let sum = 8 * 0x20; for (let i = off; i < off + 148; i++) { sum += buf[i]; } for (let i = off + 156; i < off + 512; i++) { sum += buf[i]; } this.cksumValid = sum === this.cksum; if (this.cksum === undefined && sum === 8 * 0x20) { this.nullBlock = true; } } #slurp(ex, gex = false) { Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. Also, any // null/undefined values are ignored. return !(v === null || v === undefined || (k === 'path' && gex) || (k === 'linkpath' && gex) || k === 'global'); }))); } encode(buf, off = 0) { if (!buf) { buf = this.block = Buffer.alloc(512); } if (this.#type === 'Unsupported') { this.#type = '0'; } if (!(buf.length >= off + 512)) { throw new Error('need 512 bytes for header'); } const prefixSize = this.ctime || this.atime ? 130 : 155; const split = splitPrefix(this.path || '', prefixSize); const path = split[0]; const prefix = split[1]; this.needPax = !!split[2]; this.needPax = encString(buf, off, 100, path) || this.needPax; this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax; this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax; this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax; this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax; this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax; buf[off + 156] = this.#type.charCodeAt(0); this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax; buf.write('ustar\u000000', off + 257, 8); this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax; this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax; this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax; this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax; this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax; if (buf[off + 475] !== 0) { this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax; } else { this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax; this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax; this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax; } let sum = 8 * 0x20; for (let i = off; i < off + 148; i++) { sum += buf[i]; } for (let i = off + 156; i < off + 512; i++) { sum += buf[i]; } this.cksum = sum; encNumber(buf, off + 148, 8, this.cksum); this.cksumValid = true; return this.needPax; } get type() { return (this.#type === 'Unsupported' ? this.#type : types.name.get(this.#type)); } get typeKey() { return this.#type; } set type(type) { const c = String(types.code.get(type)); if (types.isCode(c) || c === 'Unsupported') { this.#type = c; } else if (types.isCode(type)) { this.#type = type; } else { throw new TypeError('invalid entry type: ' + type); } } } const splitPrefix = (p, prefixSize) => { const pathSize = 100; let pp = p; let prefix = ''; let ret = undefined; const root = pathModule.parse(p).root || '.'; if (Buffer.byteLength(pp) < pathSize) { ret = [pp, prefix, false]; } else { // first set prefix to the dir, and path to the base prefix = pathModule.dirname(pp); pp = pathModule.basename(pp); do { if (Buffer.byteLength(pp) <= pathSize && Buffer.byteLength(prefix) <= prefixSize) { // both fit! ret = [pp, prefix, false]; } else if (Buffer.byteLength(pp) > pathSize && Buffer.byteLength(prefix) <= prefixSize) { // prefix fits in prefix, but path doesn't fit in path ret = [pp.slice(0, pathSize - 1), prefix, true]; } else { // make path take a bit from prefix pp = pathModule.join(pathModule.basename(prefix), pp); prefix = pathModule.dirname(prefix); } } while (prefix !== root && ret === undefined); // at this point, found no resolution, just truncate if (!ret) { ret = [p.slice(0, pathSize - 1), '', true]; } } return ret; }; const decString = (buf, off, size) => buf .subarray(off, off + size) .toString('utf8') .replace(/\0.*/, ''); const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size)); const numToDate = (num) => num === undefined ? undefined : new Date(num * 1000); const decNumber = (buf, off, size) => Number(buf[off]) & 0x80 ? large.parse(buf.subarray(off, off + size)) : decSmallNumber(buf, off, size); const nanUndef = (value) => (isNaN(value) ? undefined : value); const decSmallNumber = (buf, off, size) => nanUndef(parseInt(buf .subarray(off, off + size) .toString('utf8') .replace(/\0.*$/, '') .trim(), 8)); // the maximum encodable as a null-terminated octal, by field size const MAXNUM = { 12: 0o77777777777, 8: 0o7777777, }; const encNumber = (buf, off, size, num) => num === undefined ? false : num > MAXNUM[size] || num < 0 ? (large.encode(num, buf.subarray(off, off + size)), true) : (encSmallNumber(buf, off, size, num), false); const encSmallNumber = (buf, off, size, num) => buf.write(octalString(num, size), off, size, 'ascii'); const octalString = (num, size) => padOctal(Math.floor(num).toString(8), size); const padOctal = (str, size) => (str.length === size - 1 ? str : new Array(size - str.length - 1).join('0') + str + ' ') + '\0'; const encDate = (buf, off, size, date) => date === undefined ? false : (encNumber(buf, off, size, date.getTime() / 1000)); // enough to fill the longest string we've got const NULLS = new Array(156).join('\0'); // pad with nulls, return true if it's longer or non-ascii const encString = (buf, off, size, str) => str === undefined ? false : ((buf.write(str + NULLS, off, size, 'utf8'), str.length !== Buffer.byteLength(str) || str.length > size)); //# sourceMappingURL=header.js.mapexport * from './create.js'; export { create as c } from './create.js'; export * from './extract.js'; export { extract as x } from './extract.js'; export * from './header.js'; export * from './list.js'; export { list as t } from './list.js'; // classes export * from './pack.js'; export * from './parse.js'; export * from './pax.js'; export * from './read-entry.js'; export * from './replace.js'; export { replace as r } from './replace.js'; export * as types from './types.js'; export * from './unpack.js'; export * from './update.js'; export { update as u } from './update.js'; export * from './write-entry.js'; //# sourceMappingURL=index.js.map// Tar can encode large and negative numbers using a leading byte of // 0xff for negative, and 0x80 for positive. export const encode = (num, buf) => { if (!Number.isSafeInteger(num)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('cannot encode number outside of javascript safe integer range'); } else if (num < 0) { encodeNegative(num, buf); } else { encodePositive(num, buf); } return buf; }; const encodePositive = (num, buf) => { buf[0] = 0x80; for (var i = buf.length; i > 1; i--) { buf[i - 1] = num & 0xff; num = Math.floor(num / 0x100); } }; const encodeNegative = (num, buf) => { buf[0] = 0xff; var flipped = false; num = num * -1; for (var i = buf.length; i > 1; i--) { var byte = num & 0xff; num = Math.floor(num / 0x100); if (flipped) { buf[i - 1] = onesComp(byte); } else if (byte === 0) { buf[i - 1] = 0; } else { flipped = true; buf[i - 1] = twosComp(byte); } } }; export const parse = (buf) => { const pre = buf[0]; const value = pre === 0x80 ? pos(buf.subarray(1, buf.length)) : pre === 0xff ? twos(buf) : null; if (value === null) { throw Error('invalid base256 encoding'); } if (!Number.isSafeInteger(value)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('parsed number outside of javascript safe integer range'); } return value; }; const twos = (buf) => { var len = buf.length; var sum = 0; var flipped = false; for (var i = len - 1; i > -1; i--) { var byte = Number(buf[i]); var f; if (flipped) { f = onesComp(byte); } else if (byte === 0) { f = byte; } else { flipped = true; f = twosComp(byte); } if (f !== 0) { sum -= f * Math.pow(256, len - i - 1); } } return sum; }; const pos = (buf) => { var len = buf.length; var sum = 0; for (var i = len - 1; i > -1; i--) { var byte = Number(buf[i]); if (byte !== 0) { sum += byte * Math.pow(256, len - i - 1); } } return sum; }; const onesComp = (byte) => (0xff ^ byte) & 0xff; const twosComp = (byte) => ((0xff ^ byte) + 1) & 0xff; //# sourceMappingURL=large-numbers.js.map// tar -t import * as fsm from '@isaacs/fs-minipass'; import fs from 'node:fs'; import { dirname, parse } from 'path'; import { makeCommand } from './make-command.js'; import { Parser } from './parse.js'; import { stripTrailingSlashes } from './strip-trailing-slashes.js'; const onReadEntryFunction = (opt) => { const onReadEntry = opt.onReadEntry; opt.onReadEntry = onReadEntry ? e => { onReadEntry(e); e.resume(); } : e => e.resume(); }; // construct a filter that limits the file entries listed // include child entries if a dir is included export const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripTrailingSlashes(f), true])); const filter = opt.filter; const mapHas = (file, r = '') => { const root = r || parse(file).root || '.'; let ret; if (file === root) ret = false; else { const m = map.get(file); if (m !== undefined) { ret = m; } else { ret = mapHas(dirname(file), root); } } map.set(file, ret); return ret; }; opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripTrailingSlashes(file)) : file => mapHas(stripTrailingSlashes(file)); }; const listFileSync = (opt) => { const p = new Parser(opt); const file = opt.file; let fd; try { const stat = fs.statSync(file); const readSize = opt.maxReadSize || 16 * 1024 * 1024; if (stat.size < readSize) { p.end(fs.readFileSync(file)); } else { let pos = 0; const buf = Buffer.allocUnsafe(readSize); fd = fs.openSync(file, 'r'); while (pos < stat.size) { const bytesRead = fs.readSync(fd, buf, 0, readSize, pos); pos += bytesRead; p.write(buf.subarray(0, bytesRead)); } p.end(); } } finally { if (typeof fd === 'number') { try { fs.closeSync(fd); /* c8 ignore next */ } catch (er) { } } } }; const listFile = (opt, _files) => { const parse = new Parser(opt); const readSize = opt.maxReadSize || 16 * 1024 * 1024; const file = opt.file; const p = new Promise((resolve, reject) => { parse.on('error', reject); parse.on('end', resolve); fs.stat(file, (er, stat) => { if (er) { reject(er); } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }); stream.on('error', reject); stream.pipe(parse); } }); }); return p; }; export const list = makeCommand(listFileSync, listFile, opt => new Parser(opt), opt => new Parser(opt), (opt, files) => { if (files?.length) filesFilter(opt, files); if (!opt.noResume) onReadEntryFunction(opt); }); //# sourceMappingURL=list.js.mapimport { dealias, isAsyncFile, isAsyncNoFile, isSyncFile, isSyncNoFile, } from './options.js'; export const makeCommand = (syncFile, asyncFile, syncNoFile, asyncNoFile, validate) => { return Object.assign((opt_ = [], entries, cb) => { if (Array.isArray(opt_)) { entries = opt_; opt_ = {}; } if (typeof entries === 'function') { cb = entries; entries = undefined; } if (!entries) { entries = []; } else { entries = Array.from(entries); } const opt = dealias(opt_); validate?.(opt, entries); if (isSyncFile(opt)) { if (typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions'); } return syncFile(opt, entries); } else if (isAsyncFile(opt)) { const p = asyncFile(opt, entries); // weirdness to make TS happy const c = cb ? cb : undefined; return c ? p.then(() => c(), c) : p; } else if (isSyncNoFile(opt)) { if (typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions'); } return syncNoFile(opt, entries); } else if (isAsyncNoFile(opt)) { if (typeof cb === 'function') { throw new TypeError('callback only supported with file option'); } return asyncNoFile(opt, entries); /* c8 ignore start */ } else { throw new Error('impossible options??'); } /* c8 ignore stop */ }, { syncFile, asyncFile, syncNoFile, asyncNoFile, validate, }); }; //# sourceMappingURL=make-command.js.mapimport { chownr, chownrSync } from 'chownr'; import fs from 'fs'; import { mkdirp, mkdirpSync } from 'mkdirp'; import path from 'node:path'; import { CwdError } from './cwd-error.js'; import { normalizeWindowsPath } from './normalize-windows-path.js'; import { SymlinkError } from './symlink-error.js'; const cGet = (cache, key) => cache.get(normalizeWindowsPath(key)); const cSet = (cache, key, val) => cache.set(normalizeWindowsPath(key), val); const checkCwd = (dir, cb) => { fs.stat(dir, (er, st) => { if (er || !st.isDirectory()) { er = new CwdError(dir, er?.code || 'ENOTDIR'); } cb(er); }); }; /** * Wrapper around mkdirp for tar's needs. * * The main purpose is to avoid creating directories if we know that * they already exist (and track which ones exist for this purpose), * and prevent entries from being extracted into symlinked folders, * if `preservePaths` is not set. */ export const mkdir = (dir, opt, cb) => { dir = normalizeWindowsPath(dir); // if there's any overlap between mask and mode, // then we'll need an explicit chmod /* c8 ignore next */ const umask = opt.umask ?? 0o22; const mode = opt.mode | 0o0700; const needChmod = (mode & umask) !== 0; const uid = opt.uid; const gid = opt.gid; const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid); const preserve = opt.preserve; const unlink = opt.unlink; const cache = opt.cache; const cwd = normalizeWindowsPath(opt.cwd); const done = (er, created) => { if (er) { cb(er); } else { cSet(cache, dir, true); if (created && doChown) { chownr(created, uid, gid, er => done(er)); } else if (needChmod) { fs.chmod(dir, mode, cb); } else { cb(); } } }; if (cache && cGet(cache, dir) === true) { return done(); } if (dir === cwd) { return checkCwd(dir, done); } if (preserve) { return mkdirp(dir, { mode }).then(made => done(null, made ?? undefined), // oh, ts done); } const sub = normalizeWindowsPath(path.relative(cwd, dir)); const parts = sub.split('/'); mkdir_(cwd, parts, mode, cache, unlink, cwd, undefined, done); }; const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { if (!parts.length) { return cb(null, created); } const p = parts.shift(); const part = normalizeWindowsPath(path.resolve(base + '/' + p)); if (cGet(cache, part)) { return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); } fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)); }; const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => (er) => { if (er) { fs.lstat(part, (statEr, st) => { if (statEr) { statEr.path = statEr.path && normalizeWindowsPath(statEr.path); cb(statEr); } else if (st.isDirectory()) { mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); } else if (unlink) { fs.unlink(part, er => { if (er) { return cb(er); } fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)); }); } else if (st.isSymbolicLink()) { return cb(new SymlinkError(part, part + '/' + parts.join('/'))); } else { cb(er); } }); } else { created = created || part; mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); } }; const checkCwdSync = (dir) => { let ok = false; let code = undefined; try { ok = fs.statSync(dir).isDirectory(); } catch (er) { code = er?.code; } finally { if (!ok) { throw new CwdError(dir, code ?? 'ENOTDIR'); } } }; export const mkdirSync = (dir, opt) => { dir = normalizeWindowsPath(dir); // if there's any overlap between mask and mode, // then we'll need an explicit chmod /* c8 ignore next */ const umask = opt.umask ?? 0o22; const mode = opt.mode | 0o700; const needChmod = (mode & umask) !== 0; const uid = opt.uid; const gid = opt.gid; const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid); const preserve = opt.preserve; const unlink = opt.unlink; const cache = opt.cache; const cwd = normalizeWindowsPath(opt.cwd); const done = (created) => { cSet(cache, dir, true); if (created && doChown) { chownrSync(created, uid, gid); } if (needChmod) { fs.chmodSync(dir, mode); } }; if (cache && cGet(cache, dir) === true) { return done(); } if (dir === cwd) { checkCwdSync(cwd); return done(); } if (preserve) { return done(mkdirpSync(dir, mode) ?? undefined); } const sub = normalizeWindowsPath(path.relative(cwd, dir)); const parts = sub.split('/'); let created = undefined; for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) { part = normalizeWindowsPath(path.resolve(part)); if (cGet(cache, part)) { continue; } try { fs.mkdirSync(part, mode); created = created || part; cSet(cache, part, true); } catch (er) { const st = fs.lstatSync(part); if (st.isDirectory()) { cSet(cache, part, true); continue; } else if (unlink) { fs.unlinkSync(part); fs.mkdirSync(part, mode); created = created || part; cSet(cache, part, true); continue; } else if (st.isSymbolicLink()) { return new SymlinkError(part, part + '/' + parts.join('/')); } } } return done(created); }; //# sourceMappingURL=mkdir.js.mapexport const modeFix = (mode, isDir, portable) => { mode &= 0o7777; // in portable mode, use the minimum reasonable umask // if this system creates files with 0o664 by default // (as some linux distros do), then we'll write the // archive with 0o644 instead. Also, don't ever create // a file that is not readable/writable by the owner. if (portable) { mode = (mode | 0o600) & ~0o22; } // if dirs are readable, then they should be listable if (isDir) { if (mode & 0o400) { mode |= 0o100; } if (mode & 0o40) { mode |= 0o10; } if (mode & 0o4) { mode |= 0o1; } } return mode; }; //# sourceMappingURL=mode-fix.js.map// warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. const normalizeCache = Object.create(null); const { hasOwnProperty } = Object.prototype; export const normalizeUnicode = (s) => { if (!hasOwnProperty.call(normalizeCache, s)) { normalizeCache[s] = s.normalize('NFD'); } return normalizeCache[s]; }; //# sourceMappingURL=normalize-unicode.js.map// on windows, either \ or / are valid directory separators. // on unix, \ is a valid character in filenames. // so, on windows, and only on windows, we replace all \ chars with /, // so that we can use / as our one and only directory separator char. const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; export const normalizeWindowsPath = platform !== 'win32' ? (p) => p : (p) => p && p.replace(/\\/g, '/'); //# sourceMappingURL=normalize-windows-path.js.map// turn tar(1) style args like `C` into the more verbose things like `cwd` const argmap = new Map([ ['C', 'cwd'], ['f', 'file'], ['z', 'gzip'], ['P', 'preservePaths'], ['U', 'unlink'], ['strip-components', 'strip'], ['stripComponents', 'strip'], ['keep-newer', 'newer'], ['keepNewer', 'newer'], ['keep-newer-files', 'newer'], ['keepNewerFiles', 'newer'], ['k', 'keep'], ['keep-existing', 'keep'], ['keepExisting', 'keep'], ['m', 'noMtime'], ['no-mtime', 'noMtime'], ['p', 'preserveOwner'], ['L', 'follow'], ['h', 'follow'], ['onentry', 'onReadEntry'], ]); export const isSyncFile = (o) => !!o.sync && !!o.file; export const isAsyncFile = (o) => !o.sync && !!o.file; export const isSyncNoFile = (o) => !!o.sync && !o.file; export const isAsyncNoFile = (o) => !o.sync && !o.file; export const isSync = (o) => !!o.sync; export const isAsync = (o) => !o.sync; export const isFile = (o) => !!o.file; export const isNoFile = (o) => !o.file; const dealiasKey = (k) => { const d = argmap.get(k); if (d) return d; return k; }; export const dealias = (opt = {}) => { if (!opt) return {}; const result = {}; for (const [key, v] of Object.entries(opt)) { // TS doesn't know that aliases are going to always be the same type const k = dealiasKey(key); result[k] = v; } // affordance for deprecated noChmod -> chmod if (result.chmod === undefined && result.noChmod === false) { result.chmod = true; } delete result.noChmod; return result; }; //# sourceMappingURL=options.js.map// A readable tar stream creator // Technically, this is a transform stream that you write paths into, // and tar format comes out of. // The `add()` method is like `write()` but returns this, // and end() return `this` as well, so you can // do `new Pack(opt).add('files').add('dir').end().pipe(output) // You could also do something like: // streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) import fs from 'fs'; import { WriteEntry, WriteEntrySync, WriteEntryTar, } from './write-entry.js'; export class PackJob { path; absolute; entry; stat; readdir; pending = false; ignore = false; piped = false; constructor(path, absolute) { this.path = path || './'; this.absolute = absolute; } } import { Minipass } from 'minipass'; import * as zlib from 'minizlib'; import { Yallist } from 'yallist'; import { ReadEntry } from './read-entry.js'; import { warnMethod, } from './warn-method.js'; const EOF = Buffer.alloc(1024); const ONSTAT = Symbol('onStat'); const ENDED = Symbol('ended'); const QUEUE = Symbol('queue'); const CURRENT = Symbol('current'); const PROCESS = Symbol('process'); const PROCESSING = Symbol('processing'); const PROCESSJOB = Symbol('processJob'); const JOBS = Symbol('jobs'); const JOBDONE = Symbol('jobDone'); const ADDFSENTRY = Symbol('addFSEntry'); const ADDTARENTRY = Symbol('addTarEntry'); const STAT = Symbol('stat'); const READDIR = Symbol('readdir'); const ONREADDIR = Symbol('onreaddir'); const PIPE = Symbol('pipe'); const ENTRY = Symbol('entry'); const ENTRYOPT = Symbol('entryOpt'); const WRITEENTRYCLASS = Symbol('writeEntryClass'); const WRITE = Symbol('write'); const ONDRAIN = Symbol('ondrain'); import path from 'path'; import { normalizeWindowsPath } from './normalize-windows-path.js'; export class Pack extends Minipass { opt; cwd; maxReadSize; preservePaths; strict; noPax; prefix; linkCache; statCache; file; portable; zip; readdirCache; noDirRecurse; follow; noMtime; mtime; filter; jobs; [WRITEENTRYCLASS]; onWriteEntry; [QUEUE]; [JOBS] = 0; [PROCESSING] = false; [ENDED] = false; constructor(opt = {}) { //@ts-ignore super(); this.opt = opt; this.file = opt.file || ''; this.cwd = opt.cwd || process.cwd(); this.maxReadSize = opt.maxReadSize; this.preservePaths = !!opt.preservePaths; this.strict = !!opt.strict; this.noPax = !!opt.noPax; this.prefix = normalizeWindowsPath(opt.prefix || ''); this.linkCache = opt.linkCache || new Map(); this.statCache = opt.statCache || new Map(); this.readdirCache = opt.readdirCache || new Map(); this.onWriteEntry = opt.onWriteEntry; this[WRITEENTRYCLASS] = WriteEntry; if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn); } this.portable = !!opt.portable; if (opt.gzip || opt.brotli) { if (opt.gzip && opt.brotli) { throw new TypeError('gzip and brotli are mutually exclusive'); } if (opt.gzip) { if (typeof opt.gzip !== 'object') { opt.gzip = {}; } if (this.portable) { opt.gzip.portable = true; } this.zip = new zlib.Gzip(opt.gzip); } if (opt.brotli) { if (typeof opt.brotli !== 'object') { opt.brotli = {}; } this.zip = new zlib.BrotliCompress(opt.brotli); } /* c8 ignore next */ if (!this.zip) throw new Error('impossible'); const zip = this.zip; zip.on('data', chunk => super.write(chunk)); zip.on('end', () => super.end()); zip.on('drain', () => this[ONDRAIN]()); this.on('resume', () => zip.resume()); } else { this.on('drain', this[ONDRAIN]); } this.noDirRecurse = !!opt.noDirRecurse; this.follow = !!opt.follow; this.noMtime = !!opt.noMtime; if (opt.mtime) this.mtime = opt.mtime; this.filter = typeof opt.filter === 'function' ? opt.filter : () => true; this[QUEUE] = new Yallist(); this[JOBS] = 0; this.jobs = Number(opt.jobs) || 4; this[PROCESSING] = false; this[ENDED] = false; } [WRITE](chunk) { return super.write(chunk); } add(path) { this.write(path); return this; } end(path, encoding, cb) { /* c8 ignore start */ if (typeof path === 'function') { cb = path; path = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } /* c8 ignore stop */ if (path) { this.add(path); } this[ENDED] = true; this[PROCESS](); /* c8 ignore next */ if (cb) cb(); return this; } write(path) { if (this[ENDED]) { throw new Error('write after end'); } if (path instanceof ReadEntry) { this[ADDTARENTRY](path); } else { this[ADDFSENTRY](path); } return this.flowing; } [ADDTARENTRY](p) { const absolute = normalizeWindowsPath(path.resolve(this.cwd, p.path)); // in this case, we don't have to wait for the stat if (!this.filter(p.path, p)) { p.resume(); } else { const job = new PackJob(p.path, absolute); job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)); job.entry.on('end', () => this[JOBDONE](job)); this[JOBS] += 1; this[QUEUE].push(job); } this[PROCESS](); } [ADDFSENTRY](p) { const absolute = normalizeWindowsPath(path.resolve(this.cwd, p)); this[QUEUE].push(new PackJob(p, absolute)); this[PROCESS](); } [STAT](job) { job.pending = true; this[JOBS] += 1; const stat = this.follow ? 'stat' : 'lstat'; fs[stat](job.absolute, (er, stat) => { job.pending = false; this[JOBS] -= 1; if (er) { this.emit('error', er); } else { this[ONSTAT](job, stat); } }); } [ONSTAT](job, stat) { this.statCache.set(job.absolute, stat); job.stat = stat; // now we have the stat, we can filter it. if (!this.filter(job.path, stat)) { job.ignore = true; } this[PROCESS](); } [READDIR](job) { job.pending = true; this[JOBS] += 1; fs.readdir(job.absolute, (er, entries) => { job.pending = false; this[JOBS] -= 1; if (er) { return this.emit('error', er); } this[ONREADDIR](job, entries); }); } [ONREADDIR](job, entries) { this.readdirCache.set(job.absolute, entries); job.readdir = entries; this[PROCESS](); } [PROCESS]() { if (this[PROCESSING]) { return; } this[PROCESSING] = true; for (let w = this[QUEUE].head; !!w && this[JOBS] < this.jobs; w = w.next) { this[PROCESSJOB](w.value); if (w.value.ignore) { const p = w.next; this[QUEUE].removeNode(w); w.next = p; } } this[PROCESSING] = false; if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { if (this.zip) { this.zip.end(EOF); } else { super.write(EOF); super.end(); } } } get [CURRENT]() { return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value; } [JOBDONE](_job) { this[QUEUE].shift(); this[JOBS] -= 1; this[PROCESS](); } [PROCESSJOB](job) { if (job.pending) { return; } if (job.entry) { if (job === this[CURRENT] && !job.piped) { this[PIPE](job); } return; } if (!job.stat) { const sc = this.statCache.get(job.absolute); if (sc) { this[ONSTAT](job, sc); } else { this[STAT](job); } } if (!job.stat) { return; } // filtered out! if (job.ignore) { return; } if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { const rc = this.readdirCache.get(job.absolute); if (rc) { this[ONREADDIR](job, rc); } else { this[READDIR](job); } if (!job.readdir) { return; } } // we know it doesn't have an entry, because that got checked above job.entry = this[ENTRY](job); if (!job.entry) { job.ignore = true; return; } if (job === this[CURRENT] && !job.piped) { this[PIPE](job); } } [ENTRYOPT](job) { return { onwarn: (code, msg, data) => this.warn(code, msg, data), noPax: this.noPax, cwd: this.cwd, absolute: job.absolute, preservePaths: this.preservePaths, maxReadSize: this.maxReadSize, strict: this.strict, portable: this.portable, linkCache: this.linkCache, statCache: this.statCache, noMtime: this.noMtime, mtime: this.mtime, prefix: this.prefix, onWriteEntry: this.onWriteEntry, }; } [ENTRY](job) { this[JOBS] += 1; try { const e = new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)); return e .on('end', () => this[JOBDONE](job)) .on('error', er => this.emit('error', er)); } catch (er) { this.emit('error', er); } } [ONDRAIN]() { if (this[CURRENT] && this[CURRENT].entry) { this[CURRENT].entry.resume(); } } // like .pipe() but using super, because our write() is special [PIPE](job) { job.piped = true; if (job.readdir) { job.readdir.forEach(entry => { const p = job.path; const base = p === './' ? '' : p.replace(/\/*$/, '/'); this[ADDFSENTRY](base + entry); }); } const source = job.entry; const zip = this.zip; /* c8 ignore start */ if (!source) throw new Error('cannot pipe without source'); /* c8 ignore stop */ if (zip) { source.on('data', chunk => { if (!zip.write(chunk)) { source.pause(); } }); } else { source.on('data', chunk => { if (!super.write(chunk)) { source.pause(); } }); } } pause() { if (this.zip) { this.zip.pause(); } return super.pause(); } warn(code, message, data = {}) { warnMethod(this, code, message, data); } } export class PackSync extends Pack { sync = true; constructor(opt) { super(opt); this[WRITEENTRYCLASS] = WriteEntrySync; } // pause/resume are no-ops in sync streams. pause() { } resume() { } [STAT](job) { const stat = this.follow ? 'statSync' : 'lstatSync'; this[ONSTAT](job, fs[stat](job.absolute)); } [READDIR](job) { this[ONREADDIR](job, fs.readdirSync(job.absolute)); } // gotta get it all in this tick [PIPE](job) { const source = job.entry; const zip = this.zip; if (job.readdir) { job.readdir.forEach(entry => { const p = job.path; const base = p === './' ? '' : p.replace(/\/*$/, '/'); this[ADDFSENTRY](base + entry); }); } /* c8 ignore start */ if (!source) throw new Error('Cannot pipe without source'); /* c8 ignore stop */ if (zip) { source.on('data', chunk => { zip.write(chunk); }); } else { source.on('data', chunk => { super[WRITE](chunk); }); } } } //# sourceMappingURL=pack.js.map{ "type": "module" } // this[BUFFER] is the remainder of a chunk if we're waiting for // the full 512 bytes of a header to come in. We will Buffer.concat() // it to the next write(), which is a mem copy, but a small one. // // this[QUEUE] is a Yallist of entries that haven't been emitted // yet this can only get filled up if the user keeps write()ing after // a write() returns false, or does a write() with more than one entry // // We don't buffer chunks, we always parse them and either create an // entry, or push it into the active entry. The ReadEntry class knows // to throw data away if .ignore=true // // Shift entry off the buffer when it emits 'end', and emit 'entry' for // the next one in the list. // // At any time, we're pushing body chunks into the entry at WRITEENTRY, // and waiting for 'end' on the entry at READENTRY // // ignored entries get .resume() called on them straight away import { EventEmitter as EE } from 'events'; import { BrotliDecompress, Unzip } from 'minizlib'; import { Yallist } from 'yallist'; import { Header } from './header.js'; import { Pax } from './pax.js'; import { ReadEntry } from './read-entry.js'; import { warnMethod, } from './warn-method.js'; const maxMetaEntrySize = 1024 * 1024; const gzipHeader = Buffer.from([0x1f, 0x8b]); const STATE = Symbol('state'); const WRITEENTRY = Symbol('writeEntry'); const READENTRY = Symbol('readEntry'); const NEXTENTRY = Symbol('nextEntry'); const PROCESSENTRY = Symbol('processEntry'); const EX = Symbol('extendedHeader'); const GEX = Symbol('globalExtendedHeader'); const META = Symbol('meta'); const EMITMETA = Symbol('emitMeta'); const BUFFER = Symbol('buffer'); const QUEUE = Symbol('queue'); const ENDED = Symbol('ended'); const EMITTEDEND = Symbol('emittedEnd'); const EMIT = Symbol('emit'); const UNZIP = Symbol('unzip'); const CONSUMECHUNK = Symbol('consumeChunk'); const CONSUMECHUNKSUB = Symbol('consumeChunkSub'); const CONSUMEBODY = Symbol('consumeBody'); const CONSUMEMETA = Symbol('consumeMeta'); const CONSUMEHEADER = Symbol('consumeHeader'); const CONSUMING = Symbol('consuming'); const BUFFERCONCAT = Symbol('bufferConcat'); const MAYBEEND = Symbol('maybeEnd'); const WRITING = Symbol('writing'); const ABORTED = Symbol('aborted'); const DONE = Symbol('onDone'); const SAW_VALID_ENTRY = Symbol('sawValidEntry'); const SAW_NULL_BLOCK = Symbol('sawNullBlock'); const SAW_EOF = Symbol('sawEOF'); const CLOSESTREAM = Symbol('closeStream'); const noop = () => true; export class Parser extends EE { file; strict; maxMetaEntrySize; filter; brotli; writable = true; readable = false; [QUEUE] = new Yallist(); [BUFFER]; [READENTRY]; [WRITEENTRY]; [STATE] = 'begin'; [META] = ''; [EX]; [GEX]; [ENDED] = false; [UNZIP]; [ABORTED] = false; [SAW_VALID_ENTRY]; [SAW_NULL_BLOCK] = false; [SAW_EOF] = false; [WRITING] = false; [CONSUMING] = false; [EMITTEDEND] = false; constructor(opt = {}) { super(); this.file = opt.file || ''; // these BADARCHIVE errors can't be detected early. listen on DONE. this.on(DONE, () => { if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { // either less than 1 block of data, or all entries were invalid. // Either way, probably not even a tarball. this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format'); } }); if (opt.ondone) { this.on(DONE, opt.ondone); } else { this.on(DONE, () => { this.emit('prefinish'); this.emit('finish'); this.emit('end'); }); } this.strict = !!opt.strict; this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize; this.filter = typeof opt.filter === 'function' ? opt.filter : noop; // Unlike gzip, brotli doesn't have any magic bytes to identify it // Users need to explicitly tell us they're extracting a brotli file // Or we infer from the file extension const isTBR = opt.file && (opt.file.endsWith('.tar.br') || opt.file.endsWith('.tbr')); // if it's a tbr file it MIGHT be brotli, but we don't know until // we look at it and verify it's not a valid tar file. this.brotli = !opt.gzip && opt.brotli !== undefined ? opt.brotli : isTBR ? undefined : false; // have to set this so that streams are ok piping into it this.on('end', () => this[CLOSESTREAM]()); if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn); } if (typeof opt.onReadEntry === 'function') { this.on('entry', opt.onReadEntry); } } warn(code, message, data = {}) { warnMethod(this, code, message, data); } [CONSUMEHEADER](chunk, position) { if (this[SAW_VALID_ENTRY] === undefined) { this[SAW_VALID_ENTRY] = false; } let header; try { header = new Header(chunk, position, this[EX], this[GEX]); } catch (er) { return this.warn('TAR_ENTRY_INVALID', er); } if (header.nullBlock) { if (this[SAW_NULL_BLOCK]) { this[SAW_EOF] = true; // ending an archive with no entries. pointless, but legal. if (this[STATE] === 'begin') { this[STATE] = 'header'; } this[EMIT]('eof'); } else { this[SAW_NULL_BLOCK] = true; this[EMIT]('nullBlock'); } } else { this[SAW_NULL_BLOCK] = false; if (!header.cksumValid) { this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header }); } else if (!header.path) { this.warn('TAR_ENTRY_INVALID', 'path is required', { header }); } else { const type = header.type; if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath required', { header, }); } else if (!/^(Symbolic)?Link$/.test(type) && !/^(Global)?ExtendedHeader$/.test(type) && header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', { header, }); } else { const entry = (this[WRITEENTRY] = new ReadEntry(header, this[EX], this[GEX])); // we do this for meta & ignored entries as well, because they // are still valid tar, or else we wouldn't know to ignore them if (!this[SAW_VALID_ENTRY]) { if (entry.remain) { // this might be the one! const onend = () => { if (!entry.invalid) { this[SAW_VALID_ENTRY] = true; } }; entry.on('end', onend); } else { this[SAW_VALID_ENTRY] = true; } } if (entry.meta) { if (entry.size > this.maxMetaEntrySize) { entry.ignore = true; this[EMIT]('ignoredEntry', entry); this[STATE] = 'ignore'; entry.resume(); } else if (entry.size > 0) { this[META] = ''; entry.on('data', c => (this[META] += c)); this[STATE] = 'meta'; } } else { this[EX] = undefined; entry.ignore = entry.ignore || !this.filter(entry.path, entry); if (entry.ignore) { // probably valid, just not something we care about this[EMIT]('ignoredEntry', entry); this[STATE] = entry.remain ? 'ignore' : 'header'; entry.resume(); } else { if (entry.remain) { this[STATE] = 'body'; } else { this[STATE] = 'header'; entry.end(); } if (!this[READENTRY]) { this[QUEUE].push(entry); this[NEXTENTRY](); } else { this[QUEUE].push(entry); } } } } } } } [CLOSESTREAM]() { queueMicrotask(() => this.emit('close')); } [PROCESSENTRY](entry) { let go = true; if (!entry) { this[READENTRY] = undefined; go = false; } else if (Array.isArray(entry)) { const [ev, ...args] = entry; this.emit(ev, ...args); } else { this[READENTRY] = entry; this.emit('entry', entry); if (!entry.emittedEnd) { entry.on('end', () => this[NEXTENTRY]()); go = false; } } return go; } [NEXTENTRY]() { do { } while (this[PROCESSENTRY](this[QUEUE].shift())); if (!this[QUEUE].length) { // At this point, there's nothing in the queue, but we may have an // entry which is being consumed (readEntry). // If we don't, then we definitely can handle more data. // If we do, and either it's flowing, or it has never had any data // written to it, then it needs more. // The only other possibility is that it has returned false from a // write() call, so we wait for the next drain to continue. const re = this[READENTRY]; const drainNow = !re || re.flowing || re.size === re.remain; if (drainNow) { if (!this[WRITING]) { this.emit('drain'); } } else { re.once('drain', () => this.emit('drain')); } } } [CONSUMEBODY](chunk, position) { // write up to but no more than writeEntry.blockRemain const entry = this[WRITEENTRY]; /* c8 ignore start */ if (!entry) { throw new Error('attempt to consume body without entry??'); } const br = entry.blockRemain ?? 0; /* c8 ignore stop */ const c = br >= chunk.length && position === 0 ? chunk : chunk.subarray(position, position + br); entry.write(c); if (!entry.blockRemain) { this[STATE] = 'header'; this[WRITEENTRY] = undefined; entry.end(); } return c.length; } [CONSUMEMETA](chunk, position) { const entry = this[WRITEENTRY]; const ret = this[CONSUMEBODY](chunk, position); // if we finished, then the entry is reset if (!this[WRITEENTRY] && entry) { this[EMITMETA](entry); } return ret; } [EMIT](ev, data, extra) { if (!this[QUEUE].length && !this[READENTRY]) { this.emit(ev, data, extra); } else { this[QUEUE].push([ev, data, extra]); } } [EMITMETA](entry) { this[EMIT]('meta', this[META]); switch (entry.type) { case 'ExtendedHeader': case 'OldExtendedHeader': this[EX] = Pax.parse(this[META], this[EX], false); break; case 'GlobalExtendedHeader': this[GEX] = Pax.parse(this[META], this[GEX], true); break; case 'NextFileHasLongPath': case 'OldGnuLongPath': { const ex = this[EX] ?? Object.create(null); this[EX] = ex; ex.path = this[META].replace(/\0.*/, ''); break; } case 'NextFileHasLongLinkpath': { const ex = this[EX] || Object.create(null); this[EX] = ex; ex.linkpath = this[META].replace(/\0.*/, ''); break; } /* c8 ignore start */ default: throw new Error('unknown meta: ' + entry.type); /* c8 ignore stop */ } } abort(error) { this[ABORTED] = true; this.emit('abort', error); // always throws, even in non-strict mode this.warn('TAR_ABORT', error, { recoverable: false }); } write(chunk, encoding, cb) { if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, /* c8 ignore next */ typeof encoding === 'string' ? encoding : 'utf8'); } if (this[ABORTED]) { /* c8 ignore next */ cb?.(); return false; } // first write, might be gzipped const needSniff = this[UNZIP] === undefined || (this.brotli === undefined && this[UNZIP] === false); if (needSniff && chunk) { if (this[BUFFER]) { chunk = Buffer.concat([this[BUFFER], chunk]); this[BUFFER] = undefined; } if (chunk.length < gzipHeader.length) { this[BUFFER] = chunk; /* c8 ignore next */ cb?.(); return true; } // look for gzip header for (let i = 0; this[UNZIP] === undefined && i < gzipHeader.length; i++) { if (chunk[i] !== gzipHeader[i]) { this[UNZIP] = false; } } const maybeBrotli = this.brotli === undefined; if (this[UNZIP] === false && maybeBrotli) { // read the first header to see if it's a valid tar file. If so, // we can safely assume that it's not actually brotli, despite the // .tbr or .tar.br file extension. // if we ended before getting a full chunk, yes, def brotli if (chunk.length < 512) { if (this[ENDED]) { this.brotli = true; } else { this[BUFFER] = chunk; /* c8 ignore next */ cb?.(); return true; } } else { // if it's tar, it's pretty reliably not brotli, chances of // that happening are astronomical. try { new Header(chunk.subarray(0, 512)); this.brotli = false; } catch (_) { this.brotli = true; } } } if (this[UNZIP] === undefined || (this[UNZIP] === false && this.brotli)) { const ended = this[ENDED]; this[ENDED] = false; this[UNZIP] = this[UNZIP] === undefined ? new Unzip({}) : new BrotliDecompress({}); this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)); this[UNZIP].on('error', er => this.abort(er)); this[UNZIP].on('end', () => { this[ENDED] = true; this[CONSUMECHUNK](); }); this[WRITING] = true; const ret = !!this[UNZIP][ended ? 'end' : 'write'](chunk); this[WRITING] = false; cb?.(); return ret; } } this[WRITING] = true; if (this[UNZIP]) { this[UNZIP].write(chunk); } else { this[CONSUMECHUNK](chunk); } this[WRITING] = false; // return false if there's a queue, or if the current entry isn't flowing const ret = this[QUEUE].length ? false : this[READENTRY] ? this[READENTRY].flowing : true; // if we have no queue, then that means a clogged READENTRY if (!ret && !this[QUEUE].length) { this[READENTRY]?.once('drain', () => this.emit('drain')); } /* c8 ignore next */ cb?.(); return ret; } [BUFFERCONCAT](c) { if (c && !this[ABORTED]) { this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c; } } [MAYBEEND]() { if (this[ENDED] && !this[EMITTEDEND] && !this[ABORTED] && !this[CONSUMING]) { this[EMITTEDEND] = true; const entry = this[WRITEENTRY]; if (entry && entry.blockRemain) { // truncated, likely a damaged file const have = this[BUFFER] ? this[BUFFER].length : 0; this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${entry.blockRemain} more bytes, only ${have} available)`, { entry }); if (this[BUFFER]) { entry.write(this[BUFFER]); } entry.end(); } this[EMIT](DONE); } } [CONSUMECHUNK](chunk) { if (this[CONSUMING] && chunk) { this[BUFFERCONCAT](chunk); } else if (!chunk && !this[BUFFER]) { this[MAYBEEND](); } else if (chunk) { this[CONSUMING] = true; if (this[BUFFER]) { this[BUFFERCONCAT](chunk); const c = this[BUFFER]; this[BUFFER] = undefined; this[CONSUMECHUNKSUB](c); } else { this[CONSUMECHUNKSUB](chunk); } while (this[BUFFER] && this[BUFFER]?.length >= 512 && !this[ABORTED] && !this[SAW_EOF]) { const c = this[BUFFER]; this[BUFFER] = undefined; this[CONSUMECHUNKSUB](c); } this[CONSUMING] = false; } if (!this[BUFFER] || this[ENDED]) { this[MAYBEEND](); } } [CONSUMECHUNKSUB](chunk) { // we know that we are in CONSUMING mode, so anything written goes into // the buffer. Advance the position and put any remainder in the buffer. let position = 0; const length = chunk.length; while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { switch (this[STATE]) { case 'begin': case 'header': this[CONSUMEHEADER](chunk, position); position += 512; break; case 'ignore': case 'body': position += this[CONSUMEBODY](chunk, position); break; case 'meta': position += this[CONSUMEMETA](chunk, position); break; /* c8 ignore start */ default: throw new Error('invalid state: ' + this[STATE]); /* c8 ignore stop */ } } if (position < length) { if (this[BUFFER]) { this[BUFFER] = Buffer.concat([ chunk.subarray(position), this[BUFFER], ]); } else { this[BUFFER] = chunk.subarray(position); } } } end(chunk, encoding, cb) { if (typeof chunk === 'function') { cb = chunk; encoding = undefined; chunk = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } if (cb) this.once('finish', cb); if (!this[ABORTED]) { if (this[UNZIP]) { /* c8 ignore start */ if (chunk) this[UNZIP].write(chunk); /* c8 ignore stop */ this[UNZIP].end(); } else { this[ENDED] = true; if (this.brotli === undefined) chunk = chunk || Buffer.alloc(0); if (chunk) this.write(chunk); this[MAYBEEND](); } } return this; } } //# sourceMappingURL=parse.js.map// A path exclusive reservation system // reserve([list, of, paths], fn) // When the fn is first in line for all its paths, it // is called with a cb that clears the reservation. // // Used by async unpack to avoid clobbering paths in use, // while still allowing maximal safe parallelization. import { join } from 'node:path'; import { normalizeUnicode } from './normalize-unicode.js'; import { stripTrailingSlashes } from './strip-trailing-slashes.js'; const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; const isWindows = platform === 'win32'; // return a set of parent dirs for a given path // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d'] const getDirs = (path) => { const dirs = path .split('/') .slice(0, -1) .reduce((set, path) => { const s = set[set.length - 1]; if (s !== undefined) { path = join(s, path); } set.push(path || '/'); return set; }, []); return dirs; }; export class PathReservations { // path => [function or Set] // A Set object means a directory reservation // A fn is a direct reservation on that path #queues = new Map(); // fn => {paths:[path,...], dirs:[path, ...]} #reservations = new Map(); // functions currently running #running = new Set(); reserve(paths, fn) { paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { // don't need normPath, because we skip this entirely for windows return stripTrailingSlashes(join(normalizeUnicode(p))).toLowerCase(); }); const dirs = new Set(paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b))); this.#reservations.set(fn, { dirs, paths }); for (const p of paths) { const q = this.#queues.get(p); if (!q) { this.#queues.set(p, [fn]); } else { q.push(fn); } } for (const dir of dirs) { const q = this.#queues.get(dir); if (!q) { this.#queues.set(dir, [new Set([fn])]); } else { const l = q[q.length - 1]; if (l instanceof Set) { l.add(fn); } else { q.push(new Set([fn])); } } } return this.#run(fn); } // return the queues for each path the function cares about // fn => {paths, dirs} #getQueues(fn) { const res = this.#reservations.get(fn); /* c8 ignore start */ if (!res) { throw new Error('function does not have any path reservations'); } /* c8 ignore stop */ return { paths: res.paths.map((path) => this.#queues.get(path)), dirs: [...res.dirs].map(path => this.#queues.get(path)), }; } // check if fn is first in line for all its paths, and is // included in the first set for all its dir queues check(fn) { const { paths, dirs } = this.#getQueues(fn); return (paths.every(q => q && q[0] === fn) && dirs.every(q => q && q[0] instanceof Set && q[0].has(fn))); } // run the function if it's first in line and not already running #run(fn) { if (this.#running.has(fn) || !this.check(fn)) { return false; } this.#running.add(fn); fn(() => this.#clear(fn)); return true; } #clear(fn) { if (!this.#running.has(fn)) { return false; } const res = this.#reservations.get(fn); /* c8 ignore start */ if (!res) { throw new Error('invalid reservation'); } /* c8 ignore stop */ const { paths, dirs } = res; const next = new Set(); for (const path of paths) { const q = this.#queues.get(path); /* c8 ignore start */ if (!q || q?.[0] !== fn) { continue; } /* c8 ignore stop */ const q0 = q[1]; if (!q0) { this.#queues.delete(path); continue; } q.shift(); if (typeof q0 === 'function') { next.add(q0); } else { for (const f of q0) { next.add(f); } } } for (const dir of dirs) { const q = this.#queues.get(dir); const q0 = q?.[0]; /* c8 ignore next - type safety only */ if (!q || !(q0 instanceof Set)) continue; if (q0.size === 1 && q.length === 1) { this.#queues.delete(dir); continue; } else if (q0.size === 1) { q.shift(); // next one must be a function, // or else the Set would've been reused const n = q[0]; if (typeof n === 'function') { next.add(n); } } else { q0.delete(fn); } } this.#running.delete(fn); next.forEach(fn => this.#run(fn)); return true; } } //# sourceMappingURL=path-reservations.js.mapimport { basename } from 'node:path'; import { Header } from './header.js'; export class Pax { atime; mtime; ctime; charset; comment; gid; uid; gname; uname; linkpath; dev; ino; nlink; path; size; mode; global; constructor(obj, global = false) { this.atime = obj.atime; this.charset = obj.charset; this.comment = obj.comment; this.ctime = obj.ctime; this.dev = obj.dev; this.gid = obj.gid; this.global = global; this.gname = obj.gname; this.ino = obj.ino; this.linkpath = obj.linkpath; this.mtime = obj.mtime; this.nlink = obj.nlink; this.path = obj.path; this.size = obj.size; this.uid = obj.uid; this.uname = obj.uname; } encode() { const body = this.encodeBody(); if (body === '') { return Buffer.allocUnsafe(0); } const bodyLen = Buffer.byteLength(body); // round up to 512 bytes // add 512 for header const bufLen = 512 * Math.ceil(1 + bodyLen / 512); const buf = Buffer.allocUnsafe(bufLen); // 0-fill the header section, it might not hit every field for (let i = 0; i < 512; i++) { buf[i] = 0; } new Header({ // XXX split the path // then the path should be PaxHeader + basename, but less than 99, // prepend with the dirname /* c8 ignore start */ path: ('PaxHeader/' + basename(this.path ?? '')).slice(0, 99), /* c8 ignore stop */ mode: this.mode || 0o644, uid: this.uid, gid: this.gid, size: bodyLen, mtime: this.mtime, type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', linkpath: '', uname: this.uname || '', gname: this.gname || '', devmaj: 0, devmin: 0, atime: this.atime, ctime: this.ctime, }).encode(buf); buf.write(body, 512, bodyLen, 'utf8'); // null pad after the body for (let i = bodyLen + 512; i < buf.length; i++) { buf[i] = 0; } return buf; } encodeBody() { return (this.encodeField('path') + this.encodeField('ctime') + this.encodeField('atime') + this.encodeField('dev') + this.encodeField('ino') + this.encodeField('nlink') + this.encodeField('charset') + this.encodeField('comment') + this.encodeField('gid') + this.encodeField('gname') + this.encodeField('linkpath') + this.encodeField('mtime') + this.encodeField('size') + this.encodeField('uid') + this.encodeField('uname')); } encodeField(field) { if (this[field] === undefined) { return ''; } const r = this[field]; const v = r instanceof Date ? r.getTime() / 1000 : r; const s = ' ' + (field === 'dev' || field === 'ino' || field === 'nlink' ? 'SCHILY.' : '') + field + '=' + v + '\n'; const byteLen = Buffer.byteLength(s); // the digits includes the length of the digits in ascii base-10 // so if it's 9 characters, then adding 1 for the 9 makes it 10 // which makes it 11 chars. let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1; if (byteLen + digits >= Math.pow(10, digits)) { digits += 1; } const len = digits + byteLen; return len + s; } static parse(str, ex, g = false) { return new Pax(merge(parseKV(str), ex), g); } } const merge = (a, b) => b ? Object.assign({}, b, a) : a; const parseKV = (str) => str .replace(/\n$/, '') .split('\n') .reduce(parseKVLine, Object.create(null)); const parseKVLine = (set, line) => { const n = parseInt(line, 10); // XXX Values with \n in them will fail this. // Refactor to not be a naive line-by-line parse. if (n !== Buffer.byteLength(line) + 1) { return set; } line = line.slice((n + ' ').length); const kv = line.split('='); const r = kv.shift(); if (!r) { return set; } const k = r.replace(/^SCHILY\.(dev|ino|nlink)/, '$1'); const v = kv.join('='); set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ? new Date(Number(v) * 1000) : /^[0-9]+$/.test(v) ? +v : v; return set; }; //# sourceMappingURL=pax.js.mapimport { Minipass } from 'minipass'; import { normalizeWindowsPath } from './normalize-windows-path.js'; export class ReadEntry extends Minipass { extended; globalExtended; header; startBlockSize; blockRemain; remain; type; meta = false; ignore = false; path; mode; uid; gid; uname; gname; size = 0; mtime; atime; ctime; linkpath; dev; ino; nlink; invalid = false; absolute; unsupported = false; constructor(header, ex, gex) { super({}); // read entries always start life paused. this is to avoid the // situation where Minipass's auto-ending empty streams results // in an entry ending before we're ready for it. this.pause(); this.extended = ex; this.globalExtended = gex; this.header = header; /* c8 ignore start */ this.remain = header.size ?? 0; /* c8 ignore stop */ this.startBlockSize = 512 * Math.ceil(this.remain / 512); this.blockRemain = this.startBlockSize; this.type = header.type; switch (this.type) { case 'File': case 'OldFile': case 'Link': case 'SymbolicLink': case 'CharacterDevice': case 'BlockDevice': case 'Directory': case 'FIFO': case 'ContiguousFile': case 'GNUDumpDir': break; case 'NextFileHasLongLinkpath': case 'NextFileHasLongPath': case 'OldGnuLongPath': case 'GlobalExtendedHeader': case 'ExtendedHeader': case 'OldExtendedHeader': this.meta = true; break; // NOTE: gnutar and bsdtar treat unrecognized types as 'File' // it may be worth doing the same, but with a warning. default: this.ignore = true; } /* c8 ignore start */ if (!header.path) { throw new Error('no path provided for tar.ReadEntry'); } /* c8 ignore stop */ this.path = normalizeWindowsPath(header.path); this.mode = header.mode; if (this.mode) { this.mode = this.mode & 0o7777; } this.uid = header.uid; this.gid = header.gid; this.uname = header.uname; this.gname = header.gname; this.size = this.remain; this.mtime = header.mtime; this.atime = header.atime; this.ctime = header.ctime; /* c8 ignore start */ this.linkpath = header.linkpath ? normalizeWindowsPath(header.linkpath) : undefined; /* c8 ignore stop */ this.uname = header.uname; this.gname = header.gname; if (ex) { this.#slurp(ex); } if (gex) { this.#slurp(gex, true); } } write(data) { const writeLen = data.length; if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate'); } const r = this.remain; const br = this.blockRemain; this.remain = Math.max(0, r - writeLen); this.blockRemain = Math.max(0, br - writeLen); if (this.ignore) { return true; } if (r >= writeLen) { return super.write(data); } // r < writeLen return super.write(data.subarray(0, r)); } #slurp(ex, gex = false) { if (ex.path) ex.path = normalizeWindowsPath(ex.path); if (ex.linkpath) ex.linkpath = normalizeWindowsPath(ex.linkpath); Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. Also, any // null/undefined values are ignored. return !(v === null || v === undefined || (k === 'path' && gex)); }))); } } //# sourceMappingURL=read-entry.js.map// tar -r import { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass'; import fs from 'node:fs'; import path from 'node:path'; import { Header } from './header.js'; import { list } from './list.js'; import { makeCommand } from './make-command.js'; import { isFile, } from './options.js'; import { Pack, PackSync } from './pack.js'; // starting at the head of the file, read a Header // If the checksum is invalid, that's our position to start writing // If it is, jump forward by the specified size (round up to 512) // and try again. // Write the new Pack stream starting there. const replaceSync = (opt, files) => { const p = new PackSync(opt); let threw = true; let fd; let position; try { try { fd = fs.openSync(opt.file, 'r+'); } catch (er) { if (er?.code === 'ENOENT') { fd = fs.openSync(opt.file, 'w+'); } else { throw er; } } const st = fs.fstatSync(fd); const headBuf = Buffer.alloc(512); POSITION: for (position = 0; position < st.size; position += 512) { for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { bytes = fs.readSync(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos); if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { throw new Error('cannot append to compressed archives'); } if (!bytes) { break POSITION; } } const h = new Header(headBuf); if (!h.cksumValid) { break; } const entryBlockSize = 512 * Math.ceil((h.size || 0) / 512); if (position + entryBlockSize + 512 > st.size) { break; } // the 512 for the header we just parsed will be added as well // also jump ahead all the blocks for the body position += entryBlockSize; if (opt.mtimeCache && h.mtime) { opt.mtimeCache.set(String(h.path), h.mtime); } } threw = false; streamSync(opt, p, position, fd, files); } finally { if (threw) { try { fs.closeSync(fd); } catch (er) { } } } }; const streamSync = (opt, p, position, fd, files) => { const stream = new WriteStreamSync(opt.file, { fd: fd, start: position, }); p.pipe(stream); addFilesSync(p, files); }; const replaceAsync = (opt, files) => { files = Array.from(files); const p = new Pack(opt); const getPos = (fd, size, cb_) => { const cb = (er, pos) => { if (er) { fs.close(fd, _ => cb_(er)); } else { cb_(null, pos); } }; let position = 0; if (size === 0) { return cb(null, 0); } let bufPos = 0; const headBuf = Buffer.alloc(512); const onread = (er, bytes) => { if (er || typeof bytes === 'undefined') { return cb(er); } bufPos += bytes; if (bufPos < 512 && bytes) { return fs.read(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread); } if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { return cb(new Error('cannot append to compressed archives')); } // truncated header if (bufPos < 512) { return cb(null, position); } const h = new Header(headBuf); if (!h.cksumValid) { return cb(null, position); } /* c8 ignore next */ const entryBlockSize = 512 * Math.ceil((h.size ?? 0) / 512); if (position + entryBlockSize + 512 > size) { return cb(null, position); } position += entryBlockSize + 512; if (position >= size) { return cb(null, position); } if (opt.mtimeCache && h.mtime) { opt.mtimeCache.set(String(h.path), h.mtime); } bufPos = 0; fs.read(fd, headBuf, 0, 512, position, onread); }; fs.read(fd, headBuf, 0, 512, position, onread); }; const promise = new Promise((resolve, reject) => { p.on('error', reject); let flag = 'r+'; const onopen = (er, fd) => { if (er && er.code === 'ENOENT' && flag === 'r+') { flag = 'w+'; return fs.open(opt.file, flag, onopen); } if (er || !fd) { return reject(er); } fs.fstat(fd, (er, st) => { if (er) { return fs.close(fd, () => reject(er)); } getPos(fd, st.size, (er, position) => { if (er) { return reject(er); } const stream = new WriteStream(opt.file, { fd: fd, start: position, }); p.pipe(stream); stream.on('error', reject); stream.on('close', resolve); addFilesAsync(p, files); }); }); }; fs.open(opt.file, flag, onopen); }); return promise; }; const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { list({ file: path.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onReadEntry: entry => p.add(entry), }); } else { p.add(file); } }); p.end(); }; const addFilesAsync = async (p, files) => { for (let i = 0; i < files.length; i++) { const file = String(files[i]); if (file.charAt(0) === '@') { await list({ file: path.resolve(String(p.cwd), file.slice(1)), noResume: true, onReadEntry: entry => p.add(entry), }); } else { p.add(file); } } p.end(); }; export const replace = makeCommand(replaceSync, replaceAsync, /* c8 ignore start */ () => { throw new TypeError('file is required'); }, () => { throw new TypeError('file is required'); }, /* c8 ignore stop */ (opt, entries) => { if (!isFile(opt)) { throw new TypeError('file is required'); } if (opt.gzip || opt.brotli || opt.file.endsWith('.br') || opt.file.endsWith('.tbr')) { throw new TypeError('cannot append to compressed archives'); } if (!entries?.length) { throw new TypeError('no paths specified to add/replace'); } }); //# sourceMappingURL=replace.js.map// unix absolute paths are also absolute on win32, so we use this for both import { win32 } from 'node:path'; const { isAbsolute, parse } = win32; // returns [root, stripped] // Note that windows will think that //x/y/z/a has a "root" of //x/y, and in // those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip / // explicitly if it's the first character. // drive-specific relative paths on Windows get their root stripped off even // though they are not absolute, so `c:../foo` becomes ['c:', '../foo'] export const stripAbsolutePath = (path) => { let r = ''; let parsed = parse(path); while (isAbsolute(path) || parsed.root) { // windows will think that //x/y/z has a "root" of //x/y/ // but strip the //?/C:/ off of //?/C:/path const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ? '/' : parsed.root; path = path.slice(root.length); r += root; parsed = parse(path); } return [r, path]; }; //# sourceMappingURL=strip-absolute-path.js.map// warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. export const stripTrailingSlashes = (str) => { let i = str.length - 1; let slashesStart = -1; while (i > -1 && str.charAt(i) === '/') { slashesStart = i; i--; } return slashesStart === -1 ? str : str.slice(0, slashesStart); }; //# sourceMappingURL=strip-trailing-slashes.js.mapexport class SymlinkError extends Error { path; symlink; syscall = 'symlink'; code = 'TAR_SYMLINK_ERROR'; constructor(symlink, path) { super('TAR_SYMLINK_ERROR: Cannot extract through symbolic link'); this.symlink = symlink; this.path = path; } get name() { return 'SymlinkError'; } } //# sourceMappingURL=symlink-error.js.mapexport const isCode = (c) => name.has(c); export const isName = (c) => code.has(c); // map types from key to human-friendly name export const name = new Map([ ['0', 'File'], // same as File ['', 'OldFile'], ['1', 'Link'], ['2', 'SymbolicLink'], // Devices and FIFOs aren't fully supported // they are parsed, but skipped when unpacking ['3', 'CharacterDevice'], ['4', 'BlockDevice'], ['5', 'Directory'], ['6', 'FIFO'], // same as File ['7', 'ContiguousFile'], // pax headers ['g', 'GlobalExtendedHeader'], ['x', 'ExtendedHeader'], // vendor-specific stuff // skip ['A', 'SolarisACL'], // like 5, but with data, which should be skipped ['D', 'GNUDumpDir'], // metadata only, skip ['I', 'Inode'], // data = link path of next file ['K', 'NextFileHasLongLinkpath'], // data = path of next file ['L', 'NextFileHasLongPath'], // skip ['M', 'ContinuationFile'], // like L ['N', 'OldGnuLongPath'], // skip ['S', 'SparseFile'], // skip ['V', 'TapeVolumeHeader'], // like x ['X', 'OldExtendedHeader'], ]); // map the other direction export const code = new Map(Array.from(name).map(kv => [kv[1], kv[0]])); //# sourceMappingURL=types.js.map// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. // but the path reservations are required to avoid race conditions where // parallelized unpack ops may mess with one another, due to dependencies // (like a Link depending on its target) or destructive operations (like // clobbering an fs object to create one of a different type.) import * as fsm from '@isaacs/fs-minipass'; import assert from 'node:assert'; import { randomBytes } from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { getWriteFlag } from './get-write-flag.js'; import { mkdir, mkdirSync } from './mkdir.js'; import { normalizeUnicode } from './normalize-unicode.js'; import { normalizeWindowsPath } from './normalize-windows-path.js'; import { Parser } from './parse.js'; import { stripAbsolutePath } from './strip-absolute-path.js'; import { stripTrailingSlashes } from './strip-trailing-slashes.js'; import * as wc from './winchars.js'; import { PathReservations } from './path-reservations.js'; const ONENTRY = Symbol('onEntry'); const CHECKFS = Symbol('checkFs'); const CHECKFS2 = Symbol('checkFs2'); const PRUNECACHE = Symbol('pruneCache'); const ISREUSABLE = Symbol('isReusable'); const MAKEFS = Symbol('makeFs'); const FILE = Symbol('file'); const DIRECTORY = Symbol('directory'); const LINK = Symbol('link'); const SYMLINK = Symbol('symlink'); const HARDLINK = Symbol('hardlink'); const UNSUPPORTED = Symbol('unsupported'); const CHECKPATH = Symbol('checkPath'); const MKDIR = Symbol('mkdir'); const ONERROR = Symbol('onError'); const PENDING = Symbol('pending'); const PEND = Symbol('pend'); const UNPEND = Symbol('unpend'); const ENDED = Symbol('ended'); const MAYBECLOSE = Symbol('maybeClose'); const SKIP = Symbol('skip'); const DOCHOWN = Symbol('doChown'); const UID = Symbol('uid'); const GID = Symbol('gid'); const CHECKED_CWD = Symbol('checkedCwd'); const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; const isWindows = platform === 'win32'; const DEFAULT_MAX_DEPTH = 1024; // Unlinks on Windows are not atomic. // // This means that if you have a file entry, followed by another // file entry with an identical name, and you cannot re-use the file // (because it's a hardlink, or because unlink:true is set, or it's // Windows, which does not have useful nlink values), then the unlink // will be committed to the disk AFTER the new file has been written // over the old one, deleting the new file. // // To work around this, on Windows systems, we rename the file and then // delete the renamed file. It's a sloppy kludge, but frankly, I do not // know of a better way to do this, given windows' non-atomic unlink // semantics. // // See: https://github.com/npm/node-tar/issues/183 /* c8 ignore start */ const unlinkFile = (path, cb) => { if (!isWindows) { return fs.unlink(path, cb); } const name = path + '.DELETE.' + randomBytes(16).toString('hex'); fs.rename(path, name, er => { if (er) { return cb(er); } fs.unlink(name, cb); }); }; /* c8 ignore stop */ /* c8 ignore start */ const unlinkFileSync = (path) => { if (!isWindows) { return fs.unlinkSync(path); } const name = path + '.DELETE.' + randomBytes(16).toString('hex'); fs.renameSync(path, name); fs.unlinkSync(name); }; /* c8 ignore stop */ // this.gid, entry.gid, this.processUid const uint32 = (a, b, c) => a !== undefined && a === a >>> 0 ? a : b !== undefined && b === b >>> 0 ? b : c; // clear the cache if it's a case-insensitive unicode-squashing match. // we can't know if the current file system is case-sensitive or supports // unicode fully, so we check for similarity on the maximally compatible // representation. Err on the side of pruning, since all it's doing is // preventing lstats, and it's not the end of the world if we get a false // positive. // Note that on windows, we always drop the entire cache whenever a // symbolic link is encountered, because 8.3 filenames are impossible // to reason about, and collisions are hazards rather than just failures. const cacheKeyNormalize = (path) => stripTrailingSlashes(normalizeWindowsPath(normalizeUnicode(path))).toLowerCase(); // remove all cache entries matching ${abs}/** const pruneCache = (cache, abs) => { abs = cacheKeyNormalize(abs); for (const path of cache.keys()) { const pnorm = cacheKeyNormalize(path); if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) { cache.delete(path); } } }; const dropCache = (cache) => { for (const key of cache.keys()) { cache.delete(key); } }; export class Unpack extends Parser { [ENDED] = false; [CHECKED_CWD] = false; [PENDING] = 0; reservations = new PathReservations(); transform; writable = true; readable = false; dirCache; uid; gid; setOwner; preserveOwner; processGid; processUid; maxDepth; forceChown; win32; newer; keep; noMtime; preservePaths; unlink; cwd; strip; processUmask; umask; dmode; fmode; chmod; constructor(opt = {}) { opt.ondone = () => { this[ENDED] = true; this[MAYBECLOSE](); }; super(opt); this.transform = opt.transform; this.dirCache = opt.dirCache || new Map(); this.chmod = !!opt.chmod; if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { // need both or neither if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') { throw new TypeError('cannot set owner without number uid and gid'); } if (opt.preserveOwner) { throw new TypeError('cannot preserve owner in archive and also set owner explicitly'); } this.uid = opt.uid; this.gid = opt.gid; this.setOwner = true; } else { this.uid = undefined; this.gid = undefined; this.setOwner = false; } // default true for root if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') { this.preserveOwner = !!(process.getuid && process.getuid() === 0); } else { this.preserveOwner = !!opt.preserveOwner; } this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : undefined; this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : undefined; // prevent excessively deep nesting of subfolders // set to `Infinity` to remove this restriction this.maxDepth = typeof opt.maxDepth === 'number' ? opt.maxDepth : DEFAULT_MAX_DEPTH; // mostly just for testing, but useful in some cases. // Forcibly trigger a chown on every entry, no matter what this.forceChown = opt.forceChown === true; // turn > this[ONENTRY](entry)); } // a bad or damaged archive is a warning for Parser, but an error // when extracting. Mark those errors as unrecoverable, because // the Unpack contract cannot be met. warn(code, msg, data = {}) { if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') { data.recoverable = false; } return super.warn(code, msg, data); } [MAYBECLOSE]() { if (this[ENDED] && this[PENDING] === 0) { this.emit('prefinish'); this.emit('finish'); this.emit('end'); } } [CHECKPATH](entry) { const p = normalizeWindowsPath(entry.path); const parts = p.split('/'); if (this.strip) { if (parts.length < this.strip) { return false; } if (entry.type === 'Link') { const linkparts = normalizeWindowsPath(String(entry.linkpath)).split('/'); if (linkparts.length >= this.strip) { entry.linkpath = linkparts.slice(this.strip).join('/'); } else { return false; } } parts.splice(0, this.strip); entry.path = parts.join('/'); } if (isFinite(this.maxDepth) && parts.length > this.maxDepth) { this.warn('TAR_ENTRY_ERROR', 'path excessively deep', { entry, path: p, depth: parts.length, maxDepth: this.maxDepth, }); return false; } if (!this.preservePaths) { if (parts.includes('..') || /* c8 ignore next */ (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) { this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { entry, path: p, }); return false; } // strip off the root const [root, stripped] = stripAbsolutePath(p); if (root) { entry.path = String(stripped); this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { entry, path: p, }); } } if (path.isAbsolute(entry.path)) { entry.absolute = normalizeWindowsPath(path.resolve(entry.path)); } else { entry.absolute = normalizeWindowsPath(path.resolve(this.cwd, entry.path)); } // if we somehow ended up with a path that escapes the cwd, and we are // not in preservePaths mode, then something is fishy! This should have // been prevented above, so ignore this for coverage. /* c8 ignore start - defense in depth */ if (!this.preservePaths && typeof entry.absolute === 'string' && entry.absolute.indexOf(this.cwd + '/') !== 0 && entry.absolute !== this.cwd) { this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { entry, path: normalizeWindowsPath(entry.path), resolvedPath: entry.absolute, cwd: this.cwd, }); return false; } /* c8 ignore stop */ // an archive can set properties on the extraction directory, but it // may not replace the cwd with a different kind of thing entirely. if (entry.absolute === this.cwd && entry.type !== 'Directory' && entry.type !== 'GNUDumpDir') { return false; } // only encode : chars that aren't drive letter indicators if (this.win32) { const { root: aRoot } = path.win32.parse(String(entry.absolute)); entry.absolute = aRoot + wc.encode(String(entry.absolute).slice(aRoot.length)); const { root: pRoot } = path.win32.parse(entry.path); entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length)); } return true; } [ONENTRY](entry) { if (!this[CHECKPATH](entry)) { return entry.resume(); } assert.equal(typeof entry.absolute, 'string'); switch (entry.type) { case 'Directory': case 'GNUDumpDir': if (entry.mode) { entry.mode = entry.mode | 0o700; } // eslint-disable-next-line no-fallthrough case 'File': case 'OldFile': case 'ContiguousFile': case 'Link': case 'SymbolicLink': return this[CHECKFS](entry); case 'CharacterDevice': case 'BlockDevice': case 'FIFO': default: return this[UNSUPPORTED](entry); } } [ONERROR](er, entry) { // Cwd has to exist, or else nothing works. That's serious. // Other errors are warnings, which raise the error in strict // mode, but otherwise continue on. if (er.name === 'CwdError') { this.emit('error', er); } else { this.warn('TAR_ENTRY_ERROR', er, { entry }); this[UNPEND](); entry.resume(); } } [MKDIR](dir, mode, cb) { mkdir(normalizeWindowsPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, }, cb); } [DOCHOWN](entry) { // in preserve owner mode, chown if the entry doesn't match process // in set owner mode, chown if setting doesn't match process return (this.forceChown || (this.preserveOwner && ((typeof entry.uid === 'number' && entry.uid !== this.processUid) || (typeof entry.gid === 'number' && entry.gid !== this.processGid))) || (typeof this.uid === 'number' && this.uid !== this.processUid) || (typeof this.gid === 'number' && this.gid !== this.processGid)); } [UID](entry) { return uint32(this.uid, entry.uid, this.processUid); } [GID](entry) { return uint32(this.gid, entry.gid, this.processGid); } [FILE](entry, fullyDone) { const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.fmode; const stream = new fsm.WriteStream(String(entry.absolute), { // slight lie, but it can be numeric flags flags: getWriteFlag(entry.size), mode: mode, autoClose: false, }); stream.on('error', (er) => { if (stream.fd) { fs.close(stream.fd, () => { }); } // flush all the data out so that we aren't left hanging // if the error wasn't actually fatal. otherwise the parse // is blocked, and we never proceed. stream.write = () => true; this[ONERROR](er, entry); fullyDone(); }); let actions = 1; const done = (er) => { if (er) { /* c8 ignore start - we should always have a fd by now */ if (stream.fd) { fs.close(stream.fd, () => { }); } /* c8 ignore stop */ this[ONERROR](er, entry); fullyDone(); return; } if (--actions === 0) { if (stream.fd !== undefined) { fs.close(stream.fd, er => { if (er) { this[ONERROR](er, entry); } else { this[UNPEND](); } fullyDone(); }); } } }; stream.on('finish', () => { // if futimes fails, try utimes // if utimes fails, fail with the original error // same for fchown/chown const abs = String(entry.absolute); const fd = stream.fd; if (typeof fd === 'number' && entry.mtime && !this.noMtime) { actions++; const atime = entry.atime || new Date(); const mtime = entry.mtime; fs.futimes(fd, atime, mtime, er => er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) : done()); } if (typeof fd === 'number' && this[DOCHOWN](entry)) { actions++; const uid = this[UID](entry); const gid = this[GID](entry); if (typeof uid === 'number' && typeof gid === 'number') { fs.fchown(fd, uid, gid, er => er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) : done()); } } done(); }); const tx = this.transform ? this.transform(entry) || entry : entry; if (tx !== entry) { tx.on('error', (er) => { this[ONERROR](er, entry); fullyDone(); }); entry.pipe(tx); } tx.pipe(stream); } [DIRECTORY](entry, fullyDone) { const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.dmode; this[MKDIR](String(entry.absolute), mode, er => { if (er) { this[ONERROR](er, entry); fullyDone(); return; } let actions = 1; const done = () => { if (--actions === 0) { fullyDone(); this[UNPEND](); entry.resume(); } }; if (entry.mtime && !this.noMtime) { actions++; fs.utimes(String(entry.absolute), entry.atime || new Date(), entry.mtime, done); } if (this[DOCHOWN](entry)) { actions++; fs.chown(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)), done); } done(); }); } [UNSUPPORTED](entry) { entry.unsupported = true; this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry }); entry.resume(); } [SYMLINK](entry, done) { this[LINK](entry, String(entry.linkpath), 'symlink', done); } [HARDLINK](entry, done) { const linkpath = normalizeWindowsPath(path.resolve(this.cwd, String(entry.linkpath))); this[LINK](entry, linkpath, 'link', done); } [PEND]() { this[PENDING]++; } [UNPEND]() { this[PENDING]--; this[MAYBECLOSE](); } [SKIP](entry) { this[UNPEND](); entry.resume(); } // Check if we can reuse an existing filesystem entry safely and // overwrite it, rather than unlinking and recreating // Windows doesn't report a useful nlink, so we just never reuse entries [ISREUSABLE](entry, st) { return (entry.type === 'File' && !this.unlink && st.isFile() && st.nlink <= 1 && !isWindows); } // check if a thing is there, and if so, try to clobber it [CHECKFS](entry) { this[PEND](); const paths = [entry.path]; if (entry.linkpath) { paths.push(entry.linkpath); } this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)); } [PRUNECACHE](entry) { // if we are not creating a directory, and the path is in the dirCache, // then that means we are about to delete the directory we created // previously, and it is no longer going to be a directory, and neither // is any of its children. // If a symbolic link is encountered, all bets are off. There is no // reasonable way to sanitize the cache in such a way we will be able to // avoid having filesystem collisions. If this happens with a non-symlink // entry, it'll just fail to unpack, but a symlink to a directory, using an // 8.3 shortname or certain unicode attacks, can evade detection and lead // to arbitrary writes to anywhere on the system. if (entry.type === 'SymbolicLink') { dropCache(this.dirCache); } else if (entry.type !== 'Directory') { pruneCache(this.dirCache, String(entry.absolute)); } } [CHECKFS2](entry, fullyDone) { this[PRUNECACHE](entry); const done = (er) => { this[PRUNECACHE](entry); fullyDone(er); }; const checkCwd = () => { this[MKDIR](this.cwd, this.dmode, er => { if (er) { this[ONERROR](er, entry); done(); return; } this[CHECKED_CWD] = true; start(); }); }; const start = () => { if (entry.absolute !== this.cwd) { const parent = normalizeWindowsPath(path.dirname(String(entry.absolute))); if (parent !== this.cwd) { return this[MKDIR](parent, this.dmode, er => { if (er) { this[ONERROR](er, entry); done(); return; } afterMakeParent(); }); } } afterMakeParent(); }; const afterMakeParent = () => { fs.lstat(String(entry.absolute), (lstatEr, st) => { if (st && (this.keep || /* c8 ignore next */ (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) { this[SKIP](entry); done(); return; } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry, done); } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = this.chmod && entry.mode && (st.mode & 0o7777) !== entry.mode; const afterChmod = (er) => this[MAKEFS](er ?? null, entry, done); if (!needChmod) { return afterChmod(); } return fs.chmod(String(entry.absolute), Number(entry.mode), afterChmod); } // Not a dir entry, have to remove it. // NB: the only way to end up with an entry that is the cwd // itself, in such a way that == does not detect, is a // tricky windows absolute path with UNC or 8.3 parts (and // preservePaths:true, or else it will have been stripped). // In that case, the user has opted out of path protections // explicitly, so if they blow away the cwd, c'est la vie. if (entry.absolute !== this.cwd) { return fs.rmdir(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done)); } } // not a dir, and not reusable // don't remove if the cwd, we want that error if (entry.absolute === this.cwd) { return this[MAKEFS](null, entry, done); } unlinkFile(String(entry.absolute), er => this[MAKEFS](er ?? null, entry, done)); }); }; if (this[CHECKED_CWD]) { start(); } else { checkCwd(); } } [MAKEFS](er, entry, done) { if (er) { this[ONERROR](er, entry); done(); return; } switch (entry.type) { case 'File': case 'OldFile': case 'ContiguousFile': return this[FILE](entry, done); case 'Link': return this[HARDLINK](entry, done); case 'SymbolicLink': return this[SYMLINK](entry, done); case 'Directory': case 'GNUDumpDir': return this[DIRECTORY](entry, done); } } [LINK](entry, linkpath, link, done) { // XXX: get the type ('symlink' or 'junction') for windows fs[link](linkpath, String(entry.absolute), er => { if (er) { this[ONERROR](er, entry); } else { this[UNPEND](); entry.resume(); } done(); }); } } const callSync = (fn) => { try { return [null, fn()]; } catch (er) { return [er, null]; } }; export class UnpackSync extends Unpack { sync = true; [MAKEFS](er, entry) { return super[MAKEFS](er, entry, () => { }); } [CHECKFS](entry) { this[PRUNECACHE](entry); if (!this[CHECKED_CWD]) { const er = this[MKDIR](this.cwd, this.dmode); if (er) { return this[ONERROR](er, entry); } this[CHECKED_CWD] = true; } // don't bother to make the parent if the current entry is the cwd, // we've already checked it. if (entry.absolute !== this.cwd) { const parent = normalizeWindowsPath(path.dirname(String(entry.absolute))); if (parent !== this.cwd) { const mkParent = this[MKDIR](parent, this.dmode); if (mkParent) { return this[ONERROR](mkParent, entry); } } } const [lstatEr, st] = callSync(() => fs.lstatSync(String(entry.absolute))); if (st && (this.keep || /* c8 ignore next */ (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) { return this[SKIP](entry); } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry); } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = this.chmod && entry.mode && (st.mode & 0o7777) !== entry.mode; const [er] = needChmod ? callSync(() => { fs.chmodSync(String(entry.absolute), Number(entry.mode)); }) : []; return this[MAKEFS](er, entry); } // not a dir entry, have to remove it const [er] = callSync(() => fs.rmdirSync(String(entry.absolute))); this[MAKEFS](er, entry); } // not a dir, and not reusable. // don't remove if it's the cwd, since we want that error. const [er] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(String(entry.absolute))); this[MAKEFS](er, entry); } [FILE](entry, done) { const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.fmode; const oner = (er) => { let closeError; try { fs.closeSync(fd); } catch (e) { closeError = e; } if (er || closeError) { this[ONERROR](er || closeError, entry); } done(); }; let fd; try { fd = fs.openSync(String(entry.absolute), getWriteFlag(entry.size), mode); } catch (er) { return oner(er); } const tx = this.transform ? this.transform(entry) || entry : entry; if (tx !== entry) { tx.on('error', (er) => this[ONERROR](er, entry)); entry.pipe(tx); } tx.on('data', (chunk) => { try { fs.writeSync(fd, chunk, 0, chunk.length); } catch (er) { oner(er); } }); tx.on('end', () => { let er = null; // try both, falling futimes back to utimes // if either fails, handle the first error if (entry.mtime && !this.noMtime) { const atime = entry.atime || new Date(); const mtime = entry.mtime; try { fs.futimesSync(fd, atime, mtime); } catch (futimeser) { try { fs.utimesSync(String(entry.absolute), atime, mtime); } catch (utimeser) { er = futimeser; } } } if (this[DOCHOWN](entry)) { const uid = this[UID](entry); const gid = this[GID](entry); try { fs.fchownSync(fd, Number(uid), Number(gid)); } catch (fchowner) { try { fs.chownSync(String(entry.absolute), Number(uid), Number(gid)); } catch (chowner) { er = er || fchowner; } } } oner(er); }); } [DIRECTORY](entry, done) { const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.dmode; const er = this[MKDIR](String(entry.absolute), mode); if (er) { this[ONERROR](er, entry); done(); return; } if (entry.mtime && !this.noMtime) { try { fs.utimesSync(String(entry.absolute), entry.atime || new Date(), entry.mtime); /* c8 ignore next */ } catch (er) { } } if (this[DOCHOWN](entry)) { try { fs.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry))); } catch (er) { } } done(); entry.resume(); } [MKDIR](dir, mode) { try { return mkdirSync(normalizeWindowsPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, }); } catch (er) { return er; } } [LINK](entry, linkpath, link, done) { const ls = `${link}Sync`; try { fs[ls](linkpath, String(entry.absolute)); done(); entry.resume(); } catch (er) { return this[ONERROR](er, entry); } } } //# sourceMappingURL=unpack.js.map// tar -u import { makeCommand } from './make-command.js'; import { replace as r } from './replace.js'; // just call tar.r with the filter and mtimeCache export const update = makeCommand(r.syncFile, r.asyncFile, r.syncNoFile, r.asyncNoFile, (opt, entries = []) => { r.validate?.(opt, entries); mtimeFilter(opt); }); const mtimeFilter = (opt) => { const filter = opt.filter; if (!opt.mtimeCache) { opt.mtimeCache = new Map(); } opt.filter = filter ? (path, stat) => filter(path, stat) && !( /* c8 ignore start */ ((opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) > (stat.mtime ?? 0)) /* c8 ignore stop */ ) : (path, stat) => !( /* c8 ignore start */ ((opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) > (stat.mtime ?? 0)) /* c8 ignore stop */ ); }; //# sourceMappingURL=update.js.mapexport const warnMethod = (self, code, message, data = {}) => { if (self.file) { data.file = self.file; } if (self.cwd) { data.cwd = self.cwd; } data.code = (message instanceof Error && message.code) || code; data.tarCode = code; if (!self.strict && data.recoverable !== false) { if (message instanceof Error) { data = Object.assign(message, data); message = message.message; } self.emit('warn', code, message, data); } else if (message instanceof Error) { self.emit('error', Object.assign(message, data)); } else { self.emit('error', Object.assign(new Error(`${code}: ${message}`), data)); } }; //# sourceMappingURL=warn-method.js.map// When writing files on Windows, translate the characters to their // 0xf000 higher-encoded versions. const raw = ['|', '<', '>', '?', ':']; const win = raw.map(char => String.fromCharCode(0xf000 + char.charCodeAt(0))); const toWin = new Map(raw.map((char, i) => [char, win[i]])); const toRaw = new Map(win.map((char, i) => [char, raw[i]])); export const encode = (s) => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s); export const decode = (s) => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s); //# sourceMappingURL=winchars.js.mapimport fs from 'fs'; import { Minipass } from 'minipass'; import path from 'path'; import { Header } from './header.js'; import { modeFix } from './mode-fix.js'; import { normalizeWindowsPath } from './normalize-windows-path.js'; import { dealias, } from './options.js'; import { Pax } from './pax.js'; import { stripAbsolutePath } from './strip-absolute-path.js'; import { stripTrailingSlashes } from './strip-trailing-slashes.js'; import { warnMethod, } from './warn-method.js'; import * as winchars from './winchars.js'; const prefixPath = (path, prefix) => { if (!prefix) { return normalizeWindowsPath(path); } path = normalizeWindowsPath(path).replace(/^\.(\/|$)/, ''); return stripTrailingSlashes(prefix) + '/' + path; }; const maxReadSize = 16 * 1024 * 1024; const PROCESS = Symbol('process'); const FILE = Symbol('file'); const DIRECTORY = Symbol('directory'); const SYMLINK = Symbol('symlink'); const HARDLINK = Symbol('hardlink'); const HEADER = Symbol('header'); const READ = Symbol('read'); const LSTAT = Symbol('lstat'); const ONLSTAT = Symbol('onlstat'); const ONREAD = Symbol('onread'); const ONREADLINK = Symbol('onreadlink'); const OPENFILE = Symbol('openfile'); const ONOPENFILE = Symbol('onopenfile'); const CLOSE = Symbol('close'); const MODE = Symbol('mode'); const AWAITDRAIN = Symbol('awaitDrain'); const ONDRAIN = Symbol('ondrain'); const PREFIX = Symbol('prefix'); export class WriteEntry extends Minipass { path; portable; myuid = (process.getuid && process.getuid()) || 0; // until node has builtin pwnam functions, this'll have to do myuser = process.env.USER || ''; maxReadSize; linkCache; statCache; preservePaths; cwd; strict; mtime; noPax; noMtime; prefix; fd; blockLen = 0; blockRemain = 0; buf; pos = 0; remain = 0; length = 0; offset = 0; win32; absolute; header; type; linkpath; stat; onWriteEntry; #hadError = false; constructor(p, opt_ = {}) { const opt = dealias(opt_); super(); this.path = normalizeWindowsPath(p); // suppress atime, ctime, uid, gid, uname, gname this.portable = !!opt.portable; this.maxReadSize = opt.maxReadSize || maxReadSize; this.linkCache = opt.linkCache || new Map(); this.statCache = opt.statCache || new Map(); this.preservePaths = !!opt.preservePaths; this.cwd = normalizeWindowsPath(opt.cwd || process.cwd()); this.strict = !!opt.strict; this.noPax = !!opt.noPax; this.noMtime = !!opt.noMtime; this.mtime = opt.mtime; this.prefix = opt.prefix ? normalizeWindowsPath(opt.prefix) : undefined; this.onWriteEntry = opt.onWriteEntry; if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn); } let pathWarn = false; if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path); if (root && typeof stripped === 'string') { this.path = stripped; pathWarn = root; } } this.win32 = !!opt.win32 || process.platform === 'win32'; if (this.win32) { // force the \ to / normalization, since we might not *actually* // be on windows, but want \ to be considered a path separator. this.path = winchars.decode(this.path.replace(/\\/g, '/')); p = p.replace(/\\/g, '/'); } this.absolute = normalizeWindowsPath(opt.absolute || path.resolve(this.cwd, p)); if (this.path === '') { this.path = './'; } if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }); } const cs = this.statCache.get(this.absolute); if (cs) { this[ONLSTAT](cs); } else { this[LSTAT](); } } warn(code, message, data = {}) { return warnMethod(this, code, message, data); } emit(ev, ...data) { if (ev === 'error') { this.#hadError = true; } return super.emit(ev, ...data); } [LSTAT]() { fs.lstat(this.absolute, (er, stat) => { if (er) { return this.emit('error', er); } this[ONLSTAT](stat); }); } [ONLSTAT](stat) { this.statCache.set(this.absolute, stat); this.stat = stat; if (!stat.isFile()) { stat.size = 0; } this.type = getType(stat); this.emit('stat', stat); this[PROCESS](); } [PROCESS]() { switch (this.type) { case 'File': return this[FILE](); case 'Directory': return this[DIRECTORY](); case 'SymbolicLink': return this[SYMLINK](); // unsupported types are ignored. default: return this.end(); } } [MODE](mode) { return modeFix(mode, this.type === 'Directory', this.portable); } [PREFIX](path) { return prefixPath(path, this.prefix); } [HEADER]() { /* c8 ignore start */ if (!this.stat) { throw new Error('cannot write header before stat'); } /* c8 ignore stop */ if (this.type === 'Directory' && this.portable) { this.noMtime = true; } this.onWriteEntry?.(this); this.header = new Header({ path: this[PREFIX](this.path), // only apply the prefix to hard links. linkpath: this.type === 'Link' && this.linkpath !== undefined ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this[MODE](this.stat.mode), uid: this.portable ? undefined : this.stat.uid, gid: this.portable ? undefined : this.stat.gid, size: this.stat.size, mtime: this.noMtime ? undefined : this.mtime || this.stat.mtime, /* c8 ignore next */ type: this.type === 'Unsupported' ? undefined : this.type, uname: this.portable ? undefined : this.stat.uid === this.myuid ? this.myuser : '', atime: this.portable ? undefined : this.stat.atime, ctime: this.portable ? undefined : this.stat.ctime, }); if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? undefined : this.header.atime, ctime: this.portable ? undefined : this.header.ctime, gid: this.portable ? undefined : this.header.gid, mtime: this.noMtime ? undefined : (this.mtime || this.header.mtime), path: this[PREFIX](this.path), linkpath: this.type === 'Link' && this.linkpath !== undefined ? this[PREFIX](this.linkpath) : this.linkpath, size: this.header.size, uid: this.portable ? undefined : this.header.uid, uname: this.portable ? undefined : this.header.uname, dev: this.portable ? undefined : this.stat.dev, ino: this.portable ? undefined : this.stat.ino, nlink: this.portable ? undefined : this.stat.nlink, }).encode()); } const block = this.header?.block; /* c8 ignore start */ if (!block) { throw new Error('failed to encode header'); } /* c8 ignore stop */ super.write(block); } [DIRECTORY]() { /* c8 ignore start */ if (!this.stat) { throw new Error('cannot create directory entry without stat'); } /* c8 ignore stop */ if (this.path.slice(-1) !== '/') { this.path += '/'; } this.stat.size = 0; this[HEADER](); this.end(); } [SYMLINK]() { fs.readlink(this.absolute, (er, linkpath) => { if (er) { return this.emit('error', er); } this[ONREADLINK](linkpath); }); } [ONREADLINK](linkpath) { this.linkpath = normalizeWindowsPath(linkpath); this[HEADER](); this.end(); } [HARDLINK](linkpath) { /* c8 ignore start */ if (!this.stat) { throw new Error('cannot create link entry without stat'); } /* c8 ignore stop */ this.type = 'Link'; this.linkpath = normalizeWindowsPath(path.relative(this.cwd, linkpath)); this.stat.size = 0; this[HEADER](); this.end(); } [FILE]() { /* c8 ignore start */ if (!this.stat) { throw new Error('cannot create file entry without stat'); } /* c8 ignore stop */ if (this.stat.nlink > 1) { const linkKey = `${this.stat.dev}:${this.stat.ino}`; const linkpath = this.linkCache.get(linkKey); if (linkpath?.indexOf(this.cwd) === 0) { return this[HARDLINK](linkpath); } this.linkCache.set(linkKey, this.absolute); } this[HEADER](); if (this.stat.size === 0) { return this.end(); } this[OPENFILE](); } [OPENFILE]() { fs.open(this.absolute, 'r', (er, fd) => { if (er) { return this.emit('error', er); } this[ONOPENFILE](fd); }); } [ONOPENFILE](fd) { this.fd = fd; if (this.#hadError) { return this[CLOSE](); } /* c8 ignore start */ if (!this.stat) { throw new Error('should stat before calling onopenfile'); } /* c8 ignore start */ this.blockLen = 512 * Math.ceil(this.stat.size / 512); this.blockRemain = this.blockLen; const bufLen = Math.min(this.blockLen, this.maxReadSize); this.buf = Buffer.allocUnsafe(bufLen); this.offset = 0; this.pos = 0; this.remain = this.stat.size; this.length = this.buf.length; this[READ](); } [READ]() { const { fd, buf, offset, length, pos } = this; if (fd === undefined || buf === undefined) { throw new Error('cannot read file without first opening'); } fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { if (er) { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one return this[CLOSE](() => this.emit('error', er)); } this[ONREAD](bytesRead); }); } /* c8 ignore start */ [CLOSE](cb = () => { }) { /* c8 ignore stop */ if (this.fd !== undefined) fs.close(this.fd, cb); } [ONREAD](bytesRead) { if (bytesRead <= 0 && this.remain > 0) { const er = Object.assign(new Error('encountered unexpected EOF'), { path: this.absolute, syscall: 'read', code: 'EOF', }); return this[CLOSE](() => this.emit('error', er)); } if (bytesRead > this.remain) { const er = Object.assign(new Error('did not encounter expected EOF'), { path: this.absolute, syscall: 'read', code: 'EOF', }); return this[CLOSE](() => this.emit('error', er)); } /* c8 ignore start */ if (!this.buf) { throw new Error('should have created buffer prior to reading'); } /* c8 ignore stop */ // null out the rest of the buffer, if we could fit the block padding // at the end of this loop, we've incremented bytesRead and this.remain // to be incremented up to the blockRemain level, as if we had expected // to get a null-padded file, and read it until the end. then we will // decrement both remain and blockRemain by bytesRead, and know that we // reached the expected EOF, without any null buffer to append. if (bytesRead === this.remain) { for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { this.buf[i + this.offset] = 0; bytesRead++; this.remain++; } } const chunk = this.offset === 0 && bytesRead === this.buf.length ? this.buf : this.buf.subarray(this.offset, this.offset + bytesRead); const flushed = this.write(chunk); if (!flushed) { this[AWAITDRAIN](() => this[ONDRAIN]()); } else { this[ONDRAIN](); } } [AWAITDRAIN](cb) { this.once('drain', cb); } write(chunk, encoding, cb) { /* c8 ignore start - just junk to comply with NodeJS.WritableStream */ if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8'); } /* c8 ignore stop */ if (this.blockRemain < chunk.length) { const er = Object.assign(new Error('writing more data than expected'), { path: this.absolute, }); return this.emit('error', er); } this.remain -= chunk.length; this.blockRemain -= chunk.length; this.pos += chunk.length; this.offset += chunk.length; return super.write(chunk, null, cb); } [ONDRAIN]() { if (!this.remain) { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)); } return this[CLOSE](er => er ? this.emit('error', er) : this.end()); } /* c8 ignore start */ if (!this.buf) { throw new Error('buffer lost somehow in ONDRAIN'); } /* c8 ignore stop */ if (this.offset >= this.length) { // if we only have a smaller bit left to read, alloc a smaller buffer // otherwise, keep it the same length it was before. this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)); this.offset = 0; } this.length = this.buf.length - this.offset; this[READ](); } } export class WriteEntrySync extends WriteEntry { sync = true; [LSTAT]() { this[ONLSTAT](fs.lstatSync(this.absolute)); } [SYMLINK]() { this[ONREADLINK](fs.readlinkSync(this.absolute)); } [OPENFILE]() { this[ONOPENFILE](fs.openSync(this.absolute, 'r')); } [READ]() { let threw = true; try { const { fd, buf, offset, length, pos } = this; /* c8 ignore start */ if (fd === undefined || buf === undefined) { throw new Error('fd and buf must be set in READ method'); } /* c8 ignore stop */ const bytesRead = fs.readSync(fd, buf, offset, length, pos); this[ONREAD](bytesRead); threw = false; } finally { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one if (threw) { try { this[CLOSE](() => { }); } catch (er) { } } } } [AWAITDRAIN](cb) { cb(); } /* c8 ignore start */ [CLOSE](cb = () => { }) { /* c8 ignore stop */ if (this.fd !== undefined) fs.closeSync(this.fd); cb(); } } export class WriteEntryTar extends Minipass { blockLen = 0; blockRemain = 0; buf = 0; pos = 0; remain = 0; length = 0; preservePaths; portable; strict; noPax; noMtime; readEntry; type; prefix; path; mode; uid; gid; uname; gname; header; mtime; atime; ctime; linkpath; size; onWriteEntry; warn(code, message, data = {}) { return warnMethod(this, code, message, data); } constructor(readEntry, opt_ = {}) { const opt = dealias(opt_); super(); this.preservePaths = !!opt.preservePaths; this.portable = !!opt.portable; this.strict = !!opt.strict; this.noPax = !!opt.noPax; this.noMtime = !!opt.noMtime; this.onWriteEntry = opt.onWriteEntry; this.readEntry = readEntry; const { type } = readEntry; /* c8 ignore start */ if (type === 'Unsupported') { throw new Error('writing entry that should be ignored'); } /* c8 ignore stop */ this.type = type; if (this.type === 'Directory' && this.portable) { this.noMtime = true; } this.prefix = opt.prefix; this.path = normalizeWindowsPath(readEntry.path); this.mode = readEntry.mode !== undefined ? this[MODE](readEntry.mode) : undefined; this.uid = this.portable ? undefined : readEntry.uid; this.gid = this.portable ? undefined : readEntry.gid; this.uname = this.portable ? undefined : readEntry.uname; this.gname = this.portable ? undefined : readEntry.gname; this.size = readEntry.size; this.mtime = this.noMtime ? undefined : opt.mtime || readEntry.mtime; this.atime = this.portable ? undefined : readEntry.atime; this.ctime = this.portable ? undefined : readEntry.ctime; this.linkpath = readEntry.linkpath !== undefined ? normalizeWindowsPath(readEntry.linkpath) : undefined; if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn); } let pathWarn = false; if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path); if (root && typeof stripped === 'string') { this.path = stripped; pathWarn = root; } } this.remain = readEntry.size; this.blockRemain = readEntry.startBlockSize; this.onWriteEntry?.(this); this.header = new Header({ path: this[PREFIX](this.path), linkpath: this.type === 'Link' && this.linkpath !== undefined ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this.mode, uid: this.portable ? undefined : this.uid, gid: this.portable ? undefined : this.gid, size: this.size, mtime: this.noMtime ? undefined : this.mtime, type: this.type, uname: this.portable ? undefined : this.uname, atime: this.portable ? undefined : this.atime, ctime: this.portable ? undefined : this.ctime, }); if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }); } if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? undefined : this.atime, ctime: this.portable ? undefined : this.ctime, gid: this.portable ? undefined : this.gid, mtime: this.noMtime ? undefined : this.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' && this.linkpath !== undefined ? this[PREFIX](this.linkpath) : this.linkpath, size: this.size, uid: this.portable ? undefined : this.uid, uname: this.portable ? undefined : this.uname, dev: this.portable ? undefined : this.readEntry.dev, ino: this.portable ? undefined : this.readEntry.ino, nlink: this.portable ? undefined : this.readEntry.nlink, }).encode()); } const b = this.header?.block; /* c8 ignore start */ if (!b) throw new Error('failed to encode header'); /* c8 ignore stop */ super.write(b); readEntry.pipe(this); } [PREFIX](path) { return prefixPath(path, this.prefix); } [MODE](mode) { return modeFix(mode, this.type === 'Directory', this.portable); } write(chunk, encoding, cb) { /* c8 ignore start - just junk to comply with NodeJS.WritableStream */ if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8'); } /* c8 ignore stop */ const writeLen = chunk.length; if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate'); } this.blockRemain -= writeLen; return super.write(chunk, cb); } end(chunk, encoding, cb) { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)); } /* c8 ignore start - just junk to comply with NodeJS.WritableStream */ if (typeof chunk === 'function') { cb = chunk; encoding = undefined; chunk = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = undefined; } if (typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding ?? 'utf8'); } if (cb) this.once('finish', cb); chunk ? super.end(chunk, cb) : super.end(cb); /* c8 ignore stop */ return this; } } const getType = (stat) => stat.isFile() ? 'File' : stat.isDirectory() ? 'Directory' : stat.isSymbolicLink() ? 'SymbolicLink' : 'Unsupported'; //# sourceMappingURL=write-entry.js.map{ "author": "Isaac Z. Schlueter", "name": "tar", "description": "tar for node", "version": "7.4.3", "repository": { "type": "git", "url": "https://github.com/isaacs/node-tar.git" }, "scripts": { "genparse": "node scripts/generate-parse-fixtures.js", "snap": "tap", "test": "tap", "pretest": "npm run prepare", "presnap": "npm run prepare", "prepare": "tshy", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "format": "prettier --write . --log-level warn", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.0.1", "mkdirp": "^3.0.1", "yallist": "^5.0.0" }, "devDependencies": { "chmodr": "^1.2.0", "end-of-stream": "^1.4.3", "events-to-array": "^2.0.3", "mutate-fs": "^2.1.1", "nock": "^13.5.4", "prettier": "^3.2.5", "rimraf": "^5.0.5", "tap": "^18.7.2", "tshy": "^1.13.1", "typedoc": "^0.25.13" }, "license": "ISC", "engines": { "node": ">=18" }, "files": [ "dist" ], "tap": { "coverage-map": "map.js", "timeout": 0, "typecheck": true }, "prettier": { "experimentalTernaries": true, "semi": false, "printWidth": 70, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "tshy": { "exports": { "./package.json": "./package.json", ".": "./src/index.ts", "./c": "./src/create.ts", "./create": "./src/create.ts", "./replace": "./src/create.ts", "./r": "./src/create.ts", "./list": "./src/list.ts", "./t": "./src/list.ts", "./update": "./src/update.ts", "./u": "./src/update.ts", "./extract": "./src/extract.ts", "./x": "./src/extract.ts", "./pack": "./src/pack.ts", "./unpack": "./src/unpack.ts", "./parse": "./src/parse.ts", "./read-entry": "./src/read-entry.ts", "./write-entry": "./src/write-entry.ts", "./header": "./src/header.ts", "./pax": "./src/pax.ts", "./types": "./src/types.ts" } }, "exports": { "./package.json": "./package.json", ".": { "import": { "source": "./src/index.ts", "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "source": "./src/index.ts", "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } }, "./c": { "import": { "source": "./src/create.ts", "types": "./dist/esm/create.d.ts", "default": "./dist/esm/create.js" }, "require": { "source": "./src/create.ts", "types": "./dist/commonjs/create.d.ts", "default": "./dist/commonjs/create.js" } }, "./create": { "import": { "source": "./src/create.ts", "types": "./dist/esm/create.d.ts", "default": "./dist/esm/create.js" }, "require": { "source": "./src/create.ts", "types": "./dist/commonjs/create.d.ts", "default": "./dist/commonjs/create.js" } }, "./replace": { "import": { "source": "./src/create.ts", "types": "./dist/esm/create.d.ts", "default": "./dist/esm/create.js" }, "require": { "source": "./src/create.ts", "types": "./dist/commonjs/create.d.ts", "default": "./dist/commonjs/create.js" } }, "./r": { "import": { "source": "./src/create.ts", "types": "./dist/esm/create.d.ts", "default": "./dist/esm/create.js" }, "require": { "source": "./src/create.ts", "types": "./dist/commonjs/create.d.ts", "default": "./dist/commonjs/create.js" } }, "./list": { "import": { "source": "./src/list.ts", "types": "./dist/esm/list.d.ts", "default": "./dist/esm/list.js" }, "require": { "source": "./src/list.ts", "types": "./dist/commonjs/list.d.ts", "default": "./dist/commonjs/list.js" } }, "./t": { "import": { "source": "./src/list.ts", "types": "./dist/esm/list.d.ts", "default": "./dist/esm/list.js" }, "require": { "source": "./src/list.ts", "types": "./dist/commonjs/list.d.ts", "default": "./dist/commonjs/list.js" } }, "./update": { "import": { "source": "./src/update.ts", "types": "./dist/esm/update.d.ts", "default": "./dist/esm/update.js" }, "require": { "source": "./src/update.ts", "types": "./dist/commonjs/update.d.ts", "default": "./dist/commonjs/update.js" } }, "./u": { "import": { "source": "./src/update.ts", "types": "./dist/esm/update.d.ts", "default": "./dist/esm/update.js" }, "require": { "source": "./src/update.ts", "types": "./dist/commonjs/update.d.ts", "default": "./dist/commonjs/update.js" } }, "./extract": { "import": { "source": "./src/extract.ts", "types": "./dist/esm/extract.d.ts", "default": "./dist/esm/extract.js" }, "require": { "source": "./src/extract.ts", "types": "./dist/commonjs/extract.d.ts", "default": "./dist/commonjs/extract.js" } }, "./x": { "import": { "source": "./src/extract.ts", "types": "./dist/esm/extract.d.ts", "default": "./dist/esm/extract.js" }, "require": { "source": "./src/extract.ts", "types": "./dist/commonjs/extract.d.ts", "default": "./dist/commonjs/extract.js" } }, "./pack": { "import": { "source": "./src/pack.ts", "types": "./dist/esm/pack.d.ts", "default": "./dist/esm/pack.js" }, "require": { "source": "./src/pack.ts", "types": "./dist/commonjs/pack.d.ts", "default": "./dist/commonjs/pack.js" } }, "./unpack": { "import": { "source": "./src/unpack.ts", "types": "./dist/esm/unpack.d.ts", "default": "./dist/esm/unpack.js" }, "require": { "source": "./src/unpack.ts", "types": "./dist/commonjs/unpack.d.ts", "default": "./dist/commonjs/unpack.js" } }, "./parse": { "import": { "source": "./src/parse.ts", "types": "./dist/esm/parse.d.ts", "default": "./dist/esm/parse.js" }, "require": { "source": "./src/parse.ts", "types": "./dist/commonjs/parse.d.ts", "default": "./dist/commonjs/parse.js" } }, "./read-entry": { "import": { "source": "./src/read-entry.ts", "types": "./dist/esm/read-entry.d.ts", "default": "./dist/esm/read-entry.js" }, "require": { "source": "./src/read-entry.ts", "types": "./dist/commonjs/read-entry.d.ts", "default": "./dist/commonjs/read-entry.js" } }, "./write-entry": { "import": { "source": "./src/write-entry.ts", "types": "./dist/esm/write-entry.d.ts", "default": "./dist/esm/write-entry.js" }, "require": { "source": "./src/write-entry.ts", "types": "./dist/commonjs/write-entry.d.ts", "default": "./dist/commonjs/write-entry.js" } }, "./header": { "import": { "source": "./src/header.ts", "types": "./dist/esm/header.d.ts", "default": "./dist/esm/header.js" }, "require": { "source": "./src/header.ts", "types": "./dist/commonjs/header.d.ts", "default": "./dist/commonjs/header.js" } }, "./pax": { "import": { "source": "./src/pax.ts", "types": "./dist/esm/pax.d.ts", "default": "./dist/esm/pax.js" }, "require": { "source": "./src/pax.ts", "types": "./dist/commonjs/pax.d.ts", "default": "./dist/commonjs/pax.js" } }, "./types": { "import": { "source": "./src/types.ts", "types": "./dist/esm/types.d.ts", "default": "./dist/esm/types.js" }, "require": { "source": "./src/types.ts", "types": "./dist/commonjs/types.d.ts", "default": "./dist/commonjs/types.js" } } }, "type": "module", "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts" } All packages under `src/` are licensed according to the terms in their respective `LICENSE` or `LICENSE.md` files. The remainder of this project is licensed under the Blue Oak Model License, as follows: ----- # Blue Oak Model License Version 1.0.0 ## Purpose This license gives everyone as much permission to work with this software as possible, while protecting contributors from liability. ## Acceptance In order to receive this license, you must agree to its rules. The rules of this license are both obligations under that agreement and conditions to your license. You must not do anything with this software that triggers a rule that you cannot or will not follow. ## Copyright Each contributor licenses you to do everything with this software that would otherwise infringe that contributor's copyright in it. ## Notices You must ensure that everyone who gets a copy of any part of this software from you, with or without changes, also gets the text of this license or a link to . ## Excuse If anyone notifies you in writing that you have not complied with [Notices](#notices), you can keep your license by taking all practical steps to comply within 30 days after the notice. If you do not do so, your license ends immediately. ## Patent Each contributor licenses you to do everything with this software that would otherwise infringe any patent claims they can license or become able to license. ## Reliability No contributor can revoke this license. ## No Liability ***As far as the law allows, this software comes as is, without any warranty or condition, and no contributor will be liable to anyone for any damages related to this software or this license, under any kind of legal claim.*** "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Node = exports.Yallist = void 0; class Yallist { tail; head; length = 0; static create(list = []) { return new Yallist(list); } constructor(list = []) { for (const item of list) { this.push(item); } } *[Symbol.iterator]() { for (let walker = this.head; walker; walker = walker.next) { yield walker.value; } } removeNode(node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list'); } const next = node.next; const prev = node.prev; if (next) { next.prev = prev; } if (prev) { prev.next = next; } if (node === this.head) { this.head = next; } if (node === this.tail) { this.tail = prev; } this.length--; node.next = undefined; node.prev = undefined; node.list = undefined; return next; } unshiftNode(node) { if (node === this.head) { return; } if (node.list) { node.list.removeNode(node); } const head = this.head; node.list = this; node.next = head; if (head) { head.prev = node; } this.head = node; if (!this.tail) { this.tail = node; } this.length++; } pushNode(node) { if (node === this.tail) { return; } if (node.list) { node.list.removeNode(node); } const tail = this.tail; node.list = this; node.prev = tail; if (tail) { tail.next = node; } this.tail = node; if (!this.head) { this.head = node; } this.length++; } push(...args) { for (let i = 0, l = args.length; i < l; i++) { push(this, args[i]); } return this.length; } unshift(...args) { for (var i = 0, l = args.length; i < l; i++) { unshift(this, args[i]); } return this.length; } pop() { if (!this.tail) { return undefined; } const res = this.tail.value; const t = this.tail; this.tail = this.tail.prev; if (this.tail) { this.tail.next = undefined; } else { this.head = undefined; } t.list = undefined; this.length--; return res; } shift() { if (!this.head) { return undefined; } const res = this.head.value; const h = this.head; this.head = this.head.next; if (this.head) { this.head.prev = undefined; } else { this.tail = undefined; } h.list = undefined; this.length--; return res; } forEach(fn, thisp) { thisp = thisp || this; for (let walker = this.head, i = 0; !!walker; i++) { fn.call(thisp, walker.value, i, this); walker = walker.next; } } forEachReverse(fn, thisp) { thisp = thisp || this; for (let walker = this.tail, i = this.length - 1; !!walker; i--) { fn.call(thisp, walker.value, i, this); walker = walker.prev; } } get(n) { let i = 0; let walker = this.head; for (; !!walker && i < n; i++) { walker = walker.next; } if (i === n && !!walker) { return walker.value; } } getReverse(n) { let i = 0; let walker = this.tail; for (; !!walker && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev; } if (i === n && !!walker) { return walker.value; } } map(fn, thisp) { thisp = thisp || this; const res = new Yallist(); for (let walker = this.head; !!walker;) { res.push(fn.call(thisp, walker.value, this)); walker = walker.next; } return res; } mapReverse(fn, thisp) { thisp = thisp || this; var res = new Yallist(); for (let walker = this.tail; !!walker;) { res.push(fn.call(thisp, walker.value, this)); walker = walker.prev; } return res; } reduce(fn, initial) { let acc; let walker = this.head; if (arguments.length > 1) { acc = initial; } else if (this.head) { walker = this.head.next; acc = this.head.value; } else { throw new TypeError('Reduce of empty list with no initial value'); } for (var i = 0; !!walker; i++) { acc = fn(acc, walker.value, i); walker = walker.next; } return acc; } reduceReverse(fn, initial) { let acc; let walker = this.tail; if (arguments.length > 1) { acc = initial; } else if (this.tail) { walker = this.tail.prev; acc = this.tail.value; } else { throw new TypeError('Reduce of empty list with no initial value'); } for (let i = this.length - 1; !!walker; i--) { acc = fn(acc, walker.value, i); walker = walker.prev; } return acc; } toArray() { const arr = new Array(this.length); for (let i = 0, walker = this.head; !!walker; i++) { arr[i] = walker.value; walker = walker.next; } return arr; } toArrayReverse() { const arr = new Array(this.length); for (let i = 0, walker = this.tail; !!walker; i++) { arr[i] = walker.value; walker = walker.prev; } return arr; } slice(from = 0, to = this.length) { if (to < 0) { to += this.length; } if (from < 0) { from += this.length; } const ret = new Yallist(); if (to < from || to < 0) { return ret; } if (from < 0) { from = 0; } if (to > this.length) { to = this.length; } let walker = this.head; let i = 0; for (i = 0; !!walker && i < from; i++) { walker = walker.next; } for (; !!walker && i < to; i++, walker = walker.next) { ret.push(walker.value); } return ret; } sliceReverse(from = 0, to = this.length) { if (to < 0) { to += this.length; } if (from < 0) { from += this.length; } const ret = new Yallist(); if (to < from || to < 0) { return ret; } if (from < 0) { from = 0; } if (to > this.length) { to = this.length; } let i = this.length; let walker = this.tail; for (; !!walker && i > to; i--) { walker = walker.prev; } for (; !!walker && i > from; i--, walker = walker.prev) { ret.push(walker.value); } return ret; } splice(start, deleteCount = 0, ...nodes) { if (start > this.length) { start = this.length - 1; } if (start < 0) { start = this.length + start; } let walker = this.head; for (let i = 0; !!walker && i < start; i++) { walker = walker.next; } const ret = []; for (let i = 0; !!walker && i < deleteCount; i++) { ret.push(walker.value); walker = this.removeNode(walker); } if (!walker) { walker = this.tail; } else if (walker !== this.tail) { walker = walker.prev; } for (const v of nodes) { walker = insertAfter(this, walker, v); } return ret; } reverse() { const head = this.head; const tail = this.tail; for (let walker = head; !!walker; walker = walker.prev) { const p = walker.prev; walker.prev = walker.next; walker.next = p; } this.head = tail; this.tail = head; return this; } } exports.Yallist = Yallist; // insertAfter undefined means "make the node the new head of list" function insertAfter(self, node, value) { const prev = node; const next = node ? node.next : self.head; const inserted = new Node(value, prev, next, self); if (inserted.next === undefined) { self.tail = inserted; } if (inserted.prev === undefined) { self.head = inserted; } self.length++; return inserted; } function push(self, item) { self.tail = new Node(item, self.tail, undefined, self); if (!self.head) { self.head = self.tail; } self.length++; } function unshift(self, item) { self.head = new Node(item, undefined, self.head, self); if (!self.tail) { self.tail = self.head; } self.length++; } class Node { list; next; prev; value; constructor(value, prev, next, list) { this.list = list; this.value = value; if (prev) { prev.next = this; this.prev = prev; } else { this.prev = undefined; } if (next) { next.prev = this; this.next = next; } else { this.next = undefined; } } } exports.Node = Node; //# sourceMappingURL=index.js.map{ "type": "commonjs" } export class Yallist { tail; head; length = 0; static create(list = []) { return new Yallist(list); } constructor(list = []) { for (const item of list) { this.push(item); } } *[Symbol.iterator]() { for (let walker = this.head; walker; walker = walker.next) { yield walker.value; } } removeNode(node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list'); } const next = node.next; const prev = node.prev; if (next) { next.prev = prev; } if (prev) { prev.next = next; } if (node === this.head) { this.head = next; } if (node === this.tail) { this.tail = prev; } this.length--; node.next = undefined; node.prev = undefined; node.list = undefined; return next; } unshiftNode(node) { if (node === this.head) { return; } if (node.list) { node.list.removeNode(node); } const head = this.head; node.list = this; node.next = head; if (head) { head.prev = node; } this.head = node; if (!this.tail) { this.tail = node; } this.length++; } pushNode(node) { if (node === this.tail) { return; } if (node.list) { node.list.removeNode(node); } const tail = this.tail; node.list = this; node.prev = tail; if (tail) { tail.next = node; } this.tail = node; if (!this.head) { this.head = node; } this.length++; } push(...args) { for (let i = 0, l = args.length; i < l; i++) { push(this, args[i]); } return this.length; } unshift(...args) { for (var i = 0, l = args.length; i < l; i++) { unshift(this, args[i]); } return this.length; } pop() { if (!this.tail) { return undefined; } const res = this.tail.value; const t = this.tail; this.tail = this.tail.prev; if (this.tail) { this.tail.next = undefined; } else { this.head = undefined; } t.list = undefined; this.length--; return res; } shift() { if (!this.head) { return undefined; } const res = this.head.value; const h = this.head; this.head = this.head.next; if (this.head) { this.head.prev = undefined; } else { this.tail = undefined; } h.list = undefined; this.length--; return res; } forEach(fn, thisp) { thisp = thisp || this; for (let walker = this.head, i = 0; !!walker; i++) { fn.call(thisp, walker.value, i, this); walker = walker.next; } } forEachReverse(fn, thisp) { thisp = thisp || this; for (let walker = this.tail, i = this.length - 1; !!walker; i--) { fn.call(thisp, walker.value, i, this); walker = walker.prev; } } get(n) { let i = 0; let walker = this.head; for (; !!walker && i < n; i++) { walker = walker.next; } if (i === n && !!walker) { return walker.value; } } getReverse(n) { let i = 0; let walker = this.tail; for (; !!walker && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev; } if (i === n && !!walker) { return walker.value; } } map(fn, thisp) { thisp = thisp || this; const res = new Yallist(); for (let walker = this.head; !!walker;) { res.push(fn.call(thisp, walker.value, this)); walker = walker.next; } return res; } mapReverse(fn, thisp) { thisp = thisp || this; var res = new Yallist(); for (let walker = this.tail; !!walker;) { res.push(fn.call(thisp, walker.value, this)); walker = walker.prev; } return res; } reduce(fn, initial) { let acc; let walker = this.head; if (arguments.length > 1) { acc = initial; } else if (this.head) { walker = this.head.next; acc = this.head.value; } else { throw new TypeError('Reduce of empty list with no initial value'); } for (var i = 0; !!walker; i++) { acc = fn(acc, walker.value, i); walker = walker.next; } return acc; } reduceReverse(fn, initial) { let acc; let walker = this.tail; if (arguments.length > 1) { acc = initial; } else if (this.tail) { walker = this.tail.prev; acc = this.tail.value; } else { throw new TypeError('Reduce of empty list with no initial value'); } for (let i = this.length - 1; !!walker; i--) { acc = fn(acc, walker.value, i); walker = walker.prev; } return acc; } toArray() { const arr = new Array(this.length); for (let i = 0, walker = this.head; !!walker; i++) { arr[i] = walker.value; walker = walker.next; } return arr; } toArrayReverse() { const arr = new Array(this.length); for (let i = 0, walker = this.tail; !!walker; i++) { arr[i] = walker.value; walker = walker.prev; } return arr; } slice(from = 0, to = this.length) { if (to < 0) { to += this.length; } if (from < 0) { from += this.length; } const ret = new Yallist(); if (to < from || to < 0) { return ret; } if (from < 0) { from = 0; } if (to > this.length) { to = this.length; } let walker = this.head; let i = 0; for (i = 0; !!walker && i < from; i++) { walker = walker.next; } for (; !!walker && i < to; i++, walker = walker.next) { ret.push(walker.value); } return ret; } sliceReverse(from = 0, to = this.length) { if (to < 0) { to += this.length; } if (from < 0) { from += this.length; } const ret = new Yallist(); if (to < from || to < 0) { return ret; } if (from < 0) { from = 0; } if (to > this.length) { to = this.length; } let i = this.length; let walker = this.tail; for (; !!walker && i > to; i--) { walker = walker.prev; } for (; !!walker && i > from; i--, walker = walker.prev) { ret.push(walker.value); } return ret; } splice(start, deleteCount = 0, ...nodes) { if (start > this.length) { start = this.length - 1; } if (start < 0) { start = this.length + start; } let walker = this.head; for (let i = 0; !!walker && i < start; i++) { walker = walker.next; } const ret = []; for (let i = 0; !!walker && i < deleteCount; i++) { ret.push(walker.value); walker = this.removeNode(walker); } if (!walker) { walker = this.tail; } else if (walker !== this.tail) { walker = walker.prev; } for (const v of nodes) { walker = insertAfter(this, walker, v); } return ret; } reverse() { const head = this.head; const tail = this.tail; for (let walker = head; !!walker; walker = walker.prev) { const p = walker.prev; walker.prev = walker.next; walker.next = p; } this.head = tail; this.tail = head; return this; } } // insertAfter undefined means "make the node the new head of list" function insertAfter(self, node, value) { const prev = node; const next = node ? node.next : self.head; const inserted = new Node(value, prev, next, self); if (inserted.next === undefined) { self.tail = inserted; } if (inserted.prev === undefined) { self.head = inserted; } self.length++; return inserted; } function push(self, item) { self.tail = new Node(item, self.tail, undefined, self); if (!self.head) { self.head = self.tail; } self.length++; } function unshift(self, item) { self.head = new Node(item, undefined, self.head, self); if (!self.tail) { self.tail = self.head; } self.length++; } export class Node { list; next; prev; value; constructor(value, prev, next, list) { this.list = list; this.value = value; if (prev) { prev.next = this; this.prev = prev; } else { this.prev = undefined; } if (next) { next.prev = this; this.next = next; } else { this.next = undefined; } } } //# sourceMappingURL=index.js.map{ "type": "module" } { "name": "yallist", "version": "5.0.0", "description": "Yet Another Linked List", "files": [ "dist" ], "devDependencies": { "prettier": "^3.2.5", "tap": "^18.7.2", "tshy": "^1.13.1", "typedoc": "^0.25.13" }, "scripts": { "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "prepare": "tshy", "pretest": "npm run prepare", "presnap": "npm run prepare", "test": "tap", "snap": "tap", "format": "prettier --write . --loglevel warn --ignore-path ../../.prettierignore --cache", "typedoc": "typedoc" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/yallist.git" }, "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "license": "BlueOak-1.0.0", "tshy": { "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", "type": "module", "prettier": { "semi": false, "printWidth": 70, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "engines": { "node": ">=18" } } { "name": "cacache", "version": "19.0.1", "cache-version": { "content": "2", "index": "5" }, "description": "Fast, fault-tolerant, cross-platform, disk-based, data-agnostic, content-addressable cache.", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "scripts": { "test": "tap", "snap": "tap", "coverage": "tap", "test-docker": "docker run -it --rm --name pacotest -v \"$PWD\":/tmp -w /tmp node:latest npm test", "lint": "npm run eslint", "npmclilint": "npmcli-lint", "lintfix": "npm run eslint -- --fix", "postsnap": "npm run lintfix --", "postlint": "template-oss-check", "posttest": "npm run lint", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cacache.git" }, "keywords": [ "cache", "caching", "content-addressable", "sri", "sri hash", "subresource integrity", "cache", "storage", "store", "file store", "filesystem", "disk cache", "disk storage" ], "license": "ISC", "dependencies": { "@npmcli/fs": "^4.0.0", "fs-minipass": "^3.0.0", "glob": "^10.2.2", "lru-cache": "^10.0.1", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^7.0.2", "ssri": "^12.0.0", "tar": "^7.4.3", "unique-filename": "^4.0.0" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.0.0" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "windowsCI": false, "version": "4.23.3", "publish": "true" }, "author": "GitHub Inc.", "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } MIT License Copyright (c) Sindre Sorhus (https://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. { "name": "chalk", "version": "5.4.1", "description": "Terminal string styling done right", "license": "MIT", "repository": "chalk/chalk", "funding": "https://github.com/chalk/chalk?sponsor=1", "type": "module", "main": "./source/index.js", "exports": "./source/index.js", "imports": { "#ansi-styles": "./source/vendor/ansi-styles/index.js", "#supports-color": { "node": "./source/vendor/supports-color/index.js", "default": "./source/vendor/supports-color/browser.js" } }, "types": "./source/index.d.ts", "sideEffects": false, "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "scripts": { "test": "xo && c8 ava && tsd", "bench": "matcha benchmark.js" }, "files": [ "source", "!source/index.test-d.ts" ], "keywords": [ "color", "colour", "colors", "terminal", "console", "cli", "string", "ansi", "style", "styles", "tty", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "devDependencies": { "@types/node": "^16.11.10", "ava": "^3.15.0", "c8": "^7.10.0", "color-convert": "^2.0.1", "execa": "^6.0.0", "log-update": "^5.0.0", "matcha": "^0.7.0", "tsd": "^0.19.0", "xo": "^0.57.0", "yoctodelay": "^2.0.0" }, "xo": { "rules": { "unicorn/prefer-string-slice": "off", "@typescript-eslint/consistent-type-imports": "off", "@typescript-eslint/consistent-type-exports": "off", "@typescript-eslint/consistent-type-definitions": "off", "unicorn/expiring-todo-comments": "off" } }, "c8": { "reporter": [ "text", "lcov" ], "exclude": [ "source/vendor" ] } } import ansiStyles from '#ansi-styles'; import supportsColor from '#supports-color'; import { // eslint-disable-line import/order stringReplaceAll, stringEncaseCRLFWithFirstIndex, } from './utilities.js'; const {stdout: stdoutColor, stderr: stderrColor} = supportsColor; const GENERATOR = Symbol('GENERATOR'); const STYLER = Symbol('STYLER'); const IS_EMPTY = Symbol('IS_EMPTY'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m', ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; export class Chalk { constructor(options) { // eslint-disable-next-line no-constructor-return return chalkFactory(options); } } const chalkFactory = options => { const chalk = (...strings) => strings.join(' '); applyOptions(chalk, options); Object.setPrototypeOf(chalk, createChalk.prototype); return chalk; }; function createChalk(options) { return chalkFactory(options); } Object.setPrototypeOf(createChalk.prototype, Function.prototype); for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]); Object.defineProperty(this, styleName, {value: builder}); return builder; }, }; } styles.visible = { get() { const builder = createBuilder(this, this[STYLER], true); Object.defineProperty(this, 'visible', {value: builder}); return builder; }, }; const getModelAnsi = (model, level, type, ...arguments_) => { if (model === 'rgb') { if (level === 'ansi16m') { return ansiStyles[type].ansi16m(...arguments_); } if (level === 'ansi256') { return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_)); } return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_)); } if (model === 'hex') { return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_)); } return ansiStyles[type][model](...arguments_); }; const usedModels = ['rgb', 'hex', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]); return createBuilder(this, styler, this[IS_EMPTY]); }; }, }; const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]); return createBuilder(this, styler, this[IS_EMPTY]); }; }, }; } const proto = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this[GENERATOR].level; }, set(level) { this[GENERATOR].level = level; }, }, }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent, }; }; const createBuilder = (self, _styler, _isEmpty) => { // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); // We alter the prototype because we must return a function, but there is // no way to create a function with a different prototype Object.setPrototypeOf(builder, proto); builder[GENERATOR] = self; builder[STYLER] = _styler; builder[IS_EMPTY] = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self[IS_EMPTY] ? '' : string; } let styler = self[STYLER]; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.includes('\u001B')) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; Object.defineProperties(createChalk.prototype, styles); const chalk = createChalk(); export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0}); export { modifierNames, foregroundColorNames, backgroundColorNames, colorNames, // TODO: Remove these aliases in the next major version modifierNames as modifiers, foregroundColorNames as foregroundColors, backgroundColorNames as backgroundColors, colorNames as colors, } from './vendor/ansi-styles/index.js'; export { stdoutColor as supportsColor, stderrColor as supportsColorStderr, }; export default chalk; // TODO: When targeting Node.js 16, use `String.prototype.replaceAll`. export function stringReplaceAll(string, substring, replacer) { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.slice(endIndex, index) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], gray: [90, 39], // Alias of `blackBright` grey: [90, 39], // Alias of `blackBright` redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgGray: [100, 49], // Alias of `bgBlackBright` bgGrey: [100, 49], // Alias of `bgBlackBright` bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], }, }; export const modifierNames = Object.keys(styles.modifier); export const foregroundColorNames = Object.keys(styles.color); export const backgroundColorNames = Object.keys(styles.bgColor); export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; function assembleStyles() { const codes = new Map(); for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m`, }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false, }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false, }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js Object.defineProperties(styles, { rgbToAnsi256: { value(red, green, blue) { // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round(((red - 8) / 247) * 24) + 232; } return 16 + (36 * Math.round(red / 255 * 5)) + (6 * Math.round(green / 255 * 5)) + Math.round(blue / 255 * 5); }, enumerable: false, }, hexToRgb: { value(hex) { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF, /* eslint-enable no-bitwise */ ]; }, enumerable: false, }, hexToAnsi256: { value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false, }, ansi256ToAnsi: { value(code) { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = (((code - 232) * 10) + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = (remainder % 6) / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } // eslint-disable-next-line no-bitwise let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false, }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false, }, hexToAnsi: { value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false, }, }); return styles; } const ansiStyles = assembleStyles(); export default ansiStyles; /* eslint-env browser */ const level = (() => { if (!('navigator' in globalThis)) { return 0; } if (globalThis.navigator.userAgentData) { const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium'); if (brand && brand.version > 93) { return 3; } } if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) { return 1; } return 0; })(); const colorSupport = level !== 0 && { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; const supportsColor = { stdout: colorSupport, stderr: colorSupport, }; export default supportsColor; import process from 'node:process'; import os from 'node:os'; import tty from 'node:tty'; // From: https://github.com/sindresorhus/has-flag/blob/main/index.js /// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) { function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); } const {env} = process; let flagForceColor; if ( hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never') ) { flagForceColor = 0; } else if ( hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always') ) { flagForceColor = 1; } function envForceColor() { if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { return 1; } if (env.FORCE_COLOR === 'false') { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; } function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== undefined) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } } // Check for Azure DevOps pipelines. // Has to be above the `!streamIsTTY` check. if ('TF_BUILD' in env && 'AGENT_NAME' in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10_586 ) { return Number(osRelease[2]) >= 14_931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) { return 3; } if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if (env.TERM === 'xterm-kitty') { return 3; } if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': { return version >= 3 ? 3 : 2; } case 'Apple_Terminal': { return 2; } // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } export function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options, }); return translateLevel(level); } const supportsColor = { stdout: createSupportsColor({isTTY: tty.isatty(1)}), stderr: createSupportsColor({isTTY: tty.isatty(2)}), }; export default supportsColor; The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' const fs = require('fs') const path = require('path') /* istanbul ignore next */ const LCHOWN = fs.lchown ? 'lchown' : 'chown' /* istanbul ignore next */ const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' /* istanbul ignore next */ const needEISDIRHandled = fs.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/) const lchownSync = (path, uid, gid) => { try { return fs[LCHOWNSYNC](path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const chownSync = (path, uid, gid) => { try { return fs.chownSync(path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const handleEISDIR = needEISDIRHandled ? (path, uid, gid, cb) => er => { // Node prior to v10 had a very questionable implementation of // fs.lchown, which would always try to call fs.open on a directory // Fall back to fs.chown in those cases. if (!er || er.code !== 'EISDIR') cb(er) else fs.chown(path, uid, gid, cb) } : (_, __, ___, cb) => cb /* istanbul ignore next */ const handleEISDirSync = needEISDIRHandled ? (path, uid, gid) => { try { return lchownSync(path, uid, gid) } catch (er) { if (er.code !== 'EISDIR') throw er chownSync(path, uid, gid) } } : (path, uid, gid) => lchownSync(path, uid, gid) // fs.readdir could only accept an options object as of node v6 const nodeVersion = process.version let readdir = (path, options, cb) => fs.readdir(path, options, cb) let readdirSync = (path, options) => fs.readdirSync(path, options) /* istanbul ignore next */ if (/^v4\./.test(nodeVersion)) readdir = (path, options, cb) => fs.readdir(path, cb) const chown = (cpath, uid, gid, cb) => { fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er.code !== 'ENOENT' ? er : null) })) } const chownrKid = (p, child, uid, gid, cb) => { if (typeof child === 'string') return fs.lstat(path.resolve(p, child), (er, stats) => { // Skip ENOENT error if (er) return cb(er.code !== 'ENOENT' ? er : null) stats.name = child chownrKid(p, stats, uid, gid, cb) }) if (child.isDirectory()) { chownr(path.resolve(p, child.name), uid, gid, er => { if (er) return cb(er) const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) }) } else { const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) } } const chownr = (p, uid, gid, cb) => { readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb() else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er) } if (er || !children.length) return chown(p, uid, gid, cb) let len = children.length let errState = null const then = er => { if (errState) return if (er) return cb(errState = er) if (-- len === 0) return chown(p, uid, gid, cb) } children.forEach(child => chownrKid(p, child, uid, gid, then)) }) } const chownrKidSync = (p, child, uid, gid) => { if (typeof child === 'string') { try { const stats = fs.lstatSync(path.resolve(p, child)) stats.name = child child = stats } catch (er) { if (er.code === 'ENOENT') return else throw er } } if (child.isDirectory()) chownrSync(path.resolve(p, child.name), uid, gid) handleEISDirSync(path.resolve(p, child.name), uid, gid) } const chownrSync = (p, uid, gid) => { let children try { children = readdirSync(p, { withFileTypes: true }) } catch (er) { if (er.code === 'ENOENT') return else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') return handleEISDirSync(p, uid, gid) else throw er } if (children && children.length) children.forEach(child => chownrKidSync(p, child, uid, gid)) return handleEISDirSync(p, uid, gid) } module.exports = chownr chownr.sync = chownrSync { "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "name": "chownr", "description": "like `chown -R`", "version": "2.0.0", "repository": { "type": "git", "url": "git://github.com/isaacs/chownr.git" }, "main": "chownr.js", "files": [ "chownr.js" ], "devDependencies": { "mkdirp": "0.3", "rimraf": "^2.7.1", "tap": "^14.10.6" }, "tap": { "check-coverage": true }, "scripts": { "test": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags" }, "license": "ISC", "engines": { "node": ">=10" } } The MIT License (MIT) Copyright (c) 2016 Thomas Watson Steen 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. 'use strict' const vendors = require('./vendors.json') const env = process.env // Used for testing only Object.defineProperty(exports, '_vendors', { value: vendors.map(function (v) { return v.constant }) }) exports.name = null exports.isPR = null exports.id = null vendors.forEach(function (vendor) { const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env] const isCI = envs.every(function (obj) { return checkEnv(obj) }) exports[vendor.constant] = isCI if (!isCI) { return } exports.name = vendor.name exports.isPR = checkPR(vendor) exports.id = vendor.constant }) exports.isCI = !!( env.CI !== 'false' && // Bypass all checks if CI env is explicitly set to 'false' (env.BUILD_ID || // Jenkins, Cloudbees env.BUILD_NUMBER || // Jenkins, TeamCity env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari env.CI_APP_ID || // Appflow env.CI_BUILD_ID || // Appflow env.CI_BUILD_NUMBER || // Appflow env.CI_NAME || // Codeship and others env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI env.RUN_ID || // TaskCluster, dsari exports.name || false) ) function checkEnv (obj) { // "env": "CIRRUS" if (typeof obj === 'string') return !!env[obj] // "env": { "env": "NODE", "includes": "/app/.heroku/node/bin/node" } if ('env' in obj) { // Currently there are no other types, uncomment when there are // if ('includes' in obj) { return env[obj.env] && env[obj.env].includes(obj.includes) // } } if ('any' in obj) { return obj.any.some(function (k) { return !!env[k] }) } return Object.keys(obj).every(function (k) { return env[k] === obj[k] }) } function checkPR (vendor) { switch (typeof vendor.pr) { case 'string': // "pr": "CIRRUS_PR" return !!env[vendor.pr] case 'object': if ('env' in vendor.pr) { if ('any' in vendor.pr) { // "pr": { "env": "CODEBUILD_WEBHOOK_EVENT", "any": ["PULL_REQUEST_CREATED", "PULL_REQUEST_UPDATED"] } return vendor.pr.any.some(function (key) { return env[vendor.pr.env] === key }) } else { // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" } return vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne } } else if ('any' in vendor.pr) { // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] } return vendor.pr.any.some(function (key) { return !!env[key] }) } else { // "pr": { "DRONE_BUILD_EVENT": "pull_request" } return checkEnv(vendor.pr) } default: // PR detection not supported for this vendor return null } } { "name": "ci-info", "version": "4.1.0", "description": "Get details about the current Continuous Integration environment", "main": "index.js", "typings": "index.d.ts", "author": "Thomas Watson Steen (https://twitter.com/wa7son)", "license": "MIT", "repository": "https://github.com/watson/ci-info.git", "bugs": "https://github.com/watson/ci-info/issues", "homepage": "https://github.com/watson/ci-info", "contributors": [ { "name": "Sibiraj", "url": "https://github.com/sibiraj-s" } ], "funding": [ { "type": "github", "url": "https://github.com/sponsors/sibiraj-s" } ], "keywords": [ "ci", "continuous", "integration", "test", "detect" ], "files": [ "vendors.json", "index.js", "index.d.ts", "CHANGELOG.md" ], "scripts": { "lint:fix": "standard --fix", "test": "standard && node test.js", "prepare": "husky install || true" }, "devDependencies": { "clear-module": "^4.1.2", "husky": "^9.1.6", "standard": "^17.1.2", "tape": "^5.9.0" }, "engines": { "node": ">=8" } } [ { "name": "Agola CI", "constant": "AGOLA", "env": "AGOLA_GIT_REF", "pr": "AGOLA_PULL_REQUEST_ID" }, { "name": "Appcircle", "constant": "APPCIRCLE", "env": "AC_APPCIRCLE", "pr": { "env": "AC_GIT_PR", "ne": "false" } }, { "name": "AppVeyor", "constant": "APPVEYOR", "env": "APPVEYOR", "pr": "APPVEYOR_PULL_REQUEST_NUMBER" }, { "name": "AWS CodeBuild", "constant": "CODEBUILD", "env": "CODEBUILD_BUILD_ARN", "pr": { "env": "CODEBUILD_WEBHOOK_EVENT", "any": [ "PULL_REQUEST_CREATED", "PULL_REQUEST_UPDATED", "PULL_REQUEST_REOPENED" ] } }, { "name": "Azure Pipelines", "constant": "AZURE_PIPELINES", "env": "TF_BUILD", "pr": { "BUILD_REASON": "PullRequest" } }, { "name": "Bamboo", "constant": "BAMBOO", "env": "bamboo_planKey" }, { "name": "Bitbucket Pipelines", "constant": "BITBUCKET", "env": "BITBUCKET_COMMIT", "pr": "BITBUCKET_PR_ID" }, { "name": "Bitrise", "constant": "BITRISE", "env": "BITRISE_IO", "pr": "BITRISE_PULL_REQUEST" }, { "name": "Buddy", "constant": "BUDDY", "env": "BUDDY_WORKSPACE_ID", "pr": "BUDDY_EXECUTION_PULL_REQUEST_ID" }, { "name": "Buildkite", "constant": "BUILDKITE", "env": "BUILDKITE", "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" } }, { "name": "CircleCI", "constant": "CIRCLE", "env": "CIRCLECI", "pr": "CIRCLE_PULL_REQUEST" }, { "name": "Cirrus CI", "constant": "CIRRUS", "env": "CIRRUS_CI", "pr": "CIRRUS_PR" }, { "name": "Codefresh", "constant": "CODEFRESH", "env": "CF_BUILD_ID", "pr": { "any": [ "CF_PULL_REQUEST_NUMBER", "CF_PULL_REQUEST_ID" ] } }, { "name": "Codemagic", "constant": "CODEMAGIC", "env": "CM_BUILD_ID", "pr": "CM_PULL_REQUEST" }, { "name": "Codeship", "constant": "CODESHIP", "env": { "CI_NAME": "codeship" } }, { "name": "Drone", "constant": "DRONE", "env": "DRONE", "pr": { "DRONE_BUILD_EVENT": "pull_request" } }, { "name": "dsari", "constant": "DSARI", "env": "DSARI" }, { "name": "Earthly", "constant": "EARTHLY", "env": "EARTHLY_CI" }, { "name": "Expo Application Services", "constant": "EAS", "env": "EAS_BUILD" }, { "name": "Gerrit", "constant": "GERRIT", "env": "GERRIT_PROJECT" }, { "name": "Gitea Actions", "constant": "GITEA_ACTIONS", "env": "GITEA_ACTIONS" }, { "name": "GitHub Actions", "constant": "GITHUB_ACTIONS", "env": "GITHUB_ACTIONS", "pr": { "GITHUB_EVENT_NAME": "pull_request" } }, { "name": "GitLab CI", "constant": "GITLAB", "env": "GITLAB_CI", "pr": "CI_MERGE_REQUEST_ID" }, { "name": "GoCD", "constant": "GOCD", "env": "GO_PIPELINE_LABEL" }, { "name": "Google Cloud Build", "constant": "GOOGLE_CLOUD_BUILD", "env": "BUILDER_OUTPUT" }, { "name": "Harness CI", "constant": "HARNESS", "env": "HARNESS_BUILD_ID" }, { "name": "Heroku", "constant": "HEROKU", "env": { "env": "NODE", "includes": "/app/.heroku/node/bin/node" } }, { "name": "Hudson", "constant": "HUDSON", "env": "HUDSON_URL" }, { "name": "Jenkins", "constant": "JENKINS", "env": [ "JENKINS_URL", "BUILD_ID" ], "pr": { "any": [ "ghprbPullId", "CHANGE_ID" ] } }, { "name": "LayerCI", "constant": "LAYERCI", "env": "LAYERCI", "pr": "LAYERCI_PULL_REQUEST" }, { "name": "Magnum CI", "constant": "MAGNUM", "env": "MAGNUM" }, { "name": "Netlify CI", "constant": "NETLIFY", "env": "NETLIFY", "pr": { "env": "PULL_REQUEST", "ne": "false" } }, { "name": "Nevercode", "constant": "NEVERCODE", "env": "NEVERCODE", "pr": { "env": "NEVERCODE_PULL_REQUEST", "ne": "false" } }, { "name": "Prow", "constant": "PROW", "env": "PROW_JOB_ID" }, { "name": "ReleaseHub", "constant": "RELEASEHUB", "env": "RELEASE_BUILD_ID" }, { "name": "Render", "constant": "RENDER", "env": "RENDER", "pr": { "IS_PULL_REQUEST": "true" } }, { "name": "Sail CI", "constant": "SAIL", "env": "SAILCI", "pr": "SAIL_PULL_REQUEST_NUMBER" }, { "name": "Screwdriver", "constant": "SCREWDRIVER", "env": "SCREWDRIVER", "pr": { "env": "SD_PULL_REQUEST", "ne": "false" } }, { "name": "Semaphore", "constant": "SEMAPHORE", "env": "SEMAPHORE", "pr": "PULL_REQUEST_NUMBER" }, { "name": "Sourcehut", "constant": "SOURCEHUT", "env": { "CI_NAME": "sourcehut" } }, { "name": "Strider CD", "constant": "STRIDER", "env": "STRIDER" }, { "name": "TaskCluster", "constant": "TASKCLUSTER", "env": [ "TASK_ID", "RUN_ID" ] }, { "name": "TeamCity", "constant": "TEAMCITY", "env": "TEAMCITY_VERSION" }, { "name": "Travis CI", "constant": "TRAVIS", "env": "TRAVIS", "pr": { "env": "TRAVIS_PULL_REQUEST", "ne": "false" } }, { "name": "Vela", "constant": "VELA", "env": "VELA", "pr": { "VELA_PULL_REQUEST": "1" } }, { "name": "Vercel", "constant": "VERCEL", "env": { "any": [ "NOW_BUILDER", "VERCEL" ] }, "pr": "VERCEL_GIT_PULL_REQUEST_ID" }, { "name": "Visual Studio App Center", "constant": "APPCENTER", "env": "APPCENTER_BUILD_ID" }, { "name": "Woodpecker", "constant": "WOODPECKER", "env": { "CI": "woodpecker" }, "pr": { "CI_BUILD_EVENT": "pull_request" } }, { "name": "Xcode Cloud", "constant": "XCODE_CLOUD", "env": "CI_XCODE_PROJECT", "pr": "CI_PULL_REQUEST_NUMBER" }, { "name": "Xcode Server", "constant": "XCODE_SERVER", "env": "XCS" } ] Copyright (c) silverwind All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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 OWNER 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. import ipRegex from "ip-regex"; const defaultOpts = { exact: false }; const v4str = `${ipRegex.v4().source}\\/(3[0-2]|[12]?[0-9])`; const v6str = `${ipRegex.v6().source}\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])`; const v4exact = new RegExp(`^${v4str}$`); const v6exact = new RegExp(`^${v6str}$`); const v46exact = new RegExp(`(?:^${v4str}$)|(?:^${v6str}$)`); const cidrRegex = ({ exact } = defaultOpts) => exact ? v46exact : new RegExp(`(?:${v4str})|(?:${v6str})`, "g"); const v4 = cidrRegex.v4 = ({ exact } = defaultOpts) => exact ? v4exact : new RegExp(v4str, "g"); const v6 = cidrRegex.v6 = ({ exact } = defaultOpts) => exact ? v6exact : new RegExp(v6str, "g"); export { cidrRegex as default, v4, v6 }; { "name": "cidr-regex", "version": "4.1.1", "description": "Regular expression for matching IP addresses in CIDR notation", "author": "silverwind ", "contributors": [ "Felipe Apostol (http://flipjs.io/)" ], "repository": "silverwind/cidr-regex", "license": "BSD-2-Clause", "type": "module", "sideEffects": false, "main": "./dist/index.js", "exports": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist" ], "engines": { "node": ">=14" }, "dependencies": { "ip-regex": "^5.0.0" }, "devDependencies": { "@types/node": "20.12.12", "eslint": "8.57.0", "eslint-config-silverwind": "85.1.4", "eslint-config-silverwind-typescript": "3.2.7", "typescript": "5.4.5", "typescript-config-silverwind": "4.3.2", "updates": "16.1.1", "versions": "12.0.2", "vite": "5.2.11", "vite-config-silverwind": "1.1.2", "vite-plugin-dts": "3.9.1", "vitest": "1.6.0", "vitest-config-silverwind": "9.0.6" } } const chalk = require('chalk'); const columns = require('.'); // prettier-ignore const values = [ 'blue' + chalk.bgBlue('berry'), '笔è è' + chalk.yellow('苹果笔'), chalk.red('apple'), 'pomegranate', 'durian', chalk.green('star fruit'), 'パイナップル', 'apricot', 'banana', 'pineapple', chalk.bgRed.yellow('orange') ]; console.log(''); console.log(columns(values)); console.log(''); 'use strict'; const stringWidth = require('string-width'); const stripAnsi = require('strip-ansi'); const concat = Array.prototype.concat; const defaults = { character: ' ', newline: '\n', padding: 2, sort: true, width: 0, }; function byPlainText(a, b) { const plainA = stripAnsi(a); const plainB = stripAnsi(b); if (plainA === plainB) { return 0; } if (plainA > plainB) { return 1; } return -1; } function makeArray() { return []; } function makeList(count) { return Array.apply(null, Array(count)); } function padCell(fullWidth, character, value) { const valueWidth = stringWidth(value); const filler = makeList(fullWidth - valueWidth + 1); return value + filler.join(character); } function toRows(rows, cell, i) { rows[i % rows.length].push(cell); return rows; } function toString(arr) { return arr.join(''); } function columns(values, options) { values = concat.apply([], values); options = Object.assign({}, defaults, options); let cells = values.filter(Boolean).map(String); if (options.sort !== false) { cells = cells.sort(byPlainText); } const termWidth = options.width || process.stdout.columns; const cellWidth = Math.max.apply(null, cells.map(stringWidth)) + options.padding; const columnCount = Math.floor(termWidth / cellWidth) || 1; const rowCount = Math.ceil(cells.length / columnCount) || 1; if (columnCount === 1) { return cells.join(options.newline); } return cells .map(padCell.bind(null, cellWidth, options.character)) .reduce(toRows, makeList(rowCount).map(makeArray)) .map(toString) .join(options.newline); } module.exports = columns; The MIT License (MIT) Copyright (c) Shannon Moeller (shannonmoeller.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. { "name": "cli-columns", "version": "4.0.0", "description": "Columnated lists for the CLI.", "scripts": { "lint": "npx eslint --fix '*.js' && npx prettier --write '*.js'", "test": "node test.js && node color.js" }, "keywords": [ "ansi", "cli", "column", "columnate", "columns", "grid", "list", "log", "ls", "row", "rows", "unicode", "unix" ], "author": "Shannon Moeller (http://shannonmoeller.com)", "homepage": "https://github.com/shannonmoeller/cli-columns#readme", "repository": "shannonmoeller/cli-columns", "license": "MIT", "main": "index.js", "files": [ "*.js" ], "dependencies": { "string-width": "^4.2.3", "strip-ansi": "^6.0.1" }, "devDependencies": { "chalk": "^4.1.2" }, "engines": { "node": ">= 10" }, "eslintConfig": { "extends": "eslint:recommended", "env": { "node": true }, "parserOptions": { "ecmaVersion": 8 } }, "prettier": { "singleQuote": true } } 'use strict'; const assert = require('assert'); const chalk = require('chalk'); const stripAnsi = require('strip-ansi'); const columns = require('./index.js'); const tests = []; function test(msg, fn) { tests.push([msg, fn]); } process.nextTick(async function run() { for (const [msg, fn] of tests) { try { await fn(assert); console.log(`pass - ${msg}`); } catch (error) { console.error(`fail - ${msg}`, error); process.exit(1); } } }); // prettier-ignore test('should print one column list', t => { const cols = columns(['foo', ['bar', 'baz'], ['bar', 'qux']], { width: 1 }); const expected = 'bar\n' + 'bar\n' + 'baz\n' + 'foo\n' + 'qux'; t.equal(cols, expected); }); // prettier-ignore test('should print three column list', t => { const cols = columns(['foo', ['bar', 'baz'], ['bat', 'qux']], { width: 16 }); const expected = 'bar baz qux \n' + 'bat foo '; t.equal(cols, expected); }); // prettier-ignore test('should print complex list', t => { const cols = columns( [ 'foo', 'bar', 'baz', chalk.cyan('嶜憃撊') + ' 噾噿åš', 'blue' + chalk.bgBlue('berry'), chalk.red('apple'), 'pomegranate', 'durian', chalk.green('star fruit'), 'apricot', 'banana pineapple' ], { width: 80 } ); const expected = 'apple bar durian star fruit \n' + 'apricot baz foo 嶜憃撊 å™¾å™¿åš \n' + 'banana pineapple blueberry pomegranate '; t.equal(stripAnsi(cols), expected); }); // prettier-ignore test('should optionally not sort', t => { const cols = columns( [ 'foo', 'bar', 'baz', chalk.cyan('嶜憃撊') + ' 噾噿åš', 'blue' + chalk.bgBlue('berry'), chalk.red('apple'), 'pomegranate', 'durian', chalk.green('star fruit'), 'apricot', 'banana pineapple' ], { sort: false, width: 80 } ); const expected = 'foo 嶜憃撊 å™¾å™¿åš pomegranate apricot \n' + 'bar blueberry durian banana pineapple \n' + 'baz apple star fruit '; t.equal(stripAnsi(cols), expected); }); The ISC License Copyright (c) npm, Inc. and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // On windows, create a .cmd file. // Read the #! in the file to see what it uses. The vast majority // of the time, this will be either: // "#!/usr/bin/env " // or: // "#! " // // Write a binroot/pkg.bin + ".cmd" file that has this line in it: // @ %dp0% %* const { chmod, mkdir, readFile, stat, unlink, writeFile, } = require('fs/promises') const { dirname, relative } = require('path') const toBatchSyntax = require('./to-batch-syntax') // linting disabled because this regex is really long // eslint-disable-next-line max-len const shebangExpr = /^#!\s*(?:\/usr\/bin\/env\s+(?:-S\s+)?((?:[^ \t=]+=[^ \t=]+\s+)*))?([^ \t]+)(.*)$/ const cmdShimIfExists = (from, to) => stat(from).then(() => cmdShim(from, to), () => {}) // Try to unlink, but ignore errors. // Any problems will surface later. const rm = path => unlink(path).catch(() => {}) const cmdShim = (from, to) => stat(from).then(() => cmdShim_(from, to)) const cmdShim_ = (from, to) => Promise.all([ rm(to), rm(to + '.cmd'), rm(to + '.ps1'), ]).then(() => writeShim(from, to)) const writeShim = (from, to) => // make a cmd file and a sh script // First, check if the bin is a #! of some sort. // If not, then assume it's something that'll be compiled, or some other // sort of script, and just call it directly. mkdir(dirname(to), { recursive: true }) .then(() => readFile(from, 'utf8')) .then(data => { const firstLine = data.trim().split(/\r*\n/)[0] const shebang = firstLine.match(shebangExpr) if (!shebang) { return writeShim_(from, to) } const vars = shebang[1] || '' const prog = shebang[2] const args = shebang[3] || '' return writeShim_(from, to, prog, args, vars) }, () => writeShim_(from, to)) const writeShim_ = (from, to, prog, args, variables) => { let shTarget = relative(dirname(to), from) let target = shTarget.split('/').join('\\') let longProg let shProg = prog && prog.split('\\').join('/') let shLongProg let pwshProg = shProg && `"${shProg}$exe"` let pwshLongProg shTarget = shTarget.split('\\').join('/') args = args || '' variables = variables || '' if (!prog) { prog = `"%dp0%\\${target}"` shProg = `"$basedir/${shTarget}"` pwshProg = shProg args = '' target = '' shTarget = '' } else { longProg = `"%dp0%\\${prog}.exe"` shLongProg = `"$basedir/${prog}"` pwshLongProg = `"$basedir/${prog}$exe"` target = `"%dp0%\\${target}"` shTarget = `"$basedir/${shTarget}"` } // Subroutine trick to fix https://github.com/npm/cmd-shim/issues/10 // and https://github.com/npm/cli/issues/969 const head = '@ECHO off\r\n' + 'GOTO start\r\n' + ':find_dp0\r\n' + 'SET dp0=%~dp0\r\n' + 'EXIT /b\r\n' + ':start\r\n' + 'SETLOCAL\r\n' + 'CALL :find_dp0\r\n' let cmd if (longProg) { shLongProg = shLongProg.trim() args = args.trim() const variablesBatch = toBatchSyntax.convertToSetCommands(variables) cmd = head + variablesBatch + '\r\n' + `IF EXIST ${longProg} (\r\n` + ` SET "_prog=${longProg.replace(/(^")|("$)/g, '')}"\r\n` + ') ELSE (\r\n' + ` SET "_prog=${prog.replace(/(^")|("$)/g, '')}"\r\n` + ' SET PATHEXT=%PATHEXT:;.JS;=;%\r\n' + ')\r\n' + '\r\n' // prevent "Terminate Batch Job? (Y/n)" message // https://github.com/npm/cli/issues/969#issuecomment-737496588 + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & ' + `"%_prog%" ${args} ${target} %*\r\n` } else { cmd = `${head}${prog} ${args} ${target} %*\r\n` } // #!/bin/sh // basedir=`dirname "$0"` // // case `uname` in // *CYGWIN*|*MINGW*|*MSYS*) // if command -v cygpath > /dev/null 2>&1; then // basedir=`cygpath -w "$basedir"` // fi // ;; // esac // // if [ -x "$basedir/node.exe" ]; then // exec "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" // else // exec node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" // fi let sh = '#!/bin/sh\n' sh = sh + `basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")\n` + '\n' + 'case `uname` in\n' + ' *CYGWIN*|*MINGW*|*MSYS*)\n' + ' if command -v cygpath > /dev/null 2>&1; then\n' + ' basedir=`cygpath -w "$basedir"`\n' + ' fi\n' + ' ;;\n' + 'esac\n' + '\n' if (shLongProg) { sh = sh + `if [ -x ${shLongProg} ]; then\n` + ` exec ${variables}${shLongProg} ${args} ${shTarget} "$@"\n` + 'else \n' + ` exec ${variables}${shProg} ${args} ${shTarget} "$@"\n` + 'fi\n' } else { sh = sh + `exec ${shProg} ${args} ${shTarget} "$@"\n` } // #!/usr/bin/env pwsh // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent // // $ret=0 // $exe = "" // if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { // # Fix case when both the Windows and Linux builds of Node // # are installed in the same directory // $exe = ".exe" // } // if (Test-Path "$basedir/node") { // # Suport pipeline input // if ($MyInvocation.ExpectingInput) { // input | & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args // } else { // & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args // } // $ret=$LASTEXITCODE // } else { // # Support pipeline input // if ($MyInvocation.ExpectingInput) { // $input | & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args // } else { // & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args // } // $ret=$LASTEXITCODE // } // exit $ret let pwsh = '#!/usr/bin/env pwsh\n' + '$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n' + '\n' + '$exe=""\n' + 'if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {\n' + ' # Fix case when both the Windows and Linux builds of Node\n' + ' # are installed in the same directory\n' + ' $exe=".exe"\n' + '}\n' if (shLongProg) { pwsh = pwsh + '$ret=0\n' + `if (Test-Path ${pwshLongProg}) {\n` + ' # Support pipeline input\n' + ' if ($MyInvocation.ExpectingInput) {\n' + ` $input | & ${pwshLongProg} ${args} ${shTarget} $args\n` + ' } else {\n' + ` & ${pwshLongProg} ${args} ${shTarget} $args\n` + ' }\n' + ' $ret=$LASTEXITCODE\n' + '} else {\n' + ' # Support pipeline input\n' + ' if ($MyInvocation.ExpectingInput) {\n' + ` $input | & ${pwshProg} ${args} ${shTarget} $args\n` + ' } else {\n' + ` & ${pwshProg} ${args} ${shTarget} $args\n` + ' }\n' + ' $ret=$LASTEXITCODE\n' + '}\n' + 'exit $ret\n' } else { pwsh = pwsh + '# Support pipeline input\n' + 'if ($MyInvocation.ExpectingInput) {\n' + ` $input | & ${pwshProg} ${args} ${shTarget} $args\n` + '} else {\n' + ` & ${pwshProg} ${args} ${shTarget} $args\n` + '}\n' + 'exit $LASTEXITCODE\n' } return Promise.all([ writeFile(to + '.ps1', pwsh, 'utf8'), writeFile(to + '.cmd', cmd, 'utf8'), writeFile(to, sh, 'utf8'), ]).then(() => chmodShim(to)) } const chmodShim = to => Promise.all([ chmod(to, 0o755), chmod(to + '.cmd', 0o755), chmod(to + '.ps1', 0o755), ]) module.exports = cmdShim cmdShim.ifExists = cmdShimIfExists exports.replaceDollarWithPercentPair = replaceDollarWithPercentPair exports.convertToSetCommand = convertToSetCommand exports.convertToSetCommands = convertToSetCommands function convertToSetCommand (key, value) { var line = '' key = key || '' key = key.trim() value = value || '' value = value.trim() if (key && value && value.length > 0) { line = '@SET ' + key + '=' + replaceDollarWithPercentPair(value) + '\r\n' } return line } function extractVariableValuePairs (declarations) { var pairs = {} declarations.map(function (declaration) { var split = declaration.split('=') pairs[split[0]] = split[1] }) return pairs } function convertToSetCommands (variableString) { var variableValuePairs = extractVariableValuePairs(variableString.split(' ')) var variableDeclarationsAsBatch = '' Object.keys(variableValuePairs).forEach(function (key) { variableDeclarationsAsBatch += convertToSetCommand(key, variableValuePairs[key]) }) return variableDeclarationsAsBatch } function replaceDollarWithPercentPair (value) { var dollarExpressions = /\$\{?([^$@#?\- \t{}:]+)\}?/g var result = '' var startIndex = 0 do { var match = dollarExpressions.exec(value) if (match) { var betweenMatches = value.substring(startIndex, match.index) || '' result += betweenMatches + '%' + match[1] + '%' startIndex = dollarExpressions.lastIndex } } while (dollarExpressions.lastIndex > 0) result += value.slice(startIndex) return result } { "name": "cmd-shim", "version": "7.0.0", "description": "Used in npm for command line application support", "scripts": { "test": "tap", "snap": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cmd-shim.git" }, "license": "ISC", "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.1", "tap": "^16.0.1" }, "files": [ "bin/", "lib/" ], "main": "lib/index.js", "tap": { "before": "test/00-setup.js", "after": "test/zz-cleanup.js", "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "author": "GitHub Inc.", "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.1", "publish": true } } Copyright (c) 2011-2016 Heather Arthur 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. /* MIT license */ /* eslint-disable no-mixed-operators */ const cssKeywords = require('color-name'); // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(cssKeywords)) { reverseKeywords[cssKeywords[key]] = key; } const convert = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; module.exports = convert; // Hide .channels and .labels properties for (const model of Object.keys(convert)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const {channels, labels} = convert[model]; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } convert.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return ( ((x[0] - y[0]) ** 2) + ((x[1] - y[1]) ** 2) + ((x[2] - y[2]) ** 2) ); } convert.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(cssKeywords)) { const value = cssKeywords[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return cssKeywords[keyword]; }; convert.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { const xyz = convert.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - (s * f)); const t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // Assume sRGB r = r > 0.0031308 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } const ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = ((color & 1) * mult) * 255; const g = (((color >> 1) & 1) * mult) * 255; const b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = (integer >> 16) & 0xFF; const g = (integer >> 8) & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = (max - min); let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = (h % 1) * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert.gray.hsv = convert.gray.hsl; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; const conversions = require('./conversions'); const route = require('./route'); const convert = {}; const models = Object.keys(conversions); function wrapRaw(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(fromModel => { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); const routes = route(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); module.exports = convert; { "name": "color-convert", "description": "Plain color conversion functions", "version": "2.0.1", "author": "Heather Arthur ", "license": "MIT", "repository": "Qix-/color-convert", "scripts": { "pretest": "xo", "test": "node test/basic.js" }, "engines": { "node": ">=7.0.0" }, "keywords": [ "color", "colour", "convert", "converter", "conversion", "rgb", "hsl", "hsv", "hwb", "cmyk", "ansi", "ansi16" ], "files": [ "index.js", "conversions.js", "route.js" ], "xo": { "rules": { "default-case": 0, "no-inline-comments": 0, "operator-linebreak": 0 } }, "devDependencies": { "chalk": "^2.4.2", "xo": "^0.24.0" }, "dependencies": { "color-name": "~1.1.4" } } const conversions = require('./conversions'); /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { const graph = buildGraph(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } module.exports = function (fromModel) { const graph = deriveBFS(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; The MIT License (MIT) Copyright (c) 2015 Dmitry Ivanov 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.'use strict' module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; { "name": "color-name", "version": "1.1.4", "description": "A list of color names and its values", "main": "index.js", "files": [ "index.js" ], "scripts": { "test": "node test.js" }, "repository": { "type": "git", "url": "git@github.com:colorjs/color-name.git" }, "keywords": [ "color-name", "color", "color-keyword", "keyword" ], "author": "DY ", "license": "MIT", "bugs": { "url": "https://github.com/colorjs/color-name/issues" }, "homepage": "https://github.com/colorjs/color-name" } The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const {parse, sep, normalize: norm} = require('path') function* commonArrayMembers (a, b) { const [l, s] = a.length > b.length ? [a, b] : [b, a] for (const x of s) { if (x === l.shift()) yield x else break } } const commonAncestorPath = (a, b) => a === b ? a : parse(a).root !== parse(b).root ? null : [...commonArrayMembers(norm(a).split(sep), norm(b).split(sep))].join(sep) module.exports = (...paths) => paths.reduce(commonAncestorPath) { "name": "common-ancestor-path", "version": "1.0.1", "files": [ "index.js" ], "description": "Find the common ancestor of 2 or more paths on Windows or Unix", "repository": { "type": "git", "url": "git+https://github.com/isaacs/common-ancestor-path" }, "author": "Isaac Z. Schlueter (https://izs.me)", "license": "ISC", "scripts": { "test": "tap", "snap": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags" }, "tap": { "check-coverage": true }, "devDependencies": { "require-inject": "^1.4.4", "tap": "^14.10.7" } } The MIT License (MIT) Copyright (c) 2018 Made With MOXY Lda 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. 'use strict'; const cp = require('child_process'); const parse = require('./lib/parse'); const enoent = require('./lib/enoent'); function spawn(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); // Hook into child process "exit" event to emit an error if the command // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 enoent.hookChildProcess(spawned, parsed); return spawned; } function spawnSync(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); return result; } module.exports = spawn; module.exports.spawn = spawn; module.exports.sync = spawnSync; module.exports._parse = parse; module.exports._enoent = enoent; 'use strict'; const isWin = process.platform === 'win32'; function notFoundError(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: 'ENOENT', errno: 'ENOENT', syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args, }); } function hookChildProcess(cp, parsed) { if (!isWin) { return; } const originalEmit = cp.emit; cp.emit = function (name, arg1) { // If emitting "exit" event and exit code is 1, we need to check if // the command exists and emit an "error" instead // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 if (name === 'exit') { const err = verifyENOENT(arg1, parsed); if (err) { return originalEmit.call(cp, 'error', err); } } return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; } function verifyENOENT(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawn'); } return null; } function verifyENOENTSync(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawnSync'); } return null; } module.exports = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError, }; 'use strict'; const path = require('path'); const resolveCommand = require('./util/resolveCommand'); const escape = require('./util/escape'); const readShebang = require('./util/readShebang'); const isWin = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang(parsed) { parsed.file = resolveCommand(parsed); const shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand(parsed); } return parsed.file; } function parseNonShell(parsed) { if (!isWin) { return parsed; } // Detect & add support for shebangs const commandFile = detectShebang(parsed); // We don't need a shell if the command filename is an executable const needsShell = !isExecutableRegExp.test(commandFile); // If a shell is required, use cmd.exe and take care of escaping everything correctly // Note that `forceShell` is an hidden option used only in tests if (parsed.options.forceShell || needsShell) { // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, // we need to double escape them const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) // This is necessary otherwise it will always fail with ENOENT in those cases parsed.command = path.normalize(parsed.command); // Escape command & arguments parsed.command = escape.command(parsed.command); parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(' '); parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parse(command, args, options) { // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = Object.assign({}, options); // Clone object to avoid changing the original // Build our parsed object const parsed = { command, args, options, file: undefined, original: { command, args, }, }; // Delegate further parsing to shell or non-shell return options.shell ? parsed : parseNonShell(parsed); } module.exports = parse; 'use strict'; // See http://www.robvanderwoude.com/escapechars.php const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand(arg) { // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); return arg; } function escapeArgument(arg, doubleEscapeMetaChars) { // Convert to string arg = `${arg}`; // Algorithm below is based on https://qntm.org/cmd // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information // Sequence of backslashes followed by a double quote: // double up all the backslashes and escape the double quote arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'); // Sequence of backslashes followed by the end of the string // (which will become a double quote later): // double up all the backslashes arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1'); // All other backslashes occur literally // Quote the whole thing: arg = `"${arg}"`; // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); // Double escape meta chars if necessary if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp, '^$1'); } return arg; } module.exports.command = escapeCommand; module.exports.argument = escapeArgument; 'use strict'; const fs = require('fs'); const shebangCommand = require('shebang-command'); function readShebang(command) { // Read the first 150 bytes from the file const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs.openSync(command, 'r'); fs.readSync(fd, buffer, 0, size, 0); fs.closeSync(fd); } catch (e) { /* Empty */ } // Attempt to extract shebang (null is returned if not a shebang) return shebangCommand(buffer.toString()); } module.exports = readShebang; 'use strict'; const path = require('path'); const which = require('which'); const getPathKey = require('path-key'); function resolveCommandAttempt(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { /* Empty */ } } let resolved; try { resolved = which.sync(parsed.command, { path: env[getPathKey({ env })], pathExt: withoutPathExt ? path.delimiter : undefined, }); } catch (e) { /* Empty */ } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } // If we successfully resolved, ensure that an absolute path is returned // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it if (resolved) { resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } return resolved; } function resolveCommand(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } module.exports = resolveCommand; The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # which Like the unix `which` utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so `hash -r` is not needed when the PATH changes. ## USAGE ```javascript var which = require('which') // async usage which('node', function (er, resolvedPath) { // er is returned if no "node" is found on the PATH // if it is found, then the absolute path to the exec is returned }) // or promise which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) // sync usage // throws if not found var resolved = which.sync('node') // if nothrow option is used, returns null if not found resolved = which.sync('node', {nothrow: true}) // Pass options to override the PATH and PATHEXT environment vars. which('node', { path: someOtherPath }, function (er, resolved) { if (er) throw er console.log('found at %j', resolved) }) ``` ## CLI USAGE Same as the BSD `which(1)` binary. ``` usage: which [-as] program ... ``` ## OPTIONS You may pass an options object as the second argument. - `path`: Use instead of the `PATH` environment variable. - `pathExt`: Use instead of the `PATHEXT` environment variable. - `all`: Return all matches, instead of just the first one. Note that this means the function returns an array of strings instead of a single string. #!/usr/bin/env node var which = require("../") if (process.argv.length < 3) usage() function usage () { console.error('usage: which [-as] program ...') process.exit(1) } var all = false var silent = false var dashdash = false var args = process.argv.slice(2).filter(function (arg) { if (dashdash || !/^-/.test(arg)) return true if (arg === '--') { dashdash = true return false } var flags = arg.substr(1).split('') for (var f = 0; f < flags.length; f++) { var flag = flags[f] switch (flag) { case 's': silent = true break case 'a': all = true break default: console.error('which: illegal option -- ' + flag) usage() } } return false }) process.exit(args.reduce(function (pv, current) { try { var f = which.sync(current, { all: all }) if (all) f = f.join('\n') if (!silent) console.log(f) return pv; } catch (e) { return 1; } }, 0)) { "author": "Isaac Z. Schlueter (http://blog.izs.me)", "name": "which", "description": "Like which(1) unix command. Find the first instance of an executable in the PATH.", "version": "2.0.2", "repository": { "type": "git", "url": "git://github.com/isaacs/node-which.git" }, "main": "which.js", "bin": { "node-which": "./bin/node-which" }, "license": "ISC", "dependencies": { "isexe": "^2.0.0" }, "devDependencies": { "mkdirp": "^0.5.0", "rimraf": "^2.6.2", "tap": "^14.6.9" }, "scripts": { "test": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublish": "npm run changelog", "prechangelog": "bash gen-changelog.sh", "changelog": "git add CHANGELOG.md", "postchangelog": "git commit -m 'update changelog - '${npm_package_version}", "postpublish": "git push origin --follow-tags" }, "files": [ "which.js", "bin/node-which" ], "tap": { "check-coverage": true }, "engines": { "node": ">= 8" } } const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys' const path = require('path') const COLON = isWindows ? ';' : ':' const isexe = require('isexe') const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ) const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : '' const pathExt = isWindows ? pathExtExe.split(colon) : [''] if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift('') } return { pathEnv, pathExt, pathExtExe, } } const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt opt = {} } if (!opt) opt = {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd resolve(subStep(p, i, 0)) }) const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii] isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext) else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }) }) return cb ? step(0).then(res => cb(null, res), cb) : step(0) } const whichSync = (cmd, opt) => { opt = opt || {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j] try { const is = isexe.sync(cur, { pathExt: pathExtExe }) if (is) { if (opt.all) found.push(cur) else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) } module.exports = which which.sync = whichSync { "name": "cross-spawn", "version": "7.0.6", "description": "Cross platform child_process#spawn and child_process#spawnSync", "keywords": [ "spawn", "spawnSync", "windows", "cross-platform", "path-ext", "shebang", "cmd", "execute" ], "author": "André Cruz ", "homepage": "https://github.com/moxystudio/node-cross-spawn", "repository": { "type": "git", "url": "git@github.com:moxystudio/node-cross-spawn.git" }, "license": "MIT", "main": "index.js", "files": [ "lib" ], "scripts": { "lint": "eslint .", "test": "jest --env node --coverage", "prerelease": "npm t && npm run lint", "release": "standard-version", "postrelease": "git push --follow-tags origin HEAD && npm publish" }, "husky": { "hooks": { "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", "pre-commit": "lint-staged" } }, "lint-staged": { "*.js": [ "eslint --fix", "git add" ] }, "commitlint": { "extends": [ "@commitlint/config-conventional" ] }, "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" }, "devDependencies": { "@commitlint/cli": "^8.1.0", "@commitlint/config-conventional": "^8.1.0", "babel-core": "^6.26.3", "babel-jest": "^24.9.0", "babel-preset-moxy": "^3.1.0", "eslint": "^5.16.0", "eslint-config-moxy": "^7.1.0", "husky": "^3.0.5", "jest": "^24.9.0", "lint-staged": "^9.2.5", "mkdirp": "^0.5.1", "rimraf": "^3.0.0", "standard-version": "^9.5.0" }, "engines": { "node": ">= 8" } } Copyright Mathias Bynens 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. # cssesc [![Build status](https://travis-ci.org/mathiasbynens/cssesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/cssesc) [![Code coverage status](https://img.shields.io/codecov/c/github/mathiasbynens/cssesc.svg)](https://codecov.io/gh/mathiasbynens/cssesc) A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output. This is a JavaScript library for [escaping text for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes) while generating the shortest possible valid ASCII-only output. [Here’s an online demo.](https://mothereff.in/css-escapes) [A polyfill for the CSSOM `CSS.escape()` method is available in a separate repository.](https://mths.be/cssescape) (In comparison, _cssesc_ is much more powerful.) Feel free to fork if you see possible improvements! ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install cssesc ``` In a browser: ```html ``` In [Node.js](https://nodejs.org/): ```js const cssesc = require('cssesc'); ``` In Ruby using [the `ruby-cssesc` wrapper gem](https://github.com/borodean/ruby-cssesc): ```bash gem install ruby-cssesc ``` ```ruby require 'ruby-cssesc' CSSEsc.escape('I ♥ Ruby', is_identifier: true) ``` In Sass using [`sassy-escape`](https://github.com/borodean/sassy-escape): ```bash gem install sassy-escape ``` ```scss body { content: escape('I ♥ Sass', $is-identifier: true); } ``` ## API ### `cssesc(value, options)` This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes). ```js cssesc('Ich ♥ Bücher'); // → 'Ich \\2665 B\\FC cher' cssesc('foo ðŒ† bar'); // → 'foo \\1D306 bar' ``` By default, `cssesc` returns a string that can be used as part of a CSS string. If the target is a CSS identifier rather than a CSS string, use the `isIdentifier: true` setting (see below). The optional `options` argument accepts an object with the following options: #### `isIdentifier` The default value for the `isIdentifier` option is `false`. This means that the input text will be escaped for use in a CSS string literal. If you want to use the result as a CSS identifier instead (in a selector, for example), set this option to `true`. ```js cssesc('123a2b'); // → '123a2b' cssesc('123a2b', { 'isIdentifier': true }); // → '\\31 23a2b' ``` #### `quotes` The default value for the `quotes` option is `'single'`. This means that any occurences of `'` in the input text will be escaped as `\'`, so that the output can be used in a CSS string literal wrapped in single quotes. ```js cssesc('Lorem ipsum "dolor" sit \'amet\' etc.'); // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' // → "Lorem ipsum \"dolor\" sit \\'amet\\' etc." cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single' }); // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' // → "Lorem ipsum \"dolor\" sit \\'amet\\' etc." ``` If you want to use the output as part of a CSS string literal wrapped in double quotes, set the `quotes` option to `'double'`. ```js cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double' }); // → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.' // → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc." ``` #### `wrap` The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output will be a valid CSS string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting. ```js cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single', 'wrap': true }); // → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\'' // → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'" cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double', 'wrap': true }); // → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."' // → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\"" ``` #### `escapeEverything` The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols. ```js cssesc('lolwat"foo\'bar', { 'escapeEverything': true }); // → '\\6C\\6F\\6C\\77\\61\\74\\"\\66\\6F\\6F\\\'\\62\\61\\72' // → "\\6C\\6F\\6C\\77\\61\\74\\\"\\66\\6F\\6F\\'\\62\\61\\72" ``` #### Overriding the default options globally The global default settings can be overridden by modifying the `css.options` object. This saves you from passing in an `options` object for every call to `encode` if you want to use the non-default setting. ```js // Read the global default setting for `escapeEverything`: cssesc.options.escapeEverything; // → `false` by default // Override the global default setting for `escapeEverything`: cssesc.options.escapeEverything = true; // Using the global default setting for `escapeEverything`, which is now `true`: cssesc('foo © bar ≠ baz ðŒ† qux'); // → '\\66\\6F\\6F\\ \\A9\\ \\62\\61\\72\\ \\2260\\ \\62\\61\\7A\\ \\1D306\\ \\71\\75\\78' ``` ### `cssesc.version` A string representing the semantic version number. ### Using the `cssesc` binary To use the `cssesc` binary in your shell, simply install cssesc globally using npm: ```bash npm install -g cssesc ``` After that you will be able to escape text for use in CSS strings or identifiers from the command line: ```bash $ cssesc 'föo ♥ bÃ¥r ðŒ† baz' f\F6o \2665 b\E5r \1D306 baz ``` If the output needs to be a CSS identifier rather than part of a string literal, use the `-i`/`--identifier` option: ```bash $ cssesc --identifier 'föo ♥ bÃ¥r ðŒ† baz' f\F6o\ \2665\ b\E5r\ \1D306\ baz ``` See `cssesc --help` for the full list of options. ## Support This library supports the Node.js and browser versions mentioned in [`.babelrc`](https://github.com/mathiasbynens/cssesc/blob/master/.babelrc). For a version that supports a wider variety of legacy browsers and environments out-of-the-box, [see v0.1.0](https://github.com/mathiasbynens/cssesc/releases/tag/v0.1.0). ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License This library is available under the [MIT](https://mths.be/mit) license. #!/usr/bin/env node const fs = require('fs'); const cssesc = require('../cssesc.js'); const strings = process.argv.splice(2); const stdin = process.stdin; const options = {}; const log = console.log; const main = function() { const option = strings[0]; if (/^(?:-h|--help|undefined)$/.test(option)) { log( 'cssesc v%s - https://mths.be/cssesc', cssesc.version ); log([ '\nUsage:\n', '\tcssesc [string]', '\tcssesc [-i | --identifier] [string]', '\tcssesc [-s | --single-quotes] [string]', '\tcssesc [-d | --double-quotes] [string]', '\tcssesc [-w | --wrap] [string]', '\tcssesc [-e | --escape-everything] [string]', '\tcssesc [-v | --version]', '\tcssesc [-h | --help]', '\nExamples:\n', '\tcssesc \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', '\tcssesc --identifier \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', '\tcssesc --escape-everything \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', '\tcssesc --double-quotes --wrap \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', '\techo \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\' | cssesc' ].join('\n')); return process.exit(1); } if (/^(?:-v|--version)$/.test(option)) { log('v%s', cssesc.version); return process.exit(1); } strings.forEach(function(string) { // Process options if (/^(?:-i|--identifier)$/.test(string)) { options.isIdentifier = true; return; } if (/^(?:-s|--single-quotes)$/.test(string)) { options.quotes = 'single'; return; } if (/^(?:-d|--double-quotes)$/.test(string)) { options.quotes = 'double'; return; } if (/^(?:-w|--wrap)$/.test(string)) { options.wrap = true; return; } if (/^(?:-e|--escape-everything)$/.test(string)) { options.escapeEverything = true; return; } // Process string(s) let result; try { result = cssesc(string, options); log(result); } catch (exception) { log(exception.message + '\n'); log('Error: failed to escape.'); log('If you think this is a bug in cssesc, please report it:'); log('https://github.com/mathiasbynens/cssesc/issues/new'); log( '\nStack trace using cssesc@%s:\n', cssesc.version ); log(exception.stack); return process.exit(1); } }); // Return with exit status 0 outside of the `forEach` loop, in case // multiple strings were passed in. return process.exit(0); }; if (stdin.isTTY) { // handle shell arguments main(); } else { let timeout; // Either the script is called from within a non-TTY context, or `stdin` // content is being piped in. if (!process.stdout.isTTY) { // The script was called from a non-TTY context. This is a rather uncommon // use case we don’t actively support. However, we don’t want the script // to wait forever in such cases, so… timeout = setTimeout(function() { // …if no piped data arrived after a whole minute, handle shell // arguments instead. main(); }, 60000); } let data = ''; stdin.on('data', function(chunk) { clearTimeout(timeout); data += chunk; }); stdin.on('end', function() { strings.push(data.trim()); main(); }); stdin.resume(); } /*! https://mths.be/cssesc v3.0.0 by @mathias */ 'use strict'; var object = {}; var hasOwnProperty = object.hasOwnProperty; var merge = function merge(options, defaults) { if (!options) { return defaults; } var result = {}; for (var key in defaults) { // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since // only recognized option names are used. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key]; } return result; }; var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/; var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/; var regexAlwaysEscape = /['"\\]/; var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g; // https://mathiasbynens.be/notes/css-escapes#css var cssesc = function cssesc(string, options) { options = merge(options, cssesc.options); if (options.quotes != 'single' && options.quotes != 'double') { options.quotes = 'single'; } var quote = options.quotes == 'double' ? '"' : '\''; var isIdentifier = options.isIdentifier; var firstChar = string.charAt(0); var output = ''; var counter = 0; var length = string.length; while (counter < length) { var character = string.charAt(counter++); var codePoint = character.charCodeAt(); var value = void 0; // If it’s not a printable ASCII character… if (codePoint < 0x20 || codePoint > 0x7E) { if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) { // It’s a high surrogate, and there is a next character. var extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // next character is low surrogate codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000; } else { // It’s an unmatched surrogate; only append this code unit, in case // the next code unit is the high surrogate of a surrogate pair. counter--; } } value = '\\' + codePoint.toString(16).toUpperCase() + ' '; } else { if (options.escapeEverything) { if (regexAnySingleEscape.test(character)) { value = '\\' + character; } else { value = '\\' + codePoint.toString(16).toUpperCase() + ' '; } } else if (/[\t\n\f\r\x0B]/.test(character)) { value = '\\' + codePoint.toString(16).toUpperCase() + ' '; } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) { value = '\\' + character; } else { value = character; } } output += value; } if (isIdentifier) { if (/^-[-\d]/.test(output)) { output = '\\-' + output.slice(1); } else if (/\d/.test(firstChar)) { output = '\\3' + firstChar + ' ' + output.slice(1); } } // Remove spaces after `\HEX` escapes that are not followed by a hex digit, // since they’re redundant. Note that this is only possible if the escape // sequence isn’t preceded by an odd number of backslashes. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) { if ($1 && $1.length % 2) { // It’s not safe to remove the space, so don’t. return $0; } // Strip the space. return ($1 || '') + $2; }); if (!isIdentifier && options.wrap) { return quote + output + quote; } return output; }; // Expose default options (so they can be overridden globally). cssesc.options = { 'escapeEverything': false, 'isIdentifier': false, 'quotes': 'single', 'wrap': false }; cssesc.version = '3.0.0'; module.exports = cssesc; .Dd August 9, 2013 .Dt cssesc 1 .Sh NAME .Nm cssesc .Nd escape text for use in CSS string literals or identifiers .Sh SYNOPSIS .Nm .Op Fl i | -identifier Ar string .br .Op Fl s | -single-quotes Ar string .br .Op Fl d | -double-quotes Ar string .br .Op Fl w | -wrap Ar string .br .Op Fl e | -escape-everything Ar string .br .Op Fl v | -version .br .Op Fl h | -help .Sh DESCRIPTION .Nm escapes strings for use in CSS string literals or identifiers while generating the shortest possible valid ASCII-only output. .Sh OPTIONS .Bl -ohang -offset .It Sy "-s, --single-quotes" Escape any occurences of ' in the input string as \\', so that the output can be used in a CSS string literal wrapped in single quotes. .It Sy "-d, --double-quotes" Escape any occurences of " in the input string as \\", so that the output can be used in a CSS string literal wrapped in double quotes. .It Sy "-w, --wrap" Make sure the output is a valid CSS string literal wrapped in quotes. The type of quotes can be specified using the .Ar -s | --single-quotes or .Ar -d | --double-quotes settings. .It Sy "-e, --escape-everything" Escape all the symbols in the output, even printable ASCII symbols. .It Sy "-v, --version" Print cssesc's version. .It Sy "-h, --help" Show the help screen. .El .Sh EXIT STATUS The .Nm cssesc utility exits with one of the following values: .Pp .Bl -tag -width flag -compact .It Li 0 .Nm successfully escaped the given text and printed the result. .It Li 1 .Nm wasn't instructed to escape anything (for example, the .Ar --help flag was set); or, an error occurred. .El .Sh EXAMPLES .Bl -ohang -offset .It Sy "cssesc 'foo bar baz'" Print an escaped version of the given text. .It Sy echo\ 'foo bar baz'\ |\ cssesc Print an escaped version of the text that gets piped in. .El .Sh BUGS cssesc's bug tracker is located at . .Sh AUTHOR Mathias Bynens .Sh WWW { "name": "cssesc", "version": "3.0.0", "description": "A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output.", "homepage": "https://mths.be/cssesc", "engines": { "node": ">=4" }, "main": "cssesc.js", "bin": "bin/cssesc", "man": "man/cssesc.1", "keywords": [ "css", "escape", "identifier", "string", "tool" ], "license": "MIT", "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "repository": { "type": "git", "url": "https://github.com/mathiasbynens/cssesc.git" }, "bugs": "https://github.com/mathiasbynens/cssesc/issues", "files": [ "LICENSE-MIT.txt", "cssesc.js", "bin/", "man/" ], "scripts": { "build": "grunt template && babel cssesc.js -o cssesc.js", "test": "mocha tests", "cover": "istanbul cover --report html node_modules/.bin/_mocha tests -- -u exports -R spec" }, "devDependencies": { "babel-cli": "^6.26.0", "babel-preset-env": "^1.6.1", "codecov": "^1.0.1", "grunt": "^1.0.1", "grunt-template": "^1.0.0", "istanbul": "^0.4.4", "mocha": "^2.5.3", "regenerate": "^1.2.1", "requirejs": "^2.1.16" } } (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk Copyright (c) 2018-2021 Josh Junon 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. { "name": "debug", "version": "4.4.0", "repository": { "type": "git", "url": "git://github.com/debug-js/debug.git" }, "description": "Lightweight debugging utility for Node.js and the browser", "keywords": [ "debug", "log", "debugger" ], "files": [ "src", "LICENSE", "README.md" ], "author": "Josh Junon (https://github.com/qix-)", "contributors": [ "TJ Holowaychuk ", "Nathan Rajlich (http://n8.io)", "Andrew Rhyne " ], "license": "MIT", "scripts": { "lint": "xo", "test": "npm run test:node && npm run test:browser && npm run lint", "test:node": "istanbul cover _mocha -- test.js test.node.js", "test:browser": "karma start --single-run", "test:coverage": "cat ./coverage/lcov.info | coveralls" }, "dependencies": { "ms": "^2.1.3" }, "devDependencies": { "brfs": "^2.0.1", "browserify": "^16.2.3", "coveralls": "^3.0.2", "istanbul": "^0.4.5", "karma": "^3.1.4", "karma-browserify": "^6.0.0", "karma-chrome-launcher": "^2.2.0", "karma-mocha": "^1.3.0", "mocha": "^5.2.0", "mocha-lcov-reporter": "^1.2.0", "sinon": "^14.0.0", "xo": "^0.23.0" }, "peerDependenciesMeta": { "supports-color": { "optional": true } }, "main": "./src/index.js", "browser": "./src/browser.js", "engines": { "node": ">=6.0" }, "xo": { "rules": { "import/extensions": "off" } } } /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 // eslint-disable-next-line no-return-assign return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = require('ms'); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === 'string' ? namespaces : '') .trim() .replace(' ', ',') .split(',') .filter(Boolean); for (const ns of split) { if (ns[0] === '-') { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } /** * Checks if the given string matches a namespace template, honoring * asterisks as wildcards. * * @param {String} search * @param {String} template * @return {Boolean} */ function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { // Match character or proceed with wildcard if (template[templateIndex] === '*') { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; // Skip the '*' } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition // Backtrack to the last '*' and try to match more characters templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; // No match } } // Handle trailing '*' in template while (templateIndex < template.length && template[templateIndex] === '*') { templateIndex++; } return templateIndex === template.length; } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = require('./browser.js'); } else { module.exports = require('./node.js'); } /** * Module dependencies. */ const tty = require('tty'); const util = require('util'); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = require('supports-color'); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; # How to Contribute ## Pull Requests We also accept [pull requests][pull-request]! Generally we like to see pull requests that - Maintain the existing code style - Are focused on a single change (i.e. avoid large refactoring or style adjustments in untouched code if not the primary goal of the pull request) - Have [good commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) - Have tests - Don't decrease the current code coverage (see coverage/lcov-report/index.html) ## Building ``` yarn yarn test ``` Running `yarn test -- dev` will watch for tests within Node and `karma start` may be used for manual testing in browsers. If you notice any problems, please report them to the GitHub issue tracker at [http://github.com/kpdecker/jsdiff/issues](http://github.com/kpdecker/jsdiff/issues). ## Releasing A full release may be completed by first updating the `"version"` property in package.json, then running the following: ``` yarn clean yarn grunt release yarn publish ``` After releasing, remember to: * commit the `package.json` change and push it to GitHub * create a new version tag on GitHub * update `diff.js` on the `gh-pages` branch to the latest built version from the `dist/` folder. BSD 3-Clause License Copyright (c) 2009-2015, Kevin Decker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder nor the names of its 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 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. /*! diff v7.0.0 BSD 3-Clause License Copyright (c) 2009-2015, Kevin Decker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder nor the names of its 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 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. @license */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Diff = {})); })(this, (function (exports) { 'use strict'; function Diff() {} Diff.prototype = { diff: function diff(oldString, newString) { var _options$timeout; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } var self = this; function done(value) { value = self.postProcess(value, options); if (callback) { setTimeout(function () { callback(value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString, options); newString = this.castInput(newString, options); oldString = this.removeEmpty(this.tokenize(oldString, options)); newString = this.removeEmpty(this.tokenize(newString, options)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; if (options.maxEditLength != null) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; var abortAfterTimestamp = Date.now() + maxExecutionTime; var bestPath = [{ oldPos: -1, lastComponent: undefined }]; // Seed editLength = 0, i.e. the content starts with the same values var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // Identity per the equality and tokenizer return done(buildValues(self, bestPath[0].lastComponent, newString, oldString, self.useLongestToken)); } // Once we hit the right edge of the edit graph on some diagonal k, we can // definitely reach the end of the edit graph in no more than k edits, so // there's no point in considering any moves to diagonal k+1 any more (from // which we're guaranteed to need at least k+1 more edits). // Similarly, once we've reached the bottom of the edit graph, there's no // point considering moves to lower diagonals. // We record this fact by setting minDiagonalToConsider and // maxDiagonalToConsider to some finite value once we've hit the edge of // the edit graph. // This optimization is not faithful to the original algorithm presented in // Myers's paper, which instead pointlessly extends D-paths off the end of // the edit graph - see page 7 of Myers's paper which notes this point // explicitly and illustrates it with a diagram. This has major performance // implications for some common scenarios. For instance, to compute a diff // where the new text simply appends d characters on the end of the // original text of length n, the true Myers algorithm will take O(n+d^2) // time while this optimization needs only O(n+d) time. var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { var basePath = void 0; var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = false; if (addPath) { // what newPos will be after we do an insertion: var addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } var canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the old string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { basePath = self.addToPath(addPath, true, false, 0, options); } else { basePath = self.addToPath(removePath, false, true, 1, options); } newPos = self.extractCommon(basePath, newString, oldString, diagonalPath, options); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // If we have hit the end of both strings, then we are done return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken)); } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced, or until the edit length exceeds options.maxEditLength (if given), // in which case it will return undefined. if (callback) { (function exec() { setTimeout(function () { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { var ret = execEditLength(); if (ret) { return ret; } } } }, addToPath: function addToPath(path, added, removed, oldPosInc, options) { var last = path.lastComponent; if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath, options) { var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options)) { newPos++; oldPos++; commonCount++; if (options.oneChangePerToken) { basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; } } if (commonCount && !options.oneChangePerToken) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; } basePath.oldPos = oldPos; return newPos; }, equals: function equals(left, right, options) { if (options.comparator) { return options.comparator(left, right); } else { return left === right || options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return Array.from(value); }, join: function join(chars) { return chars.join(''); }, postProcess: function postProcess(changeObjects) { return changeObjects; } }; function buildValues(diff, lastComponent, newString, oldString, useLongestToken) { // First we convert our linked list of components in reverse order to an // array in the right order: var components = []; var nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; } } return components; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function longestCommonPrefix(str1, str2) { var i; for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[i] != str2[i]) { return str1.slice(0, i); } } return str1.slice(0, i); } function longestCommonSuffix(str1, str2) { var i; // Unlike longestCommonPrefix, we need a special case to handle all scenarios // where we return the empty string since str1.slice(-0) will return the // entire string. if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) { return ''; } for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) { return str1.slice(-i); } } return str1.slice(-i); } function replacePrefix(string, oldPrefix, newPrefix) { if (string.slice(0, oldPrefix.length) != oldPrefix) { throw Error("string ".concat(JSON.stringify(string), " doesn't start with prefix ").concat(JSON.stringify(oldPrefix), "; this is a bug")); } return newPrefix + string.slice(oldPrefix.length); } function replaceSuffix(string, oldSuffix, newSuffix) { if (!oldSuffix) { return string + newSuffix; } if (string.slice(-oldSuffix.length) != oldSuffix) { throw Error("string ".concat(JSON.stringify(string), " doesn't end with suffix ").concat(JSON.stringify(oldSuffix), "; this is a bug")); } return string.slice(0, -oldSuffix.length) + newSuffix; } function removePrefix(string, oldPrefix) { return replacePrefix(string, oldPrefix, ''); } function removeSuffix(string, oldSuffix) { return replaceSuffix(string, oldSuffix, ''); } function maximumOverlap(string1, string2) { return string2.slice(0, overlapCount(string1, string2)); } // Nicked from https://stackoverflow.com/a/60422853/1709587 function overlapCount(a, b) { // Deal with cases where the strings differ in length var startA = 0; if (a.length > b.length) { startA = a.length - b.length; } var endB = b.length; if (a.length < b.length) { endB = a.length; } // Create a back-reference for each index // that should be followed in case of a mismatch. // We only need B to make these references: var map = Array(endB); var k = 0; // Index that lags behind j map[0] = 0; for (var j = 1; j < endB; j++) { if (b[j] == b[k]) { map[j] = map[k]; // skip over the same character (optional optimisation) } else { map[j] = k; } while (k > 0 && b[j] != b[k]) { k = map[k]; } if (b[j] == b[k]) { k++; } } // Phase 2: use these references while iterating over A k = 0; for (var i = startA; i < a.length; i++) { while (k > 0 && a[i] != b[k]) { k = map[k]; } if (a[i] == b[k]) { k++; } } return k; } /** * Returns true if the string consistently uses Windows line endings. */ function hasOnlyWinLineEndings(string) { return string.includes('\r\n') && !string.startsWith('\n') && !string.match(/[^\r]\n/); } /** * Returns true if the string consistently uses Unix line endings. */ function hasOnlyUnixLineEndings(string) { return !string.includes('\r\n') && string.includes('\n'); } // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 Ë™ ˙ Dot Above // - U+02DA Ëš ˚ Ring Above // - U+02DB Ë› ˛ Ogonek // - U+02DC Ëœ ˜ Small Tilde // - U+02DD Ë ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = "a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}"; // Each token is one of the following: // - A punctuation mark plus the surrounding whitespace // - A word plus the surrounding whitespace // - Pure whitespace (but only in the special case where this the entire text // is just whitespace) // // We have to include surrounding whitespace in the tokens because the two // alternative approaches produce horribly broken results: // * If we just discard the whitespace, we can't fully reproduce the original // text from the sequence of tokens and any attempt to render the diff will // get the whitespace wrong. // * If we have separate tokens for whitespace, then in a typical text every // second token will be a single space character. But this often results in // the optimal diff between two texts being a perverse one that preserves // the spaces between words but deletes and reinserts actual common words. // See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640 // for an example. // // Keeping the surrounding whitespace of course has implications for .equals // and .join, not just .tokenize. // This regex does NOT fully implement the tokenization rules described above. // Instead, it gives runs of whitespace their own "token". The tokenize method // then handles stitching whitespace tokens onto adjacent word or punctuation // tokens. var tokenizeIncludingWhitespace = new RegExp("[".concat(extendedWordChars, "]+|\\s+|[^").concat(extendedWordChars, "]"), 'ug'); var wordDiff = new Diff(); wordDiff.equals = function (left, right, options) { if (options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left.trim() === right.trim(); }; wordDiff.tokenize = function (value) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var parts; if (options.intlSegmenter) { if (options.intlSegmenter.resolvedOptions().granularity != 'word') { throw new Error('The segmenter passed must have a granularity of "word"'); } parts = Array.from(options.intlSegmenter.segment(value), function (segment) { return segment.segment; }); } else { parts = value.match(tokenizeIncludingWhitespace) || []; } var tokens = []; var prevPart = null; parts.forEach(function (part) { if (/\s/.test(part)) { if (prevPart == null) { tokens.push(part); } else { tokens.push(tokens.pop() + part); } } else if (/\s/.test(prevPart)) { if (tokens[tokens.length - 1] == prevPart) { tokens.push(tokens.pop() + part); } else { tokens.push(prevPart + part); } } else { tokens.push(part); } prevPart = part; }); return tokens; }; wordDiff.join = function (tokens) { // Tokens being joined here will always have appeared consecutively in the // same text, so we can simply strip off the leading whitespace from all the // tokens except the first (and except any whitespace-only tokens - but such // a token will always be the first and only token anyway) and then join them // and the whitespace around words and punctuation will end up correct. return tokens.map(function (token, i) { if (i == 0) { return token; } else { return token.replace(/^\s+/, ''); } }).join(''); }; wordDiff.postProcess = function (changes, options) { if (!changes || options.oneChangePerToken) { return changes; } var lastKeep = null; // Change objects representing any insertion or deletion since the last // "keep" change object. There can be at most one of each. var insertion = null; var deletion = null; changes.forEach(function (change) { if (change.added) { insertion = change; } else if (change.removed) { deletion = change; } else { if (insertion || deletion) { // May be false at start of text dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change); } lastKeep = change; insertion = null; deletion = null; } }); if (insertion || deletion) { dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null); } return changes; }; function diffWords(oldStr, newStr, options) { // This option has never been documented and never will be (it's clearer to // just call `diffWordsWithSpace` directly if you need that behavior), but // has existed in jsdiff for a long time, so we retain support for it here // for the sake of backwards compatibility. if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) { return diffWordsWithSpace(oldStr, newStr, options); } return wordDiff.diff(oldStr, newStr, options); } function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) { // Before returning, we tidy up the leading and trailing whitespace of the // change objects to eliminate cases where trailing whitespace in one object // is repeated as leading whitespace in the next. // Below are examples of the outcomes we want here to explain the code. // I=insert, K=keep, D=delete // 1. diffing 'foo bar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' // After cleanup, we want: K:'foo ' D:'bar ' K:'baz' // // 2. Diffing 'foo bar baz' vs 'foo qux baz' // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz' // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz' // // 3. Diffing 'foo\nbar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:'\nbar ' K:' baz' // After cleanup, we want K'foo' D:'\nbar' K:' baz' // // 4. Diffing 'foo baz' vs 'foo\nbar baz' // Prior to cleanup, we have K:'foo\n' I:'\nbar ' K:' baz' // After cleanup, we ideally want K'foo' I:'\nbar' K:' baz' // but don't actually manage this currently (the pre-cleanup change // objects don't contain enough information to make it possible). // // 5. Diffing 'foo bar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' // After cleanup, we want K:'foo ' D:' bar ' K:'baz' // // Our handling is unavoidably imperfect in the case where there's a single // indel between keeps and the whitespace has changed. For instance, consider // diffing 'foo\tbar\nbaz' vs 'foo baz'. Unless we create an extra change // object to represent the insertion of the space character (which isn't even // a token), we have no way to avoid losing information about the texts' // original whitespace in the result we return. Still, we do our best to // output something that will look sensible if we e.g. print it with // insertions in green and deletions in red. // Between two "keep" change objects (or before the first or after the last // change object), we can have either: // * A "delete" followed by an "insert" // * Just an "insert" // * Just a "delete" // We handle the three cases separately. if (deletion && insertion) { var oldWsPrefix = deletion.value.match(/^\s*/)[0]; var oldWsSuffix = deletion.value.match(/\s*$/)[0]; var newWsPrefix = insertion.value.match(/^\s*/)[0]; var newWsSuffix = insertion.value.match(/\s*$/)[0]; if (startKeep) { var commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix); startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix); deletion.value = removePrefix(deletion.value, commonWsPrefix); insertion.value = removePrefix(insertion.value, commonWsPrefix); } if (endKeep) { var commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix); endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix); deletion.value = removeSuffix(deletion.value, commonWsSuffix); insertion.value = removeSuffix(insertion.value, commonWsSuffix); } } else if (insertion) { // The whitespaces all reflect what was in the new text rather than // the old, so we essentially have no information about whitespace // insertion or deletion. We just want to dedupe the whitespace. // We do that by having each change object keep its trailing // whitespace and deleting duplicate leading whitespace where // present. if (startKeep) { insertion.value = insertion.value.replace(/^\s*/, ''); } if (endKeep) { endKeep.value = endKeep.value.replace(/^\s*/, ''); } // otherwise we've got a deletion and no insertion } else if (startKeep && endKeep) { var newWsFull = endKeep.value.match(/^\s*/)[0], delWsStart = deletion.value.match(/^\s*/)[0], delWsEnd = deletion.value.match(/\s*$/)[0]; // Any whitespace that comes straight after startKeep in both the old and // new texts, assign to startKeep and remove from the deletion. var newWsStart = longestCommonPrefix(newWsFull, delWsStart); deletion.value = removePrefix(deletion.value, newWsStart); // Any whitespace that comes straight before endKeep in both the old and // new texts, and hasn't already been assigned to startKeep, assign to // endKeep and remove from the deletion. var newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd); deletion.value = removeSuffix(deletion.value, newWsEnd); endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd); // If there's any whitespace from the new text that HASN'T already been // assigned, assign it to the start: startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length)); } else if (endKeep) { // We are at the start of the text. Preserve all the whitespace on // endKeep, and just remove whitespace from the end of deletion to the // extent that it overlaps with the start of endKeep. var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0]; var deletionWsSuffix = deletion.value.match(/\s*$/)[0]; var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix); deletion.value = removeSuffix(deletion.value, overlap); } else if (startKeep) { // We are at the END of the text. Preserve all the whitespace on // startKeep, and just remove whitespace from the start of deletion to // the extent that it overlaps with the end of startKeep. var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0]; var deletionWsPrefix = deletion.value.match(/^\s*/)[0]; var _overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix); deletion.value = removePrefix(deletion.value, _overlap); } } var wordWithSpaceDiff = new Diff(); wordWithSpaceDiff.tokenize = function (value) { // Slightly different to the tokenizeIncludingWhitespace regex used above in // that this one treats each individual newline as a distinct tokens, rather // than merging them into other surrounding whitespace. This was requested // in https://github.com/kpdecker/jsdiff/issues/180 & // https://github.com/kpdecker/jsdiff/issues/211 var regex = new RegExp("(\\r?\\n)|[".concat(extendedWordChars, "]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars, "]"), 'ug'); return value.match(regex) || []; }; function diffWordsWithSpace(oldStr, newStr, options) { return wordWithSpaceDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } var lineDiff = new Diff(); lineDiff.tokenize = function (value, options) { if (options.stripTrailingCr) { // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior value = value.replace(/\r\n/g, '\n'); } var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { retLines.push(line); } } return retLines; }; lineDiff.equals = function (left, right, options) { // If we're ignoring whitespace, we need to normalise lines by stripping // whitespace before checking equality. (This has an annoying interaction // with newlineIsToken that requires special handling: if newlines get their // own token, then we DON'T want to trim the *newline* tokens down to empty // strings, since this would cause us to treat whitespace-only line content // as equal to a separator between lines, which would be weird and // inconsistent with the documented behavior of the options.) if (options.ignoreWhitespace) { if (!options.newlineIsToken || !left.includes('\n')) { left = left.trim(); } if (!options.newlineIsToken || !right.includes('\n')) { right = right.trim(); } } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { if (left.endsWith('\n')) { left = left.slice(0, -1); } if (right.endsWith('\n')) { right = right.slice(0, -1); } } return Diff.prototype.equals.call(this, left, right, options); }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } // Kept for backwards compatibility. This is a rather arbitrary wrapper method // that just calls `diffLines` with `ignoreWhitespace: true`. It's confusing to // have two ways to do exactly the same thing in the API, so we no longer // document this one (library users should explicitly use `diffLines` with // `ignoreWhitespace: true` instead) but we keep it around to maintain // compatibility with code that used old versions. function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value, options) { var undefinedReplacement = options.undefinedReplacement, _options$stringifyRep = options.stringifyReplacer, stringifyReplacer = _options$stringifyRep === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _options$stringifyRep; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right, options) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === Object.prototype.toString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(obj, _key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function unixToWin(patch) { if (Array.isArray(patch)) { return patch.map(unixToWin); } return _objectSpread2(_objectSpread2({}, patch), {}, { hunks: patch.hunks.map(function (hunk) { return _objectSpread2(_objectSpread2({}, hunk), {}, { lines: hunk.lines.map(function (line, i) { var _hunk$lines; return line.startsWith('\\') || line.endsWith('\r') || (_hunk$lines = hunk.lines[i + 1]) !== null && _hunk$lines !== void 0 && _hunk$lines.startsWith('\\') ? line : line + '\r'; }) }); }) }); } function winToUnix(patch) { if (Array.isArray(patch)) { return patch.map(winToUnix); } return _objectSpread2(_objectSpread2({}, patch), {}, { hunks: patch.hunks.map(function (hunk) { return _objectSpread2(_objectSpread2({}, hunk), {}, { lines: hunk.lines.map(function (line) { return line.endsWith('\r') ? line.substring(0, line.length - 1) : line; }) }); }) }); } /** * Returns true if the patch consistently uses Unix line endings (or only involves one line and has * no line endings). */ function isUnix(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return !patch.some(function (index) { return index.hunks.some(function (hunk) { return hunk.lines.some(function (line) { return !line.startsWith('\\') && line.endsWith('\r'); }); }); }); } /** * Returns true if the patch uses Windows line endings and only Windows line endings. */ function isWin(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return patch.some(function (index) { return index.hunks.some(function (hunk) { return hunk.lines.some(function (line) { return line.endsWith('\r'); }); }); }) && patch.every(function (index) { return index.hunks.every(function (hunk) { return hunk.lines.every(function (line, i) { var _hunk$lines2; return line.startsWith('\\') || line.endsWith('\r') || ((_hunk$lines2 = hunk.lines[i + 1]) === null || _hunk$lines2 === void 0 ? void 0 : _hunk$lines2.startsWith('\\')); }); }); }); } function parsePatch(uniDiff) { var diffstr = uniDiff.split(/\n/), list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:\s|diff\s|\-\-\-\s|\+\+\+\s|===================================================================)/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line) { throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], lines: [] }; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } var addCount = 0, removeCount = 0; for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || (_diffstr$i = diffstr[i]) !== null && _diffstr$i !== void 0 && _diffstr$i.startsWith('\\')); i++) { var _diffstr$i; var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { throw new Error("Hunk at line ".concat(chunkHeaderIndex + 1, " contained invalid line ").concat(diffstr[i])); } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform sanity checking if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return start + localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return start - localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { if (hasOnlyWinLineEndings(source) && isUnix(uniDiff)) { uniDiff = unixToWin(uniDiff); } else if (hasOnlyUnixLineEndings(source) && isWin(uniDiff)) { uniDiff = winToUnix(uniDiff); } } // Apply the diff to the input var lines = source.split('\n'), hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, fuzzFactor = options.fuzzFactor || 0, minLine = 0; if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { throw new Error('fuzzFactor must be a non-negative integer'); } // Special case for empty patch. if (!hunks.length) { return source; } // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a // newline that already exists - then we either return false and fail to apply the patch (if // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0). // If we do need to remove/add a newline at EOF, this will always be in the final hunk: var prevLine = '', removeEOFNL = false, addEOFNL = false; for (var i = 0; i < hunks[hunks.length - 1].lines.length; i++) { var line = hunks[hunks.length - 1].lines[i]; if (line[0] == '\\') { if (prevLine[0] == '+') { removeEOFNL = true; } else if (prevLine[0] == '-') { addEOFNL = true; } } prevLine = line; } if (removeEOFNL) { if (addEOFNL) { // This means the final line gets changed but doesn't have a trailing newline in either the // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if // fuzzFactor is 0, we simply validate that the source file has no trailing newline. if (!fuzzFactor && lines[lines.length - 1] == '') { return false; } } else if (lines[lines.length - 1] == '') { lines.pop(); } else if (!fuzzFactor) { return false; } } else if (addEOFNL) { if (lines[lines.length - 1] != '') { lines.push(''); } else if (!fuzzFactor) { return false; } } /** * Checks if the hunk can be made to fit at the provided location with at most `maxErrors` * insertions, substitutions, or deletions, while ensuring also that: * - lines deleted in the hunk match exactly, and * - wherever an insertion operation or block of insertion operations appears in the hunk, the * immediately preceding and following lines of context match exactly * * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0]. * * If the hunk can be applied, returns an object with properties `oldLineLastI` and * `replacementLines`. Otherwise, returns null. */ function applyHunk(hunkLines, toPos, maxErrors) { var hunkLinesI = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var lastContextLineMatched = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; var patchedLines = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; var patchedLinesLength = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; var nConsecutiveOldContextLines = 0; var nextContextLineMustMatch = false; for (; hunkLinesI < hunkLines.length; hunkLinesI++) { var hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : ' ', content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; if (operation === '-') { if (compareLine(toPos + 1, lines[toPos], operation, content)) { toPos++; nConsecutiveOldContextLines = 0; } else { if (!maxErrors || lines[toPos] == null) { return null; } patchedLines[patchedLinesLength] = lines[toPos]; return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); } } if (operation === '+') { if (!lastContextLineMatched) { return null; } patchedLines[patchedLinesLength] = content; patchedLinesLength++; nConsecutiveOldContextLines = 0; nextContextLineMustMatch = true; } if (operation === ' ') { nConsecutiveOldContextLines++; patchedLines[patchedLinesLength] = lines[toPos]; if (compareLine(toPos + 1, lines[toPos], operation, content)) { patchedLinesLength++; lastContextLineMatched = true; nextContextLineMustMatch = false; toPos++; } else { if (nextContextLineMustMatch || !maxErrors) { return null; } // Consider 3 possibilities in sequence: // 1. lines contains a *substitution* not included in the patch context, or // 2. lines contains an *insertion* not included in the patch context, or // 3. lines contains a *deletion* not included in the patch context // The first two options are of course only possible if the line from lines is non-null - // i.e. only option 3 is possible if we've overrun the end of the old file. return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); } } } // Before returning, trim any unmodified context lines off the end of patchedLines and reduce // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region // that starts in this hunk's trailing context. patchedLinesLength -= nConsecutiveOldContextLines; toPos -= nConsecutiveOldContextLines; patchedLines.length = patchedLinesLength; return { patchedLines: patchedLines, oldLineLastI: toPos - 1 }; } var resultLines = []; // Search best fit offsets for each hunk based on the previous ones var prevHunkOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var hunk = hunks[_i]; var hunkResult = void 0; var maxLine = lines.length - hunk.oldLines + fuzzFactor; var toPos = void 0; for (var maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { toPos = hunk.oldStart + prevHunkOffset - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; toPos !== undefined; toPos = iterator()) { hunkResult = applyHunk(hunk.lines, toPos, maxErrors); if (hunkResult) { break; } } if (hunkResult) { break; } } if (!hunkResult) { return false; } // Copy everything from the end of where we applied the last hunk to the start of this hunk for (var _i2 = minLine; _i2 < toPos; _i2++) { resultLines.push(lines[_i2]); } // Add the lines produced by applying the hunk: for (var _i3 = 0; _i3 < hunkResult.patchedLines.length; _i3++) { var _line = hunkResult.patchedLines[_i3]; resultLines.push(_line); } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunkResult.oldLineLastI + 1; // Note the offset between where the patch said the hunk should've applied and where we // applied it, so we can adjust future hunks accordingly: prevHunkOffset = toPos + 1 - hunk.oldStart; } // Copy over the rest of the lines from the old text for (var _i4 = minLine; _i4 < lines.length; _i4++) { resultLines.push(lines[_i4]); } return resultLines.join('\n'); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options === 'function') { options = { callback: options }; } if (typeof options.context === 'undefined') { options.context = 4; } if (options.newlineIsToken) { throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions'); } if (!options.callback) { return diffLinesResultToPatch(diffLines(oldStr, newStr, options)); } else { var _options = options, _callback = _options.callback; diffLines(oldStr, newStr, _objectSpread2(_objectSpread2({}, options), {}, { callback: function callback(diff) { var patch = diffLinesResultToPatch(diff); _callback(patch); } })); } function diffLinesResultToPatch(diff) { // STEP 1: Build up the patch with no "\ No newline at end of file" lines and with the arrays // of lines containing trailing newline characters. We'll tidy up later... if (!diff) { return; } diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop() { var current = diff[i], lines = current.lines || splitLines(current.value); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var _hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; hunks.push(_hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(); } // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add // "\ No newline at end of file". for (var _i = 0, _hunks = hunks; _i < _hunks.length; _i++) { var hunk = _hunks[_i]; for (var _i2 = 0; _i2 < hunk.lines.length; _i2++) { if (hunk.lines[_i2].endsWith('\n')) { hunk.lines[_i2] = hunk.lines[_i2].slice(0, -1); } else { hunk.lines.splice(_i2 + 1, 0, '\\ No newline at end of file'); _i2++; // Skip the line we just added, then continue iterating } } } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } } function formatPatch(diff) { if (Array.isArray(diff)) { return diff.map(formatPatch).join('\n'); } var ret = []; if (diff.oldFileName == diff.newFileName) { ret.push('Index: ' + diff.oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { var _options2; if (typeof options === 'function') { options = { callback: options }; } if (!((_options2 = options) !== null && _options2 !== void 0 && _options2.callback)) { var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); if (!patchObj) { return; } return formatPatch(patchObj); } else { var _options3 = options, _callback2 = _options3.callback; structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, _objectSpread2(_objectSpread2({}, options), {}, { callback: function callback(patchObj) { if (!patchObj) { _callback2(); } else { _callback2(formatPatch(patchObj)); } } })); } } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } /** * Split `text` into an array of lines, including the trailing newline character (where present) */ function splitLines(text) { var hasTrailingNl = text.endsWith('\n'); var result = text.split('\n').map(function (line) { return line + '\n'; }); if (hasTrailingNl) { result.pop(); } else { result.push(result.pop().slice(0, -1)); } return result; } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } function reversePatch(structuredPatch) { if (Array.isArray(structuredPatch)) { return structuredPatch.map(reversePatch).reverse(); } return _objectSpread2(_objectSpread2({}, structuredPatch), {}, { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(function (hunk) { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, lines: hunk.lines.map(function (l) { if (l.startsWith('-')) { return "+".concat(l.slice(1)); } if (l.startsWith('+')) { return "-".concat(l.slice(1)); } return l; }) }; }) }); } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } exports.Diff = Diff; exports.applyPatch = applyPatch; exports.applyPatches = applyPatches; exports.canonicalize = canonicalize; exports.convertChangesToDMP = convertChangesToDMP; exports.convertChangesToXML = convertChangesToXML; exports.createPatch = createPatch; exports.createTwoFilesPatch = createTwoFilesPatch; exports.diffArrays = diffArrays; exports.diffChars = diffChars; exports.diffCss = diffCss; exports.diffJson = diffJson; exports.diffLines = diffLines; exports.diffSentences = diffSentences; exports.diffTrimmedLines = diffTrimmedLines; exports.diffWords = diffWords; exports.diffWordsWithSpace = diffWordsWithSpace; exports.formatPatch = formatPatch; exports.merge = merge; exports.parsePatch = parsePatch; exports.reversePatch = reversePatch; exports.structuredPatch = structuredPatch; })); /*! diff v7.0.0 BSD 3-Clause License Copyright (c) 2009-2015, Kevin Decker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder nor the names of its 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 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. @license */ !function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).Diff={})}(this,function(e){"use strict";function r(){}function w(e,n,t,r,i){for(var o,l=[];n;)l.push(n),o=n.previousComponent,delete n.previousComponent,n=o;l.reverse();for(var a=0,u=l.length,s=0,f=0;ae.length?n:e}),d.value=e.join(c)):d.value=e.join(t.slice(s,s+d.count)),s+=d.count,d.added||(f+=d.count))}return l}r.prototype={diff:function(l,a){var u=2=d&&c<=v+1)return f(w(s,p[0].lastComponent,a,l,s.useLongestToken));var g=-1/0,m=1/0;function i(){for(var e=Math.max(g,-h);e<=Math.min(m,h);e+=2){var n=void 0,t=p[e-1],r=p[e+1],i=(t&&(p[e-1]=void 0),!1),o=(r&&(o=r.oldPos-e,i=r&&0<=o&&o=d&&c<=v+1)return f(w(s,n.lastComponent,a,l,s.useLongestToken));(p[e]=n).oldPos+1>=d&&(m=Math.min(m,e-1)),c<=v+1&&(g=Math.max(g,e+1))}else p[e]=void 0}h++}if(n)!function e(){setTimeout(function(){if(tr)return n();i()||e()},0)}();else for(;h<=t&&Date.now()<=r;){var o=i();if(o)return o}},addToPath:function(e,n,t,r,i){var o=e.lastComponent;return o&&!i.oneChangePerToken&&o.added===n&&o.removed===t?{oldPos:e.oldPos+r,lastComponent:{count:o.count+1,added:n,removed:t,previousComponent:o.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:n,removed:t,previousComponent:o}}},extractCommon:function(e,n,t,r,i){for(var o=n.length,l=t.length,a=e.oldPos,u=a-r,s=0;u+1n.length&&(t=e.length-n.length);var r=n.length;e.lengthe.length)&&(n=e.length);for(var t=0,r=new Array(n);te.length)return!1;for(var t=0;t"):r.removed&&n.push(""),n.push(r.value.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")),r.added?n.push(""):r.removed&&n.push("")}return n.join("")},e.createPatch=function(e,n,t,r,i,o){return M(e,e,n,t,r,i,o)},e.createTwoFilesPatch=M,e.diffArrays=function(e,n,t){return F.diff(e,n,t)},e.diffChars=function(e,n,t){return I.diff(e,n,t)},e.diffCss=function(e,n,t){return m.diff(e,n,t)},e.diffJson=function(e,n,t){return x.diff(e,n,t)},e.diffLines=y,e.diffSentences=function(e,n,t){return g.diff(e,n,t)},e.diffTrimmedLines=function(e,n,t){return t=function(e,n){if("function"==typeof e)n.callback=e;else if(e)for(var t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}(t,{ignoreWhitespace:!0}),v.diff(e,n,t)},e.diffWords=function(e,n,t){return null==(null==t?void 0:t.ignoreWhitespace)||t.ignoreWhitespace?i.diff(e,n,t):a(e,n,t)},e.diffWordsWithSpace=a,e.formatPatch=E,e.merge=function(e,n,t){e=J(e,t),n=J(n,t);for(var r={},i=((e.index||n.index)&&(r.index=e.index||n.index),(e.newFileName||n.newFileName)&&(q(e)?q(n)?(r.oldFileName=H(r,e.oldFileName,n.oldFileName),r.newFileName=H(r,e.newFileName,n.newFileName),r.oldHeader=H(r,e.oldHeader,n.oldHeader),r.newHeader=H(r,e.newHeader,n.newHeader)):(r.oldFileName=e.oldFileName,r.newFileName=e.newFileName,r.oldHeader=e.oldHeader,r.newHeader=e.newHeader):(r.oldFileName=n.oldFileName||e.oldFileName,r.newFileName=n.newFileName||e.newFileName,r.oldHeader=n.oldHeader||e.oldHeader,r.newHeader=n.newHeader||e.newHeader)),r.hunks=[],0),o=0,l=0,a=0;i'); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2hhbmdlcyIsInJldCIsImkiLCJsZW5ndGgiLCJjaGFuZ2UiLCJhZGRlZCIsInB1c2giLCJyZW1vdmVkIiwiZXNjYXBlSFRNTCIsInZhbHVlIiwiam9pbiIsInMiLCJuIiwicmVwbGFjZSJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L3htbC5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gY29udmVydENoYW5nZXNUb1hNTChjaGFuZ2VzKSB7XG4gIGxldCByZXQgPSBbXTtcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBjaGFuZ2VzLmxlbmd0aDsgaSsrKSB7XG4gICAgbGV0IGNoYW5nZSA9IGNoYW5nZXNbaV07XG4gICAgaWYgKGNoYW5nZS5hZGRlZCkge1xuICAgICAgcmV0LnB1c2goJzxpbnM+Jyk7XG4gICAgfSBlbHNlIGlmIChjaGFuZ2UucmVtb3ZlZCkge1xuICAgICAgcmV0LnB1c2goJzxkZWw+Jyk7XG4gICAgfVxuXG4gICAgcmV0LnB1c2goZXNjYXBlSFRNTChjaGFuZ2UudmFsdWUpKTtcblxuICAgIGlmIChjaGFuZ2UuYWRkZWQpIHtcbiAgICAgIHJldC5wdXNoKCc8L2lucz4nKTtcbiAgICB9IGVsc2UgaWYgKGNoYW5nZS5yZW1vdmVkKSB7XG4gICAgICByZXQucHVzaCgnPC9kZWw+Jyk7XG4gICAgfVxuICB9XG4gIHJldHVybiByZXQuam9pbignJyk7XG59XG5cbmZ1bmN0aW9uIGVzY2FwZUhUTUwocykge1xuICBsZXQgbiA9IHM7XG4gIG4gPSBuLnJlcGxhY2UoLyYvZywgJyZhbXA7Jyk7XG4gIG4gPSBuLnJlcGxhY2UoLzwvZywgJyZsdDsnKTtcbiAgbiA9IG4ucmVwbGFjZSgvPi9nLCAnJmd0OycpO1xuICBuID0gbi5yZXBsYWNlKC9cIi9nLCAnJnF1b3Q7Jyk7XG5cbiAgcmV0dXJuIG47XG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBQU8sU0FBU0EsbUJBQW1CQSxDQUFDQyxPQUFPLEVBQUU7RUFDM0MsSUFBSUMsR0FBRyxHQUFHLEVBQUU7RUFDWixLQUFLLElBQUlDLENBQUMsR0FBRyxDQUFDLEVBQUVBLENBQUMsR0FBR0YsT0FBTyxDQUFDRyxNQUFNLEVBQUVELENBQUMsRUFBRSxFQUFFO0lBQ3ZDLElBQUlFLE1BQU0sR0FBR0osT0FBTyxDQUFDRSxDQUFDLENBQUM7SUFDdkIsSUFBSUUsTUFBTSxDQUFDQyxLQUFLLEVBQUU7TUFDaEJKLEdBQUcsQ0FBQ0ssSUFBSSxDQUFDLE9BQU8sQ0FBQztJQUNuQixDQUFDLE1BQU0sSUFBSUYsTUFBTSxDQUFDRyxPQUFPLEVBQUU7TUFDekJOLEdBQUcsQ0FBQ0ssSUFBSSxDQUFDLE9BQU8sQ0FBQztJQUNuQjtJQUVBTCxHQUFHLENBQUNLLElBQUksQ0FBQ0UsVUFBVSxDQUFDSixNQUFNLENBQUNLLEtBQUssQ0FBQyxDQUFDO0lBRWxDLElBQUlMLE1BQU0sQ0FBQ0MsS0FBSyxFQUFFO01BQ2hCSixHQUFHLENBQUNLLElBQUksQ0FBQyxRQUFRLENBQUM7SUFDcEIsQ0FBQyxNQUFNLElBQUlGLE1BQU0sQ0FBQ0csT0FBTyxFQUFFO01BQ3pCTixHQUFHLENBQUNLLElBQUksQ0FBQyxRQUFRLENBQUM7SUFDcEI7RUFDRjtFQUNBLE9BQU9MLEdBQUcsQ0FBQ1MsSUFBSSxDQUFDLEVBQUUsQ0FBQztBQUNyQjtBQUVBLFNBQVNGLFVBQVVBLENBQUNHLENBQUMsRUFBRTtFQUNyQixJQUFJQyxDQUFDLEdBQUdELENBQUM7RUFDVEMsQ0FBQyxHQUFHQSxDQUFDLENBQUNDLE9BQU8sQ0FBQyxJQUFJLEVBQUUsT0FBTyxDQUFDO0VBQzVCRCxDQUFDLEdBQUdBLENBQUMsQ0FBQ0MsT0FBTyxDQUFDLElBQUksRUFBRSxNQUFNLENBQUM7RUFDM0JELENBQUMsR0FBR0EsQ0FBQyxDQUFDQyxPQUFPLENBQUMsSUFBSSxFQUFFLE1BQU0sQ0FBQztFQUMzQkQsQ0FBQyxHQUFHQSxDQUFDLENBQUNDLE9BQU8sQ0FBQyxJQUFJLEVBQUUsUUFBUSxDQUFDO0VBRTdCLE9BQU9ELENBQUM7QUFDViIsImlnbm9yZUxpc3QiOltdfQ== /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayDiff = void 0; exports.diffArrays = diffArrays; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var arrayDiff = /*istanbul ignore start*/ exports.arrayDiff = /*istanbul ignore end*/ new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYmFzZSIsIl9pbnRlcm9wUmVxdWlyZURlZmF1bHQiLCJyZXF1aXJlIiwib2JqIiwiX19lc01vZHVsZSIsImFycmF5RGlmZiIsImV4cG9ydHMiLCJEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsInNsaWNlIiwiam9pbiIsInJlbW92ZUVtcHR5IiwiZGlmZkFycmF5cyIsIm9sZEFyciIsIm5ld0FyciIsImNhbGxiYWNrIiwiZGlmZiJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2FycmF5LmpzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cbmV4cG9ydCBjb25zdCBhcnJheURpZmYgPSBuZXcgRGlmZigpO1xuYXJyYXlEaWZmLnRva2VuaXplID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgcmV0dXJuIHZhbHVlLnNsaWNlKCk7XG59O1xuYXJyYXlEaWZmLmpvaW4gPSBhcnJheURpZmYucmVtb3ZlRW1wdHkgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWU7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkFycmF5cyhvbGRBcnIsIG5ld0FyciwgY2FsbGJhY2spIHsgcmV0dXJuIGFycmF5RGlmZi5kaWZmKG9sZEFyciwgbmV3QXJyLCBjYWxsYmFjayk7IH1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBQSxLQUFBLEdBQUFDLHNCQUFBLENBQUFDLE9BQUE7QUFBQTtBQUFBO0FBQTBCLG1DQUFBRCx1QkFBQUUsR0FBQSxXQUFBQSxHQUFBLElBQUFBLEdBQUEsQ0FBQUMsVUFBQSxHQUFBRCxHQUFBLGdCQUFBQSxHQUFBO0FBQUE7QUFFbkIsSUFBTUUsU0FBUztBQUFBO0FBQUFDLE9BQUEsQ0FBQUQsU0FBQTtBQUFBO0FBQUc7QUFBSUU7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSSxDQUFDLENBQUM7QUFDbkNGLFNBQVMsQ0FBQ0csUUFBUSxHQUFHLFVBQVNDLEtBQUssRUFBRTtFQUNuQyxPQUFPQSxLQUFLLENBQUNDLEtBQUssQ0FBQyxDQUFDO0FBQ3RCLENBQUM7QUFDREwsU0FBUyxDQUFDTSxJQUFJLEdBQUdOLFNBQVMsQ0FBQ08sV0FBVyxHQUFHLFVBQVNILEtBQUssRUFBRTtFQUN2RCxPQUFPQSxLQUFLO0FBQ2QsQ0FBQztBQUVNLFNBQVNJLFVBQVVBLENBQUNDLE1BQU0sRUFBRUMsTUFBTSxFQUFFQyxRQUFRLEVBQUU7RUFBRSxPQUFPWCxTQUFTLENBQUNZLElBQUksQ0FBQ0gsTUFBTSxFQUFFQyxNQUFNLEVBQUVDLFFBQVEsQ0FBQztBQUFFIiwiaWdub3JlTGlzdCI6W119 /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = Diff; /*istanbul ignore end*/ function Diff() {} Diff.prototype = { /*istanbul ignore start*/ /*istanbul ignore end*/ diff: function diff(oldString, newString) { /*istanbul ignore start*/ var _options$timeout; var /*istanbul ignore end*/ options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } var self = this; function done(value) { value = self.postProcess(value, options); if (callback) { setTimeout(function () { callback(value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString, options); newString = this.castInput(newString, options); oldString = this.removeEmpty(this.tokenize(oldString, options)); newString = this.removeEmpty(this.tokenize(newString, options)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; if (options.maxEditLength != null) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } var maxExecutionTime = /*istanbul ignore start*/ (_options$timeout = /*istanbul ignore end*/ options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; var abortAfterTimestamp = Date.now() + maxExecutionTime; var bestPath = [{ oldPos: -1, lastComponent: undefined }]; // Seed editLength = 0, i.e. the content starts with the same values var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // Identity per the equality and tokenizer return done(buildValues(self, bestPath[0].lastComponent, newString, oldString, self.useLongestToken)); } // Once we hit the right edge of the edit graph on some diagonal k, we can // definitely reach the end of the edit graph in no more than k edits, so // there's no point in considering any moves to diagonal k+1 any more (from // which we're guaranteed to need at least k+1 more edits). // Similarly, once we've reached the bottom of the edit graph, there's no // point considering moves to lower diagonals. // We record this fact by setting minDiagonalToConsider and // maxDiagonalToConsider to some finite value once we've hit the edge of // the edit graph. // This optimization is not faithful to the original algorithm presented in // Myers's paper, which instead pointlessly extends D-paths off the end of // the edit graph - see page 7 of Myers's paper which notes this point // explicitly and illustrates it with a diagram. This has major performance // implications for some common scenarios. For instance, to compute a diff // where the new text simply appends d characters on the end of the // original text of length n, the true Myers algorithm will take O(n+d^2) // time while this optimization needs only O(n+d) time. var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { var basePath = /*istanbul ignore start*/ void 0 /*istanbul ignore end*/ ; var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = false; if (addPath) { // what newPos will be after we do an insertion: var addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } var canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the old string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { basePath = self.addToPath(addPath, true, false, 0, options); } else { basePath = self.addToPath(removePath, false, true, 1, options); } newPos = self.extractCommon(basePath, newString, oldString, diagonalPath, options); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // If we have hit the end of both strings, then we are done return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken)); } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced, or until the edit length exceeds options.maxEditLength (if given), // in which case it will return undefined. if (callback) { (function exec() { setTimeout(function () { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { var ret = execEditLength(); if (ret) { return ret; } } } }, /*istanbul ignore start*/ /*istanbul ignore end*/ addToPath: function addToPath(path, added, removed, oldPosInc, options) { var last = path.lastComponent; if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; } }, /*istanbul ignore start*/ /*istanbul ignore end*/ extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath, options) { var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options)) { newPos++; oldPos++; commonCount++; if (options.oneChangePerToken) { basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; } } if (commonCount && !options.oneChangePerToken) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; } basePath.oldPos = oldPos; return newPos; }, /*istanbul ignore start*/ /*istanbul ignore end*/ equals: function equals(left, right, options) { if (options.comparator) { return options.comparator(left, right); } else { return left === right || options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, /*istanbul ignore start*/ /*istanbul ignore end*/ removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, /*istanbul ignore start*/ /*istanbul ignore end*/ castInput: function castInput(value) { return value; }, /*istanbul ignore start*/ /*istanbul ignore end*/ tokenize: function tokenize(value) { return Array.from(value); }, /*istanbul ignore start*/ /*istanbul ignore end*/ join: function join(chars) { return chars.join(''); }, /*istanbul ignore start*/ /*istanbul ignore end*/ postProcess: function postProcess(changeObjects) { return changeObjects; } }; function buildValues(diff, lastComponent, newString, oldString, useLongestToken) { // First we convert our linked list of components in reverse order to an // array in the right order: var components = []; var nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; } } return components; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJEaWZmIiwicHJvdG90eXBlIiwiZGlmZiIsIm9sZFN0cmluZyIsIm5ld1N0cmluZyIsIl9vcHRpb25zJHRpbWVvdXQiLCJvcHRpb25zIiwiYXJndW1lbnRzIiwibGVuZ3RoIiwidW5kZWZpbmVkIiwiY2FsbGJhY2siLCJzZWxmIiwiZG9uZSIsInZhbHVlIiwicG9zdFByb2Nlc3MiLCJzZXRUaW1lb3V0IiwiY2FzdElucHV0IiwicmVtb3ZlRW1wdHkiLCJ0b2tlbml6ZSIsIm5ld0xlbiIsIm9sZExlbiIsImVkaXRMZW5ndGgiLCJtYXhFZGl0TGVuZ3RoIiwiTWF0aCIsIm1pbiIsIm1heEV4ZWN1dGlvblRpbWUiLCJ0aW1lb3V0IiwiSW5maW5pdHkiLCJhYm9ydEFmdGVyVGltZXN0YW1wIiwiRGF0ZSIsIm5vdyIsImJlc3RQYXRoIiwib2xkUG9zIiwibGFzdENvbXBvbmVudCIsIm5ld1BvcyIsImV4dHJhY3RDb21tb24iLCJidWlsZFZhbHVlcyIsInVzZUxvbmdlc3RUb2tlbiIsIm1pbkRpYWdvbmFsVG9Db25zaWRlciIsIm1heERpYWdvbmFsVG9Db25zaWRlciIsImV4ZWNFZGl0TGVuZ3RoIiwiZGlhZ29uYWxQYXRoIiwibWF4IiwiYmFzZVBhdGgiLCJyZW1vdmVQYXRoIiwiYWRkUGF0aCIsImNhbkFkZCIsImFkZFBhdGhOZXdQb3MiLCJjYW5SZW1vdmUiLCJhZGRUb1BhdGgiLCJleGVjIiwicmV0IiwicGF0aCIsImFkZGVkIiwicmVtb3ZlZCIsIm9sZFBvc0luYyIsImxhc3QiLCJvbmVDaGFuZ2VQZXJUb2tlbiIsImNvdW50IiwicHJldmlvdXNDb21wb25lbnQiLCJjb21tb25Db3VudCIsImVxdWFscyIsImxlZnQiLCJyaWdodCIsImNvbXBhcmF0b3IiLCJpZ25vcmVDYXNlIiwidG9Mb3dlckNhc2UiLCJhcnJheSIsImkiLCJwdXNoIiwiQXJyYXkiLCJmcm9tIiwiam9pbiIsImNoYXJzIiwiY2hhbmdlT2JqZWN0cyIsImNvbXBvbmVudHMiLCJuZXh0Q29tcG9uZW50IiwicmV2ZXJzZSIsImNvbXBvbmVudFBvcyIsImNvbXBvbmVudExlbiIsImNvbXBvbmVudCIsInNsaWNlIiwibWFwIiwib2xkVmFsdWUiXSwic291cmNlcyI6WyIuLi8uLi9zcmMvZGlmZi9iYXNlLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uIERpZmYoKSB7fVxuXG5EaWZmLnByb3RvdHlwZSA9IHtcbiAgZGlmZihvbGRTdHJpbmcsIG5ld1N0cmluZywgb3B0aW9ucyA9IHt9KSB7XG4gICAgbGV0IGNhbGxiYWNrID0gb3B0aW9ucy5jYWxsYmFjaztcbiAgICBpZiAodHlwZW9mIG9wdGlvbnMgPT09ICdmdW5jdGlvbicpIHtcbiAgICAgIGNhbGxiYWNrID0gb3B0aW9ucztcbiAgICAgIG9wdGlvbnMgPSB7fTtcbiAgICB9XG5cbiAgICBsZXQgc2VsZiA9IHRoaXM7XG5cbiAgICBmdW5jdGlvbiBkb25lKHZhbHVlKSB7XG4gICAgICB2YWx1ZSA9IHNlbGYucG9zdFByb2Nlc3ModmFsdWUsIG9wdGlvbnMpO1xuICAgICAgaWYgKGNhbGxiYWNrKSB7XG4gICAgICAgIHNldFRpbWVvdXQoZnVuY3Rpb24oKSB7IGNhbGxiYWNrKHZhbHVlKTsgfSwgMCk7XG4gICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgcmV0dXJuIHZhbHVlO1xuICAgICAgfVxuICAgIH1cblxuICAgIC8vIEFsbG93IHN1YmNsYXNzZXMgdG8gbWFzc2FnZSB0aGUgaW5wdXQgcHJpb3IgdG8gcnVubmluZ1xuICAgIG9sZFN0cmluZyA9IHRoaXMuY2FzdElucHV0KG9sZFN0cmluZywgb3B0aW9ucyk7XG4gICAgbmV3U3RyaW5nID0gdGhpcy5jYXN0SW5wdXQobmV3U3RyaW5nLCBvcHRpb25zKTtcblxuICAgIG9sZFN0cmluZyA9IHRoaXMucmVtb3ZlRW1wdHkodGhpcy50b2tlbml6ZShvbGRTdHJpbmcsIG9wdGlvbnMpKTtcbiAgICBuZXdTdHJpbmcgPSB0aGlzLnJlbW92ZUVtcHR5KHRoaXMudG9rZW5pemUobmV3U3RyaW5nLCBvcHRpb25zKSk7XG5cbiAgICBsZXQgbmV3TGVuID0gbmV3U3RyaW5nLmxlbmd0aCwgb2xkTGVuID0gb2xkU3RyaW5nLmxlbmd0aDtcbiAgICBsZXQgZWRpdExlbmd0aCA9IDE7XG4gICAgbGV0IG1heEVkaXRMZW5ndGggPSBuZXdMZW4gKyBvbGRMZW47XG4gICAgaWYob3B0aW9ucy5tYXhFZGl0TGVuZ3RoICE9IG51bGwpIHtcbiAgICAgIG1heEVkaXRMZW5ndGggPSBNYXRoLm1pbihtYXhFZGl0TGVuZ3RoLCBvcHRpb25zLm1heEVkaXRMZW5ndGgpO1xuICAgIH1cbiAgICBjb25zdCBtYXhFeGVjdXRpb25UaW1lID0gb3B0aW9ucy50aW1lb3V0ID8/IEluZmluaXR5O1xuICAgIGNvbnN0IGFib3J0QWZ0ZXJUaW1lc3RhbXAgPSBEYXRlLm5vdygpICsgbWF4RXhlY3V0aW9uVGltZTtcblxuICAgIGxldCBiZXN0UGF0aCA9IFt7IG9sZFBvczogLTEsIGxhc3RDb21wb25lbnQ6IHVuZGVmaW5lZCB9XTtcblxuICAgIC8vIFNlZWQgZWRpdExlbmd0aCA9IDAsIGkuZS4gdGhlIGNvbnRlbnQgc3RhcnRzIHdpdGggdGhlIHNhbWUgdmFsdWVzXG4gICAgbGV0IG5ld1BvcyA9IHRoaXMuZXh0cmFjdENvbW1vbihiZXN0UGF0aFswXSwgbmV3U3RyaW5nLCBvbGRTdHJpbmcsIDAsIG9wdGlvbnMpO1xuICAgIGlmIChiZXN0UGF0aFswXS5vbGRQb3MgKyAxID49IG9sZExlbiAmJiBuZXdQb3MgKyAxID49IG5ld0xlbikge1xuICAgICAgLy8gSWRlbnRpdHkgcGVyIHRoZSBlcXVhbGl0eSBhbmQgdG9rZW5pemVyXG4gICAgICByZXR1cm4gZG9uZShidWlsZFZhbHVlcyhzZWxmLCBiZXN0UGF0aFswXS5sYXN0Q29tcG9uZW50LCBuZXdTdHJpbmcsIG9sZFN0cmluZywgc2VsZi51c2VMb25nZXN0VG9rZW4pKTtcbiAgICB9XG5cbiAgICAvLyBPbmNlIHdlIGhpdCB0aGUgcmlnaHQgZWRnZSBvZiB0aGUgZWRpdCBncmFwaCBvbiBzb21lIGRpYWdvbmFsIGssIHdlIGNhblxuICAgIC8vIGRlZmluaXRlbHkgcmVhY2ggdGhlIGVuZCBvZiB0aGUgZWRpdCBncmFwaCBpbiBubyBtb3JlIHRoYW4gayBlZGl0cywgc29cbiAgICAvLyB0aGVyZSdzIG5vIHBvaW50IGluIGNvbnNpZGVyaW5nIGFueSBtb3ZlcyB0byBkaWFnb25hbCBrKzEgYW55IG1vcmUgKGZyb21cbiAgICAvLyB3aGljaCB3ZSdyZSBndWFyYW50ZWVkIHRvIG5lZWQgYXQgbGVhc3QgaysxIG1vcmUgZWRpdHMpLlxuICAgIC8vIFNpbWlsYXJseSwgb25jZSB3ZSd2ZSByZWFjaGVkIHRoZSBib3R0b20gb2YgdGhlIGVkaXQgZ3JhcGgsIHRoZXJlJ3Mgbm9cbiAgICAvLyBwb2ludCBjb25zaWRlcmluZyBtb3ZlcyB0byBsb3dlciBkaWFnb25hbHMuXG4gICAgLy8gV2UgcmVjb3JkIHRoaXMgZmFjdCBieSBzZXR0aW5nIG1pbkRpYWdvbmFsVG9Db25zaWRlciBhbmRcbiAgICAvLyBtYXhEaWFnb25hbFRvQ29uc2lkZXIgdG8gc29tZSBmaW5pdGUgdmFsdWUgb25jZSB3ZSd2ZSBoaXQgdGhlIGVkZ2Ugb2ZcbiAgICAvLyB0aGUgZWRpdCBncmFwaC5cbiAgICAvLyBUaGlzIG9wdGltaXphdGlvbiBpcyBub3QgZmFpdGhmdWwgdG8gdGhlIG9yaWdpbmFsIGFsZ29yaXRobSBwcmVzZW50ZWQgaW5cbiAgICAvLyBNeWVycydzIHBhcGVyLCB3aGljaCBpbnN0ZWFkIHBvaW50bGVzc2x5IGV4dGVuZHMgRC1wYXRocyBvZmYgdGhlIGVuZCBvZlxuICAgIC8vIHRoZSBlZGl0IGdyYXBoIC0gc2VlIHBhZ2UgNyBvZiBNeWVycydzIHBhcGVyIHdoaWNoIG5vdGVzIHRoaXMgcG9pbnRcbiAgICAvLyBleHBsaWNpdGx5IGFuZCBpbGx1c3RyYXRlcyBpdCB3aXRoIGEgZGlhZ3JhbS4gVGhpcyBoYXMgbWFqb3IgcGVyZm9ybWFuY2VcbiAgICAvLyBpbXBsaWNhdGlvbnMgZm9yIHNvbWUgY29tbW9uIHNjZW5hcmlvcy4gRm9yIGluc3RhbmNlLCB0byBjb21wdXRlIGEgZGlmZlxuICAgIC8vIHdoZXJlIHRoZSBuZXcgdGV4dCBzaW1wbHkgYXBwZW5kcyBkIGNoYXJhY3RlcnMgb24gdGhlIGVuZCBvZiB0aGVcbiAgICAvLyBvcmlnaW5hbCB0ZXh0IG9mIGxlbmd0aCBuLCB0aGUgdHJ1ZSBNeWVycyBhbGdvcml0aG0gd2lsbCB0YWtlIE8obitkXjIpXG4gICAgLy8gdGltZSB3aGlsZSB0aGlzIG9wdGltaXphdGlvbiBuZWVkcyBvbmx5IE8obitkKSB0aW1lLlxuICAgIGxldCBtaW5EaWFnb25hbFRvQ29uc2lkZXIgPSAtSW5maW5pdHksIG1heERpYWdvbmFsVG9Db25zaWRlciA9IEluZmluaXR5O1xuXG4gICAgLy8gTWFpbiB3b3JrZXIgbWV0aG9kLiBjaGVja3MgYWxsIHBlcm11dGF0aW9ucyBvZiBhIGdpdmVuIGVkaXQgbGVuZ3RoIGZvciBhY2NlcHRhbmNlLlxuICAgIGZ1bmN0aW9uIGV4ZWNFZGl0TGVuZ3RoKCkge1xuICAgICAgZm9yIChcbiAgICAgICAgbGV0IGRpYWdvbmFsUGF0aCA9IE1hdGgubWF4KG1pbkRpYWdvbmFsVG9Db25zaWRlciwgLWVkaXRMZW5ndGgpO1xuICAgICAgICBkaWFnb25hbFBhdGggPD0gTWF0aC5taW4obWF4RGlhZ29uYWxUb0NvbnNpZGVyLCBlZGl0TGVuZ3RoKTtcbiAgICAgICAgZGlhZ29uYWxQYXRoICs9IDJcbiAgICAgICkge1xuICAgICAgICBsZXQgYmFzZVBhdGg7XG4gICAgICAgIGxldCByZW1vdmVQYXRoID0gYmVzdFBhdGhbZGlhZ29uYWxQYXRoIC0gMV0sXG4gICAgICAgICAgICBhZGRQYXRoID0gYmVzdFBhdGhbZGlhZ29uYWxQYXRoICsgMV07XG4gICAgICAgIGlmIChyZW1vdmVQYXRoKSB7XG4gICAgICAgICAgLy8gTm8gb25lIGVsc2UgaXMgZ29pbmcgdG8gYXR0ZW1wdCB0byB1c2UgdGhpcyB2YWx1ZSwgY2xlYXIgaXRcbiAgICAgICAgICBiZXN0UGF0aFtkaWFnb25hbFBhdGggLSAxXSA9IHVuZGVmaW5lZDtcbiAgICAgICAgfVxuXG4gICAgICAgIGxldCBjYW5BZGQgPSBmYWxzZTtcbiAgICAgICAgaWYgKGFkZFBhdGgpIHtcbiAgICAgICAgICAvLyB3aGF0IG5ld1BvcyB3aWxsIGJlIGFmdGVyIHdlIGRvIGFuIGluc2VydGlvbjpcbiAgICAgICAgICBjb25zdCBhZGRQYXRoTmV3UG9zID0gYWRkUGF0aC5vbGRQb3MgLSBkaWFnb25hbFBhdGg7XG4gICAgICAgICAgY2FuQWRkID0gYWRkUGF0aCAmJiAwIDw9IGFkZFBhdGhOZXdQb3MgJiYgYWRkUGF0aE5ld1BvcyA8IG5ld0xlbjtcbiAgICAgICAgfVxuXG4gICAgICAgIGxldCBjYW5SZW1vdmUgPSByZW1vdmVQYXRoICYmIHJlbW92ZVBhdGgub2xkUG9zICsgMSA8IG9sZExlbjtcbiAgICAgICAgaWYgKCFjYW5BZGQgJiYgIWNhblJlbW92ZSkge1xuICAgICAgICAgIC8vIElmIHRoaXMgcGF0aCBpcyBhIHRlcm1pbmFsIHRoZW4gcHJ1bmVcbiAgICAgICAgICBiZXN0UGF0aFtkaWFnb25hbFBhdGhdID0gdW5kZWZpbmVkO1xuICAgICAgICAgIGNvbnRpbnVlO1xuICAgICAgICB9XG5cbiAgICAgICAgLy8gU2VsZWN0IHRoZSBkaWFnb25hbCB0aGF0IHdlIHdhbnQgdG8gYnJhbmNoIGZyb20uIFdlIHNlbGVjdCB0aGUgcHJpb3JcbiAgICAgICAgLy8gcGF0aCB3aG9zZSBwb3NpdGlvbiBpbiB0aGUgb2xkIHN0cmluZyBpcyB0aGUgZmFydGhlc3QgZnJvbSB0aGUgb3JpZ2luXG4gICAgICAgIC8vIGFuZCBkb2VzIG5vdCBwYXNzIHRoZSBib3VuZHMgb2YgdGhlIGRpZmYgZ3JhcGhcbiAgICAgICAgaWYgKCFjYW5SZW1vdmUgfHwgKGNhbkFkZCAmJiByZW1vdmVQYXRoLm9sZFBvcyA8IGFkZFBhdGgub2xkUG9zKSkge1xuICAgICAgICAgIGJhc2VQYXRoID0gc2VsZi5hZGRUb1BhdGgoYWRkUGF0aCwgdHJ1ZSwgZmFsc2UsIDAsIG9wdGlvbnMpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIGJhc2VQYXRoID0gc2VsZi5hZGRUb1BhdGgocmVtb3ZlUGF0aCwgZmFsc2UsIHRydWUsIDEsIG9wdGlvbnMpO1xuICAgICAgICB9XG5cbiAgICAgICAgbmV3UG9zID0gc2VsZi5leHRyYWN0Q29tbW9uKGJhc2VQYXRoLCBuZXdTdHJpbmcsIG9sZFN0cmluZywgZGlhZ29uYWxQYXRoLCBvcHRpb25zKTtcblxuICAgICAgICBpZiAoYmFzZVBhdGgub2xkUG9zICsgMSA+PSBvbGRMZW4gJiYgbmV3UG9zICsgMSA+PSBuZXdMZW4pIHtcbiAgICAgICAgICAvLyBJZiB3ZSBoYXZlIGhpdCB0aGUgZW5kIG9mIGJvdGggc3RyaW5ncywgdGhlbiB3ZSBhcmUgZG9uZVxuICAgICAgICAgIHJldHVybiBkb25lKGJ1aWxkVmFsdWVzKHNlbGYsIGJhc2VQYXRoLmxhc3RDb21wb25lbnQsIG5ld1N0cmluZywgb2xkU3RyaW5nLCBzZWxmLnVzZUxvbmdlc3RUb2tlbikpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIGJlc3RQYXRoW2RpYWdvbmFsUGF0aF0gPSBiYXNlUGF0aDtcbiAgICAgICAgICBpZiAoYmFzZVBhdGgub2xkUG9zICsgMSA+PSBvbGRMZW4pIHtcbiAgICAgICAgICAgIG1heERpYWdvbmFsVG9Db25zaWRlciA9IE1hdGgubWluKG1heERpYWdvbmFsVG9Db25zaWRlciwgZGlhZ29uYWxQYXRoIC0gMSk7XG4gICAgICAgICAgfVxuICAgICAgICAgIGlmIChuZXdQb3MgKyAxID49IG5ld0xlbikge1xuICAgICAgICAgICAgbWluRGlhZ29uYWxUb0NvbnNpZGVyID0gTWF0aC5tYXgobWluRGlhZ29uYWxUb0NvbnNpZGVyLCBkaWFnb25hbFBhdGggKyAxKTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgZWRpdExlbmd0aCsrO1xuICAgIH1cblxuICAgIC8vIFBlcmZvcm1zIHRoZSBsZW5ndGggb2YgZWRpdCBpdGVyYXRpb24uIElzIGEgYml0IGZ1Z2x5IGFzIHRoaXMgaGFzIHRvIHN1cHBvcnQgdGhlXG4gICAgLy8gc3luYyBhbmQgYXN5bmMgbW9kZSB3aGljaCBpcyBuZXZlciBmdW4uIExvb3BzIG92ZXIgZXhlY0VkaXRMZW5ndGggdW50aWwgYSB2YWx1ZVxuICAgIC8vIGlzIHByb2R1Y2VkLCBvciB1bnRpbCB0aGUgZWRpdCBsZW5ndGggZXhjZWVkcyBvcHRpb25zLm1heEVkaXRMZW5ndGggKGlmIGdpdmVuKSxcbiAgICAvLyBpbiB3aGljaCBjYXNlIGl0IHdpbGwgcmV0dXJuIHVuZGVmaW5lZC5cbiAgICBpZiAoY2FsbGJhY2spIHtcbiAgICAgIChmdW5jdGlvbiBleGVjKCkge1xuICAgICAgICBzZXRUaW1lb3V0KGZ1bmN0aW9uKCkge1xuICAgICAgICAgIGlmIChlZGl0TGVuZ3RoID4gbWF4RWRpdExlbmd0aCB8fCBEYXRlLm5vdygpID4gYWJvcnRBZnRlclRpbWVzdGFtcCkge1xuICAgICAgICAgICAgcmV0dXJuIGNhbGxiYWNrKCk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKCFleGVjRWRpdExlbmd0aCgpKSB7XG4gICAgICAgICAgICBleGVjKCk7XG4gICAgICAgICAgfVxuICAgICAgICB9LCAwKTtcbiAgICAgIH0oKSk7XG4gICAgfSBlbHNlIHtcbiAgICAgIHdoaWxlIChlZGl0TGVuZ3RoIDw9IG1heEVkaXRMZW5ndGggJiYgRGF0ZS5ub3coKSA8PSBhYm9ydEFmdGVyVGltZXN0YW1wKSB7XG4gICAgICAgIGxldCByZXQgPSBleGVjRWRpdExlbmd0aCgpO1xuICAgICAgICBpZiAocmV0KSB7XG4gICAgICAgICAgcmV0dXJuIHJldDtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cbiAgfSxcblxuICBhZGRUb1BhdGgocGF0aCwgYWRkZWQsIHJlbW92ZWQsIG9sZFBvc0luYywgb3B0aW9ucykge1xuICAgIGxldCBsYXN0ID0gcGF0aC5sYXN0Q29tcG9uZW50O1xuICAgIGlmIChsYXN0ICYmICFvcHRpb25zLm9uZUNoYW5nZVBlclRva2VuICYmIGxhc3QuYWRkZWQgPT09IGFkZGVkICYmIGxhc3QucmVtb3ZlZCA9PT0gcmVtb3ZlZCkge1xuICAgICAgcmV0dXJuIHtcbiAgICAgICAgb2xkUG9zOiBwYXRoLm9sZFBvcyArIG9sZFBvc0luYyxcbiAgICAgICAgbGFzdENvbXBvbmVudDoge2NvdW50OiBsYXN0LmNvdW50ICsgMSwgYWRkZWQ6IGFkZGVkLCByZW1vdmVkOiByZW1vdmVkLCBwcmV2aW91c0NvbXBvbmVudDogbGFzdC5wcmV2aW91c0NvbXBvbmVudCB9XG4gICAgICB9O1xuICAgIH0gZWxzZSB7XG4gICAgICByZXR1cm4ge1xuICAgICAgICBvbGRQb3M6IHBhdGgub2xkUG9zICsgb2xkUG9zSW5jLFxuICAgICAgICBsYXN0Q29tcG9uZW50OiB7Y291bnQ6IDEsIGFkZGVkOiBhZGRlZCwgcmVtb3ZlZDogcmVtb3ZlZCwgcHJldmlvdXNDb21wb25lbnQ6IGxhc3QgfVxuICAgICAgfTtcbiAgICB9XG4gIH0sXG4gIGV4dHJhY3RDb21tb24oYmFzZVBhdGgsIG5ld1N0cmluZywgb2xkU3RyaW5nLCBkaWFnb25hbFBhdGgsIG9wdGlvbnMpIHtcbiAgICBsZXQgbmV3TGVuID0gbmV3U3RyaW5nLmxlbmd0aCxcbiAgICAgICAgb2xkTGVuID0gb2xkU3RyaW5nLmxlbmd0aCxcbiAgICAgICAgb2xkUG9zID0gYmFzZVBhdGgub2xkUG9zLFxuICAgICAgICBuZXdQb3MgPSBvbGRQb3MgLSBkaWFnb25hbFBhdGgsXG5cbiAgICAgICAgY29tbW9uQ291bnQgPSAwO1xuICAgIHdoaWxlIChuZXdQb3MgKyAxIDwgbmV3TGVuICYmIG9sZFBvcyArIDEgPCBvbGRMZW4gJiYgdGhpcy5lcXVhbHMob2xkU3RyaW5nW29sZFBvcyArIDFdLCBuZXdTdHJpbmdbbmV3UG9zICsgMV0sIG9wdGlvbnMpKSB7XG4gICAgICBuZXdQb3MrKztcbiAgICAgIG9sZFBvcysrO1xuICAgICAgY29tbW9uQ291bnQrKztcbiAgICAgIGlmIChvcHRpb25zLm9uZUNoYW5nZVBlclRva2VuKSB7XG4gICAgICAgIGJhc2VQYXRoLmxhc3RDb21wb25lbnQgPSB7Y291bnQ6IDEsIHByZXZpb3VzQ29tcG9uZW50OiBiYXNlUGF0aC5sYXN0Q29tcG9uZW50LCBhZGRlZDogZmFsc2UsIHJlbW92ZWQ6IGZhbHNlfTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICBpZiAoY29tbW9uQ291bnQgJiYgIW9wdGlvbnMub25lQ2hhbmdlUGVyVG9rZW4pIHtcbiAgICAgIGJhc2VQYXRoLmxhc3RDb21wb25lbnQgPSB7Y291bnQ6IGNvbW1vbkNvdW50LCBwcmV2aW91c0NvbXBvbmVudDogYmFzZVBhdGgubGFzdENvbXBvbmVudCwgYWRkZWQ6IGZhbHNlLCByZW1vdmVkOiBmYWxzZX07XG4gICAgfVxuXG4gICAgYmFzZVBhdGgub2xkUG9zID0gb2xkUG9zO1xuICAgIHJldHVybiBuZXdQb3M7XG4gIH0sXG5cbiAgZXF1YWxzKGxlZnQsIHJpZ2h0LCBvcHRpb25zKSB7XG4gICAgaWYgKG9wdGlvbnMuY29tcGFyYXRvcikge1xuICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGFyYXRvcihsZWZ0LCByaWdodCk7XG4gICAgfSBlbHNlIHtcbiAgICAgIHJldHVybiBsZWZ0ID09PSByaWdodFxuICAgICAgICB8fCAob3B0aW9ucy5pZ25vcmVDYXNlICYmIGxlZnQudG9Mb3dlckNhc2UoKSA9PT0gcmlnaHQudG9Mb3dlckNhc2UoKSk7XG4gICAgfVxuICB9LFxuICByZW1vdmVFbXB0eShhcnJheSkge1xuICAgIGxldCByZXQgPSBbXTtcbiAgICBmb3IgKGxldCBpID0gMDsgaSA8IGFycmF5Lmxlbmd0aDsgaSsrKSB7XG4gICAgICBpZiAoYXJyYXlbaV0pIHtcbiAgICAgICAgcmV0LnB1c2goYXJyYXlbaV0pO1xuICAgICAgfVxuICAgIH1cbiAgICByZXR1cm4gcmV0O1xuICB9LFxuICBjYXN0SW5wdXQodmFsdWUpIHtcbiAgICByZXR1cm4gdmFsdWU7XG4gIH0sXG4gIHRva2VuaXplKHZhbHVlKSB7XG4gICAgcmV0dXJuIEFycmF5LmZyb20odmFsdWUpO1xuICB9LFxuICBqb2luKGNoYXJzKSB7XG4gICAgcmV0dXJuIGNoYXJzLmpvaW4oJycpO1xuICB9LFxuICBwb3N0UHJvY2VzcyhjaGFuZ2VPYmplY3RzKSB7XG4gICAgcmV0dXJuIGNoYW5nZU9iamVjdHM7XG4gIH1cbn07XG5cbmZ1bmN0aW9uIGJ1aWxkVmFsdWVzKGRpZmYsIGxhc3RDb21wb25lbnQsIG5ld1N0cmluZywgb2xkU3RyaW5nLCB1c2VMb25nZXN0VG9rZW4pIHtcbiAgLy8gRmlyc3Qgd2UgY29udmVydCBvdXIgbGlua2VkIGxpc3Qgb2YgY29tcG9uZW50cyBpbiByZXZlcnNlIG9yZGVyIHRvIGFuXG4gIC8vIGFycmF5IGluIHRoZSByaWdodCBvcmRlcjpcbiAgY29uc3QgY29tcG9uZW50cyA9IFtdO1xuICBsZXQgbmV4dENvbXBvbmVudDtcbiAgd2hpbGUgKGxhc3RDb21wb25lbnQpIHtcbiAgICBjb21wb25lbnRzLnB1c2gobGFzdENvbXBvbmVudCk7XG4gICAgbmV4dENvbXBvbmVudCA9IGxhc3RDb21wb25lbnQucHJldmlvdXNDb21wb25lbnQ7XG4gICAgZGVsZXRlIGxhc3RDb21wb25lbnQucHJldmlvdXNDb21wb25lbnQ7XG4gICAgbGFzdENvbXBvbmVudCA9IG5leHRDb21wb25lbnQ7XG4gIH1cbiAgY29tcG9uZW50cy5yZXZlcnNlKCk7XG5cbiAgbGV0IGNvbXBvbmVudFBvcyA9IDAsXG4gICAgICBjb21wb25lbnRMZW4gPSBjb21wb25lbnRzLmxlbmd0aCxcbiAgICAgIG5ld1BvcyA9IDAsXG4gICAgICBvbGRQb3MgPSAwO1xuXG4gIGZvciAoOyBjb21wb25lbnRQb3MgPCBjb21wb25lbnRMZW47IGNvbXBvbmVudFBvcysrKSB7XG4gICAgbGV0IGNvbXBvbmVudCA9IGNvbXBvbmVudHNbY29tcG9uZW50UG9zXTtcbiAgICBpZiAoIWNvbXBvbmVudC5yZW1vdmVkKSB7XG4gICAgICBpZiAoIWNvbXBvbmVudC5hZGRlZCAmJiB1c2VMb25nZXN0VG9rZW4pIHtcbiAgICAgICAgbGV0IHZhbHVlID0gbmV3U3RyaW5nLnNsaWNlKG5ld1BvcywgbmV3UG9zICsgY29tcG9uZW50LmNvdW50KTtcbiAgICAgICAgdmFsdWUgPSB2YWx1ZS5tYXAoZnVuY3Rpb24odmFsdWUsIGkpIHtcbiAgICAgICAgICBsZXQgb2xkVmFsdWUgPSBvbGRTdHJpbmdbb2xkUG9zICsgaV07XG4gICAgICAgICAgcmV0dXJuIG9sZFZhbHVlLmxlbmd0aCA+IHZhbHVlLmxlbmd0aCA/IG9sZFZhbHVlIDogdmFsdWU7XG4gICAgICAgIH0pO1xuXG4gICAgICAgIGNvbXBvbmVudC52YWx1ZSA9IGRpZmYuam9pbih2YWx1ZSk7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBjb21wb25lbnQudmFsdWUgPSBkaWZmLmpvaW4obmV3U3RyaW5nLnNsaWNlKG5ld1BvcywgbmV3UG9zICsgY29tcG9uZW50LmNvdW50KSk7XG4gICAgICB9XG4gICAgICBuZXdQb3MgKz0gY29tcG9uZW50LmNvdW50O1xuXG4gICAgICAvLyBDb21tb24gY2FzZVxuICAgICAgaWYgKCFjb21wb25lbnQuYWRkZWQpIHtcbiAgICAgICAgb2xkUG9zICs9IGNvbXBvbmVudC5jb3VudDtcbiAgICAgIH1cbiAgICB9IGVsc2Uge1xuICAgICAgY29tcG9uZW50LnZhbHVlID0gZGlmZi5qb2luKG9sZFN0cmluZy5zbGljZShvbGRQb3MsIG9sZFBvcyArIGNvbXBvbmVudC5jb3VudCkpO1xuICAgICAgb2xkUG9zICs9IGNvbXBvbmVudC5jb3VudDtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gY29tcG9uZW50cztcbn1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7QUFBZSxTQUFTQSxJQUFJQSxDQUFBLEVBQUcsQ0FBQztBQUVoQ0EsSUFBSSxDQUFDQyxTQUFTLEdBQUc7RUFBQTtFQUFBO0VBQ2ZDLElBQUksV0FBQUEsS0FBQ0MsU0FBUyxFQUFFQyxTQUFTLEVBQWdCO0lBQUE7SUFBQSxJQUFBQyxnQkFBQTtJQUFBO0lBQUE7SUFBZEMsT0FBTyxHQUFBQyxTQUFBLENBQUFDLE1BQUEsUUFBQUQsU0FBQSxRQUFBRSxTQUFBLEdBQUFGLFNBQUEsTUFBRyxDQUFDLENBQUM7SUFDckMsSUFBSUcsUUFBUSxHQUFHSixPQUFPLENBQUNJLFFBQVE7SUFDL0IsSUFBSSxPQUFPSixPQUFPLEtBQUssVUFBVSxFQUFFO01BQ2pDSSxRQUFRLEdBQUdKLE9BQU87TUFDbEJBLE9BQU8sR0FBRyxDQUFDLENBQUM7SUFDZDtJQUVBLElBQUlLLElBQUksR0FBRyxJQUFJO0lBRWYsU0FBU0MsSUFBSUEsQ0FBQ0MsS0FBSyxFQUFFO01BQ25CQSxLQUFLLEdBQUdGLElBQUksQ0FBQ0csV0FBVyxDQUFDRCxLQUFLLEVBQUVQLE9BQU8sQ0FBQztNQUN4QyxJQUFJSSxRQUFRLEVBQUU7UUFDWkssVUFBVSxDQUFDLFlBQVc7VUFBRUwsUUFBUSxDQUFDRyxLQUFLLENBQUM7UUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQzlDLE9BQU8sSUFBSTtNQUNiLENBQUMsTUFBTTtRQUNMLE9BQU9BLEtBQUs7TUFDZDtJQUNGOztJQUVBO0lBQ0FWLFNBQVMsR0FBRyxJQUFJLENBQUNhLFNBQVMsQ0FBQ2IsU0FBUyxFQUFFRyxPQUFPLENBQUM7SUFDOUNGLFNBQVMsR0FBRyxJQUFJLENBQUNZLFNBQVMsQ0FBQ1osU0FBUyxFQUFFRSxPQUFPLENBQUM7SUFFOUNILFNBQVMsR0FBRyxJQUFJLENBQUNjLFdBQVcsQ0FBQyxJQUFJLENBQUNDLFFBQVEsQ0FBQ2YsU0FBUyxFQUFFRyxPQUFPLENBQUMsQ0FBQztJQUMvREYsU0FBUyxHQUFHLElBQUksQ0FBQ2EsV0FBVyxDQUFDLElBQUksQ0FBQ0MsUUFBUSxDQUFDZCxTQUFTLEVBQUVFLE9BQU8sQ0FBQyxDQUFDO0lBRS9ELElBQUlhLE1BQU0sR0FBR2YsU0FBUyxDQUFDSSxNQUFNO01BQUVZLE1BQU0sR0FBR2pCLFNBQVMsQ0FBQ0ssTUFBTTtJQUN4RCxJQUFJYSxVQUFVLEdBQUcsQ0FBQztJQUNsQixJQUFJQyxhQUFhLEdBQUdILE1BQU0sR0FBR0MsTUFBTTtJQUNuQyxJQUFHZCxPQUFPLENBQUNnQixhQUFhLElBQUksSUFBSSxFQUFFO01BQ2hDQSxhQUFhLEdBQUdDLElBQUksQ0FBQ0MsR0FBRyxDQUFDRixhQUFhLEVBQUVoQixPQUFPLENBQUNnQixhQUFhLENBQUM7SUFDaEU7SUFDQSxJQUFNRyxnQkFBZ0I7SUFBQTtJQUFBLENBQUFwQixnQkFBQTtJQUFBO0lBQUdDLE9BQU8sQ0FBQ29CLE9BQU8sY0FBQXJCLGdCQUFBLGNBQUFBLGdCQUFBLEdBQUlzQixRQUFRO0lBQ3BELElBQU1DLG1CQUFtQixHQUFHQyxJQUFJLENBQUNDLEdBQUcsQ0FBQyxDQUFDLEdBQUdMLGdCQUFnQjtJQUV6RCxJQUFJTSxRQUFRLEdBQUcsQ0FBQztNQUFFQyxNQUFNLEVBQUUsQ0FBQyxDQUFDO01BQUVDLGFBQWEsRUFBRXhCO0lBQVUsQ0FBQyxDQUFDOztJQUV6RDtJQUNBLElBQUl5QixNQUFNLEdBQUcsSUFBSSxDQUFDQyxhQUFhLENBQUNKLFFBQVEsQ0FBQyxDQUFDLENBQUMsRUFBRTNCLFNBQVMsRUFBRUQsU0FBUyxFQUFFLENBQUMsRUFBRUcsT0FBTyxDQUFDO0lBQzlFLElBQUl5QixRQUFRLENBQUMsQ0FBQyxDQUFDLENBQUNDLE1BQU0sR0FBRyxDQUFDLElBQUlaLE1BQU0sSUFBSWMsTUFBTSxHQUFHLENBQUMsSUFBSWYsTUFBTSxFQUFFO01BQzVEO01BQ0EsT0FBT1AsSUFBSSxDQUFDd0IsV0FBVyxDQUFDekIsSUFBSSxFQUFFb0IsUUFBUSxDQUFDLENBQUMsQ0FBQyxDQUFDRSxhQUFhLEVBQUU3QixTQUFTLEVBQUVELFNBQVMsRUFBRVEsSUFBSSxDQUFDMEIsZUFBZSxDQUFDLENBQUM7SUFDdkc7O0lBRUE7SUFDQTtJQUNBO0lBQ0E7SUFDQTtJQUNBO0lBQ0E7SUFDQTtJQUNBO0lBQ0E7SUFDQTtJQUNBO0lBQ0E7SUFDQTtJQUNBO0lBQ0E7SUFDQTtJQUNBLElBQUlDLHFCQUFxQixHQUFHLENBQUNYLFFBQVE7TUFBRVkscUJBQXFCLEdBQUdaLFFBQVE7O0lBRXZFO0lBQ0EsU0FBU2EsY0FBY0EsQ0FBQSxFQUFHO01BQ3hCLEtBQ0UsSUFBSUMsWUFBWSxHQUFHbEIsSUFBSSxDQUFDbUIsR0FBRyxDQUFDSixxQkFBcUIsRUFBRSxDQUFDakIsVUFBVSxDQUFDLEVBQy9Eb0IsWUFBWSxJQUFJbEIsSUFBSSxDQUFDQyxHQUFHLENBQUNlLHFCQUFxQixFQUFFbEIsVUFBVSxDQUFDLEVBQzNEb0IsWUFBWSxJQUFJLENBQUMsRUFDakI7UUFDQSxJQUFJRSxRQUFRO1FBQUE7UUFBQTtRQUFBO1FBQUE7UUFDWixJQUFJQyxVQUFVLEdBQUdiLFFBQVEsQ0FBQ1UsWUFBWSxHQUFHLENBQUMsQ0FBQztVQUN2Q0ksT0FBTyxHQUFHZCxRQUFRLENBQUNVLFlBQVksR0FBRyxDQUFDLENBQUM7UUFDeEMsSUFBSUcsVUFBVSxFQUFFO1VBQ2Q7VUFDQWIsUUFBUSxDQUFDVSxZQUFZLEdBQUcsQ0FBQyxDQUFDLEdBQUdoQyxTQUFTO1FBQ3hDO1FBRUEsSUFBSXFDLE1BQU0sR0FBRyxLQUFLO1FBQ2xCLElBQUlELE9BQU8sRUFBRTtVQUNYO1VBQ0EsSUFBTUUsYUFBYSxHQUFHRixPQUFPLENBQUNiLE1BQU0sR0FBR1MsWUFBWTtVQUNuREssTUFBTSxHQUFHRCxPQUFPLElBQUksQ0FBQyxJQUFJRSxhQUFhLElBQUlBLGFBQWEsR0FBRzVCLE1BQU07UUFDbEU7UUFFQSxJQUFJNkIsU0FBUyxHQUFHSixVQUFVLElBQUlBLFVBQVUsQ0FBQ1osTUFBTSxHQUFHLENBQUMsR0FBR1osTUFBTTtRQUM1RCxJQUFJLENBQUMwQixNQUFNLElBQUksQ0FBQ0UsU0FBUyxFQUFFO1VBQ3pCO1VBQ0FqQixRQUFRLENBQUNVLFlBQVksQ0FBQyxHQUFHaEMsU0FBUztVQUNsQztRQUNGOztRQUVBO1FBQ0E7UUFDQTtRQUNBLElBQUksQ0FBQ3VDLFNBQVMsSUFBS0YsTUFBTSxJQUFJRixVQUFVLENBQUNaLE1BQU0sR0FBR2EsT0FBTyxDQUFDYixNQUFPLEVBQUU7VUFDaEVXLFFBQVEsR0FBR2hDLElBQUksQ0FBQ3NDLFNBQVMsQ0FBQ0osT0FBTyxFQUFFLElBQUksRUFBRSxLQUFLLEVBQUUsQ0FBQyxFQUFFdkMsT0FBTyxDQUFDO1FBQzdELENBQUMsTUFBTTtVQUNMcUMsUUFBUSxHQUFHaEMsSUFBSSxDQUFDc0MsU0FBUyxDQUFDTCxVQUFVLEVBQUUsS0FBSyxFQUFFLElBQUksRUFBRSxDQUFDLEVBQUV0QyxPQUFPLENBQUM7UUFDaEU7UUFFQTRCLE1BQU0sR0FBR3ZCLElBQUksQ0FBQ3dCLGFBQWEsQ0FBQ1EsUUFBUSxFQUFFdkMsU0FBUyxFQUFFRCxTQUFTLEVBQUVzQyxZQUFZLEVBQUVuQyxPQUFPLENBQUM7UUFFbEYsSUFBSXFDLFFBQVEsQ0FBQ1gsTUFBTSxHQUFHLENBQUMsSUFBSVosTUFBTSxJQUFJYyxNQUFNLEdBQUcsQ0FBQyxJQUFJZixNQUFNLEVBQUU7VUFDekQ7VUFDQSxPQUFPUCxJQUFJLENBQUN3QixXQUFXLENBQUN6QixJQUFJLEVBQUVnQyxRQUFRLENBQUNWLGFBQWEsRUFBRTdCLFNBQVMsRUFBRUQsU0FBUyxFQUFFUSxJQUFJLENBQUMwQixlQUFlLENBQUMsQ0FBQztRQUNwRyxDQUFDLE1BQU07VUFDTE4sUUFBUSxDQUFDVSxZQUFZLENBQUMsR0FBR0UsUUFBUTtVQUNqQyxJQUFJQSxRQUFRLENBQUNYLE1BQU0sR0FBRyxDQUFDLElBQUlaLE1BQU0sRUFBRTtZQUNqQ21CLHFCQUFxQixHQUFHaEIsSUFBSSxDQUFDQyxHQUFHLENBQUNlLHFCQUFxQixFQUFFRSxZQUFZLEdBQUcsQ0FBQyxDQUFDO1VBQzNFO1VBQ0EsSUFBSVAsTUFBTSxHQUFHLENBQUMsSUFBSWYsTUFBTSxFQUFFO1lBQ3hCbUIscUJBQXFCLEdBQUdmLElBQUksQ0FBQ21CLEdBQUcsQ0FBQ0oscUJBQXFCLEVBQUVHLFlBQVksR0FBRyxDQUFDLENBQUM7VUFDM0U7UUFDRjtNQUNGO01BRUFwQixVQUFVLEVBQUU7SUFDZDs7SUFFQTtJQUNBO0lBQ0E7SUFDQTtJQUNBLElBQUlYLFFBQVEsRUFBRTtNQUNYLFVBQVN3QyxJQUFJQSxDQUFBLEVBQUc7UUFDZm5DLFVBQVUsQ0FBQyxZQUFXO1VBQ3BCLElBQUlNLFVBQVUsR0FBR0MsYUFBYSxJQUFJTyxJQUFJLENBQUNDLEdBQUcsQ0FBQyxDQUFDLEdBQUdGLG1CQUFtQixFQUFFO1lBQ2xFLE9BQU9sQixRQUFRLENBQUMsQ0FBQztVQUNuQjtVQUVBLElBQUksQ0FBQzhCLGNBQWMsQ0FBQyxDQUFDLEVBQUU7WUFDckJVLElBQUksQ0FBQyxDQUFDO1VBQ1I7UUFDRixDQUFDLEVBQUUsQ0FBQyxDQUFDO01BQ1AsQ0FBQyxFQUFDLENBQUM7SUFDTCxDQUFDLE1BQU07TUFDTCxPQUFPN0IsVUFBVSxJQUFJQyxhQUFhLElBQUlPLElBQUksQ0FBQ0MsR0FBRyxDQUFDLENBQUMsSUFBSUYsbUJBQW1CLEVBQUU7UUFDdkUsSUFBSXVCLEdBQUcsR0FBR1gsY0FBYyxDQUFDLENBQUM7UUFDMUIsSUFBSVcsR0FBRyxFQUFFO1VBQ1AsT0FBT0EsR0FBRztRQUNaO01BQ0Y7SUFDRjtFQUNGLENBQUM7RUFBQTtFQUFBO0VBRURGLFNBQVMsV0FBQUEsVUFBQ0csSUFBSSxFQUFFQyxLQUFLLEVBQUVDLE9BQU8sRUFBRUMsU0FBUyxFQUFFakQsT0FBTyxFQUFFO0lBQ2xELElBQUlrRCxJQUFJLEdBQUdKLElBQUksQ0FBQ25CLGFBQWE7SUFDN0IsSUFBSXVCLElBQUksSUFBSSxDQUFDbEQsT0FBTyxDQUFDbUQsaUJBQWlCLElBQUlELElBQUksQ0FBQ0gsS0FBSyxLQUFLQSxLQUFLLElBQUlHLElBQUksQ0FBQ0YsT0FBTyxLQUFLQSxPQUFPLEVBQUU7TUFDMUYsT0FBTztRQUNMdEIsTUFBTSxFQUFFb0IsSUFBSSxDQUFDcEIsTUFBTSxHQUFHdUIsU0FBUztRQUMvQnRCLGFBQWEsRUFBRTtVQUFDeUIsS0FBSyxFQUFFRixJQUFJLENBQUNFLEtBQUssR0FBRyxDQUFDO1VBQUVMLEtBQUssRUFBRUEsS0FBSztVQUFFQyxPQUFPLEVBQUVBLE9BQU87VUFBRUssaUJBQWlCLEVBQUVILElBQUksQ0FBQ0c7UUFBa0I7TUFDbkgsQ0FBQztJQUNILENBQUMsTUFBTTtNQUNMLE9BQU87UUFDTDNCLE1BQU0sRUFBRW9CLElBQUksQ0FBQ3BCLE1BQU0sR0FBR3VCLFNBQVM7UUFDL0J0QixhQUFhLEVBQUU7VUFBQ3lCLEtBQUssRUFBRSxDQUFDO1VBQUVMLEtBQUssRUFBRUEsS0FBSztVQUFFQyxPQUFPLEVBQUVBLE9BQU87VUFBRUssaUJBQWlCLEVBQUVIO1FBQUs7TUFDcEYsQ0FBQztJQUNIO0VBQ0YsQ0FBQztFQUFBO0VBQUE7RUFDRHJCLGFBQWEsV0FBQUEsY0FBQ1EsUUFBUSxFQUFFdkMsU0FBUyxFQUFFRCxTQUFTLEVBQUVzQyxZQUFZLEVBQUVuQyxPQUFPLEVBQUU7SUFDbkUsSUFBSWEsTUFBTSxHQUFHZixTQUFTLENBQUNJLE1BQU07TUFDekJZLE1BQU0sR0FBR2pCLFNBQVMsQ0FBQ0ssTUFBTTtNQUN6QndCLE1BQU0sR0FBR1csUUFBUSxDQUFDWCxNQUFNO01BQ3hCRSxNQUFNLEdBQUdGLE1BQU0sR0FBR1MsWUFBWTtNQUU5Qm1CLFdBQVcsR0FBRyxDQUFDO0lBQ25CLE9BQU8xQixNQUFNLEdBQUcsQ0FBQyxHQUFHZixNQUFNLElBQUlhLE1BQU0sR0FBRyxDQUFDLEdBQUdaLE1BQU0sSUFBSSxJQUFJLENBQUN5QyxNQUFNLENBQUMxRCxTQUFTLENBQUM2QixNQUFNLEdBQUcsQ0FBQyxDQUFDLEVBQUU1QixTQUFTLENBQUM4QixNQUFNLEdBQUcsQ0FBQyxDQUFDLEVBQUU1QixPQUFPLENBQUMsRUFBRTtNQUN2SDRCLE1BQU0sRUFBRTtNQUNSRixNQUFNLEVBQUU7TUFDUjRCLFdBQVcsRUFBRTtNQUNiLElBQUl0RCxPQUFPLENBQUNtRCxpQkFBaUIsRUFBRTtRQUM3QmQsUUFBUSxDQUFDVixhQUFhLEdBQUc7VUFBQ3lCLEtBQUssRUFBRSxDQUFDO1VBQUVDLGlCQUFpQixFQUFFaEIsUUFBUSxDQUFDVixhQUFhO1VBQUVvQixLQUFLLEVBQUUsS0FBSztVQUFFQyxPQUFPLEVBQUU7UUFBSyxDQUFDO01BQzlHO0lBQ0Y7SUFFQSxJQUFJTSxXQUFXLElBQUksQ0FBQ3RELE9BQU8sQ0FBQ21ELGlCQUFpQixFQUFFO01BQzdDZCxRQUFRLENBQUNWLGFBQWEsR0FBRztRQUFDeUIsS0FBSyxFQUFFRSxXQUFXO1FBQUVELGlCQUFpQixFQUFFaEIsUUFBUSxDQUFDVixhQUFhO1FBQUVvQixLQUFLLEVBQUUsS0FBSztRQUFFQyxPQUFPLEVBQUU7TUFBSyxDQUFDO0lBQ3hIO0lBRUFYLFFBQVEsQ0FBQ1gsTUFBTSxHQUFHQSxNQUFNO0lBQ3hCLE9BQU9FLE1BQU07RUFDZixDQUFDO0VBQUE7RUFBQTtFQUVEMkIsTUFBTSxXQUFBQSxPQUFDQyxJQUFJLEVBQUVDLEtBQUssRUFBRXpELE9BQU8sRUFBRTtJQUMzQixJQUFJQSxPQUFPLENBQUMwRCxVQUFVLEVBQUU7TUFDdEIsT0FBTzFELE9BQU8sQ0FBQzBELFVBQVUsQ0FBQ0YsSUFBSSxFQUFFQyxLQUFLLENBQUM7SUFDeEMsQ0FBQyxNQUFNO01BQ0wsT0FBT0QsSUFBSSxLQUFLQyxLQUFLLElBQ2Z6RCxPQUFPLENBQUMyRCxVQUFVLElBQUlILElBQUksQ0FBQ0ksV0FBVyxDQUFDLENBQUMsS0FBS0gsS0FBSyxDQUFDRyxXQUFXLENBQUMsQ0FBRTtJQUN6RTtFQUNGLENBQUM7RUFBQTtFQUFBO0VBQ0RqRCxXQUFXLFdBQUFBLFlBQUNrRCxLQUFLLEVBQUU7SUFDakIsSUFBSWhCLEdBQUcsR0FBRyxFQUFFO0lBQ1osS0FBSyxJQUFJaUIsQ0FBQyxHQUFHLENBQUMsRUFBRUEsQ0FBQyxHQUFHRCxLQUFLLENBQUMzRCxNQUFNLEVBQUU0RCxDQUFDLEVBQUUsRUFBRTtNQUNyQyxJQUFJRCxLQUFLLENBQUNDLENBQUMsQ0FBQyxFQUFFO1FBQ1pqQixHQUFHLENBQUNrQixJQUFJLENBQUNGLEtBQUssQ0FBQ0MsQ0FBQyxDQUFDLENBQUM7TUFDcEI7SUFDRjtJQUNBLE9BQU9qQixHQUFHO0VBQ1osQ0FBQztFQUFBO0VBQUE7RUFDRG5DLFNBQVMsV0FBQUEsVUFBQ0gsS0FBSyxFQUFFO0lBQ2YsT0FBT0EsS0FBSztFQUNkLENBQUM7RUFBQTtFQUFBO0VBQ0RLLFFBQVEsV0FBQUEsU0FBQ0wsS0FBSyxFQUFFO0lBQ2QsT0FBT3lELEtBQUssQ0FBQ0MsSUFBSSxDQUFDMUQsS0FBSyxDQUFDO0VBQzFCLENBQUM7RUFBQTtFQUFBO0VBQ0QyRCxJQUFJLFdBQUFBLEtBQUNDLEtBQUssRUFBRTtJQUNWLE9BQU9BLEtBQUssQ0FBQ0QsSUFBSSxDQUFDLEVBQUUsQ0FBQztFQUN2QixDQUFDO0VBQUE7RUFBQTtFQUNEMUQsV0FBVyxXQUFBQSxZQUFDNEQsYUFBYSxFQUFFO0lBQ3pCLE9BQU9BLGFBQWE7RUFDdEI7QUFDRixDQUFDO0FBRUQsU0FBU3RDLFdBQVdBLENBQUNsQyxJQUFJLEVBQUUrQixhQUFhLEVBQUU3QixTQUFTLEVBQUVELFNBQVMsRUFBRWtDLGVBQWUsRUFBRTtFQUMvRTtFQUNBO0VBQ0EsSUFBTXNDLFVBQVUsR0FBRyxFQUFFO0VBQ3JCLElBQUlDLGFBQWE7RUFDakIsT0FBTzNDLGFBQWEsRUFBRTtJQUNwQjBDLFVBQVUsQ0FBQ04sSUFBSSxDQUFDcEMsYUFBYSxDQUFDO0lBQzlCMkMsYUFBYSxHQUFHM0MsYUFBYSxDQUFDMEIsaUJBQWlCO0lBQy9DLE9BQU8xQixhQUFhLENBQUMwQixpQkFBaUI7SUFDdEMxQixhQUFhLEdBQUcyQyxhQUFhO0VBQy9CO0VBQ0FELFVBQVUsQ0FBQ0UsT0FBTyxDQUFDLENBQUM7RUFFcEIsSUFBSUMsWUFBWSxHQUFHLENBQUM7SUFDaEJDLFlBQVksR0FBR0osVUFBVSxDQUFDbkUsTUFBTTtJQUNoQzBCLE1BQU0sR0FBRyxDQUFDO0lBQ1ZGLE1BQU0sR0FBRyxDQUFDO0VBRWQsT0FBTzhDLFlBQVksR0FBR0MsWUFBWSxFQUFFRCxZQUFZLEVBQUUsRUFBRTtJQUNsRCxJQUFJRSxTQUFTLEdBQUdMLFVBQVUsQ0FBQ0csWUFBWSxDQUFDO0lBQ3hDLElBQUksQ0FBQ0UsU0FBUyxDQUFDMUIsT0FBTyxFQUFFO01BQ3RCLElBQUksQ0FBQzBCLFNBQVMsQ0FBQzNCLEtBQUssSUFBSWhCLGVBQWUsRUFBRTtRQUN2QyxJQUFJeEIsS0FBSyxHQUFHVCxTQUFTLENBQUM2RSxLQUFLLENBQUMvQyxNQUFNLEVBQUVBLE1BQU0sR0FBRzhDLFNBQVMsQ0FBQ3RCLEtBQUssQ0FBQztRQUM3RDdDLEtBQUssR0FBR0EsS0FBSyxDQUFDcUUsR0FBRyxDQUFDLFVBQVNyRSxLQUFLLEVBQUV1RCxDQUFDLEVBQUU7VUFDbkMsSUFBSWUsUUFBUSxHQUFHaEYsU0FBUyxDQUFDNkIsTUFBTSxHQUFHb0MsQ0FBQyxDQUFDO1VBQ3BDLE9BQU9lLFFBQVEsQ0FBQzNFLE1BQU0sR0FBR0ssS0FBSyxDQUFDTCxNQUFNLEdBQUcyRSxRQUFRLEdBQUd0RSxLQUFLO1FBQzFELENBQUMsQ0FBQztRQUVGbUUsU0FBUyxDQUFDbkUsS0FBSyxHQUFHWCxJQUFJLENBQUNzRSxJQUFJLENBQUMzRCxLQUFLLENBQUM7TUFDcEMsQ0FBQyxNQUFNO1FBQ0xtRSxTQUFTLENBQUNuRSxLQUFLLEdBQUdYLElBQUksQ0FBQ3NFLElBQUksQ0FBQ3BFLFNBQVMsQ0FBQzZFLEtBQUssQ0FBQy9DLE1BQU0sRUFBRUEsTUFBTSxHQUFHOEMsU0FBUyxDQUFDdEIsS0FBSyxDQUFDLENBQUM7TUFDaEY7TUFDQXhCLE1BQU0sSUFBSThDLFNBQVMsQ0FBQ3RCLEtBQUs7O01BRXpCO01BQ0EsSUFBSSxDQUFDc0IsU0FBUyxDQUFDM0IsS0FBSyxFQUFFO1FBQ3BCckIsTUFBTSxJQUFJZ0QsU0FBUyxDQUFDdEIsS0FBSztNQUMzQjtJQUNGLENBQUMsTUFBTTtNQUNMc0IsU0FBUyxDQUFDbkUsS0FBSyxHQUFHWCxJQUFJLENBQUNzRSxJQUFJLENBQUNyRSxTQUFTLENBQUM4RSxLQUFLLENBQUNqRCxNQUFNLEVBQUVBLE1BQU0sR0FBR2dELFNBQVMsQ0FBQ3RCLEtBQUssQ0FBQyxDQUFDO01BQzlFMUIsTUFBTSxJQUFJZ0QsU0FBUyxDQUFDdEIsS0FBSztJQUMzQjtFQUNGO0VBRUEsT0FBT2lCLFVBQVU7QUFDbkIiLCJpZ25vcmVMaXN0IjpbXX0= /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.characterDiff = void 0; exports.diffChars = diffChars; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var characterDiff = /*istanbul ignore start*/ exports.characterDiff = /*istanbul ignore end*/ new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYmFzZSIsIl9pbnRlcm9wUmVxdWlyZURlZmF1bHQiLCJyZXF1aXJlIiwib2JqIiwiX19lc01vZHVsZSIsImNoYXJhY3RlckRpZmYiLCJleHBvcnRzIiwiRGlmZiIsImRpZmZDaGFycyIsIm9sZFN0ciIsIm5ld1N0ciIsIm9wdGlvbnMiLCJkaWZmIl0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL2RpZmYvY2hhcmFjdGVyLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cbmV4cG9ydCBjb25zdCBjaGFyYWN0ZXJEaWZmID0gbmV3IERpZmYoKTtcbmV4cG9ydCBmdW5jdGlvbiBkaWZmQ2hhcnMob2xkU3RyLCBuZXdTdHIsIG9wdGlvbnMpIHsgcmV0dXJuIGNoYXJhY3RlckRpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7IH1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBQSxLQUFBLEdBQUFDLHNCQUFBLENBQUFDLE9BQUE7QUFBQTtBQUFBO0FBQTBCLG1DQUFBRCx1QkFBQUUsR0FBQSxXQUFBQSxHQUFBLElBQUFBLEdBQUEsQ0FBQUMsVUFBQSxHQUFBRCxHQUFBLGdCQUFBQSxHQUFBO0FBQUE7QUFFbkIsSUFBTUUsYUFBYTtBQUFBO0FBQUFDLE9BQUEsQ0FBQUQsYUFBQTtBQUFBO0FBQUc7QUFBSUU7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSSxDQUFDLENBQUM7QUFDaEMsU0FBU0MsU0FBU0EsQ0FBQ0MsTUFBTSxFQUFFQyxNQUFNLEVBQUVDLE9BQU8sRUFBRTtFQUFFLE9BQU9OLGFBQWEsQ0FBQ08sSUFBSSxDQUFDSCxNQUFNLEVBQUVDLE1BQU0sRUFBRUMsT0FBTyxDQUFDO0FBQUUiLCJpZ25vcmVMaXN0IjpbXX0= /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cssDiff = void 0; exports.diffCss = diffCss; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var cssDiff = /*istanbul ignore start*/ exports.cssDiff = /*istanbul ignore end*/ new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYmFzZSIsIl9pbnRlcm9wUmVxdWlyZURlZmF1bHQiLCJyZXF1aXJlIiwib2JqIiwiX19lc01vZHVsZSIsImNzc0RpZmYiLCJleHBvcnRzIiwiRGlmZiIsInRva2VuaXplIiwidmFsdWUiLCJzcGxpdCIsImRpZmZDc3MiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwic291cmNlcyI6WyIuLi8uLi9zcmMvZGlmZi9jc3MuanMiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNzc0RpZmYgPSBuZXcgRGlmZigpO1xuY3NzRGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZS5zcGxpdCgvKFt7fTo7LF18XFxzKykvKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmQ3NzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gY3NzRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBQSxLQUFBLEdBQUFDLHNCQUFBLENBQUFDLE9BQUE7QUFBQTtBQUFBO0FBQTBCLG1DQUFBRCx1QkFBQUUsR0FBQSxXQUFBQSxHQUFBLElBQUFBLEdBQUEsQ0FBQUMsVUFBQSxHQUFBRCxHQUFBLGdCQUFBQSxHQUFBO0FBQUE7QUFFbkIsSUFBTUUsT0FBTztBQUFBO0FBQUFDLE9BQUEsQ0FBQUQsT0FBQTtBQUFBO0FBQUc7QUFBSUU7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSSxDQUFDLENBQUM7QUFDakNGLE9BQU8sQ0FBQ0csUUFBUSxHQUFHLFVBQVNDLEtBQUssRUFBRTtFQUNqQyxPQUFPQSxLQUFLLENBQUNDLEtBQUssQ0FBQyxlQUFlLENBQUM7QUFDckMsQ0FBQztBQUVNLFNBQVNDLE9BQU9BLENBQUNDLE1BQU0sRUFBRUMsTUFBTSxFQUFFQyxRQUFRLEVBQUU7RUFBRSxPQUFPVCxPQUFPLENBQUNVLElBQUksQ0FBQ0gsTUFBTSxFQUFFQyxNQUFNLEVBQUVDLFFBQVEsQ0FBQztBQUFFIiwiaWdub3JlTGlzdCI6W119 /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.canonicalize = canonicalize; exports.diffJson = diffJson; exports.jsonDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _line = require("./line") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } /*istanbul ignore end*/ var jsonDiff = /*istanbul ignore start*/ exports.jsonDiff = /*istanbul ignore end*/ new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = /*istanbul ignore start*/ _line /*istanbul ignore end*/ . /*istanbul ignore start*/ lineDiff /*istanbul ignore end*/ .tokenize; jsonDiff.castInput = function (value, options) { var /*istanbul ignore start*/ /*istanbul ignore end*/ undefinedReplacement = options.undefinedReplacement, /*istanbul ignore start*/ _options$stringifyRep = /*istanbul ignore end*/ options.stringifyReplacer, /*istanbul ignore start*/ /*istanbul ignore end*/ stringifyReplacer = _options$stringifyRep === void 0 ? function (k, v) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ typeof v === 'undefined' ? undefinedReplacement : v ); } : _options$stringifyRep; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right, options) { return ( /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ].prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options) ); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === Object.prototype.toString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if ( /*istanbul ignore start*/ _typeof( /*istanbul ignore end*/ obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(obj, _key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYmFzZSIsIl9pbnRlcm9wUmVxdWlyZURlZmF1bHQiLCJyZXF1aXJlIiwiX2xpbmUiLCJvYmoiLCJfX2VzTW9kdWxlIiwiX3R5cGVvZiIsIm8iLCJTeW1ib2wiLCJpdGVyYXRvciIsImNvbnN0cnVjdG9yIiwicHJvdG90eXBlIiwianNvbkRpZmYiLCJleHBvcnRzIiwiRGlmZiIsInVzZUxvbmdlc3RUb2tlbiIsInRva2VuaXplIiwibGluZURpZmYiLCJjYXN0SW5wdXQiLCJ2YWx1ZSIsIm9wdGlvbnMiLCJ1bmRlZmluZWRSZXBsYWNlbWVudCIsIl9vcHRpb25zJHN0cmluZ2lmeVJlcCIsInN0cmluZ2lmeVJlcGxhY2VyIiwiayIsInYiLCJKU09OIiwic3RyaW5naWZ5IiwiY2Fub25pY2FsaXplIiwiZXF1YWxzIiwibGVmdCIsInJpZ2h0IiwiY2FsbCIsInJlcGxhY2UiLCJkaWZmSnNvbiIsIm9sZE9iaiIsIm5ld09iaiIsImRpZmYiLCJzdGFjayIsInJlcGxhY2VtZW50U3RhY2siLCJyZXBsYWNlciIsImtleSIsImkiLCJsZW5ndGgiLCJjYW5vbmljYWxpemVkT2JqIiwiT2JqZWN0IiwidG9TdHJpbmciLCJwdXNoIiwiQXJyYXkiLCJwb3AiLCJ0b0pTT04iLCJzb3J0ZWRLZXlzIiwiaGFzT3duUHJvcGVydHkiLCJzb3J0Il0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL2RpZmYvanNvbi5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuaW1wb3J0IHtsaW5lRGlmZn0gZnJvbSAnLi9saW5lJztcblxuZXhwb3J0IGNvbnN0IGpzb25EaWZmID0gbmV3IERpZmYoKTtcbi8vIERpc2NyaW1pbmF0ZSBiZXR3ZWVuIHR3byBsaW5lcyBvZiBwcmV0dHktcHJpbnRlZCwgc2VyaWFsaXplZCBKU09OIHdoZXJlIG9uZSBvZiB0aGVtIGhhcyBhXG4vLyBkYW5nbGluZyBjb21tYSBhbmQgdGhlIG90aGVyIGRvZXNuJ3QuIFR1cm5zIG91dCBpbmNsdWRpbmcgdGhlIGRhbmdsaW5nIGNvbW1hIHlpZWxkcyB0aGUgbmljZXN0IG91dHB1dDpcbmpzb25EaWZmLnVzZUxvbmdlc3RUb2tlbiA9IHRydWU7XG5cbmpzb25EaWZmLnRva2VuaXplID0gbGluZURpZmYudG9rZW5pemU7XG5qc29uRGlmZi5jYXN0SW5wdXQgPSBmdW5jdGlvbih2YWx1ZSwgb3B0aW9ucykge1xuICBjb25zdCB7dW5kZWZpbmVkUmVwbGFjZW1lbnQsIHN0cmluZ2lmeVJlcGxhY2VyID0gKGssIHYpID0+IHR5cGVvZiB2ID09PSAndW5kZWZpbmVkJyA/IHVuZGVmaW5lZFJlcGxhY2VtZW50IDogdn0gPSBvcHRpb25zO1xuXG4gIHJldHVybiB0eXBlb2YgdmFsdWUgPT09ICdzdHJpbmcnID8gdmFsdWUgOiBKU09OLnN0cmluZ2lmeShjYW5vbmljYWxpemUodmFsdWUsIG51bGwsIG51bGwsIHN0cmluZ2lmeVJlcGxhY2VyKSwgc3RyaW5naWZ5UmVwbGFjZXIsICcgICcpO1xufTtcbmpzb25EaWZmLmVxdWFscyA9IGZ1bmN0aW9uKGxlZnQsIHJpZ2h0LCBvcHRpb25zKSB7XG4gIHJldHVybiBEaWZmLnByb3RvdHlwZS5lcXVhbHMuY2FsbChqc29uRGlmZiwgbGVmdC5yZXBsYWNlKC8sKFtcXHJcXG5dKS9nLCAnJDEnKSwgcmlnaHQucmVwbGFjZSgvLChbXFxyXFxuXSkvZywgJyQxJyksIG9wdGlvbnMpO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZKc29uKG9sZE9iaiwgbmV3T2JqLCBvcHRpb25zKSB7IHJldHVybiBqc29uRGlmZi5kaWZmKG9sZE9iaiwgbmV3T2JqLCBvcHRpb25zKTsgfVxuXG4vLyBUaGlzIGZ1bmN0aW9uIGhhbmRsZXMgdGhlIHByZXNlbmNlIG9mIGNpcmN1bGFyIHJlZmVyZW5jZXMgYnkgYmFpbGluZyBvdXQgd2hlbiBlbmNvdW50ZXJpbmcgYW5cbi8vIG9iamVjdCB0aGF0IGlzIGFscmVhZHkgb24gdGhlIFwic3RhY2tcIiBvZiBpdGVtcyBiZWluZyBwcm9jZXNzZWQuIEFjY2VwdHMgYW4gb3B0aW9uYWwgcmVwbGFjZXJcbmV4cG9ydCBmdW5jdGlvbiBjYW5vbmljYWxpemUob2JqLCBzdGFjaywgcmVwbGFjZW1lbnRTdGFjaywgcmVwbGFjZXIsIGtleSkge1xuICBzdGFjayA9IHN0YWNrIHx8IFtdO1xuICByZXBsYWNlbWVudFN0YWNrID0gcmVwbGFjZW1lbnRTdGFjayB8fCBbXTtcblxuICBpZiAocmVwbGFjZXIpIHtcbiAgICBvYmogPSByZXBsYWNlcihrZXksIG9iaik7XG4gIH1cblxuICBsZXQgaTtcblxuICBmb3IgKGkgPSAwOyBpIDwgc3RhY2subGVuZ3RoOyBpICs9IDEpIHtcbiAgICBpZiAoc3RhY2tbaV0gPT09IG9iaikge1xuICAgICAgcmV0dXJuIHJlcGxhY2VtZW50U3RhY2tbaV07XG4gICAgfVxuICB9XG5cbiAgbGV0IGNhbm9uaWNhbGl6ZWRPYmo7XG5cbiAgaWYgKCdbb2JqZWN0IEFycmF5XScgPT09IE9iamVjdC5wcm90b3R5cGUudG9TdHJpbmcuY2FsbChvYmopKSB7XG4gICAgc3RhY2sucHVzaChvYmopO1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBuZXcgQXJyYXkob2JqLmxlbmd0aCk7XG4gICAgcmVwbGFjZW1lbnRTdGFjay5wdXNoKGNhbm9uaWNhbGl6ZWRPYmopO1xuICAgIGZvciAoaSA9IDA7IGkgPCBvYmoubGVuZ3RoOyBpICs9IDEpIHtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpbaV0gPSBjYW5vbmljYWxpemUob2JqW2ldLCBzdGFjaywgcmVwbGFjZW1lbnRTdGFjaywgcmVwbGFjZXIsIGtleSk7XG4gICAgfVxuICAgIHN0YWNrLnBvcCgpO1xuICAgIHJlcGxhY2VtZW50U3RhY2sucG9wKCk7XG4gICAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG4gIH1cblxuICBpZiAob2JqICYmIG9iai50b0pTT04pIHtcbiAgICBvYmogPSBvYmoudG9KU09OKCk7XG4gIH1cblxuICBpZiAodHlwZW9mIG9iaiA9PT0gJ29iamVjdCcgJiYgb2JqICE9PSBudWxsKSB7XG4gICAgc3RhY2sucHVzaChvYmopO1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSB7fTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnB1c2goY2Fub25pY2FsaXplZE9iaik7XG4gICAgbGV0IHNvcnRlZEtleXMgPSBbXSxcbiAgICAgICAga2V5O1xuICAgIGZvciAoa2V5IGluIG9iaikge1xuICAgICAgLyogaXN0YW5idWwgaWdub3JlIGVsc2UgKi9cbiAgICAgIGlmIChPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwob2JqLCBrZXkpKSB7XG4gICAgICAgIHNvcnRlZEtleXMucHVzaChrZXkpO1xuICAgICAgfVxuICAgIH1cbiAgICBzb3J0ZWRLZXlzLnNvcnQoKTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgc29ydGVkS2V5cy5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAga2V5ID0gc29ydGVkS2V5c1tpXTtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpba2V5XSA9IGNhbm9uaWNhbGl6ZShvYmpba2V5XSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICB9IGVsc2Uge1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBvYmo7XG4gIH1cbiAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUFBLEtBQUEsR0FBQUMsc0JBQUEsQ0FBQUMsT0FBQTtBQUFBO0FBQUE7QUFDQTtBQUFBO0FBQUFDLEtBQUEsR0FBQUQsT0FBQTtBQUFBO0FBQUE7QUFBZ0MsbUNBQUFELHVCQUFBRyxHQUFBLFdBQUFBLEdBQUEsSUFBQUEsR0FBQSxDQUFBQyxVQUFBLEdBQUFELEdBQUEsZ0JBQUFBLEdBQUE7QUFBQSxTQUFBRSxRQUFBQyxDQUFBLHNDQUFBRCxPQUFBLHdCQUFBRSxNQUFBLHVCQUFBQSxNQUFBLENBQUFDLFFBQUEsYUFBQUYsQ0FBQSxrQkFBQUEsQ0FBQSxnQkFBQUEsQ0FBQSxXQUFBQSxDQUFBLHlCQUFBQyxNQUFBLElBQUFELENBQUEsQ0FBQUcsV0FBQSxLQUFBRixNQUFBLElBQUFELENBQUEsS0FBQUMsTUFBQSxDQUFBRyxTQUFBLHFCQUFBSixDQUFBLEtBQUFELE9BQUEsQ0FBQUMsQ0FBQTtBQUFBO0FBRXpCLElBQU1LLFFBQVE7QUFBQTtBQUFBQyxPQUFBLENBQUFELFFBQUE7QUFBQTtBQUFHO0FBQUlFO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBLENBQUksQ0FBQyxDQUFDO0FBQ2xDO0FBQ0E7QUFDQUYsUUFBUSxDQUFDRyxlQUFlLEdBQUcsSUFBSTtBQUUvQkgsUUFBUSxDQUFDSSxRQUFRO0FBQUdDO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQVE7QUFBQSxDQUFDRCxRQUFRO0FBQ3JDSixRQUFRLENBQUNNLFNBQVMsR0FBRyxVQUFTQyxLQUFLLEVBQUVDLE9BQU8sRUFBRTtFQUM1QztJQUFBO0lBQUE7SUFBT0Msb0JBQW9CLEdBQXVGRCxPQUFPLENBQWxIQyxvQkFBb0I7SUFBQTtJQUFBQyxxQkFBQTtJQUFBO0lBQXVGRixPQUFPLENBQTVGRyxpQkFBaUI7SUFBQTtJQUFBO0lBQWpCQSxpQkFBaUIsR0FBQUQscUJBQUEsY0FBRyxVQUFDRSxDQUFDLEVBQUVDLENBQUM7SUFBQTtJQUFBO01BQUE7UUFBQTtRQUFLLE9BQU9BLENBQUMsS0FBSyxXQUFXLEdBQUdKLG9CQUFvQixHQUFHSTtNQUFDO0lBQUEsSUFBQUgscUJBQUE7RUFFOUcsT0FBTyxPQUFPSCxLQUFLLEtBQUssUUFBUSxHQUFHQSxLQUFLLEdBQUdPLElBQUksQ0FBQ0MsU0FBUyxDQUFDQyxZQUFZLENBQUNULEtBQUssRUFBRSxJQUFJLEVBQUUsSUFBSSxFQUFFSSxpQkFBaUIsQ0FBQyxFQUFFQSxpQkFBaUIsRUFBRSxJQUFJLENBQUM7QUFDeEksQ0FBQztBQUNEWCxRQUFRLENBQUNpQixNQUFNLEdBQUcsVUFBU0MsSUFBSSxFQUFFQyxLQUFLLEVBQUVYLE9BQU8sRUFBRTtFQUMvQyxPQUFPTjtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQSxDQUFJLENBQUNILFNBQVMsQ0FBQ2tCLE1BQU0sQ0FBQ0csSUFBSSxDQUFDcEIsUUFBUSxFQUFFa0IsSUFBSSxDQUFDRyxPQUFPLENBQUMsWUFBWSxFQUFFLElBQUksQ0FBQyxFQUFFRixLQUFLLENBQUNFLE9BQU8sQ0FBQyxZQUFZLEVBQUUsSUFBSSxDQUFDLEVBQUViLE9BQU87RUFBQztBQUMzSCxDQUFDO0FBRU0sU0FBU2MsUUFBUUEsQ0FBQ0MsTUFBTSxFQUFFQyxNQUFNLEVBQUVoQixPQUFPLEVBQUU7RUFBRSxPQUFPUixRQUFRLENBQUN5QixJQUFJLENBQUNGLE1BQU0sRUFBRUMsTUFBTSxFQUFFaEIsT0FBTyxDQUFDO0FBQUU7O0FBRW5HO0FBQ0E7QUFDTyxTQUFTUSxZQUFZQSxDQUFDeEIsR0FBRyxFQUFFa0MsS0FBSyxFQUFFQyxnQkFBZ0IsRUFBRUMsUUFBUSxFQUFFQyxHQUFHLEVBQUU7RUFDeEVILEtBQUssR0FBR0EsS0FBSyxJQUFJLEVBQUU7RUFDbkJDLGdCQUFnQixHQUFHQSxnQkFBZ0IsSUFBSSxFQUFFO0VBRXpDLElBQUlDLFFBQVEsRUFBRTtJQUNacEMsR0FBRyxHQUFHb0MsUUFBUSxDQUFDQyxHQUFHLEVBQUVyQyxHQUFHLENBQUM7RUFDMUI7RUFFQSxJQUFJc0MsQ0FBQztFQUVMLEtBQUtBLENBQUMsR0FBRyxDQUFDLEVBQUVBLENBQUMsR0FBR0osS0FBSyxDQUFDSyxNQUFNLEVBQUVELENBQUMsSUFBSSxDQUFDLEVBQUU7SUFDcEMsSUFBSUosS0FBSyxDQUFDSSxDQUFDLENBQUMsS0FBS3RDLEdBQUcsRUFBRTtNQUNwQixPQUFPbUMsZ0JBQWdCLENBQUNHLENBQUMsQ0FBQztJQUM1QjtFQUNGO0VBRUEsSUFBSUUsZ0JBQWdCO0VBRXBCLElBQUksZ0JBQWdCLEtBQUtDLE1BQU0sQ0FBQ2xDLFNBQVMsQ0FBQ21DLFFBQVEsQ0FBQ2QsSUFBSSxDQUFDNUIsR0FBRyxDQUFDLEVBQUU7SUFDNURrQyxLQUFLLENBQUNTLElBQUksQ0FBQzNDLEdBQUcsQ0FBQztJQUNmd0MsZ0JBQWdCLEdBQUcsSUFBSUksS0FBSyxDQUFDNUMsR0FBRyxDQUFDdUMsTUFBTSxDQUFDO0lBQ3hDSixnQkFBZ0IsQ0FBQ1EsSUFBSSxDQUFDSCxnQkFBZ0IsQ0FBQztJQUN2QyxLQUFLRixDQUFDLEdBQUcsQ0FBQyxFQUFFQSxDQUFDLEdBQUd0QyxHQUFHLENBQUN1QyxNQUFNLEVBQUVELENBQUMsSUFBSSxDQUFDLEVBQUU7TUFDbENFLGdCQUFnQixDQUFDRixDQUFDLENBQUMsR0FBR2QsWUFBWSxDQUFDeEIsR0FBRyxDQUFDc0MsQ0FBQyxDQUFDLEVBQUVKLEtBQUssRUFBRUMsZ0JBQWdCLEVBQUVDLFFBQVEsRUFBRUMsR0FBRyxDQUFDO0lBQ3BGO0lBQ0FILEtBQUssQ0FBQ1csR0FBRyxDQUFDLENBQUM7SUFDWFYsZ0JBQWdCLENBQUNVLEdBQUcsQ0FBQyxDQUFDO0lBQ3RCLE9BQU9MLGdCQUFnQjtFQUN6QjtFQUVBLElBQUl4QyxHQUFHLElBQUlBLEdBQUcsQ0FBQzhDLE1BQU0sRUFBRTtJQUNyQjlDLEdBQUcsR0FBR0EsR0FBRyxDQUFDOEMsTUFBTSxDQUFDLENBQUM7RUFDcEI7RUFFQTtFQUFJO0VBQUE1QyxPQUFBO0VBQUE7RUFBT0YsR0FBRyxNQUFLLFFBQVEsSUFBSUEsR0FBRyxLQUFLLElBQUksRUFBRTtJQUMzQ2tDLEtBQUssQ0FBQ1MsSUFBSSxDQUFDM0MsR0FBRyxDQUFDO0lBQ2Z3QyxnQkFBZ0IsR0FBRyxDQUFDLENBQUM7SUFDckJMLGdCQUFnQixDQUFDUSxJQUFJLENBQUNILGdCQUFnQixDQUFDO0lBQ3ZDLElBQUlPLFVBQVUsR0FBRyxFQUFFO01BQ2ZWLElBQUc7SUFDUCxLQUFLQSxJQUFHLElBQUlyQyxHQUFHLEVBQUU7TUFDZjtNQUNBLElBQUl5QyxNQUFNLENBQUNsQyxTQUFTLENBQUN5QyxjQUFjLENBQUNwQixJQUFJLENBQUM1QixHQUFHLEVBQUVxQyxJQUFHLENBQUMsRUFBRTtRQUNsRFUsVUFBVSxDQUFDSixJQUFJLENBQUNOLElBQUcsQ0FBQztNQUN0QjtJQUNGO0lBQ0FVLFVBQVUsQ0FBQ0UsSUFBSSxDQUFDLENBQUM7SUFDakIsS0FBS1gsQ0FBQyxHQUFHLENBQUMsRUFBRUEsQ0FBQyxHQUFHUyxVQUFVLENBQUNSLE1BQU0sRUFBRUQsQ0FBQyxJQUFJLENBQUMsRUFBRTtNQUN6Q0QsSUFBRyxHQUFHVSxVQUFVLENBQUNULENBQUMsQ0FBQztNQUNuQkUsZ0JBQWdCLENBQUNILElBQUcsQ0FBQyxHQUFHYixZQUFZLENBQUN4QixHQUFHLENBQUNxQyxJQUFHLENBQUMsRUFBRUgsS0FBSyxFQUFFQyxnQkFBZ0IsRUFBRUMsUUFBUSxFQUFFQyxJQUFHLENBQUM7SUFDeEY7SUFDQUgsS0FBSyxDQUFDVyxHQUFHLENBQUMsQ0FBQztJQUNYVixnQkFBZ0IsQ0FBQ1UsR0FBRyxDQUFDLENBQUM7RUFDeEIsQ0FBQyxNQUFNO0lBQ0xMLGdCQUFnQixHQUFHeEMsR0FBRztFQUN4QjtFQUNBLE9BQU93QyxnQkFBZ0I7QUFDekIiLCJpZ25vcmVMaXN0IjpbXX0= /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffLines = diffLines; exports.diffTrimmedLines = diffTrimmedLines; exports.lineDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _params = require("../util/params") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var lineDiff = /*istanbul ignore start*/ exports.lineDiff = /*istanbul ignore end*/ new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); lineDiff.tokenize = function (value, options) { if (options.stripTrailingCr) { // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior value = value.replace(/\r\n/g, '\n'); } var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { retLines.push(line); } } return retLines; }; lineDiff.equals = function (left, right, options) { // If we're ignoring whitespace, we need to normalise lines by stripping // whitespace before checking equality. (This has an annoying interaction // with newlineIsToken that requires special handling: if newlines get their // own token, then we DON'T want to trim the *newline* tokens down to empty // strings, since this would cause us to treat whitespace-only line content // as equal to a separator between lines, which would be weird and // inconsistent with the documented behavior of the options.) if (options.ignoreWhitespace) { if (!options.newlineIsToken || !left.includes('\n')) { left = left.trim(); } if (!options.newlineIsToken || !right.includes('\n')) { right = right.trim(); } } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { if (left.endsWith('\n')) { left = left.slice(0, -1); } if (right.endsWith('\n')) { right = right.slice(0, -1); } } return ( /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ].prototype.equals.call(this, left, right, options) ); }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } // Kept for backwards compatibility. This is a rather arbitrary wrapper method // that just calls `diffLines` with `ignoreWhitespace: true`. It's confusing to // have two ways to do exactly the same thing in the API, so we no longer // document this one (library users should explicitly use `diffLines` with // `ignoreWhitespace: true` instead) but we keep it around to maintain // compatibility with code that used old versions. function diffTrimmedLines(oldStr, newStr, callback) { var options = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _params /*istanbul ignore end*/ . /*istanbul ignore start*/ generateOptions) /*istanbul ignore end*/ (callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYmFzZSIsIl9pbnRlcm9wUmVxdWlyZURlZmF1bHQiLCJyZXF1aXJlIiwiX3BhcmFtcyIsIm9iaiIsIl9fZXNNb2R1bGUiLCJsaW5lRGlmZiIsImV4cG9ydHMiLCJEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsIm9wdGlvbnMiLCJzdHJpcFRyYWlsaW5nQ3IiLCJyZXBsYWNlIiwicmV0TGluZXMiLCJsaW5lc0FuZE5ld2xpbmVzIiwic3BsaXQiLCJsZW5ndGgiLCJwb3AiLCJpIiwibGluZSIsIm5ld2xpbmVJc1Rva2VuIiwicHVzaCIsImVxdWFscyIsImxlZnQiLCJyaWdodCIsImlnbm9yZVdoaXRlc3BhY2UiLCJpbmNsdWRlcyIsInRyaW0iLCJpZ25vcmVOZXdsaW5lQXRFb2YiLCJlbmRzV2l0aCIsInNsaWNlIiwicHJvdG90eXBlIiwiY2FsbCIsImRpZmZMaW5lcyIsIm9sZFN0ciIsIm5ld1N0ciIsImNhbGxiYWNrIiwiZGlmZiIsImRpZmZUcmltbWVkTGluZXMiLCJnZW5lcmF0ZU9wdGlvbnMiXSwic291cmNlcyI6WyIuLi8uLi9zcmMvZGlmZi9saW5lLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5pbXBvcnQge2dlbmVyYXRlT3B0aW9uc30gZnJvbSAnLi4vdXRpbC9wYXJhbXMnO1xuXG5leHBvcnQgY29uc3QgbGluZURpZmYgPSBuZXcgRGlmZigpO1xubGluZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSwgb3B0aW9ucykge1xuICBpZihvcHRpb25zLnN0cmlwVHJhaWxpbmdDcikge1xuICAgIC8vIHJlbW92ZSBvbmUgXFxyIGJlZm9yZSBcXG4gdG8gbWF0Y2ggR05VIGRpZmYncyAtLXN0cmlwLXRyYWlsaW5nLWNyIGJlaGF2aW9yXG4gICAgdmFsdWUgPSB2YWx1ZS5yZXBsYWNlKC9cXHJcXG4vZywgJ1xcbicpO1xuICB9XG5cbiAgbGV0IHJldExpbmVzID0gW10sXG4gICAgICBsaW5lc0FuZE5ld2xpbmVzID0gdmFsdWUuc3BsaXQoLyhcXG58XFxyXFxuKS8pO1xuXG4gIC8vIElnbm9yZSB0aGUgZmluYWwgZW1wdHkgdG9rZW4gdGhhdCBvY2N1cnMgaWYgdGhlIHN0cmluZyBlbmRzIHdpdGggYSBuZXcgbGluZVxuICBpZiAoIWxpbmVzQW5kTmV3bGluZXNbbGluZXNBbmROZXdsaW5lcy5sZW5ndGggLSAxXSkge1xuICAgIGxpbmVzQW5kTmV3bGluZXMucG9wKCk7XG4gIH1cblxuICAvLyBNZXJnZSB0aGUgY29udGVudCBhbmQgbGluZSBzZXBhcmF0b3JzIGludG8gc2luZ2xlIHRva2Vuc1xuICBmb3IgKGxldCBpID0gMDsgaSA8IGxpbmVzQW5kTmV3bGluZXMubGVuZ3RoOyBpKyspIHtcbiAgICBsZXQgbGluZSA9IGxpbmVzQW5kTmV3bGluZXNbaV07XG5cbiAgICBpZiAoaSAlIDIgJiYgIW9wdGlvbnMubmV3bGluZUlzVG9rZW4pIHtcbiAgICAgIHJldExpbmVzW3JldExpbmVzLmxlbmd0aCAtIDFdICs9IGxpbmU7XG4gICAgfSBlbHNlIHtcbiAgICAgIHJldExpbmVzLnB1c2gobGluZSk7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIHJldExpbmVzO1xufTtcblxubGluZURpZmYuZXF1YWxzID0gZnVuY3Rpb24obGVmdCwgcmlnaHQsIG9wdGlvbnMpIHtcbiAgLy8gSWYgd2UncmUgaWdub3Jpbmcgd2hpdGVzcGFjZSwgd2UgbmVlZCB0byBub3JtYWxpc2UgbGluZXMgYnkgc3RyaXBwaW5nXG4gIC8vIHdoaXRlc3BhY2UgYmVmb3JlIGNoZWNraW5nIGVxdWFsaXR5LiAoVGhpcyBoYXMgYW4gYW5ub3lpbmcgaW50ZXJhY3Rpb25cbiAgLy8gd2l0aCBuZXdsaW5lSXNUb2tlbiB0aGF0IHJlcXVpcmVzIHNwZWNpYWwgaGFuZGxpbmc6IGlmIG5ld2xpbmVzIGdldCB0aGVpclxuICAvLyBvd24gdG9rZW4sIHRoZW4gd2UgRE9OJ1Qgd2FudCB0byB0cmltIHRoZSAqbmV3bGluZSogdG9rZW5zIGRvd24gdG8gZW1wdHlcbiAgLy8gc3RyaW5ncywgc2luY2UgdGhpcyB3b3VsZCBjYXVzZSB1cyB0byB0cmVhdCB3aGl0ZXNwYWNlLW9ubHkgbGluZSBjb250ZW50XG4gIC8vIGFzIGVxdWFsIHRvIGEgc2VwYXJhdG9yIGJldHdlZW4gbGluZXMsIHdoaWNoIHdvdWxkIGJlIHdlaXJkIGFuZFxuICAvLyBpbmNvbnNpc3RlbnQgd2l0aCB0aGUgZG9jdW1lbnRlZCBiZWhhdmlvciBvZiB0aGUgb3B0aW9ucy4pXG4gIGlmIChvcHRpb25zLmlnbm9yZVdoaXRlc3BhY2UpIHtcbiAgICBpZiAoIW9wdGlvbnMubmV3bGluZUlzVG9rZW4gfHwgIWxlZnQuaW5jbHVkZXMoJ1xcbicpKSB7XG4gICAgICBsZWZ0ID0gbGVmdC50cmltKCk7XG4gICAgfVxuICAgIGlmICghb3B0aW9ucy5uZXdsaW5lSXNUb2tlbiB8fCAhcmlnaHQuaW5jbHVkZXMoJ1xcbicpKSB7XG4gICAgICByaWdodCA9IHJpZ2h0LnRyaW0oKTtcbiAgICB9XG4gIH0gZWxzZSBpZiAob3B0aW9ucy5pZ25vcmVOZXdsaW5lQXRFb2YgJiYgIW9wdGlvbnMubmV3bGluZUlzVG9rZW4pIHtcbiAgICBpZiAobGVmdC5lbmRzV2l0aCgnXFxuJykpIHtcbiAgICAgIGxlZnQgPSBsZWZ0LnNsaWNlKDAsIC0xKTtcbiAgICB9XG4gICAgaWYgKHJpZ2h0LmVuZHNXaXRoKCdcXG4nKSkge1xuICAgICAgcmlnaHQgPSByaWdodC5zbGljZSgwLCAtMSk7XG4gICAgfVxuICB9XG4gIHJldHVybiBEaWZmLnByb3RvdHlwZS5lcXVhbHMuY2FsbCh0aGlzLCBsZWZ0LCByaWdodCwgb3B0aW9ucyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gbGluZURpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spOyB9XG5cbi8vIEtlcHQgZm9yIGJhY2t3YXJkcyBjb21wYXRpYmlsaXR5LiBUaGlzIGlzIGEgcmF0aGVyIGFyYml0cmFyeSB3cmFwcGVyIG1ldGhvZFxuLy8gdGhhdCBqdXN0IGNhbGxzIGBkaWZmTGluZXNgIHdpdGggYGlnbm9yZVdoaXRlc3BhY2U6IHRydWVgLiBJdCdzIGNvbmZ1c2luZyB0b1xuLy8gaGF2ZSB0d28gd2F5cyB0byBkbyBleGFjdGx5IHRoZSBzYW1lIHRoaW5nIGluIHRoZSBBUEksIHNvIHdlIG5vIGxvbmdlclxuLy8gZG9jdW1lbnQgdGhpcyBvbmUgKGxpYnJhcnkgdXNlcnMgc2hvdWxkIGV4cGxpY2l0bHkgdXNlIGBkaWZmTGluZXNgIHdpdGhcbi8vIGBpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlYCBpbnN0ZWFkKSBidXQgd2Uga2VlcCBpdCBhcm91bmQgdG8gbWFpbnRhaW5cbi8vIGNvbXBhdGliaWxpdHkgd2l0aCBjb2RlIHRoYXQgdXNlZCBvbGQgdmVyc2lvbnMuXG5leHBvcnQgZnVuY3Rpb24gZGlmZlRyaW1tZWRMaW5lcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHtcbiAgbGV0IG9wdGlvbnMgPSBnZW5lcmF0ZU9wdGlvbnMoY2FsbGJhY2ssIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiBsaW5lRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7OztBQUFBO0FBQUE7QUFBQUEsS0FBQSxHQUFBQyxzQkFBQSxDQUFBQyxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQUMsT0FBQSxHQUFBRCxPQUFBO0FBQUE7QUFBQTtBQUErQyxtQ0FBQUQsdUJBQUFHLEdBQUEsV0FBQUEsR0FBQSxJQUFBQSxHQUFBLENBQUFDLFVBQUEsR0FBQUQsR0FBQSxnQkFBQUEsR0FBQTtBQUFBO0FBRXhDLElBQU1FLFFBQVE7QUFBQTtBQUFBQyxPQUFBLENBQUFELFFBQUE7QUFBQTtBQUFHO0FBQUlFO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBO0FBQUFBLENBQUksQ0FBQyxDQUFDO0FBQ2xDRixRQUFRLENBQUNHLFFBQVEsR0FBRyxVQUFTQyxLQUFLLEVBQUVDLE9BQU8sRUFBRTtFQUMzQyxJQUFHQSxPQUFPLENBQUNDLGVBQWUsRUFBRTtJQUMxQjtJQUNBRixLQUFLLEdBQUdBLEtBQUssQ0FBQ0csT0FBTyxDQUFDLE9BQU8sRUFBRSxJQUFJLENBQUM7RUFDdEM7RUFFQSxJQUFJQyxRQUFRLEdBQUcsRUFBRTtJQUNiQyxnQkFBZ0IsR0FBR0wsS0FBSyxDQUFDTSxLQUFLLENBQUMsV0FBVyxDQUFDOztFQUUvQztFQUNBLElBQUksQ0FBQ0QsZ0JBQWdCLENBQUNBLGdCQUFnQixDQUFDRSxNQUFNLEdBQUcsQ0FBQyxDQUFDLEVBQUU7SUFDbERGLGdCQUFnQixDQUFDRyxHQUFHLENBQUMsQ0FBQztFQUN4Qjs7RUFFQTtFQUNBLEtBQUssSUFBSUMsQ0FBQyxHQUFHLENBQUMsRUFBRUEsQ0FBQyxHQUFHSixnQkFBZ0IsQ0FBQ0UsTUFBTSxFQUFFRSxDQUFDLEVBQUUsRUFBRTtJQUNoRCxJQUFJQyxJQUFJLEdBQUdMLGdCQUFnQixDQUFDSSxDQUFDLENBQUM7SUFFOUIsSUFBSUEsQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDUixPQUFPLENBQUNVLGNBQWMsRUFBRTtNQUNwQ1AsUUFBUSxDQUFDQSxRQUFRLENBQUNHLE1BQU0sR0FBRyxDQUFDLENBQUMsSUFBSUcsSUFBSTtJQUN2QyxDQUFDLE1BQU07TUFDTE4sUUFBUSxDQUFDUSxJQUFJLENBQUNGLElBQUksQ0FBQztJQUNyQjtFQUNGO0VBRUEsT0FBT04sUUFBUTtBQUNqQixDQUFDO0FBRURSLFFBQVEsQ0FBQ2lCLE1BQU0sR0FBRyxVQUFTQyxJQUFJLEVBQUVDLEtBQUssRUFBRWQsT0FBTyxFQUFFO0VBQy9DO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0EsSUFBSUEsT0FBTyxDQUFDZSxnQkFBZ0IsRUFBRTtJQUM1QixJQUFJLENBQUNmLE9BQU8sQ0FBQ1UsY0FBYyxJQUFJLENBQUNHLElBQUksQ0FBQ0csUUFBUSxDQUFDLElBQUksQ0FBQyxFQUFFO01BQ25ESCxJQUFJLEdBQUdBLElBQUksQ0FBQ0ksSUFBSSxDQUFDLENBQUM7SUFDcEI7SUFDQSxJQUFJLENBQUNqQixPQUFPLENBQUNVLGNBQWMsSUFBSSxDQUFDSSxLQUFLLENBQUNFLFFBQVEsQ0FBQyxJQUFJLENBQUMsRUFBRTtNQUNwREYsS0FBSyxHQUFHQSxLQUFLLENBQUNHLElBQUksQ0FBQyxDQUFDO0lBQ3RCO0VBQ0YsQ0FBQyxNQUFNLElBQUlqQixPQUFPLENBQUNrQixrQkFBa0IsSUFBSSxDQUFDbEIsT0FBTyxDQUFDVSxjQUFjLEVBQUU7SUFDaEUsSUFBSUcsSUFBSSxDQUFDTSxRQUFRLENBQUMsSUFBSSxDQUFDLEVBQUU7TUFDdkJOLElBQUksR0FBR0EsSUFBSSxDQUFDTyxLQUFLLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxDQUFDO0lBQzFCO0lBQ0EsSUFBSU4sS0FBSyxDQUFDSyxRQUFRLENBQUMsSUFBSSxDQUFDLEVBQUU7TUFDeEJMLEtBQUssR0FBR0EsS0FBSyxDQUFDTSxLQUFLLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxDQUFDO0lBQzVCO0VBQ0Y7RUFDQSxPQUFPdkI7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsQ0FBSSxDQUFDd0IsU0FBUyxDQUFDVCxNQUFNLENBQUNVLElBQUksQ0FBQyxJQUFJLEVBQUVULElBQUksRUFBRUMsS0FBSyxFQUFFZCxPQUFPO0VBQUM7QUFDL0QsQ0FBQztBQUVNLFNBQVN1QixTQUFTQSxDQUFDQyxNQUFNLEVBQUVDLE1BQU0sRUFBRUMsUUFBUSxFQUFFO0VBQUUsT0FBTy9CLFFBQVEsQ0FBQ2dDLElBQUksQ0FBQ0gsTUFBTSxFQUFFQyxNQUFNLEVBQUVDLFFBQVEsQ0FBQztBQUFFOztBQUV0RztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDTyxTQUFTRSxnQkFBZ0JBLENBQUNKLE1BQU0sRUFBRUMsTUFBTSxFQUFFQyxRQUFRLEVBQUU7RUFDekQsSUFBSTFCLE9BQU87RUFBRztFQUFBO0VBQUE7RUFBQTZCO0VBQUFBO0VBQUFBO0VBQUFBO0VBQUFBO0VBQUFBLGVBQWU7RUFBQTtFQUFBLENBQUNILFFBQVEsRUFBRTtJQUFDWCxnQkFBZ0IsRUFBRTtFQUFJLENBQUMsQ0FBQztFQUNqRSxPQUFPcEIsUUFBUSxDQUFDZ0MsSUFBSSxDQUFDSCxNQUFNLEVBQUVDLE1BQU0sRUFBRXpCLE9BQU8sQ0FBQztBQUMvQyIsImlnbm9yZUxpc3QiOltdfQ== /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffSentences = diffSentences; exports.sentenceDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var sentenceDiff = /*istanbul ignore start*/ exports.sentenceDiff = /*istanbul ignore end*/ new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYmFzZSIsIl9pbnRlcm9wUmVxdWlyZURlZmF1bHQiLCJyZXF1aXJlIiwib2JqIiwiX19lc01vZHVsZSIsInNlbnRlbmNlRGlmZiIsImV4cG9ydHMiLCJEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsInNwbGl0IiwiZGlmZlNlbnRlbmNlcyIsIm9sZFN0ciIsIm5ld1N0ciIsImNhbGxiYWNrIiwiZGlmZiJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cblxuZXhwb3J0IGNvbnN0IHNlbnRlbmNlRGlmZiA9IG5ldyBEaWZmKCk7XG5zZW50ZW5jZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhcXFMuKz9bLiE/XSkoPz1cXHMrfCQpLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZlNlbnRlbmNlcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIHNlbnRlbmNlRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBQSxLQUFBLEdBQUFDLHNCQUFBLENBQUFDLE9BQUE7QUFBQTtBQUFBO0FBQTBCLG1DQUFBRCx1QkFBQUUsR0FBQSxXQUFBQSxHQUFBLElBQUFBLEdBQUEsQ0FBQUMsVUFBQSxHQUFBRCxHQUFBLGdCQUFBQSxHQUFBO0FBQUE7QUFHbkIsSUFBTUUsWUFBWTtBQUFBO0FBQUFDLE9BQUEsQ0FBQUQsWUFBQTtBQUFBO0FBQUc7QUFBSUU7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSSxDQUFDLENBQUM7QUFDdENGLFlBQVksQ0FBQ0csUUFBUSxHQUFHLFVBQVNDLEtBQUssRUFBRTtFQUN0QyxPQUFPQSxLQUFLLENBQUNDLEtBQUssQ0FBQyx1QkFBdUIsQ0FBQztBQUM3QyxDQUFDO0FBRU0sU0FBU0MsYUFBYUEsQ0FBQ0MsTUFBTSxFQUFFQyxNQUFNLEVBQUVDLFFBQVEsRUFBRTtFQUFFLE9BQU9ULFlBQVksQ0FBQ1UsSUFBSSxDQUFDSCxNQUFNLEVBQUVDLE1BQU0sRUFBRUMsUUFBUSxDQUFDO0FBQUUiLCJpZ25vcmVMaXN0IjpbXX0= /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffWords = diffWords; exports.diffWordsWithSpace = diffWordsWithSpace; exports.wordWithSpaceDiff = exports.wordDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _string = require("../util/string") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 Ë™ ˙ Dot Above // - U+02DA Ëš ˚ Ring Above // - U+02DB Ë› ˛ Ogonek // - U+02DC Ëœ ˜ Small Tilde // - U+02DD Ë ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = "a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}"; // Each token is one of the following: // - A punctuation mark plus the surrounding whitespace // - A word plus the surrounding whitespace // - Pure whitespace (but only in the special case where this the entire text // is just whitespace) // // We have to include surrounding whitespace in the tokens because the two // alternative approaches produce horribly broken results: // * If we just discard the whitespace, we can't fully reproduce the original // text from the sequence of tokens and any attempt to render the diff will // get the whitespace wrong. // * If we have separate tokens for whitespace, then in a typical text every // second token will be a single space character. But this often results in // the optimal diff between two texts being a perverse one that preserves // the spaces between words but deletes and reinserts actual common words. // See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640 // for an example. // // Keeping the surrounding whitespace of course has implications for .equals // and .join, not just .tokenize. // This regex does NOT fully implement the tokenization rules described above. // Instead, it gives runs of whitespace their own "token". The tokenize method // then handles stitching whitespace tokens onto adjacent word or punctuation // tokens. var tokenizeIncludingWhitespace = new RegExp( /*istanbul ignore start*/ "[".concat( /*istanbul ignore end*/ extendedWordChars, "]+|\\s+|[^").concat(extendedWordChars, "]"), 'ug'); var wordDiff = /*istanbul ignore start*/ exports.wordDiff = /*istanbul ignore end*/ new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); wordDiff.equals = function (left, right, options) { if (options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left.trim() === right.trim(); }; wordDiff.tokenize = function (value) { /*istanbul ignore start*/ var /*istanbul ignore end*/ options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var parts; if (options.intlSegmenter) { if (options.intlSegmenter.resolvedOptions().granularity != 'word') { throw new Error('The segmenter passed must have a granularity of "word"'); } parts = Array.from(options.intlSegmenter.segment(value), function (segment) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ segment.segment ); }); } else { parts = value.match(tokenizeIncludingWhitespace) || []; } var tokens = []; var prevPart = null; parts.forEach(function (part) { if (/\s/.test(part)) { if (prevPart == null) { tokens.push(part); } else { tokens.push(tokens.pop() + part); } } else if (/\s/.test(prevPart)) { if (tokens[tokens.length - 1] == prevPart) { tokens.push(tokens.pop() + part); } else { tokens.push(prevPart + part); } } else { tokens.push(part); } prevPart = part; }); return tokens; }; wordDiff.join = function (tokens) { // Tokens being joined here will always have appeared consecutively in the // same text, so we can simply strip off the leading whitespace from all the // tokens except the first (and except any whitespace-only tokens - but such // a token will always be the first and only token anyway) and then join them // and the whitespace around words and punctuation will end up correct. return tokens.map(function (token, i) { if (i == 0) { return token; } else { return token.replace(/^\s+/, ''); } }).join(''); }; wordDiff.postProcess = function (changes, options) { if (!changes || options.oneChangePerToken) { return changes; } var lastKeep = null; // Change objects representing any insertion or deletion since the last // "keep" change object. There can be at most one of each. var insertion = null; var deletion = null; changes.forEach(function (change) { if (change.added) { insertion = change; } else if (change.removed) { deletion = change; } else { if (insertion || deletion) { // May be false at start of text dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change); } lastKeep = change; insertion = null; deletion = null; } }); if (insertion || deletion) { dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null); } return changes; }; function diffWords(oldStr, newStr, options) { // This option has never been documented and never will be (it's clearer to // just call `diffWordsWithSpace` directly if you need that behavior), but // has existed in jsdiff for a long time, so we retain support for it here // for the sake of backwards compatibility. if ( /*istanbul ignore start*/ ( /*istanbul ignore end*/ options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) { return diffWordsWithSpace(oldStr, newStr, options); } return wordDiff.diff(oldStr, newStr, options); } function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) { // Before returning, we tidy up the leading and trailing whitespace of the // change objects to eliminate cases where trailing whitespace in one object // is repeated as leading whitespace in the next. // Below are examples of the outcomes we want here to explain the code. // I=insert, K=keep, D=delete // 1. diffing 'foo bar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' // After cleanup, we want: K:'foo ' D:'bar ' K:'baz' // // 2. Diffing 'foo bar baz' vs 'foo qux baz' // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz' // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz' // // 3. Diffing 'foo\nbar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:'\nbar ' K:' baz' // After cleanup, we want K'foo' D:'\nbar' K:' baz' // // 4. Diffing 'foo baz' vs 'foo\nbar baz' // Prior to cleanup, we have K:'foo\n' I:'\nbar ' K:' baz' // After cleanup, we ideally want K'foo' I:'\nbar' K:' baz' // but don't actually manage this currently (the pre-cleanup change // objects don't contain enough information to make it possible). // // 5. Diffing 'foo bar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' // After cleanup, we want K:'foo ' D:' bar ' K:'baz' // // Our handling is unavoidably imperfect in the case where there's a single // indel between keeps and the whitespace has changed. For instance, consider // diffing 'foo\tbar\nbaz' vs 'foo baz'. Unless we create an extra change // object to represent the insertion of the space character (which isn't even // a token), we have no way to avoid losing information about the texts' // original whitespace in the result we return. Still, we do our best to // output something that will look sensible if we e.g. print it with // insertions in green and deletions in red. // Between two "keep" change objects (or before the first or after the last // change object), we can have either: // * A "delete" followed by an "insert" // * Just an "insert" // * Just a "delete" // We handle the three cases separately. if (deletion && insertion) { var oldWsPrefix = deletion.value.match(/^\s*/)[0]; var oldWsSuffix = deletion.value.match(/\s*$/)[0]; var newWsPrefix = insertion.value.match(/^\s*/)[0]; var newWsSuffix = insertion.value.match(/\s*$/)[0]; if (startKeep) { var commonWsPrefix = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ longestCommonPrefix) /*istanbul ignore end*/ (oldWsPrefix, newWsPrefix); startKeep.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ replaceSuffix) /*istanbul ignore end*/ (startKeep.value, newWsPrefix, commonWsPrefix); deletion.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removePrefix) /*istanbul ignore end*/ (deletion.value, commonWsPrefix); insertion.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removePrefix) /*istanbul ignore end*/ (insertion.value, commonWsPrefix); } if (endKeep) { var commonWsSuffix = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ longestCommonSuffix) /*istanbul ignore end*/ (oldWsSuffix, newWsSuffix); endKeep.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ replacePrefix) /*istanbul ignore end*/ (endKeep.value, newWsSuffix, commonWsSuffix); deletion.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removeSuffix) /*istanbul ignore end*/ (deletion.value, commonWsSuffix); insertion.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removeSuffix) /*istanbul ignore end*/ (insertion.value, commonWsSuffix); } } else if (insertion) { // The whitespaces all reflect what was in the new text rather than // the old, so we essentially have no information about whitespace // insertion or deletion. We just want to dedupe the whitespace. // We do that by having each change object keep its trailing // whitespace and deleting duplicate leading whitespace where // present. if (startKeep) { insertion.value = insertion.value.replace(/^\s*/, ''); } if (endKeep) { endKeep.value = endKeep.value.replace(/^\s*/, ''); } // otherwise we've got a deletion and no insertion } else if (startKeep && endKeep) { var newWsFull = endKeep.value.match(/^\s*/)[0], delWsStart = deletion.value.match(/^\s*/)[0], delWsEnd = deletion.value.match(/\s*$/)[0]; // Any whitespace that comes straight after startKeep in both the old and // new texts, assign to startKeep and remove from the deletion. var newWsStart = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ longestCommonPrefix) /*istanbul ignore end*/ (newWsFull, delWsStart); deletion.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removePrefix) /*istanbul ignore end*/ (deletion.value, newWsStart); // Any whitespace that comes straight before endKeep in both the old and // new texts, and hasn't already been assigned to startKeep, assign to // endKeep and remove from the deletion. var newWsEnd = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ longestCommonSuffix) /*istanbul ignore end*/ ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removePrefix) /*istanbul ignore end*/ (newWsFull, newWsStart), delWsEnd); deletion.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removeSuffix) /*istanbul ignore end*/ (deletion.value, newWsEnd); endKeep.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ replacePrefix) /*istanbul ignore end*/ (endKeep.value, newWsFull, newWsEnd); // If there's any whitespace from the new text that HASN'T already been // assigned, assign it to the start: startKeep.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ replaceSuffix) /*istanbul ignore end*/ (startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length)); } else if (endKeep) { // We are at the start of the text. Preserve all the whitespace on // endKeep, and just remove whitespace from the end of deletion to the // extent that it overlaps with the start of endKeep. var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0]; var deletionWsSuffix = deletion.value.match(/\s*$/)[0]; var overlap = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ maximumOverlap) /*istanbul ignore end*/ (deletionWsSuffix, endKeepWsPrefix); deletion.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removeSuffix) /*istanbul ignore end*/ (deletion.value, overlap); } else if (startKeep) { // We are at the END of the text. Preserve all the whitespace on // startKeep, and just remove whitespace from the start of deletion to // the extent that it overlaps with the end of startKeep. var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0]; var deletionWsPrefix = deletion.value.match(/^\s*/)[0]; var _overlap = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ maximumOverlap) /*istanbul ignore end*/ (startKeepWsSuffix, deletionWsPrefix); deletion.value = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ removePrefix) /*istanbul ignore end*/ (deletion.value, _overlap); } } var wordWithSpaceDiff = /*istanbul ignore start*/ exports.wordWithSpaceDiff = /*istanbul ignore end*/ new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); wordWithSpaceDiff.tokenize = function (value) { // Slightly different to the tokenizeIncludingWhitespace regex used above in // that this one treats each individual newline as a distinct tokens, rather // than merging them into other surrounding whitespace. This was requested // in https://github.com/kpdecker/jsdiff/issues/180 & // https://github.com/kpdecker/jsdiff/issues/211 var regex = new RegExp( /*istanbul ignore start*/ "(\\r?\\n)|[".concat( /*istanbul ignore end*/ extendedWordChars, "]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars, "]"), 'ug'); return value.match(regex) || []; }; function diffWordsWithSpace(oldStr, newStr, options) { return wordWithSpaceDiff.diff(oldStr, newStr, options); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYmFzZSIsIl9pbnRlcm9wUmVxdWlyZURlZmF1bHQiLCJyZXF1aXJlIiwiX3N0cmluZyIsIm9iaiIsIl9fZXNNb2R1bGUiLCJleHRlbmRlZFdvcmRDaGFycyIsInRva2VuaXplSW5jbHVkaW5nV2hpdGVzcGFjZSIsIlJlZ0V4cCIsImNvbmNhdCIsIndvcmREaWZmIiwiZXhwb3J0cyIsIkRpZmYiLCJlcXVhbHMiLCJsZWZ0IiwicmlnaHQiLCJvcHRpb25zIiwiaWdub3JlQ2FzZSIsInRvTG93ZXJDYXNlIiwidHJpbSIsInRva2VuaXplIiwidmFsdWUiLCJhcmd1bWVudHMiLCJsZW5ndGgiLCJ1bmRlZmluZWQiLCJwYXJ0cyIsImludGxTZWdtZW50ZXIiLCJyZXNvbHZlZE9wdGlvbnMiLCJncmFudWxhcml0eSIsIkVycm9yIiwiQXJyYXkiLCJmcm9tIiwic2VnbWVudCIsIm1hdGNoIiwidG9rZW5zIiwicHJldlBhcnQiLCJmb3JFYWNoIiwicGFydCIsInRlc3QiLCJwdXNoIiwicG9wIiwiam9pbiIsIm1hcCIsInRva2VuIiwiaSIsInJlcGxhY2UiLCJwb3N0UHJvY2VzcyIsImNoYW5nZXMiLCJvbmVDaGFuZ2VQZXJUb2tlbiIsImxhc3RLZWVwIiwiaW5zZXJ0aW9uIiwiZGVsZXRpb24iLCJjaGFuZ2UiLCJhZGRlZCIsInJlbW92ZWQiLCJkZWR1cGVXaGl0ZXNwYWNlSW5DaGFuZ2VPYmplY3RzIiwiZGlmZldvcmRzIiwib2xkU3RyIiwibmV3U3RyIiwiaWdub3JlV2hpdGVzcGFjZSIsImRpZmZXb3Jkc1dpdGhTcGFjZSIsImRpZmYiLCJzdGFydEtlZXAiLCJlbmRLZWVwIiwib2xkV3NQcmVmaXgiLCJvbGRXc1N1ZmZpeCIsIm5ld1dzUHJlZml4IiwibmV3V3NTdWZmaXgiLCJjb21tb25Xc1ByZWZpeCIsImxvbmdlc3RDb21tb25QcmVmaXgiLCJyZXBsYWNlU3VmZml4IiwicmVtb3ZlUHJlZml4IiwiY29tbW9uV3NTdWZmaXgiLCJsb25nZXN0Q29tbW9uU3VmZml4IiwicmVwbGFjZVByZWZpeCIsInJlbW92ZVN1ZmZpeCIsIm5ld1dzRnVsbCIsImRlbFdzU3RhcnQiLCJkZWxXc0VuZCIsIm5ld1dzU3RhcnQiLCJuZXdXc0VuZCIsInNsaWNlIiwiZW5kS2VlcFdzUHJlZml4IiwiZGVsZXRpb25Xc1N1ZmZpeCIsIm92ZXJsYXAiLCJtYXhpbXVtT3ZlcmxhcCIsInN0YXJ0S2VlcFdzU3VmZml4IiwiZGVsZXRpb25Xc1ByZWZpeCIsIndvcmRXaXRoU3BhY2VEaWZmIiwicmVnZXgiXSwic291cmNlcyI6WyIuLi8uLi9zcmMvZGlmZi93b3JkLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5pbXBvcnQgeyBsb25nZXN0Q29tbW9uUHJlZml4LCBsb25nZXN0Q29tbW9uU3VmZml4LCByZXBsYWNlUHJlZml4LCByZXBsYWNlU3VmZml4LCByZW1vdmVQcmVmaXgsIHJlbW92ZVN1ZmZpeCwgbWF4aW11bU92ZXJsYXAgfSBmcm9tICcuLi91dGlsL3N0cmluZyc7XG5cbi8vIEJhc2VkIG9uIGh0dHBzOi8vZW4ud2lraXBlZGlhLm9yZy93aWtpL0xhdGluX3NjcmlwdF9pbl9Vbmljb2RlXG4vL1xuLy8gUmFuZ2VzIGFuZCBleGNlcHRpb25zOlxuLy8gTGF0aW4tMSBTdXBwbGVtZW50LCAwMDgw4oCTMDBGRlxuLy8gIC0gVSswMEQ3ICDDlyBNdWx0aXBsaWNhdGlvbiBzaWduXG4vLyAgLSBVKzAwRjcgIMO3IERpdmlzaW9uIHNpZ25cbi8vIExhdGluIEV4dGVuZGVkLUEsIDAxMDDigJMwMTdGXG4vLyBMYXRpbiBFeHRlbmRlZC1CLCAwMTgw4oCTMDI0RlxuLy8gSVBBIEV4dGVuc2lvbnMsIDAyNTDigJMwMkFGXG4vLyBTcGFjaW5nIE1vZGlmaWVyIExldHRlcnMsIDAyQjDigJMwMkZGXG4vLyAgLSBVKzAyQzcgIMuHICYjNzExOyAgQ2Fyb25cbi8vICAtIFUrMDJEOCAgy5ggJiM3Mjg7ICBCcmV2ZVxuLy8gIC0gVSswMkQ5ICDLmSAmIzcyOTsgIERvdCBBYm92ZVxuLy8gIC0gVSswMkRBICDLmiAmIzczMDsgIFJpbmcgQWJvdmVcbi8vICAtIFUrMDJEQiAgy5sgJiM3MzE7ICBPZ29uZWtcbi8vICAtIFUrMDJEQyAgy5wgJiM3MzI7ICBTbWFsbCBUaWxkZVxuLy8gIC0gVSswMkREICDLnSAmIzczMzsgIERvdWJsZSBBY3V0ZSBBY2NlbnRcbi8vIExhdGluIEV4dGVuZGVkIEFkZGl0aW9uYWwsIDFFMDDigJMxRUZGXG5jb25zdCBleHRlbmRlZFdvcmRDaGFycyA9ICdhLXpBLVowLTlfXFxcXHV7QzB9LVxcXFx1e0ZGfVxcXFx1e0Q4fS1cXFxcdXtGNn1cXFxcdXtGOH0tXFxcXHV7MkM2fVxcXFx1ezJDOH0tXFxcXHV7MkQ3fVxcXFx1ezJERX0tXFxcXHV7MkZGfVxcXFx1ezFFMDB9LVxcXFx1ezFFRkZ9JztcblxuLy8gRWFjaCB0b2tlbiBpcyBvbmUgb2YgdGhlIGZvbGxvd2luZzpcbi8vIC0gQSBwdW5jdHVhdGlvbiBtYXJrIHBsdXMgdGhlIHN1cnJvdW5kaW5nIHdoaXRlc3BhY2Vcbi8vIC0gQSB3b3JkIHBsdXMgdGhlIHN1cnJvdW5kaW5nIHdoaXRlc3BhY2Vcbi8vIC0gUHVyZSB3aGl0ZXNwYWNlIChidXQgb25seSBpbiB0aGUgc3BlY2lhbCBjYXNlIHdoZXJlIHRoaXMgdGhlIGVudGlyZSB0ZXh0XG4vLyAgIGlzIGp1c3Qgd2hpdGVzcGFjZSlcbi8vXG4vLyBXZSBoYXZlIHRvIGluY2x1ZGUgc3Vycm91bmRpbmcgd2hpdGVzcGFjZSBpbiB0aGUgdG9rZW5zIGJlY2F1c2UgdGhlIHR3b1xuLy8gYWx0ZXJuYXRpdmUgYXBwcm9hY2hlcyBwcm9kdWNlIGhvcnJpYmx5IGJyb2tlbiByZXN1bHRzOlxuLy8gKiBJZiB3ZSBqdXN0IGRpc2NhcmQgdGhlIHdoaXRlc3BhY2UsIHdlIGNhbid0IGZ1bGx5IHJlcHJvZHVjZSB0aGUgb3JpZ2luYWxcbi8vICAgdGV4dCBmcm9tIHRoZSBzZXF1ZW5jZSBvZiB0b2tlbnMgYW5kIGFueSBhdHRlbXB0IHRvIHJlbmRlciB0aGUgZGlmZiB3aWxsXG4vLyAgIGdldCB0aGUgd2hpdGVzcGFjZSB3cm9uZy5cbi8vICogSWYgd2UgaGF2ZSBzZXBhcmF0ZSB0b2tlbnMgZm9yIHdoaXRlc3BhY2UsIHRoZW4gaW4gYSB0eXBpY2FsIHRleHQgZXZlcnlcbi8vICAgc2Vjb25kIHRva2VuIHdpbGwgYmUgYSBzaW5nbGUgc3BhY2UgY2hhcmFjdGVyLiBCdXQgdGhpcyBvZnRlbiByZXN1bHRzIGluXG4vLyAgIHRoZSBvcHRpbWFsIGRpZmYgYmV0d2VlbiB0d28gdGV4dHMgYmVpbmcgYSBwZXJ2ZXJzZSBvbmUgdGhhdCBwcmVzZXJ2ZXNcbi8vICAgdGhlIHNwYWNlcyBiZXR3ZWVuIHdvcmRzIGJ1dCBkZWxldGVzIGFuZCByZWluc2VydHMgYWN0dWFsIGNvbW1vbiB3b3Jkcy5cbi8vICAgU2VlIGh0dHBzOi8vZ2l0aHViLmNvbS9rcGRlY2tlci9qc2RpZmYvaXNzdWVzLzE2MCNpc3N1ZWNvbW1lbnQtMTg2NjA5OTY0MFxuLy8gICBmb3IgYW4gZXhhbXBsZS5cbi8vXG4vLyBLZWVwaW5nIHRoZSBzdXJyb3VuZGluZyB3aGl0ZXNwYWNlIG9mIGNvdXJzZSBoYXMgaW1wbGljYXRpb25zIGZvciAuZXF1YWxzXG4vLyBhbmQgLmpvaW4sIG5vdCBqdXN0IC50b2tlbml6ZS5cblxuLy8gVGhpcyByZWdleCBkb2VzIE5PVCBmdWxseSBpbXBsZW1lbnQgdGhlIHRva2VuaXphdGlvbiBydWxlcyBkZXNjcmliZWQgYWJvdmUuXG4vLyBJbnN0ZWFkLCBpdCBnaXZlcyBydW5zIG9mIHdoaXRlc3BhY2UgdGhlaXIgb3duIFwidG9rZW5cIi4gVGhlIHRva2VuaXplIG1ldGhvZFxuLy8gdGhlbiBoYW5kbGVzIHN0aXRjaGluZyB3aGl0ZXNwYWNlIHRva2VucyBvbnRvIGFkamFjZW50IHdvcmQgb3IgcHVuY3R1YXRpb25cbi8vIHRva2Vucy5cbmNvbnN0IHRva2VuaXplSW5jbHVkaW5nV2hpdGVzcGFjZSA9IG5ldyBSZWdFeHAoYFske2V4dGVuZGVkV29yZENoYXJzfV0rfFxcXFxzK3xbXiR7ZXh0ZW5kZWRXb3JkQ2hhcnN9XWAsICd1ZycpO1xuXG5leHBvcnQgY29uc3Qgd29yZERpZmYgPSBuZXcgRGlmZigpO1xud29yZERpZmYuZXF1YWxzID0gZnVuY3Rpb24obGVmdCwgcmlnaHQsIG9wdGlvbnMpIHtcbiAgaWYgKG9wdGlvbnMuaWdub3JlQ2FzZSkge1xuICAgIGxlZnQgPSBsZWZ0LnRvTG93ZXJDYXNlKCk7XG4gICAgcmlnaHQgPSByaWdodC50b0xvd2VyQ2FzZSgpO1xuICB9XG5cbiAgcmV0dXJuIGxlZnQudHJpbSgpID09PSByaWdodC50cmltKCk7XG59O1xuXG53b3JkRGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlLCBvcHRpb25zID0ge30pIHtcbiAgbGV0IHBhcnRzO1xuICBpZiAob3B0aW9ucy5pbnRsU2VnbWVudGVyKSB7XG4gICAgaWYgKG9wdGlvbnMuaW50bFNlZ21lbnRlci5yZXNvbHZlZE9wdGlvbnMoKS5ncmFudWxhcml0eSAhPSAnd29yZCcpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignVGhlIHNlZ21lbnRlciBwYXNzZWQgbXVzdCBoYXZlIGEgZ3JhbnVsYXJpdHkgb2YgXCJ3b3JkXCInKTtcbiAgICB9XG4gICAgcGFydHMgPSBBcnJheS5mcm9tKG9wdGlvbnMuaW50bFNlZ21lbnRlci5zZWdtZW50KHZhbHVlKSwgc2VnbWVudCA9PiBzZWdtZW50LnNlZ21lbnQpO1xuICB9IGVsc2Uge1xuICAgIHBhcnRzID0gdmFsdWUubWF0Y2godG9rZW5pemVJbmNsdWRpbmdXaGl0ZXNwYWNlKSB8fCBbXTtcbiAgfVxuICBjb25zdCB0b2tlbnMgPSBbXTtcbiAgbGV0IHByZXZQYXJ0ID0gbnVsbDtcbiAgcGFydHMuZm9yRWFjaChwYXJ0ID0+IHtcbiAgICBpZiAoKC9cXHMvKS50ZXN0KHBhcnQpKSB7XG4gICAgICBpZiAocHJldlBhcnQgPT0gbnVsbCkge1xuICAgICAgICB0b2tlbnMucHVzaChwYXJ0KTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIHRva2Vucy5wdXNoKHRva2Vucy5wb3AoKSArIHBhcnQpO1xuICAgICAgfVxuICAgIH0gZWxzZSBpZiAoKC9cXHMvKS50ZXN0KHByZXZQYXJ0KSkge1xuICAgICAgaWYgKHRva2Vuc1t0b2tlbnMubGVuZ3RoIC0gMV0gPT0gcHJldlBhcnQpIHtcbiAgICAgICAgdG9rZW5zLnB1c2godG9rZW5zLnBvcCgpICsgcGFydCk7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICB0b2tlbnMucHVzaChwcmV2UGFydCArIHBhcnQpO1xuICAgICAgfVxuICAgIH0gZWxzZSB7XG4gICAgICB0b2tlbnMucHVzaChwYXJ0KTtcbiAgICB9XG5cbiAgICBwcmV2UGFydCA9IHBhcnQ7XG4gIH0pO1xuICByZXR1cm4gdG9rZW5zO1xufTtcblxud29yZERpZmYuam9pbiA9IGZ1bmN0aW9uKHRva2Vucykge1xuICAvLyBUb2tlbnMgYmVpbmcgam9pbmVkIGhlcmUgd2lsbCBhbHdheXMgaGF2ZSBhcHBlYXJlZCBjb25zZWN1dGl2ZWx5IGluIHRoZVxuICAvLyBzYW1lIHRleHQsIHNvIHdlIGNhbiBzaW1wbHkgc3RyaXAgb2ZmIHRoZSBsZWFkaW5nIHdoaXRlc3BhY2UgZnJvbSBhbGwgdGhlXG4gIC8vIHRva2VucyBleGNlcHQgdGhlIGZpcnN0IChhbmQgZXhjZXB0IGFueSB3aGl0ZXNwYWNlLW9ubHkgdG9rZW5zIC0gYnV0IHN1Y2hcbiAgLy8gYSB0b2tlbiB3aWxsIGFsd2F5cyBiZSB0aGUgZmlyc3QgYW5kIG9ubHkgdG9rZW4gYW55d2F5KSBhbmQgdGhlbiBqb2luIHRoZW1cbiAgLy8gYW5kIHRoZSB3aGl0ZXNwYWNlIGFyb3VuZCB3b3JkcyBhbmQgcHVuY3R1YXRpb24gd2lsbCBlbmQgdXAgY29ycmVjdC5cbiAgcmV0dXJuIHRva2Vucy5tYXAoKHRva2VuLCBpKSA9PiB7XG4gICAgaWYgKGkgPT0gMCkge1xuICAgICAgcmV0dXJuIHRva2VuO1xuICAgIH0gZWxzZSB7XG4gICAgICByZXR1cm4gdG9rZW4ucmVwbGFjZSgoL15cXHMrLyksICcnKTtcbiAgICB9XG4gIH0pLmpvaW4oJycpO1xufTtcblxud29yZERpZmYucG9zdFByb2Nlc3MgPSBmdW5jdGlvbihjaGFuZ2VzLCBvcHRpb25zKSB7XG4gIGlmICghY2hhbmdlcyB8fCBvcHRpb25zLm9uZUNoYW5nZVBlclRva2VuKSB7XG4gICAgcmV0dXJuIGNoYW5nZXM7XG4gIH1cblxuICBsZXQgbGFzdEtlZXAgPSBudWxsO1xuICAvLyBDaGFuZ2Ugb2JqZWN0cyByZXByZXNlbnRpbmcgYW55IGluc2VydGlvbiBvciBkZWxldGlvbiBzaW5jZSB0aGUgbGFzdFxuICAvLyBcImtlZXBcIiBjaGFuZ2Ugb2JqZWN0LiBUaGVyZSBjYW4gYmUgYXQgbW9zdCBvbmUgb2YgZWFjaC5cbiAgbGV0IGluc2VydGlvbiA9IG51bGw7XG4gIGxldCBkZWxldGlvbiA9IG51bGw7XG4gIGNoYW5nZXMuZm9yRWFjaChjaGFuZ2UgPT4ge1xuICAgIGlmIChjaGFuZ2UuYWRkZWQpIHtcbiAgICAgIGluc2VydGlvbiA9IGNoYW5nZTtcbiAgICB9IGVsc2UgaWYgKGNoYW5nZS5yZW1vdmVkKSB7XG4gICAgICBkZWxldGlvbiA9IGNoYW5nZTtcbiAgICB9IGVsc2Uge1xuICAgICAgaWYgKGluc2VydGlvbiB8fCBkZWxldGlvbikgeyAvLyBNYXkgYmUgZmFsc2UgYXQgc3RhcnQgb2YgdGV4dFxuICAgICAgICBkZWR1cGVXaGl0ZXNwYWNlSW5DaGFuZ2VPYmplY3RzKGxhc3RLZWVwLCBkZWxldGlvbiwgaW5zZXJ0aW9uLCBjaGFuZ2UpO1xuICAgICAgfVxuICAgICAgbGFzdEtlZXAgPSBjaGFuZ2U7XG4gICAgICBpbnNlcnRpb24gPSBudWxsO1xuICAgICAgZGVsZXRpb24gPSBudWxsO1xuICAgIH1cbiAgfSk7XG4gIGlmIChpbnNlcnRpb24gfHwgZGVsZXRpb24pIHtcbiAgICBkZWR1cGVXaGl0ZXNwYWNlSW5DaGFuZ2VPYmplY3RzKGxhc3RLZWVwLCBkZWxldGlvbiwgaW5zZXJ0aW9uLCBudWxsKTtcbiAgfVxuICByZXR1cm4gY2hhbmdlcztcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmV29yZHMob2xkU3RyLCBuZXdTdHIsIG9wdGlvbnMpIHtcbiAgLy8gVGhpcyBvcHRpb24gaGFzIG5ldmVyIGJlZW4gZG9jdW1lbnRlZCBhbmQgbmV2ZXIgd2lsbCBiZSAoaXQncyBjbGVhcmVyIHRvXG4gIC8vIGp1c3QgY2FsbCBgZGlmZldvcmRzV2l0aFNwYWNlYCBkaXJlY3RseSBpZiB5b3UgbmVlZCB0aGF0IGJlaGF2aW9yKSwgYnV0XG4gIC8vIGhhcyBleGlzdGVkIGluIGpzZGlmZiBmb3IgYSBsb25nIHRpbWUsIHNvIHdlIHJldGFpbiBzdXBwb3J0IGZvciBpdCBoZXJlXG4gIC8vIGZvciB0aGUgc2FrZSBvZiBiYWNrd2FyZHMgY29tcGF0aWJpbGl0eS5cbiAgaWYgKG9wdGlvbnM/Lmlnbm9yZVdoaXRlc3BhY2UgIT0gbnVsbCAmJiAhb3B0aW9ucy5pZ25vcmVXaGl0ZXNwYWNlKSB7XG4gICAgcmV0dXJuIGRpZmZXb3Jkc1dpdGhTcGFjZShvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG4gIH1cblxuICByZXR1cm4gd29yZERpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG5cbmZ1bmN0aW9uIGRlZHVwZVdoaXRlc3BhY2VJbkNoYW5nZU9iamVjdHMoc3RhcnRLZWVwLCBkZWxldGlvbiwgaW5zZXJ0aW9uLCBlbmRLZWVwKSB7XG4gIC8vIEJlZm9yZSByZXR1cm5pbmcsIHdlIHRpZHkgdXAgdGhlIGxlYWRpbmcgYW5kIHRyYWlsaW5nIHdoaXRlc3BhY2Ugb2YgdGhlXG4gIC8vIGNoYW5nZSBvYmplY3RzIHRvIGVsaW1pbmF0ZSBjYXNlcyB3aGVyZSB0cmFpbGluZyB3aGl0ZXNwYWNlIGluIG9uZSBvYmplY3RcbiAgLy8gaXMgcmVwZWF0ZWQgYXMgbGVhZGluZyB3aGl0ZXNwYWNlIGluIHRoZSBuZXh0LlxuICAvLyBCZWxvdyBhcmUgZXhhbXBsZXMgb2YgdGhlIG91dGNvbWVzIHdlIHdhbnQgaGVyZSB0byBleHBsYWluIHRoZSBjb2RlLlxuICAvLyBJPWluc2VydCwgSz1rZWVwLCBEPWRlbGV0ZVxuICAvLyAxLiBkaWZmaW5nICdmb28gYmFyIGJheicgdnMgJ2ZvbyBiYXonXG4gIC8vICAgIFByaW9yIHRvIGNsZWFudXAsIHdlIGhhdmUgSzonZm9vICcgRDonIGJhciAnIEs6JyBiYXonXG4gIC8vICAgIEFmdGVyIGNsZWFudXAsIHdlIHdhbnQ6ICAgSzonZm9vICcgRDonYmFyICcgSzonYmF6J1xuICAvL1xuICAvLyAyLiBEaWZmaW5nICdmb28gYmFyIGJheicgdnMgJ2ZvbyBxdXggYmF6J1xuICAvLyAgICBQcmlvciB0byBjbGVhbnVwLCB3ZSBoYXZlIEs6J2ZvbyAnIEQ6JyBiYXIgJyBJOicgcXV4ICcgSzonIGJheidcbiAgLy8gICAgQWZ0ZXIgY2xlYW51cCwgd2Ugd2FudCBLOidmb28gJyBEOidiYXInIEk6J3F1eCcgSzonIGJheidcbiAgLy9cbiAgLy8gMy4gRGlmZmluZyAnZm9vXFxuYmFyIGJheicgdnMgJ2ZvbyBiYXonXG4gIC8vICAgIFByaW9yIHRvIGNsZWFudXAsIHdlIGhhdmUgSzonZm9vICcgRDonXFxuYmFyICcgSzonIGJheidcbiAgLy8gICAgQWZ0ZXIgY2xlYW51cCwgd2Ugd2FudCBLJ2ZvbycgRDonXFxuYmFyJyBLOicgYmF6J1xuICAvL1xuICAvLyA0LiBEaWZmaW5nICdmb28gYmF6JyB2cyAnZm9vXFxuYmFyIGJheidcbiAgLy8gICAgUHJpb3IgdG8gY2xlYW51cCwgd2UgaGF2ZSBLOidmb29cXG4nIEk6J1xcbmJhciAnIEs6JyBiYXonXG4gIC8vICAgIEFmdGVyIGNsZWFudXAsIHdlIGlkZWFsbHkgd2FudCBLJ2ZvbycgSTonXFxuYmFyJyBLOicgYmF6J1xuICAvLyAgICBidXQgZG9uJ3QgYWN0dWFsbHkgbWFuYWdlIHRoaXMgY3VycmVudGx5ICh0aGUgcHJlLWNsZWFudXAgY2hhbmdlXG4gIC8vICAgIG9iamVjdHMgZG9uJ3QgY29udGFpbiBlbm91Z2ggaW5mb3JtYXRpb24gdG8gbWFrZSBpdCBwb3NzaWJsZSkuXG4gIC8vXG4gIC8vIDUuIERpZmZpbmcgJ2ZvbyAgIGJhciBiYXonIHZzICdmb28gIGJheidcbiAgLy8gICAgUHJpb3IgdG8gY2xlYW51cCwgd2UgaGF2ZSBLOidmb28gICcgRDonICAgYmFyICcgSzonICBiYXonXG4gIC8vICAgIEFmdGVyIGNsZWFudXAsIHdlIHdhbnQgSzonZm9vICAnIEQ6JyBiYXIgJyBLOidiYXonXG4gIC8vXG4gIC8vIE91ciBoYW5kbGluZyBpcyB1bmF2b2lkYWJseSBpbXBlcmZlY3QgaW4gdGhlIGNhc2Ugd2hlcmUgdGhlcmUncyBhIHNpbmdsZVxuICAvLyBpbmRlbCBiZXR3ZWVuIGtlZXBzIGFuZCB0aGUgd2hpdGVzcGFjZSBoYXMgY2hhbmdlZC4gRm9yIGluc3RhbmNlLCBjb25zaWRlclxuICAvLyBkaWZmaW5nICdmb29cXHRiYXJcXG5iYXonIHZzICdmb28gYmF6Jy4gVW5sZXNzIHdlIGNyZWF0ZSBhbiBleHRyYSBjaGFuZ2VcbiAgLy8gb2JqZWN0IHRvIHJlcHJlc2VudCB0aGUgaW5zZXJ0aW9uIG9mIHRoZSBzcGFjZSBjaGFyYWN0ZXIgKHdoaWNoIGlzbid0IGV2ZW5cbiAgLy8gYSB0b2tlbiksIHdlIGhhdmUgbm8gd2F5IHRvIGF2b2lkIGxvc2luZyBpbmZvcm1hdGlvbiBhYm91dCB0aGUgdGV4dHMnXG4gIC8vIG9yaWdpbmFsIHdoaXRlc3BhY2UgaW4gdGhlIHJlc3VsdCB3ZSByZXR1cm4uIFN0aWxsLCB3ZSBkbyBvdXIgYmVzdCB0b1xuICAvLyBvdXRwdXQgc29tZXRoaW5nIHRoYXQgd2lsbCBsb29rIHNlbnNpYmxlIGlmIHdlIGUuZy4gcHJpbnQgaXQgd2l0aFxuICAvLyBpbnNlcnRpb25zIGluIGdyZWVuIGFuZCBkZWxldGlvbnMgaW4gcmVkLlxuXG4gIC8vIEJldHdlZW4gdHdvIFwia2VlcFwiIGNoYW5nZSBvYmplY3RzIChvciBiZWZvcmUgdGhlIGZpcnN0IG9yIGFmdGVyIHRoZSBsYXN0XG4gIC8vIGNoYW5nZSBvYmplY3QpLCB3ZSBjYW4gaGF2ZSBlaXRoZXI6XG4gIC8vICogQSBcImRlbGV0ZVwiIGZvbGxvd2VkIGJ5IGFuIFwiaW5zZXJ0XCJcbiAgLy8gKiBKdXN0IGFuIFwiaW5zZXJ0XCJcbiAgLy8gKiBKdXN0IGEgXCJkZWxldGVcIlxuICAvLyBXZSBoYW5kbGUgdGhlIHRocmVlIGNhc2VzIHNlcGFyYXRlbHkuXG4gIGlmIChkZWxldGlvbiAmJiBpbnNlcnRpb24pIHtcbiAgICBjb25zdCBvbGRXc1ByZWZpeCA9IGRlbGV0aW9uLnZhbHVlLm1hdGNoKC9eXFxzKi8pWzBdO1xuICAgIGNvbnN0IG9sZFdzU3VmZml4ID0gZGVsZXRpb24udmFsdWUubWF0Y2goL1xccyokLylbMF07XG4gICAgY29uc3QgbmV3V3NQcmVmaXggPSBpbnNlcnRpb24udmFsdWUubWF0Y2goL15cXHMqLylbMF07XG4gICAgY29uc3QgbmV3V3NTdWZmaXggPSBpbnNlcnRpb24udmFsdWUubWF0Y2goL1xccyokLylbMF07XG5cbiAgICBpZiAoc3RhcnRLZWVwKSB7XG4gICAgICBjb25zdCBjb21tb25Xc1ByZWZpeCA9IGxvbmdlc3RDb21tb25QcmVmaXgob2xkV3NQcmVmaXgsIG5ld1dzUHJlZml4KTtcbiAgICAgIHN0YXJ0S2VlcC52YWx1ZSA9IHJlcGxhY2VTdWZmaXgoc3RhcnRLZWVwLnZhbHVlLCBuZXdXc1ByZWZpeCwgY29tbW9uV3NQcmVmaXgpO1xuICAgICAgZGVsZXRpb24udmFsdWUgPSByZW1vdmVQcmVmaXgoZGVsZXRpb24udmFsdWUsIGNvbW1vbldzUHJlZml4KTtcbiAgICAgIGluc2VydGlvbi52YWx1ZSA9IHJlbW92ZVByZWZpeChpbnNlcnRpb24udmFsdWUsIGNvbW1vbldzUHJlZml4KTtcbiAgICB9XG4gICAgaWYgKGVuZEtlZXApIHtcbiAgICAgIGNvbnN0IGNvbW1vbldzU3VmZml4ID0gbG9uZ2VzdENvbW1vblN1ZmZpeChvbGRXc1N1ZmZpeCwgbmV3V3NTdWZmaXgpO1xuICAgICAgZW5kS2VlcC52YWx1ZSA9IHJlcGxhY2VQcmVmaXgoZW5kS2VlcC52YWx1ZSwgbmV3V3NTdWZmaXgsIGNvbW1vbldzU3VmZml4KTtcbiAgICAgIGRlbGV0aW9uLnZhbHVlID0gcmVtb3ZlU3VmZml4KGRlbGV0aW9uLnZhbHVlLCBjb21tb25Xc1N1ZmZpeCk7XG4gICAgICBpbnNlcnRpb24udmFsdWUgPSByZW1vdmVTdWZmaXgoaW5zZXJ0aW9uLnZhbHVlLCBjb21tb25Xc1N1ZmZpeCk7XG4gICAgfVxuICB9IGVsc2UgaWYgKGluc2VydGlvbikge1xuICAgIC8vIFRoZSB3aGl0ZXNwYWNlcyBhbGwgcmVmbGVjdCB3aGF0IHdhcyBpbiB0aGUgbmV3IHRleHQgcmF0aGVyIHRoYW5cbiAgICAvLyB0aGUgb2xkLCBzbyB3ZSBlc3NlbnRpYWxseSBoYXZlIG5vIGluZm9ybWF0aW9uIGFib3V0IHdoaXRlc3BhY2VcbiAgICAvLyBpbnNlcnRpb24gb3IgZGVsZXRpb24uIFdlIGp1c3Qgd2FudCB0byBkZWR1cGUgdGhlIHdoaXRlc3BhY2UuXG4gICAgLy8gV2UgZG8gdGhhdCBieSBoYXZpbmcgZWFjaCBjaGFuZ2Ugb2JqZWN0IGtlZXAgaXRzIHRyYWlsaW5nXG4gICAgLy8gd2hpdGVzcGFjZSBhbmQgZGVsZXRpbmcgZHVwbGljYXRlIGxlYWRpbmcgd2hpdGVzcGFjZSB3aGVyZVxuICAgIC8vIHByZXNlbnQuXG4gICAgaWYgKHN0YXJ0S2VlcCkge1xuICAgICAgaW5zZXJ0aW9uLnZhbHVlID0gaW5zZXJ0aW9uLnZhbHVlLnJlcGxhY2UoL15cXHMqLywgJycpO1xuICAgIH1cbiAgICBpZiAoZW5kS2VlcCkge1xuICAgICAgZW5kS2VlcC52YWx1ZSA9IGVuZEtlZXAudmFsdWUucmVwbGFjZSgvXlxccyovLCAnJyk7XG4gICAgfVxuICAvLyBvdGhlcndpc2Ugd2UndmUgZ290IGEgZGVsZXRpb24gYW5kIG5vIGluc2VydGlvblxuICB9IGVsc2UgaWYgKHN0YXJ0S2VlcCAmJiBlbmRLZWVwKSB7XG4gICAgY29uc3QgbmV3V3NGdWxsID0gZW5kS2VlcC52YWx1ZS5tYXRjaCgvXlxccyovKVswXSxcbiAgICAgICAgZGVsV3NTdGFydCA9IGRlbGV0aW9uLnZhbHVlLm1hdGNoKC9eXFxzKi8pWzBdLFxuICAgICAgICBkZWxXc0VuZCA9IGRlbGV0aW9uLnZhbHVlLm1hdGNoKC9cXHMqJC8pWzBdO1xuXG4gICAgLy8gQW55IHdoaXRlc3BhY2UgdGhhdCBjb21lcyBzdHJhaWdodCBhZnRlciBzdGFydEtlZXAgaW4gYm90aCB0aGUgb2xkIGFuZFxuICAgIC8vIG5ldyB0ZXh0cywgYXNzaWduIHRvIHN0YXJ0S2VlcCBhbmQgcmVtb3ZlIGZyb20gdGhlIGRlbGV0aW9uLlxuICAgIGNvbnN0IG5ld1dzU3RhcnQgPSBsb25nZXN0Q29tbW9uUHJlZml4KG5ld1dzRnVsbCwgZGVsV3NTdGFydCk7XG4gICAgZGVsZXRpb24udmFsdWUgPSByZW1vdmVQcmVmaXgoZGVsZXRpb24udmFsdWUsIG5ld1dzU3RhcnQpO1xuXG4gICAgLy8gQW55IHdoaXRlc3BhY2UgdGhhdCBjb21lcyBzdHJhaWdodCBiZWZvcmUgZW5kS2VlcCBpbiBib3RoIHRoZSBvbGQgYW5kXG4gICAgLy8gbmV3IHRleHRzLCBhbmQgaGFzbid0IGFscmVhZHkgYmVlbiBhc3NpZ25lZCB0byBzdGFydEtlZXAsIGFzc2lnbiB0b1xuICAgIC8vIGVuZEtlZXAgYW5kIHJlbW92ZSBmcm9tIHRoZSBkZWxldGlvbi5cbiAgICBjb25zdCBuZXdXc0VuZCA9IGxvbmdlc3RDb21tb25TdWZmaXgoXG4gICAgICByZW1vdmVQcmVmaXgobmV3V3NGdWxsLCBuZXdXc1N0YXJ0KSxcbiAgICAgIGRlbFdzRW5kXG4gICAgKTtcbiAgICBkZWxldGlvbi52YWx1ZSA9IHJlbW92ZVN1ZmZpeChkZWxldGlvbi52YWx1ZSwgbmV3V3NFbmQpO1xuICAgIGVuZEtlZXAudmFsdWUgPSByZXBsYWNlUHJlZml4KGVuZEtlZXAudmFsdWUsIG5ld1dzRnVsbCwgbmV3V3NFbmQpO1xuXG4gICAgLy8gSWYgdGhlcmUncyBhbnkgd2hpdGVzcGFjZSBmcm9tIHRoZSBuZXcgdGV4dCB0aGF0IEhBU04nVCBhbHJlYWR5IGJlZW5cbiAgICAvLyBhc3NpZ25lZCwgYXNzaWduIGl0IHRvIHRoZSBzdGFydDpcbiAgICBzdGFydEtlZXAudmFsdWUgPSByZXBsYWNlU3VmZml4KFxuICAgICAgc3RhcnRLZWVwLnZhbHVlLFxuICAgICAgbmV3V3NGdWxsLFxuICAgICAgbmV3V3NGdWxsLnNsaWNlKDAsIG5ld1dzRnVsbC5sZW5ndGggLSBuZXdXc0VuZC5sZW5ndGgpXG4gICAgKTtcbiAgfSBlbHNlIGlmIChlbmRLZWVwKSB7XG4gICAgLy8gV2UgYXJlIGF0IHRoZSBzdGFydCBvZiB0aGUgdGV4dC4gUHJlc2VydmUgYWxsIHRoZSB3aGl0ZXNwYWNlIG9uXG4gICAgLy8gZW5kS2VlcCwgYW5kIGp1c3QgcmVtb3ZlIHdoaXRlc3BhY2UgZnJvbSB0aGUgZW5kIG9mIGRlbGV0aW9uIHRvIHRoZVxuICAgIC8vIGV4dGVudCB0aGF0IGl0IG92ZXJsYXBzIHdpdGggdGhlIHN0YXJ0IG9mIGVuZEtlZXAuXG4gICAgY29uc3QgZW5kS2VlcFdzUHJlZml4ID0gZW5kS2VlcC52YWx1ZS5tYXRjaCgvXlxccyovKVswXTtcbiAgICBjb25zdCBkZWxldGlvbldzU3VmZml4ID0gZGVsZXRpb24udmFsdWUubWF0Y2goL1xccyokLylbMF07XG4gICAgY29uc3Qgb3ZlcmxhcCA9IG1heGltdW1PdmVybGFwKGRlbGV0aW9uV3NTdWZmaXgsIGVuZEtlZXBXc1ByZWZpeCk7XG4gICAgZGVsZXRpb24udmFsdWUgPSByZW1vdmVTdWZmaXgoZGVsZXRpb24udmFsdWUsIG92ZXJsYXApO1xuICB9IGVsc2UgaWYgKHN0YXJ0S2VlcCkge1xuICAgIC8vIFdlIGFyZSBhdCB0aGUgRU5EIG9mIHRoZSB0ZXh0LiBQcmVzZXJ2ZSBhbGwgdGhlIHdoaXRlc3BhY2Ugb25cbiAgICAvLyBzdGFydEtlZXAsIGFuZCBqdXN0IHJlbW92ZSB3aGl0ZXNwYWNlIGZyb20gdGhlIHN0YXJ0IG9mIGRlbGV0aW9uIHRvXG4gICAgLy8gdGhlIGV4dGVudCB0aGF0IGl0IG92ZXJsYXBzIHdpdGggdGhlIGVuZCBvZiBzdGFydEtlZXAuXG4gICAgY29uc3Qgc3RhcnRLZWVwV3NTdWZmaXggPSBzdGFydEtlZXAudmFsdWUubWF0Y2goL1xccyokLylbMF07XG4gICAgY29uc3QgZGVsZXRpb25Xc1ByZWZpeCA9IGRlbGV0aW9uLnZhbHVlLm1hdGNoKC9eXFxzKi8pWzBdO1xuICAgIGNvbnN0IG92ZXJsYXAgPSBtYXhpbXVtT3ZlcmxhcChzdGFydEtlZXBXc1N1ZmZpeCwgZGVsZXRpb25Xc1ByZWZpeCk7XG4gICAgZGVsZXRpb24udmFsdWUgPSByZW1vdmVQcmVmaXgoZGVsZXRpb24udmFsdWUsIG92ZXJsYXApO1xuICB9XG59XG5cblxuZXhwb3J0IGNvbnN0IHdvcmRXaXRoU3BhY2VEaWZmID0gbmV3IERpZmYoKTtcbndvcmRXaXRoU3BhY2VEaWZmLnRva2VuaXplID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgLy8gU2xpZ2h0bHkgZGlmZmVyZW50IHRvIHRoZSB0b2tlbml6ZUluY2x1ZGluZ1doaXRlc3BhY2UgcmVnZXggdXNlZCBhYm92ZSBpblxuICAvLyB0aGF0IHRoaXMgb25lIHRyZWF0cyBlYWNoIGluZGl2aWR1YWwgbmV3bGluZSBhcyBhIGRpc3RpbmN0IHRva2VucywgcmF0aGVyXG4gIC8vIHRoYW4gbWVyZ2luZyB0aGVtIGludG8gb3RoZXIgc3Vycm91bmRpbmcgd2hpdGVzcGFjZS4gVGhpcyB3YXMgcmVxdWVzdGVkXG4gIC8vIGluIGh0dHBzOi8vZ2l0aHViLmNvbS9rcGRlY2tlci9qc2RpZmYvaXNzdWVzLzE4MCAmXG4gIC8vICAgIGh0dHBzOi8vZ2l0aHViLmNvbS9rcGRlY2tlci9qc2RpZmYvaXNzdWVzLzIxMVxuICBjb25zdCByZWdleCA9IG5ldyBSZWdFeHAoYChcXFxccj9cXFxcbil8WyR7ZXh0ZW5kZWRXb3JkQ2hhcnN9XSt8W15cXFxcU1xcXFxuXFxcXHJdK3xbXiR7ZXh0ZW5kZWRXb3JkQ2hhcnN9XWAsICd1ZycpO1xuICByZXR1cm4gdmFsdWUubWF0Y2gocmVnZXgpIHx8IFtdO1xufTtcbmV4cG9ydCBmdW5jdGlvbiBkaWZmV29yZHNXaXRoU3BhY2Uob2xkU3RyLCBuZXdTdHIsIG9wdGlvbnMpIHtcbiAgcmV0dXJuIHdvcmRXaXRoU3BhY2VEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIG9wdGlvbnMpO1xufVxuIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBQSxLQUFBLEdBQUFDLHNCQUFBLENBQUFDLE9BQUE7QUFBQTtBQUFBO0FBQ0E7QUFBQTtBQUFBQyxPQUFBLEdBQUFELE9BQUE7QUFBQTtBQUFBO0FBQW9KLG1DQUFBRCx1QkFBQUcsR0FBQSxXQUFBQSxHQUFBLElBQUFBLEdBQUEsQ0FBQUMsVUFBQSxHQUFBRCxHQUFBLGdCQUFBQSxHQUFBO0FBQUE7QUFFcEo7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBTUUsaUJBQWlCLEdBQUcsK0dBQStHOztBQUV6STtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBTUMsMkJBQTJCLEdBQUcsSUFBSUMsTUFBTTtBQUFBO0FBQUEsSUFBQUMsTUFBQTtBQUFBO0FBQUtILGlCQUFpQixnQkFBQUcsTUFBQSxDQUFhSCxpQkFBaUIsUUFBSyxJQUFJLENBQUM7QUFFckcsSUFBTUksUUFBUTtBQUFBO0FBQUFDLE9BQUEsQ0FBQUQsUUFBQTtBQUFBO0FBQUc7QUFBSUU7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSSxDQUFDLENBQUM7QUFDbENGLFFBQVEsQ0FBQ0csTUFBTSxHQUFHLFVBQVNDLElBQUksRUFBRUMsS0FBSyxFQUFFQyxPQUFPLEVBQUU7RUFDL0MsSUFBSUEsT0FBTyxDQUFDQyxVQUFVLEVBQUU7SUFDdEJILElBQUksR0FBR0EsSUFBSSxDQUFDSSxXQUFXLENBQUMsQ0FBQztJQUN6QkgsS0FBSyxHQUFHQSxLQUFLLENBQUNHLFdBQVcsQ0FBQyxDQUFDO0VBQzdCO0VBRUEsT0FBT0osSUFBSSxDQUFDSyxJQUFJLENBQUMsQ0FBQyxLQUFLSixLQUFLLENBQUNJLElBQUksQ0FBQyxDQUFDO0FBQ3JDLENBQUM7QUFFRFQsUUFBUSxDQUFDVSxRQUFRLEdBQUcsVUFBU0MsS0FBSyxFQUFnQjtFQUFBO0VBQUE7RUFBQTtFQUFkTCxPQUFPLEdBQUFNLFNBQUEsQ0FBQUMsTUFBQSxRQUFBRCxTQUFBLFFBQUFFLFNBQUEsR0FBQUYsU0FBQSxNQUFHLENBQUMsQ0FBQztFQUM5QyxJQUFJRyxLQUFLO0VBQ1QsSUFBSVQsT0FBTyxDQUFDVSxhQUFhLEVBQUU7SUFDekIsSUFBSVYsT0FBTyxDQUFDVSxhQUFhLENBQUNDLGVBQWUsQ0FBQyxDQUFDLENBQUNDLFdBQVcsSUFBSSxNQUFNLEVBQUU7TUFDakUsTUFBTSxJQUFJQyxLQUFLLENBQUMsd0RBQXdELENBQUM7SUFDM0U7SUFDQUosS0FBSyxHQUFHSyxLQUFLLENBQUNDLElBQUksQ0FBQ2YsT0FBTyxDQUFDVSxhQUFhLENBQUNNLE9BQU8sQ0FBQ1gsS0FBSyxDQUFDLEVBQUUsVUFBQVcsT0FBTztJQUFBO0lBQUE7TUFBQTtRQUFBO1FBQUlBLE9BQU8sQ0FBQ0E7TUFBTztJQUFBLEVBQUM7RUFDdEYsQ0FBQyxNQUFNO0lBQ0xQLEtBQUssR0FBR0osS0FBSyxDQUFDWSxLQUFLLENBQUMxQiwyQkFBMkIsQ0FBQyxJQUFJLEVBQUU7RUFDeEQ7RUFDQSxJQUFNMkIsTUFBTSxHQUFHLEVBQUU7RUFDakIsSUFBSUMsUUFBUSxHQUFHLElBQUk7RUFDbkJWLEtBQUssQ0FBQ1csT0FBTyxDQUFDLFVBQUFDLElBQUksRUFBSTtJQUNwQixJQUFLLElBQUksQ0FBRUMsSUFBSSxDQUFDRCxJQUFJLENBQUMsRUFBRTtNQUNyQixJQUFJRixRQUFRLElBQUksSUFBSSxFQUFFO1FBQ3BCRCxNQUFNLENBQUNLLElBQUksQ0FBQ0YsSUFBSSxDQUFDO01BQ25CLENBQUMsTUFBTTtRQUNMSCxNQUFNLENBQUNLLElBQUksQ0FBQ0wsTUFBTSxDQUFDTSxHQUFHLENBQUMsQ0FBQyxHQUFHSCxJQUFJLENBQUM7TUFDbEM7SUFDRixDQUFDLE1BQU0sSUFBSyxJQUFJLENBQUVDLElBQUksQ0FBQ0gsUUFBUSxDQUFDLEVBQUU7TUFDaEMsSUFBSUQsTUFBTSxDQUFDQSxNQUFNLENBQUNYLE1BQU0sR0FBRyxDQUFDLENBQUMsSUFBSVksUUFBUSxFQUFFO1FBQ3pDRCxNQUFNLENBQUNLLElBQUksQ0FBQ0wsTUFBTSxDQUFDTSxHQUFHLENBQUMsQ0FBQyxHQUFHSCxJQUFJLENBQUM7TUFDbEMsQ0FBQyxNQUFNO1FBQ0xILE1BQU0sQ0FBQ0ssSUFBSSxDQUFDSixRQUFRLEdBQUdFLElBQUksQ0FBQztNQUM5QjtJQUNGLENBQUMsTUFBTTtNQUNMSCxNQUFNLENBQUNLLElBQUksQ0FBQ0YsSUFBSSxDQUFDO0lBQ25CO0lBRUFGLFFBQVEsR0FBR0UsSUFBSTtFQUNqQixDQUFDLENBQUM7RUFDRixPQUFPSCxNQUFNO0FBQ2YsQ0FBQztBQUVEeEIsUUFBUSxDQUFDK0IsSUFBSSxHQUFHLFVBQVNQLE1BQU0sRUFBRTtFQUMvQjtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0EsT0FBT0EsTUFBTSxDQUFDUSxHQUFHLENBQUMsVUFBQ0MsS0FBSyxFQUFFQyxDQUFDLEVBQUs7SUFDOUIsSUFBSUEsQ0FBQyxJQUFJLENBQUMsRUFBRTtNQUNWLE9BQU9ELEtBQUs7SUFDZCxDQUFDLE1BQU07TUFDTCxPQUFPQSxLQUFLLENBQUNFLE9BQU8sQ0FBRSxNQUFNLEVBQUcsRUFBRSxDQUFDO0lBQ3BDO0VBQ0YsQ0FBQyxDQUFDLENBQUNKLElBQUksQ0FBQyxFQUFFLENBQUM7QUFDYixDQUFDO0FBRUQvQixRQUFRLENBQUNvQyxXQUFXLEdBQUcsVUFBU0MsT0FBTyxFQUFFL0IsT0FBTyxFQUFFO0VBQ2hELElBQUksQ0FBQytCLE9BQU8sSUFBSS9CLE9BQU8sQ0FBQ2dDLGlCQUFpQixFQUFFO0lBQ3pDLE9BQU9ELE9BQU87RUFDaEI7RUFFQSxJQUFJRSxRQUFRLEdBQUcsSUFBSTtFQUNuQjtFQUNBO0VBQ0EsSUFBSUMsU0FBUyxHQUFHLElBQUk7RUFDcEIsSUFBSUMsUUFBUSxHQUFHLElBQUk7RUFDbkJKLE9BQU8sQ0FBQ1gsT0FBTyxDQUFDLFVBQUFnQixNQUFNLEVBQUk7SUFDeEIsSUFBSUEsTUFBTSxDQUFDQyxLQUFLLEVBQUU7TUFDaEJILFNBQVMsR0FBR0UsTUFBTTtJQUNwQixDQUFDLE1BQU0sSUFBSUEsTUFBTSxDQUFDRSxPQUFPLEVBQUU7TUFDekJILFFBQVEsR0FBR0MsTUFBTTtJQUNuQixDQUFDLE1BQU07TUFDTCxJQUFJRixTQUFTLElBQUlDLFFBQVEsRUFBRTtRQUFFO1FBQzNCSSwrQkFBK0IsQ0FBQ04sUUFBUSxFQUFFRSxRQUFRLEVBQUVELFNBQVMsRUFBRUUsTUFBTSxDQUFDO01BQ3hFO01BQ0FILFFBQVEsR0FBR0csTUFBTTtNQUNqQkYsU0FBUyxHQUFHLElBQUk7TUFDaEJDLFFBQVEsR0FBRyxJQUFJO0lBQ2pCO0VBQ0YsQ0FBQyxDQUFDO0VBQ0YsSUFBSUQsU0FBUyxJQUFJQyxRQUFRLEVBQUU7SUFDekJJLCtCQUErQixDQUFDTixRQUFRLEVBQUVFLFFBQVEsRUFBRUQsU0FBUyxFQUFFLElBQUksQ0FBQztFQUN0RTtFQUNBLE9BQU9ILE9BQU87QUFDaEIsQ0FBQztBQUVNLFNBQVNTLFNBQVNBLENBQUNDLE1BQU0sRUFBRUMsTUFBTSxFQUFFMUMsT0FBTyxFQUFFO0VBQ2pEO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFBSTtFQUFBO0VBQUE7RUFBQUEsT0FBTyxhQUFQQSxPQUFPLHVCQUFQQSxPQUFPLENBQUUyQyxnQkFBZ0IsS0FBSSxJQUFJLElBQUksQ0FBQzNDLE9BQU8sQ0FBQzJDLGdCQUFnQixFQUFFO0lBQ2xFLE9BQU9DLGtCQUFrQixDQUFDSCxNQUFNLEVBQUVDLE1BQU0sRUFBRTFDLE9BQU8sQ0FBQztFQUNwRDtFQUVBLE9BQU9OLFFBQVEsQ0FBQ21ELElBQUksQ0FBQ0osTUFBTSxFQUFFQyxNQUFNLEVBQUUxQyxPQUFPLENBQUM7QUFDL0M7QUFFQSxTQUFTdUMsK0JBQStCQSxDQUFDTyxTQUFTLEVBQUVYLFFBQVEsRUFBRUQsU0FBUyxFQUFFYSxPQUFPLEVBQUU7RUFDaEY7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQTs7RUFFQTtFQUNBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQSxJQUFJWixRQUFRLElBQUlELFNBQVMsRUFBRTtJQUN6QixJQUFNYyxXQUFXLEdBQUdiLFFBQVEsQ0FBQzlCLEtBQUssQ0FBQ1ksS0FBSyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUNuRCxJQUFNZ0MsV0FBVyxHQUFHZCxRQUFRLENBQUM5QixLQUFLLENBQUNZLEtBQUssQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDbkQsSUFBTWlDLFdBQVcsR0FBR2hCLFNBQVMsQ0FBQzdCLEtBQUssQ0FBQ1ksS0FBSyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUNwRCxJQUFNa0MsV0FBVyxHQUFHakIsU0FBUyxDQUFDN0IsS0FBSyxDQUFDWSxLQUFLLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBRXBELElBQUk2QixTQUFTLEVBQUU7TUFDYixJQUFNTSxjQUFjO01BQUc7TUFBQTtNQUFBO01BQUFDO01BQUFBO01BQUFBO01BQUFBO01BQUFBO01BQUFBLG1CQUFtQjtNQUFBO01BQUEsQ0FBQ0wsV0FBVyxFQUFFRSxXQUFXLENBQUM7TUFDcEVKLFNBQVMsQ0FBQ3pDLEtBQUs7TUFBRztNQUFBO01BQUE7TUFBQWlEO01BQUFBO01BQUFBO01BQUFBO01BQUFBO01BQUFBLGFBQWE7TUFBQTtNQUFBLENBQUNSLFNBQVMsQ0FBQ3pDLEtBQUssRUFBRTZDLFdBQVcsRUFBRUUsY0FBYyxDQUFDO01BQzdFakIsUUFBUSxDQUFDOUIsS0FBSztNQUFHO01BQUE7TUFBQTtNQUFBa0Q7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUEsWUFBWTtNQUFBO01BQUEsQ0FBQ3BCLFFBQVEsQ0FBQzlCLEtBQUssRUFBRStDLGNBQWMsQ0FBQztNQUM3RGxCLFNBQVMsQ0FBQzdCLEtBQUs7TUFBRztNQUFBO01BQUE7TUFBQWtEO01BQUFBO01BQUFBO01BQUFBO01BQUFBO01BQUFBLFlBQVk7TUFBQTtNQUFBLENBQUNyQixTQUFTLENBQUM3QixLQUFLLEVBQUUrQyxjQUFjLENBQUM7SUFDakU7SUFDQSxJQUFJTCxPQUFPLEVBQUU7TUFDWCxJQUFNUyxjQUFjO01BQUc7TUFBQTtNQUFBO01BQUFDO01BQUFBO01BQUFBO01BQUFBO01BQUFBO01BQUFBLG1CQUFtQjtNQUFBO01BQUEsQ0FBQ1IsV0FBVyxFQUFFRSxXQUFXLENBQUM7TUFDcEVKLE9BQU8sQ0FBQzFDLEtBQUs7TUFBRztNQUFBO01BQUE7TUFBQXFEO01BQUFBO01BQUFBO01BQUFBO01BQUFBO01BQUFBLGFBQWE7TUFBQTtNQUFBLENBQUNYLE9BQU8sQ0FBQzFDLEtBQUssRUFBRThDLFdBQVcsRUFBRUssY0FBYyxDQUFDO01BQ3pFckIsUUFBUSxDQUFDOUIsS0FBSztNQUFHO01BQUE7TUFBQTtNQUFBc0Q7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUEsWUFBWTtNQUFBO01BQUEsQ0FBQ3hCLFFBQVEsQ0FBQzlCLEtBQUssRUFBRW1ELGNBQWMsQ0FBQztNQUM3RHRCLFNBQVMsQ0FBQzdCLEtBQUs7TUFBRztNQUFBO01BQUE7TUFBQXNEO01BQUFBO01BQUFBO01BQUFBO01BQUFBO01BQUFBLFlBQVk7TUFBQTtNQUFBLENBQUN6QixTQUFTLENBQUM3QixLQUFLLEVBQUVtRCxjQUFjLENBQUM7SUFDakU7RUFDRixDQUFDLE1BQU0sSUFBSXRCLFNBQVMsRUFBRTtJQUNwQjtJQUNBO0lBQ0E7SUFDQTtJQUNBO0lBQ0E7SUFDQSxJQUFJWSxTQUFTLEVBQUU7TUFDYlosU0FBUyxDQUFDN0IsS0FBSyxHQUFHNkIsU0FBUyxDQUFDN0IsS0FBSyxDQUFDd0IsT0FBTyxDQUFDLE1BQU0sRUFBRSxFQUFFLENBQUM7SUFDdkQ7SUFDQSxJQUFJa0IsT0FBTyxFQUFFO01BQ1hBLE9BQU8sQ0FBQzFDLEtBQUssR0FBRzBDLE9BQU8sQ0FBQzFDLEtBQUssQ0FBQ3dCLE9BQU8sQ0FBQyxNQUFNLEVBQUUsRUFBRSxDQUFDO0lBQ25EO0lBQ0Y7RUFDQSxDQUFDLE1BQU0sSUFBSWlCLFNBQVMsSUFBSUMsT0FBTyxFQUFFO0lBQy9CLElBQU1hLFNBQVMsR0FBR2IsT0FBTyxDQUFDMUMsS0FBSyxDQUFDWSxLQUFLLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO01BQzVDNEMsVUFBVSxHQUFHMUIsUUFBUSxDQUFDOUIsS0FBSyxDQUFDWSxLQUFLLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO01BQzVDNkMsUUFBUSxHQUFHM0IsUUFBUSxDQUFDOUIsS0FBSyxDQUFDWSxLQUFLLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDOztJQUU5QztJQUNBO0lBQ0EsSUFBTThDLFVBQVU7SUFBRztJQUFBO0lBQUE7SUFBQVY7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsbUJBQW1CO0lBQUE7SUFBQSxDQUFDTyxTQUFTLEVBQUVDLFVBQVUsQ0FBQztJQUM3RDFCLFFBQVEsQ0FBQzlCLEtBQUs7SUFBRztJQUFBO0lBQUE7SUFBQWtEO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBLFlBQVk7SUFBQTtJQUFBLENBQUNwQixRQUFRLENBQUM5QixLQUFLLEVBQUUwRCxVQUFVLENBQUM7O0lBRXpEO0lBQ0E7SUFDQTtJQUNBLElBQU1DLFFBQVE7SUFBRztJQUFBO0lBQUE7SUFBQVA7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsbUJBQW1CO0lBQUE7SUFBQTtJQUNsQztJQUFBO0lBQUE7SUFBQUY7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsWUFBWTtJQUFBO0lBQUEsQ0FBQ0ssU0FBUyxFQUFFRyxVQUFVLENBQUMsRUFDbkNELFFBQ0YsQ0FBQztJQUNEM0IsUUFBUSxDQUFDOUIsS0FBSztJQUFHO0lBQUE7SUFBQTtJQUFBc0Q7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsWUFBWTtJQUFBO0lBQUEsQ0FBQ3hCLFFBQVEsQ0FBQzlCLEtBQUssRUFBRTJELFFBQVEsQ0FBQztJQUN2RGpCLE9BQU8sQ0FBQzFDLEtBQUs7SUFBRztJQUFBO0lBQUE7SUFBQXFEO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBLGFBQWE7SUFBQTtJQUFBLENBQUNYLE9BQU8sQ0FBQzFDLEtBQUssRUFBRXVELFNBQVMsRUFBRUksUUFBUSxDQUFDOztJQUVqRTtJQUNBO0lBQ0FsQixTQUFTLENBQUN6QyxLQUFLO0lBQUc7SUFBQTtJQUFBO0lBQUFpRDtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQSxhQUFhO0lBQUE7SUFBQSxDQUM3QlIsU0FBUyxDQUFDekMsS0FBSyxFQUNmdUQsU0FBUyxFQUNUQSxTQUFTLENBQUNLLEtBQUssQ0FBQyxDQUFDLEVBQUVMLFNBQVMsQ0FBQ3JELE1BQU0sR0FBR3lELFFBQVEsQ0FBQ3pELE1BQU0sQ0FDdkQsQ0FBQztFQUNILENBQUMsTUFBTSxJQUFJd0MsT0FBTyxFQUFFO0lBQ2xCO0lBQ0E7SUFDQTtJQUNBLElBQU1tQixlQUFlLEdBQUduQixPQUFPLENBQUMxQyxLQUFLLENBQUNZLEtBQUssQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDdEQsSUFBTWtELGdCQUFnQixHQUFHaEMsUUFBUSxDQUFDOUIsS0FBSyxDQUFDWSxLQUFLLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBQ3hELElBQU1tRCxPQUFPO0lBQUc7SUFBQTtJQUFBO0lBQUFDO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBLGNBQWM7SUFBQTtJQUFBLENBQUNGLGdCQUFnQixFQUFFRCxlQUFlLENBQUM7SUFDakUvQixRQUFRLENBQUM5QixLQUFLO0lBQUc7SUFBQTtJQUFBO0lBQUFzRDtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQSxZQUFZO0lBQUE7SUFBQSxDQUFDeEIsUUFBUSxDQUFDOUIsS0FBSyxFQUFFK0QsT0FBTyxDQUFDO0VBQ3hELENBQUMsTUFBTSxJQUFJdEIsU0FBUyxFQUFFO0lBQ3BCO0lBQ0E7SUFDQTtJQUNBLElBQU13QixpQkFBaUIsR0FBR3hCLFNBQVMsQ0FBQ3pDLEtBQUssQ0FBQ1ksS0FBSyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUMxRCxJQUFNc0QsZ0JBQWdCLEdBQUdwQyxRQUFRLENBQUM5QixLQUFLLENBQUNZLEtBQUssQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDeEQsSUFBTW1ELFFBQU87SUFBRztJQUFBO0lBQUE7SUFBQUM7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsY0FBYztJQUFBO0lBQUEsQ0FBQ0MsaUJBQWlCLEVBQUVDLGdCQUFnQixDQUFDO0lBQ25FcEMsUUFBUSxDQUFDOUIsS0FBSztJQUFHO0lBQUE7SUFBQTtJQUFBa0Q7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsWUFBWTtJQUFBO0lBQUEsQ0FBQ3BCLFFBQVEsQ0FBQzlCLEtBQUssRUFBRStELFFBQU8sQ0FBQztFQUN4RDtBQUNGO0FBR08sSUFBTUksaUJBQWlCO0FBQUE7QUFBQTdFLE9BQUEsQ0FBQTZFLGlCQUFBO0FBQUE7QUFBRztBQUFJNUU7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSSxDQUFDLENBQUM7QUFDM0M0RSxpQkFBaUIsQ0FBQ3BFLFFBQVEsR0FBRyxVQUFTQyxLQUFLLEVBQUU7RUFDM0M7RUFDQTtFQUNBO0VBQ0E7RUFDQTtFQUNBLElBQU1vRSxLQUFLLEdBQUcsSUFBSWpGLE1BQU07RUFBQTtFQUFBLGNBQUFDLE1BQUE7RUFBQTtFQUFlSCxpQkFBaUIseUJBQUFHLE1BQUEsQ0FBc0JILGlCQUFpQixRQUFLLElBQUksQ0FBQztFQUN6RyxPQUFPZSxLQUFLLENBQUNZLEtBQUssQ0FBQ3dELEtBQUssQ0FBQyxJQUFJLEVBQUU7QUFDakMsQ0FBQztBQUNNLFNBQVM3QixrQkFBa0JBLENBQUNILE1BQU0sRUFBRUMsTUFBTSxFQUFFMUMsT0FBTyxFQUFFO0VBQzFELE9BQU93RSxpQkFBaUIsQ0FBQzNCLElBQUksQ0FBQ0osTUFBTSxFQUFFQyxNQUFNLEVBQUUxQyxPQUFPLENBQUM7QUFDeEQiLCJpZ25vcmVMaXN0IjpbXX0= function Diff() {} Diff.prototype = { diff: function diff(oldString, newString) { var _options$timeout; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } var self = this; function done(value) { value = self.postProcess(value, options); if (callback) { setTimeout(function () { callback(value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString, options); newString = this.castInput(newString, options); oldString = this.removeEmpty(this.tokenize(oldString, options)); newString = this.removeEmpty(this.tokenize(newString, options)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; if (options.maxEditLength != null) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; var abortAfterTimestamp = Date.now() + maxExecutionTime; var bestPath = [{ oldPos: -1, lastComponent: undefined }]; // Seed editLength = 0, i.e. the content starts with the same values var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // Identity per the equality and tokenizer return done(buildValues(self, bestPath[0].lastComponent, newString, oldString, self.useLongestToken)); } // Once we hit the right edge of the edit graph on some diagonal k, we can // definitely reach the end of the edit graph in no more than k edits, so // there's no point in considering any moves to diagonal k+1 any more (from // which we're guaranteed to need at least k+1 more edits). // Similarly, once we've reached the bottom of the edit graph, there's no // point considering moves to lower diagonals. // We record this fact by setting minDiagonalToConsider and // maxDiagonalToConsider to some finite value once we've hit the edge of // the edit graph. // This optimization is not faithful to the original algorithm presented in // Myers's paper, which instead pointlessly extends D-paths off the end of // the edit graph - see page 7 of Myers's paper which notes this point // explicitly and illustrates it with a diagram. This has major performance // implications for some common scenarios. For instance, to compute a diff // where the new text simply appends d characters on the end of the // original text of length n, the true Myers algorithm will take O(n+d^2) // time while this optimization needs only O(n+d) time. var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { var basePath = void 0; var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = false; if (addPath) { // what newPos will be after we do an insertion: var addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } var canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the old string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { basePath = self.addToPath(addPath, true, false, 0, options); } else { basePath = self.addToPath(removePath, false, true, 1, options); } newPos = self.extractCommon(basePath, newString, oldString, diagonalPath, options); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // If we have hit the end of both strings, then we are done return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken)); } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced, or until the edit length exceeds options.maxEditLength (if given), // in which case it will return undefined. if (callback) { (function exec() { setTimeout(function () { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { var ret = execEditLength(); if (ret) { return ret; } } } }, addToPath: function addToPath(path, added, removed, oldPosInc, options) { var last = path.lastComponent; if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath, options) { var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options)) { newPos++; oldPos++; commonCount++; if (options.oneChangePerToken) { basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; } } if (commonCount && !options.oneChangePerToken) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; } basePath.oldPos = oldPos; return newPos; }, equals: function equals(left, right, options) { if (options.comparator) { return options.comparator(left, right); } else { return left === right || options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return Array.from(value); }, join: function join(chars) { return chars.join(''); }, postProcess: function postProcess(changeObjects) { return changeObjects; } }; function buildValues(diff, lastComponent, newString, oldString, useLongestToken) { // First we convert our linked list of components in reverse order to an // array in the right order: var components = []; var nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; } } return components; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function longestCommonPrefix(str1, str2) { var i; for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[i] != str2[i]) { return str1.slice(0, i); } } return str1.slice(0, i); } function longestCommonSuffix(str1, str2) { var i; // Unlike longestCommonPrefix, we need a special case to handle all scenarios // where we return the empty string since str1.slice(-0) will return the // entire string. if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) { return ''; } for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) { return str1.slice(-i); } } return str1.slice(-i); } function replacePrefix(string, oldPrefix, newPrefix) { if (string.slice(0, oldPrefix.length) != oldPrefix) { throw Error("string ".concat(JSON.stringify(string), " doesn't start with prefix ").concat(JSON.stringify(oldPrefix), "; this is a bug")); } return newPrefix + string.slice(oldPrefix.length); } function replaceSuffix(string, oldSuffix, newSuffix) { if (!oldSuffix) { return string + newSuffix; } if (string.slice(-oldSuffix.length) != oldSuffix) { throw Error("string ".concat(JSON.stringify(string), " doesn't end with suffix ").concat(JSON.stringify(oldSuffix), "; this is a bug")); } return string.slice(0, -oldSuffix.length) + newSuffix; } function removePrefix(string, oldPrefix) { return replacePrefix(string, oldPrefix, ''); } function removeSuffix(string, oldSuffix) { return replaceSuffix(string, oldSuffix, ''); } function maximumOverlap(string1, string2) { return string2.slice(0, overlapCount(string1, string2)); } // Nicked from https://stackoverflow.com/a/60422853/1709587 function overlapCount(a, b) { // Deal with cases where the strings differ in length var startA = 0; if (a.length > b.length) { startA = a.length - b.length; } var endB = b.length; if (a.length < b.length) { endB = a.length; } // Create a back-reference for each index // that should be followed in case of a mismatch. // We only need B to make these references: var map = Array(endB); var k = 0; // Index that lags behind j map[0] = 0; for (var j = 1; j < endB; j++) { if (b[j] == b[k]) { map[j] = map[k]; // skip over the same character (optional optimisation) } else { map[j] = k; } while (k > 0 && b[j] != b[k]) { k = map[k]; } if (b[j] == b[k]) { k++; } } // Phase 2: use these references while iterating over A k = 0; for (var i = startA; i < a.length; i++) { while (k > 0 && a[i] != b[k]) { k = map[k]; } if (a[i] == b[k]) { k++; } } return k; } /** * Returns true if the string consistently uses Windows line endings. */ function hasOnlyWinLineEndings(string) { return string.includes('\r\n') && !string.startsWith('\n') && !string.match(/[^\r]\n/); } /** * Returns true if the string consistently uses Unix line endings. */ function hasOnlyUnixLineEndings(string) { return !string.includes('\r\n') && string.includes('\n'); } // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 Ë™ ˙ Dot Above // - U+02DA Ëš ˚ Ring Above // - U+02DB Ë› ˛ Ogonek // - U+02DC Ëœ ˜ Small Tilde // - U+02DD Ë ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = "a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}"; // Each token is one of the following: // - A punctuation mark plus the surrounding whitespace // - A word plus the surrounding whitespace // - Pure whitespace (but only in the special case where this the entire text // is just whitespace) // // We have to include surrounding whitespace in the tokens because the two // alternative approaches produce horribly broken results: // * If we just discard the whitespace, we can't fully reproduce the original // text from the sequence of tokens and any attempt to render the diff will // get the whitespace wrong. // * If we have separate tokens for whitespace, then in a typical text every // second token will be a single space character. But this often results in // the optimal diff between two texts being a perverse one that preserves // the spaces between words but deletes and reinserts actual common words. // See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640 // for an example. // // Keeping the surrounding whitespace of course has implications for .equals // and .join, not just .tokenize. // This regex does NOT fully implement the tokenization rules described above. // Instead, it gives runs of whitespace their own "token". The tokenize method // then handles stitching whitespace tokens onto adjacent word or punctuation // tokens. var tokenizeIncludingWhitespace = new RegExp("[".concat(extendedWordChars, "]+|\\s+|[^").concat(extendedWordChars, "]"), 'ug'); var wordDiff = new Diff(); wordDiff.equals = function (left, right, options) { if (options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left.trim() === right.trim(); }; wordDiff.tokenize = function (value) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var parts; if (options.intlSegmenter) { if (options.intlSegmenter.resolvedOptions().granularity != 'word') { throw new Error('The segmenter passed must have a granularity of "word"'); } parts = Array.from(options.intlSegmenter.segment(value), function (segment) { return segment.segment; }); } else { parts = value.match(tokenizeIncludingWhitespace) || []; } var tokens = []; var prevPart = null; parts.forEach(function (part) { if (/\s/.test(part)) { if (prevPart == null) { tokens.push(part); } else { tokens.push(tokens.pop() + part); } } else if (/\s/.test(prevPart)) { if (tokens[tokens.length - 1] == prevPart) { tokens.push(tokens.pop() + part); } else { tokens.push(prevPart + part); } } else { tokens.push(part); } prevPart = part; }); return tokens; }; wordDiff.join = function (tokens) { // Tokens being joined here will always have appeared consecutively in the // same text, so we can simply strip off the leading whitespace from all the // tokens except the first (and except any whitespace-only tokens - but such // a token will always be the first and only token anyway) and then join them // and the whitespace around words and punctuation will end up correct. return tokens.map(function (token, i) { if (i == 0) { return token; } else { return token.replace(/^\s+/, ''); } }).join(''); }; wordDiff.postProcess = function (changes, options) { if (!changes || options.oneChangePerToken) { return changes; } var lastKeep = null; // Change objects representing any insertion or deletion since the last // "keep" change object. There can be at most one of each. var insertion = null; var deletion = null; changes.forEach(function (change) { if (change.added) { insertion = change; } else if (change.removed) { deletion = change; } else { if (insertion || deletion) { // May be false at start of text dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change); } lastKeep = change; insertion = null; deletion = null; } }); if (insertion || deletion) { dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null); } return changes; }; function diffWords(oldStr, newStr, options) { // This option has never been documented and never will be (it's clearer to // just call `diffWordsWithSpace` directly if you need that behavior), but // has existed in jsdiff for a long time, so we retain support for it here // for the sake of backwards compatibility. if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) { return diffWordsWithSpace(oldStr, newStr, options); } return wordDiff.diff(oldStr, newStr, options); } function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) { // Before returning, we tidy up the leading and trailing whitespace of the // change objects to eliminate cases where trailing whitespace in one object // is repeated as leading whitespace in the next. // Below are examples of the outcomes we want here to explain the code. // I=insert, K=keep, D=delete // 1. diffing 'foo bar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' // After cleanup, we want: K:'foo ' D:'bar ' K:'baz' // // 2. Diffing 'foo bar baz' vs 'foo qux baz' // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz' // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz' // // 3. Diffing 'foo\nbar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:'\nbar ' K:' baz' // After cleanup, we want K'foo' D:'\nbar' K:' baz' // // 4. Diffing 'foo baz' vs 'foo\nbar baz' // Prior to cleanup, we have K:'foo\n' I:'\nbar ' K:' baz' // After cleanup, we ideally want K'foo' I:'\nbar' K:' baz' // but don't actually manage this currently (the pre-cleanup change // objects don't contain enough information to make it possible). // // 5. Diffing 'foo bar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' // After cleanup, we want K:'foo ' D:' bar ' K:'baz' // // Our handling is unavoidably imperfect in the case where there's a single // indel between keeps and the whitespace has changed. For instance, consider // diffing 'foo\tbar\nbaz' vs 'foo baz'. Unless we create an extra change // object to represent the insertion of the space character (which isn't even // a token), we have no way to avoid losing information about the texts' // original whitespace in the result we return. Still, we do our best to // output something that will look sensible if we e.g. print it with // insertions in green and deletions in red. // Between two "keep" change objects (or before the first or after the last // change object), we can have either: // * A "delete" followed by an "insert" // * Just an "insert" // * Just a "delete" // We handle the three cases separately. if (deletion && insertion) { var oldWsPrefix = deletion.value.match(/^\s*/)[0]; var oldWsSuffix = deletion.value.match(/\s*$/)[0]; var newWsPrefix = insertion.value.match(/^\s*/)[0]; var newWsSuffix = insertion.value.match(/\s*$/)[0]; if (startKeep) { var commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix); startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix); deletion.value = removePrefix(deletion.value, commonWsPrefix); insertion.value = removePrefix(insertion.value, commonWsPrefix); } if (endKeep) { var commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix); endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix); deletion.value = removeSuffix(deletion.value, commonWsSuffix); insertion.value = removeSuffix(insertion.value, commonWsSuffix); } } else if (insertion) { // The whitespaces all reflect what was in the new text rather than // the old, so we essentially have no information about whitespace // insertion or deletion. We just want to dedupe the whitespace. // We do that by having each change object keep its trailing // whitespace and deleting duplicate leading whitespace where // present. if (startKeep) { insertion.value = insertion.value.replace(/^\s*/, ''); } if (endKeep) { endKeep.value = endKeep.value.replace(/^\s*/, ''); } // otherwise we've got a deletion and no insertion } else if (startKeep && endKeep) { var newWsFull = endKeep.value.match(/^\s*/)[0], delWsStart = deletion.value.match(/^\s*/)[0], delWsEnd = deletion.value.match(/\s*$/)[0]; // Any whitespace that comes straight after startKeep in both the old and // new texts, assign to startKeep and remove from the deletion. var newWsStart = longestCommonPrefix(newWsFull, delWsStart); deletion.value = removePrefix(deletion.value, newWsStart); // Any whitespace that comes straight before endKeep in both the old and // new texts, and hasn't already been assigned to startKeep, assign to // endKeep and remove from the deletion. var newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd); deletion.value = removeSuffix(deletion.value, newWsEnd); endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd); // If there's any whitespace from the new text that HASN'T already been // assigned, assign it to the start: startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length)); } else if (endKeep) { // We are at the start of the text. Preserve all the whitespace on // endKeep, and just remove whitespace from the end of deletion to the // extent that it overlaps with the start of endKeep. var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0]; var deletionWsSuffix = deletion.value.match(/\s*$/)[0]; var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix); deletion.value = removeSuffix(deletion.value, overlap); } else if (startKeep) { // We are at the END of the text. Preserve all the whitespace on // startKeep, and just remove whitespace from the start of deletion to // the extent that it overlaps with the end of startKeep. var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0]; var deletionWsPrefix = deletion.value.match(/^\s*/)[0]; var _overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix); deletion.value = removePrefix(deletion.value, _overlap); } } var wordWithSpaceDiff = new Diff(); wordWithSpaceDiff.tokenize = function (value) { // Slightly different to the tokenizeIncludingWhitespace regex used above in // that this one treats each individual newline as a distinct tokens, rather // than merging them into other surrounding whitespace. This was requested // in https://github.com/kpdecker/jsdiff/issues/180 & // https://github.com/kpdecker/jsdiff/issues/211 var regex = new RegExp("(\\r?\\n)|[".concat(extendedWordChars, "]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars, "]"), 'ug'); return value.match(regex) || []; }; function diffWordsWithSpace(oldStr, newStr, options) { return wordWithSpaceDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } var lineDiff = new Diff(); lineDiff.tokenize = function (value, options) { if (options.stripTrailingCr) { // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior value = value.replace(/\r\n/g, '\n'); } var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { retLines.push(line); } } return retLines; }; lineDiff.equals = function (left, right, options) { // If we're ignoring whitespace, we need to normalise lines by stripping // whitespace before checking equality. (This has an annoying interaction // with newlineIsToken that requires special handling: if newlines get their // own token, then we DON'T want to trim the *newline* tokens down to empty // strings, since this would cause us to treat whitespace-only line content // as equal to a separator between lines, which would be weird and // inconsistent with the documented behavior of the options.) if (options.ignoreWhitespace) { if (!options.newlineIsToken || !left.includes('\n')) { left = left.trim(); } if (!options.newlineIsToken || !right.includes('\n')) { right = right.trim(); } } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { if (left.endsWith('\n')) { left = left.slice(0, -1); } if (right.endsWith('\n')) { right = right.slice(0, -1); } } return Diff.prototype.equals.call(this, left, right, options); }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } // Kept for backwards compatibility. This is a rather arbitrary wrapper method // that just calls `diffLines` with `ignoreWhitespace: true`. It's confusing to // have two ways to do exactly the same thing in the API, so we no longer // document this one (library users should explicitly use `diffLines` with // `ignoreWhitespace: true` instead) but we keep it around to maintain // compatibility with code that used old versions. function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value, options) { var undefinedReplacement = options.undefinedReplacement, _options$stringifyRep = options.stringifyReplacer, stringifyReplacer = _options$stringifyRep === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _options$stringifyRep; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right, options) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === Object.prototype.toString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(obj, _key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function unixToWin(patch) { if (Array.isArray(patch)) { return patch.map(unixToWin); } return _objectSpread2(_objectSpread2({}, patch), {}, { hunks: patch.hunks.map(function (hunk) { return _objectSpread2(_objectSpread2({}, hunk), {}, { lines: hunk.lines.map(function (line, i) { var _hunk$lines; return line.startsWith('\\') || line.endsWith('\r') || (_hunk$lines = hunk.lines[i + 1]) !== null && _hunk$lines !== void 0 && _hunk$lines.startsWith('\\') ? line : line + '\r'; }) }); }) }); } function winToUnix(patch) { if (Array.isArray(patch)) { return patch.map(winToUnix); } return _objectSpread2(_objectSpread2({}, patch), {}, { hunks: patch.hunks.map(function (hunk) { return _objectSpread2(_objectSpread2({}, hunk), {}, { lines: hunk.lines.map(function (line) { return line.endsWith('\r') ? line.substring(0, line.length - 1) : line; }) }); }) }); } /** * Returns true if the patch consistently uses Unix line endings (or only involves one line and has * no line endings). */ function isUnix(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return !patch.some(function (index) { return index.hunks.some(function (hunk) { return hunk.lines.some(function (line) { return !line.startsWith('\\') && line.endsWith('\r'); }); }); }); } /** * Returns true if the patch uses Windows line endings and only Windows line endings. */ function isWin(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return patch.some(function (index) { return index.hunks.some(function (hunk) { return hunk.lines.some(function (line) { return line.endsWith('\r'); }); }); }) && patch.every(function (index) { return index.hunks.every(function (hunk) { return hunk.lines.every(function (line, i) { var _hunk$lines2; return line.startsWith('\\') || line.endsWith('\r') || ((_hunk$lines2 = hunk.lines[i + 1]) === null || _hunk$lines2 === void 0 ? void 0 : _hunk$lines2.startsWith('\\')); }); }); }); } function parsePatch(uniDiff) { var diffstr = uniDiff.split(/\n/), list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:\s|diff\s|\-\-\-\s|\+\+\+\s|===================================================================)/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line) { throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], lines: [] }; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } var addCount = 0, removeCount = 0; for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || (_diffstr$i = diffstr[i]) !== null && _diffstr$i !== void 0 && _diffstr$i.startsWith('\\')); i++) { var _diffstr$i; var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { throw new Error("Hunk at line ".concat(chunkHeaderIndex + 1, " contained invalid line ").concat(diffstr[i])); } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform sanity checking if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return start + localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return start - localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { if (hasOnlyWinLineEndings(source) && isUnix(uniDiff)) { uniDiff = unixToWin(uniDiff); } else if (hasOnlyUnixLineEndings(source) && isWin(uniDiff)) { uniDiff = winToUnix(uniDiff); } } // Apply the diff to the input var lines = source.split('\n'), hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, fuzzFactor = options.fuzzFactor || 0, minLine = 0; if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { throw new Error('fuzzFactor must be a non-negative integer'); } // Special case for empty patch. if (!hunks.length) { return source; } // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a // newline that already exists - then we either return false and fail to apply the patch (if // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0). // If we do need to remove/add a newline at EOF, this will always be in the final hunk: var prevLine = '', removeEOFNL = false, addEOFNL = false; for (var i = 0; i < hunks[hunks.length - 1].lines.length; i++) { var line = hunks[hunks.length - 1].lines[i]; if (line[0] == '\\') { if (prevLine[0] == '+') { removeEOFNL = true; } else if (prevLine[0] == '-') { addEOFNL = true; } } prevLine = line; } if (removeEOFNL) { if (addEOFNL) { // This means the final line gets changed but doesn't have a trailing newline in either the // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if // fuzzFactor is 0, we simply validate that the source file has no trailing newline. if (!fuzzFactor && lines[lines.length - 1] == '') { return false; } } else if (lines[lines.length - 1] == '') { lines.pop(); } else if (!fuzzFactor) { return false; } } else if (addEOFNL) { if (lines[lines.length - 1] != '') { lines.push(''); } else if (!fuzzFactor) { return false; } } /** * Checks if the hunk can be made to fit at the provided location with at most `maxErrors` * insertions, substitutions, or deletions, while ensuring also that: * - lines deleted in the hunk match exactly, and * - wherever an insertion operation or block of insertion operations appears in the hunk, the * immediately preceding and following lines of context match exactly * * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0]. * * If the hunk can be applied, returns an object with properties `oldLineLastI` and * `replacementLines`. Otherwise, returns null. */ function applyHunk(hunkLines, toPos, maxErrors) { var hunkLinesI = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var lastContextLineMatched = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; var patchedLines = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; var patchedLinesLength = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; var nConsecutiveOldContextLines = 0; var nextContextLineMustMatch = false; for (; hunkLinesI < hunkLines.length; hunkLinesI++) { var hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : ' ', content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; if (operation === '-') { if (compareLine(toPos + 1, lines[toPos], operation, content)) { toPos++; nConsecutiveOldContextLines = 0; } else { if (!maxErrors || lines[toPos] == null) { return null; } patchedLines[patchedLinesLength] = lines[toPos]; return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); } } if (operation === '+') { if (!lastContextLineMatched) { return null; } patchedLines[patchedLinesLength] = content; patchedLinesLength++; nConsecutiveOldContextLines = 0; nextContextLineMustMatch = true; } if (operation === ' ') { nConsecutiveOldContextLines++; patchedLines[patchedLinesLength] = lines[toPos]; if (compareLine(toPos + 1, lines[toPos], operation, content)) { patchedLinesLength++; lastContextLineMatched = true; nextContextLineMustMatch = false; toPos++; } else { if (nextContextLineMustMatch || !maxErrors) { return null; } // Consider 3 possibilities in sequence: // 1. lines contains a *substitution* not included in the patch context, or // 2. lines contains an *insertion* not included in the patch context, or // 3. lines contains a *deletion* not included in the patch context // The first two options are of course only possible if the line from lines is non-null - // i.e. only option 3 is possible if we've overrun the end of the old file. return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); } } } // Before returning, trim any unmodified context lines off the end of patchedLines and reduce // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region // that starts in this hunk's trailing context. patchedLinesLength -= nConsecutiveOldContextLines; toPos -= nConsecutiveOldContextLines; patchedLines.length = patchedLinesLength; return { patchedLines: patchedLines, oldLineLastI: toPos - 1 }; } var resultLines = []; // Search best fit offsets for each hunk based on the previous ones var prevHunkOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var hunk = hunks[_i]; var hunkResult = void 0; var maxLine = lines.length - hunk.oldLines + fuzzFactor; var toPos = void 0; for (var maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { toPos = hunk.oldStart + prevHunkOffset - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; toPos !== undefined; toPos = iterator()) { hunkResult = applyHunk(hunk.lines, toPos, maxErrors); if (hunkResult) { break; } } if (hunkResult) { break; } } if (!hunkResult) { return false; } // Copy everything from the end of where we applied the last hunk to the start of this hunk for (var _i2 = minLine; _i2 < toPos; _i2++) { resultLines.push(lines[_i2]); } // Add the lines produced by applying the hunk: for (var _i3 = 0; _i3 < hunkResult.patchedLines.length; _i3++) { var _line = hunkResult.patchedLines[_i3]; resultLines.push(_line); } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunkResult.oldLineLastI + 1; // Note the offset between where the patch said the hunk should've applied and where we // applied it, so we can adjust future hunks accordingly: prevHunkOffset = toPos + 1 - hunk.oldStart; } // Copy over the rest of the lines from the old text for (var _i4 = minLine; _i4 < lines.length; _i4++) { resultLines.push(lines[_i4]); } return resultLines.join('\n'); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options === 'function') { options = { callback: options }; } if (typeof options.context === 'undefined') { options.context = 4; } if (options.newlineIsToken) { throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions'); } if (!options.callback) { return diffLinesResultToPatch(diffLines(oldStr, newStr, options)); } else { var _options = options, _callback = _options.callback; diffLines(oldStr, newStr, _objectSpread2(_objectSpread2({}, options), {}, { callback: function callback(diff) { var patch = diffLinesResultToPatch(diff); _callback(patch); } })); } function diffLinesResultToPatch(diff) { // STEP 1: Build up the patch with no "\ No newline at end of file" lines and with the arrays // of lines containing trailing newline characters. We'll tidy up later... if (!diff) { return; } diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop() { var current = diff[i], lines = current.lines || splitLines(current.value); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var _hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; hunks.push(_hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(); } // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add // "\ No newline at end of file". for (var _i = 0, _hunks = hunks; _i < _hunks.length; _i++) { var hunk = _hunks[_i]; for (var _i2 = 0; _i2 < hunk.lines.length; _i2++) { if (hunk.lines[_i2].endsWith('\n')) { hunk.lines[_i2] = hunk.lines[_i2].slice(0, -1); } else { hunk.lines.splice(_i2 + 1, 0, '\\ No newline at end of file'); _i2++; // Skip the line we just added, then continue iterating } } } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } } function formatPatch(diff) { if (Array.isArray(diff)) { return diff.map(formatPatch).join('\n'); } var ret = []; if (diff.oldFileName == diff.newFileName) { ret.push('Index: ' + diff.oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { var _options2; if (typeof options === 'function') { options = { callback: options }; } if (!((_options2 = options) !== null && _options2 !== void 0 && _options2.callback)) { var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); if (!patchObj) { return; } return formatPatch(patchObj); } else { var _options3 = options, _callback2 = _options3.callback; structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, _objectSpread2(_objectSpread2({}, options), {}, { callback: function callback(patchObj) { if (!patchObj) { _callback2(); } else { _callback2(formatPatch(patchObj)); } } })); } } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } /** * Split `text` into an array of lines, including the trailing newline character (where present) */ function splitLines(text) { var hasTrailingNl = text.endsWith('\n'); var result = text.split('\n').map(function (line) { return line + '\n'; }); if (hasTrailingNl) { result.pop(); } else { result.push(result.pop().slice(0, -1)); } return result; } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } function reversePatch(structuredPatch) { if (Array.isArray(structuredPatch)) { return structuredPatch.map(reversePatch).reverse(); } return _objectSpread2(_objectSpread2({}, structuredPatch), {}, { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(function (hunk) { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, lines: hunk.lines.map(function (l) { if (l.startsWith('-')) { return "+".concat(l.slice(1)); } if (l.startsWith('+')) { return "-".concat(l.slice(1)); } return l; }) }; }) }); } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } export { Diff, applyPatch, applyPatches, canonicalize, convertChangesToDMP, convertChangesToXML, createPatch, createTwoFilesPatch, diffArrays, diffChars, diffCss, diffJson, diffLines, diffSentences, diffTrimmedLines, diffWords, diffWordsWithSpace, formatPatch, merge, parsePatch, reversePatch, structuredPatch }; /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "Diff", { enumerable: true, get: function get() { return _base["default"]; } }); Object.defineProperty(exports, "applyPatch", { enumerable: true, get: function get() { return _apply.applyPatch; } }); Object.defineProperty(exports, "applyPatches", { enumerable: true, get: function get() { return _apply.applyPatches; } }); Object.defineProperty(exports, "canonicalize", { enumerable: true, get: function get() { return _json.canonicalize; } }); Object.defineProperty(exports, "convertChangesToDMP", { enumerable: true, get: function get() { return _dmp.convertChangesToDMP; } }); Object.defineProperty(exports, "convertChangesToXML", { enumerable: true, get: function get() { return _xml.convertChangesToXML; } }); Object.defineProperty(exports, "createPatch", { enumerable: true, get: function get() { return _create.createPatch; } }); Object.defineProperty(exports, "createTwoFilesPatch", { enumerable: true, get: function get() { return _create.createTwoFilesPatch; } }); Object.defineProperty(exports, "diffArrays", { enumerable: true, get: function get() { return _array.diffArrays; } }); Object.defineProperty(exports, "diffChars", { enumerable: true, get: function get() { return _character.diffChars; } }); Object.defineProperty(exports, "diffCss", { enumerable: true, get: function get() { return _css.diffCss; } }); Object.defineProperty(exports, "diffJson", { enumerable: true, get: function get() { return _json.diffJson; } }); Object.defineProperty(exports, "diffLines", { enumerable: true, get: function get() { return _line.diffLines; } }); Object.defineProperty(exports, "diffSentences", { enumerable: true, get: function get() { return _sentence.diffSentences; } }); Object.defineProperty(exports, "diffTrimmedLines", { enumerable: true, get: function get() { return _line.diffTrimmedLines; } }); Object.defineProperty(exports, "diffWords", { enumerable: true, get: function get() { return _word.diffWords; } }); Object.defineProperty(exports, "diffWordsWithSpace", { enumerable: true, get: function get() { return _word.diffWordsWithSpace; } }); Object.defineProperty(exports, "formatPatch", { enumerable: true, get: function get() { return _create.formatPatch; } }); Object.defineProperty(exports, "merge", { enumerable: true, get: function get() { return _merge.merge; } }); Object.defineProperty(exports, "parsePatch", { enumerable: true, get: function get() { return _parse.parsePatch; } }); Object.defineProperty(exports, "reversePatch", { enumerable: true, get: function get() { return _reverse.reversePatch; } }); Object.defineProperty(exports, "structuredPatch", { enumerable: true, get: function get() { return _create.structuredPatch; } }); /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./diff/base")) /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _character = require("./diff/character") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _word = require("./diff/word") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _line = require("./diff/line") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _sentence = require("./diff/sentence") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _css = require("./diff/css") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _json = require("./diff/json") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _array = require("./diff/array") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _apply = require("./patch/apply") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _parse = require("./patch/parse") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _merge = require("./patch/merge") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _reverse = require("./patch/reverse") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _create = require("./patch/create") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _dmp = require("./convert/dmp") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _xml = require("./convert/xml") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYmFzZSIsIl9pbnRlcm9wUmVxdWlyZURlZmF1bHQiLCJyZXF1aXJlIiwiX2NoYXJhY3RlciIsIl93b3JkIiwiX2xpbmUiLCJfc2VudGVuY2UiLCJfY3NzIiwiX2pzb24iLCJfYXJyYXkiLCJfYXBwbHkiLCJfcGFyc2UiLCJfbWVyZ2UiLCJfcmV2ZXJzZSIsIl9jcmVhdGUiLCJfZG1wIiwiX3htbCIsIm9iaiIsIl9fZXNNb2R1bGUiXSwic291cmNlcyI6WyIuLi9zcmMvaW5kZXguanMiXSwic291cmNlc0NvbnRlbnQiOlsiLyogU2VlIExJQ0VOU0UgZmlsZSBmb3IgdGVybXMgb2YgdXNlICovXG5cbi8qXG4gKiBUZXh0IGRpZmYgaW1wbGVtZW50YXRpb24uXG4gKlxuICogVGhpcyBsaWJyYXJ5IHN1cHBvcnRzIHRoZSBmb2xsb3dpbmcgQVBJczpcbiAqIERpZmYuZGlmZkNoYXJzOiBDaGFyYWN0ZXIgYnkgY2hhcmFjdGVyIGRpZmZcbiAqIERpZmYuZGlmZldvcmRzOiBXb3JkIChhcyBkZWZpbmVkIGJ5IFxcYiByZWdleCkgZGlmZiB3aGljaCBpZ25vcmVzIHdoaXRlc3BhY2VcbiAqIERpZmYuZGlmZkxpbmVzOiBMaW5lIGJhc2VkIGRpZmZcbiAqXG4gKiBEaWZmLmRpZmZDc3M6IERpZmYgdGFyZ2V0ZWQgYXQgQ1NTIGNvbnRlbnRcbiAqXG4gKiBUaGVzZSBtZXRob2RzIGFyZSBiYXNlZCBvbiB0aGUgaW1wbGVtZW50YXRpb24gcHJvcG9zZWQgaW5cbiAqIFwiQW4gTyhORCkgRGlmZmVyZW5jZSBBbGdvcml0aG0gYW5kIGl0cyBWYXJpYXRpb25zXCIgKE15ZXJzLCAxOTg2KS5cbiAqIGh0dHA6Ly9jaXRlc2VlcnguaXN0LnBzdS5lZHUvdmlld2RvYy9zdW1tYXJ5P2RvaT0xMC4xLjEuNC42OTI3XG4gKi9cbmltcG9ydCBEaWZmIGZyb20gJy4vZGlmZi9iYXNlJztcbmltcG9ydCB7ZGlmZkNoYXJzfSBmcm9tICcuL2RpZmYvY2hhcmFjdGVyJztcbmltcG9ydCB7ZGlmZldvcmRzLCBkaWZmV29yZHNXaXRoU3BhY2V9IGZyb20gJy4vZGlmZi93b3JkJztcbmltcG9ydCB7ZGlmZkxpbmVzLCBkaWZmVHJpbW1lZExpbmVzfSBmcm9tICcuL2RpZmYvbGluZSc7XG5pbXBvcnQge2RpZmZTZW50ZW5jZXN9IGZyb20gJy4vZGlmZi9zZW50ZW5jZSc7XG5cbmltcG9ydCB7ZGlmZkNzc30gZnJvbSAnLi9kaWZmL2Nzcyc7XG5pbXBvcnQge2RpZmZKc29uLCBjYW5vbmljYWxpemV9IGZyb20gJy4vZGlmZi9qc29uJztcblxuaW1wb3J0IHtkaWZmQXJyYXlzfSBmcm9tICcuL2RpZmYvYXJyYXknO1xuXG5pbXBvcnQge2FwcGx5UGF0Y2gsIGFwcGx5UGF0Y2hlc30gZnJvbSAnLi9wYXRjaC9hcHBseSc7XG5pbXBvcnQge3BhcnNlUGF0Y2h9IGZyb20gJy4vcGF0Y2gvcGFyc2UnO1xuaW1wb3J0IHttZXJnZX0gZnJvbSAnLi9wYXRjaC9tZXJnZSc7XG5pbXBvcnQge3JldmVyc2VQYXRjaH0gZnJvbSAnLi9wYXRjaC9yZXZlcnNlJztcbmltcG9ydCB7c3RydWN0dXJlZFBhdGNoLCBjcmVhdGVUd29GaWxlc1BhdGNoLCBjcmVhdGVQYXRjaCwgZm9ybWF0UGF0Y2h9IGZyb20gJy4vcGF0Y2gvY3JlYXRlJztcblxuaW1wb3J0IHtjb252ZXJ0Q2hhbmdlc1RvRE1QfSBmcm9tICcuL2NvbnZlcnQvZG1wJztcbmltcG9ydCB7Y29udmVydENoYW5nZXNUb1hNTH0gZnJvbSAnLi9jb252ZXJ0L3htbCc7XG5cbmV4cG9ydCB7XG4gIERpZmYsXG5cbiAgZGlmZkNoYXJzLFxuICBkaWZmV29yZHMsXG4gIGRpZmZXb3Jkc1dpdGhTcGFjZSxcbiAgZGlmZkxpbmVzLFxuICBkaWZmVHJpbW1lZExpbmVzLFxuICBkaWZmU2VudGVuY2VzLFxuXG4gIGRpZmZDc3MsXG4gIGRpZmZKc29uLFxuXG4gIGRpZmZBcnJheXMsXG5cbiAgc3RydWN0dXJlZFBhdGNoLFxuICBjcmVhdGVUd29GaWxlc1BhdGNoLFxuICBjcmVhdGVQYXRjaCxcbiAgZm9ybWF0UGF0Y2gsXG4gIGFwcGx5UGF0Y2gsXG4gIGFwcGx5UGF0Y2hlcyxcbiAgcGFyc2VQYXRjaCxcbiAgbWVyZ2UsXG4gIHJldmVyc2VQYXRjaCxcbiAgY29udmVydENoYW5nZXNUb0RNUCxcbiAgY29udmVydENoYW5nZXNUb1hNTCxcbiAgY2Fub25pY2FsaXplXG59O1xuIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBZ0JBO0FBQUE7QUFBQUEsS0FBQSxHQUFBQyxzQkFBQSxDQUFBQyxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQUMsVUFBQSxHQUFBRCxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQUUsS0FBQSxHQUFBRixPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQUcsS0FBQSxHQUFBSCxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQUksU0FBQSxHQUFBSixPQUFBO0FBQUE7QUFBQTtBQUVBO0FBQUE7QUFBQUssSUFBQSxHQUFBTCxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQU0sS0FBQSxHQUFBTixPQUFBO0FBQUE7QUFBQTtBQUVBO0FBQUE7QUFBQU8sTUFBQSxHQUFBUCxPQUFBO0FBQUE7QUFBQTtBQUVBO0FBQUE7QUFBQVEsTUFBQSxHQUFBUixPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQVMsTUFBQSxHQUFBVCxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQVUsTUFBQSxHQUFBVixPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQVcsUUFBQSxHQUFBWCxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQVksT0FBQSxHQUFBWixPQUFBO0FBQUE7QUFBQTtBQUVBO0FBQUE7QUFBQWEsSUFBQSxHQUFBYixPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQWMsSUFBQSxHQUFBZCxPQUFBO0FBQUE7QUFBQTtBQUFrRCxtQ0FBQUQsdUJBQUFnQixHQUFBLFdBQUFBLEdBQUEsSUFBQUEsR0FBQSxDQUFBQyxVQUFBLEdBQUFELEdBQUEsZ0JBQUFBLEdBQUE7QUFBQSIsImlnbm9yZUxpc3QiOltdfQ== function Diff() {} Diff.prototype = { diff: function diff(oldString, newString) { var _options$timeout; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } var self = this; function done(value) { value = self.postProcess(value, options); if (callback) { setTimeout(function () { callback(value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString, options); newString = this.castInput(newString, options); oldString = this.removeEmpty(this.tokenize(oldString, options)); newString = this.removeEmpty(this.tokenize(newString, options)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; if (options.maxEditLength != null) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; var abortAfterTimestamp = Date.now() + maxExecutionTime; var bestPath = [{ oldPos: -1, lastComponent: undefined }]; // Seed editLength = 0, i.e. the content starts with the same values var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // Identity per the equality and tokenizer return done(buildValues(self, bestPath[0].lastComponent, newString, oldString, self.useLongestToken)); } // Once we hit the right edge of the edit graph on some diagonal k, we can // definitely reach the end of the edit graph in no more than k edits, so // there's no point in considering any moves to diagonal k+1 any more (from // which we're guaranteed to need at least k+1 more edits). // Similarly, once we've reached the bottom of the edit graph, there's no // point considering moves to lower diagonals. // We record this fact by setting minDiagonalToConsider and // maxDiagonalToConsider to some finite value once we've hit the edge of // the edit graph. // This optimization is not faithful to the original algorithm presented in // Myers's paper, which instead pointlessly extends D-paths off the end of // the edit graph - see page 7 of Myers's paper which notes this point // explicitly and illustrates it with a diagram. This has major performance // implications for some common scenarios. For instance, to compute a diff // where the new text simply appends d characters on the end of the // original text of length n, the true Myers algorithm will take O(n+d^2) // time while this optimization needs only O(n+d) time. var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { var basePath = void 0; var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = false; if (addPath) { // what newPos will be after we do an insertion: var addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } var canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the old string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { basePath = self.addToPath(addPath, true, false, 0, options); } else { basePath = self.addToPath(removePath, false, true, 1, options); } newPos = self.extractCommon(basePath, newString, oldString, diagonalPath, options); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // If we have hit the end of both strings, then we are done return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken)); } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced, or until the edit length exceeds options.maxEditLength (if given), // in which case it will return undefined. if (callback) { (function exec() { setTimeout(function () { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { var ret = execEditLength(); if (ret) { return ret; } } } }, addToPath: function addToPath(path, added, removed, oldPosInc, options) { var last = path.lastComponent; if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath, options) { var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options)) { newPos++; oldPos++; commonCount++; if (options.oneChangePerToken) { basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; } } if (commonCount && !options.oneChangePerToken) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; } basePath.oldPos = oldPos; return newPos; }, equals: function equals(left, right, options) { if (options.comparator) { return options.comparator(left, right); } else { return left === right || options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return Array.from(value); }, join: function join(chars) { return chars.join(''); }, postProcess: function postProcess(changeObjects) { return changeObjects; } }; function buildValues(diff, lastComponent, newString, oldString, useLongestToken) { // First we convert our linked list of components in reverse order to an // array in the right order: var components = []; var nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; } } return components; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function longestCommonPrefix(str1, str2) { var i; for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[i] != str2[i]) { return str1.slice(0, i); } } return str1.slice(0, i); } function longestCommonSuffix(str1, str2) { var i; // Unlike longestCommonPrefix, we need a special case to handle all scenarios // where we return the empty string since str1.slice(-0) will return the // entire string. if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) { return ''; } for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) { return str1.slice(-i); } } return str1.slice(-i); } function replacePrefix(string, oldPrefix, newPrefix) { if (string.slice(0, oldPrefix.length) != oldPrefix) { throw Error("string ".concat(JSON.stringify(string), " doesn't start with prefix ").concat(JSON.stringify(oldPrefix), "; this is a bug")); } return newPrefix + string.slice(oldPrefix.length); } function replaceSuffix(string, oldSuffix, newSuffix) { if (!oldSuffix) { return string + newSuffix; } if (string.slice(-oldSuffix.length) != oldSuffix) { throw Error("string ".concat(JSON.stringify(string), " doesn't end with suffix ").concat(JSON.stringify(oldSuffix), "; this is a bug")); } return string.slice(0, -oldSuffix.length) + newSuffix; } function removePrefix(string, oldPrefix) { return replacePrefix(string, oldPrefix, ''); } function removeSuffix(string, oldSuffix) { return replaceSuffix(string, oldSuffix, ''); } function maximumOverlap(string1, string2) { return string2.slice(0, overlapCount(string1, string2)); } // Nicked from https://stackoverflow.com/a/60422853/1709587 function overlapCount(a, b) { // Deal with cases where the strings differ in length var startA = 0; if (a.length > b.length) { startA = a.length - b.length; } var endB = b.length; if (a.length < b.length) { endB = a.length; } // Create a back-reference for each index // that should be followed in case of a mismatch. // We only need B to make these references: var map = Array(endB); var k = 0; // Index that lags behind j map[0] = 0; for (var j = 1; j < endB; j++) { if (b[j] == b[k]) { map[j] = map[k]; // skip over the same character (optional optimisation) } else { map[j] = k; } while (k > 0 && b[j] != b[k]) { k = map[k]; } if (b[j] == b[k]) { k++; } } // Phase 2: use these references while iterating over A k = 0; for (var i = startA; i < a.length; i++) { while (k > 0 && a[i] != b[k]) { k = map[k]; } if (a[i] == b[k]) { k++; } } return k; } /** * Returns true if the string consistently uses Windows line endings. */ function hasOnlyWinLineEndings(string) { return string.includes('\r\n') && !string.startsWith('\n') && !string.match(/[^\r]\n/); } /** * Returns true if the string consistently uses Unix line endings. */ function hasOnlyUnixLineEndings(string) { return !string.includes('\r\n') && string.includes('\n'); } // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 Ë™ ˙ Dot Above // - U+02DA Ëš ˚ Ring Above // - U+02DB Ë› ˛ Ogonek // - U+02DC Ëœ ˜ Small Tilde // - U+02DD Ë ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = "a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}"; // Each token is one of the following: // - A punctuation mark plus the surrounding whitespace // - A word plus the surrounding whitespace // - Pure whitespace (but only in the special case where this the entire text // is just whitespace) // // We have to include surrounding whitespace in the tokens because the two // alternative approaches produce horribly broken results: // * If we just discard the whitespace, we can't fully reproduce the original // text from the sequence of tokens and any attempt to render the diff will // get the whitespace wrong. // * If we have separate tokens for whitespace, then in a typical text every // second token will be a single space character. But this often results in // the optimal diff between two texts being a perverse one that preserves // the spaces between words but deletes and reinserts actual common words. // See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640 // for an example. // // Keeping the surrounding whitespace of course has implications for .equals // and .join, not just .tokenize. // This regex does NOT fully implement the tokenization rules described above. // Instead, it gives runs of whitespace their own "token". The tokenize method // then handles stitching whitespace tokens onto adjacent word or punctuation // tokens. var tokenizeIncludingWhitespace = new RegExp("[".concat(extendedWordChars, "]+|\\s+|[^").concat(extendedWordChars, "]"), 'ug'); var wordDiff = new Diff(); wordDiff.equals = function (left, right, options) { if (options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left.trim() === right.trim(); }; wordDiff.tokenize = function (value) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var parts; if (options.intlSegmenter) { if (options.intlSegmenter.resolvedOptions().granularity != 'word') { throw new Error('The segmenter passed must have a granularity of "word"'); } parts = Array.from(options.intlSegmenter.segment(value), function (segment) { return segment.segment; }); } else { parts = value.match(tokenizeIncludingWhitespace) || []; } var tokens = []; var prevPart = null; parts.forEach(function (part) { if (/\s/.test(part)) { if (prevPart == null) { tokens.push(part); } else { tokens.push(tokens.pop() + part); } } else if (/\s/.test(prevPart)) { if (tokens[tokens.length - 1] == prevPart) { tokens.push(tokens.pop() + part); } else { tokens.push(prevPart + part); } } else { tokens.push(part); } prevPart = part; }); return tokens; }; wordDiff.join = function (tokens) { // Tokens being joined here will always have appeared consecutively in the // same text, so we can simply strip off the leading whitespace from all the // tokens except the first (and except any whitespace-only tokens - but such // a token will always be the first and only token anyway) and then join them // and the whitespace around words and punctuation will end up correct. return tokens.map(function (token, i) { if (i == 0) { return token; } else { return token.replace(/^\s+/, ''); } }).join(''); }; wordDiff.postProcess = function (changes, options) { if (!changes || options.oneChangePerToken) { return changes; } var lastKeep = null; // Change objects representing any insertion or deletion since the last // "keep" change object. There can be at most one of each. var insertion = null; var deletion = null; changes.forEach(function (change) { if (change.added) { insertion = change; } else if (change.removed) { deletion = change; } else { if (insertion || deletion) { // May be false at start of text dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change); } lastKeep = change; insertion = null; deletion = null; } }); if (insertion || deletion) { dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null); } return changes; }; function diffWords(oldStr, newStr, options) { // This option has never been documented and never will be (it's clearer to // just call `diffWordsWithSpace` directly if you need that behavior), but // has existed in jsdiff for a long time, so we retain support for it here // for the sake of backwards compatibility. if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) { return diffWordsWithSpace(oldStr, newStr, options); } return wordDiff.diff(oldStr, newStr, options); } function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) { // Before returning, we tidy up the leading and trailing whitespace of the // change objects to eliminate cases where trailing whitespace in one object // is repeated as leading whitespace in the next. // Below are examples of the outcomes we want here to explain the code. // I=insert, K=keep, D=delete // 1. diffing 'foo bar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' // After cleanup, we want: K:'foo ' D:'bar ' K:'baz' // // 2. Diffing 'foo bar baz' vs 'foo qux baz' // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz' // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz' // // 3. Diffing 'foo\nbar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:'\nbar ' K:' baz' // After cleanup, we want K'foo' D:'\nbar' K:' baz' // // 4. Diffing 'foo baz' vs 'foo\nbar baz' // Prior to cleanup, we have K:'foo\n' I:'\nbar ' K:' baz' // After cleanup, we ideally want K'foo' I:'\nbar' K:' baz' // but don't actually manage this currently (the pre-cleanup change // objects don't contain enough information to make it possible). // // 5. Diffing 'foo bar baz' vs 'foo baz' // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' // After cleanup, we want K:'foo ' D:' bar ' K:'baz' // // Our handling is unavoidably imperfect in the case where there's a single // indel between keeps and the whitespace has changed. For instance, consider // diffing 'foo\tbar\nbaz' vs 'foo baz'. Unless we create an extra change // object to represent the insertion of the space character (which isn't even // a token), we have no way to avoid losing information about the texts' // original whitespace in the result we return. Still, we do our best to // output something that will look sensible if we e.g. print it with // insertions in green and deletions in red. // Between two "keep" change objects (or before the first or after the last // change object), we can have either: // * A "delete" followed by an "insert" // * Just an "insert" // * Just a "delete" // We handle the three cases separately. if (deletion && insertion) { var oldWsPrefix = deletion.value.match(/^\s*/)[0]; var oldWsSuffix = deletion.value.match(/\s*$/)[0]; var newWsPrefix = insertion.value.match(/^\s*/)[0]; var newWsSuffix = insertion.value.match(/\s*$/)[0]; if (startKeep) { var commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix); startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix); deletion.value = removePrefix(deletion.value, commonWsPrefix); insertion.value = removePrefix(insertion.value, commonWsPrefix); } if (endKeep) { var commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix); endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix); deletion.value = removeSuffix(deletion.value, commonWsSuffix); insertion.value = removeSuffix(insertion.value, commonWsSuffix); } } else if (insertion) { // The whitespaces all reflect what was in the new text rather than // the old, so we essentially have no information about whitespace // insertion or deletion. We just want to dedupe the whitespace. // We do that by having each change object keep its trailing // whitespace and deleting duplicate leading whitespace where // present. if (startKeep) { insertion.value = insertion.value.replace(/^\s*/, ''); } if (endKeep) { endKeep.value = endKeep.value.replace(/^\s*/, ''); } // otherwise we've got a deletion and no insertion } else if (startKeep && endKeep) { var newWsFull = endKeep.value.match(/^\s*/)[0], delWsStart = deletion.value.match(/^\s*/)[0], delWsEnd = deletion.value.match(/\s*$/)[0]; // Any whitespace that comes straight after startKeep in both the old and // new texts, assign to startKeep and remove from the deletion. var newWsStart = longestCommonPrefix(newWsFull, delWsStart); deletion.value = removePrefix(deletion.value, newWsStart); // Any whitespace that comes straight before endKeep in both the old and // new texts, and hasn't already been assigned to startKeep, assign to // endKeep and remove from the deletion. var newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd); deletion.value = removeSuffix(deletion.value, newWsEnd); endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd); // If there's any whitespace from the new text that HASN'T already been // assigned, assign it to the start: startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length)); } else if (endKeep) { // We are at the start of the text. Preserve all the whitespace on // endKeep, and just remove whitespace from the end of deletion to the // extent that it overlaps with the start of endKeep. var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0]; var deletionWsSuffix = deletion.value.match(/\s*$/)[0]; var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix); deletion.value = removeSuffix(deletion.value, overlap); } else if (startKeep) { // We are at the END of the text. Preserve all the whitespace on // startKeep, and just remove whitespace from the start of deletion to // the extent that it overlaps with the end of startKeep. var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0]; var deletionWsPrefix = deletion.value.match(/^\s*/)[0]; var _overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix); deletion.value = removePrefix(deletion.value, _overlap); } } var wordWithSpaceDiff = new Diff(); wordWithSpaceDiff.tokenize = function (value) { // Slightly different to the tokenizeIncludingWhitespace regex used above in // that this one treats each individual newline as a distinct tokens, rather // than merging them into other surrounding whitespace. This was requested // in https://github.com/kpdecker/jsdiff/issues/180 & // https://github.com/kpdecker/jsdiff/issues/211 var regex = new RegExp("(\\r?\\n)|[".concat(extendedWordChars, "]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars, "]"), 'ug'); return value.match(regex) || []; }; function diffWordsWithSpace(oldStr, newStr, options) { return wordWithSpaceDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } var lineDiff = new Diff(); lineDiff.tokenize = function (value, options) { if (options.stripTrailingCr) { // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior value = value.replace(/\r\n/g, '\n'); } var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { retLines.push(line); } } return retLines; }; lineDiff.equals = function (left, right, options) { // If we're ignoring whitespace, we need to normalise lines by stripping // whitespace before checking equality. (This has an annoying interaction // with newlineIsToken that requires special handling: if newlines get their // own token, then we DON'T want to trim the *newline* tokens down to empty // strings, since this would cause us to treat whitespace-only line content // as equal to a separator between lines, which would be weird and // inconsistent with the documented behavior of the options.) if (options.ignoreWhitespace) { if (!options.newlineIsToken || !left.includes('\n')) { left = left.trim(); } if (!options.newlineIsToken || !right.includes('\n')) { right = right.trim(); } } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { if (left.endsWith('\n')) { left = left.slice(0, -1); } if (right.endsWith('\n')) { right = right.slice(0, -1); } } return Diff.prototype.equals.call(this, left, right, options); }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } // Kept for backwards compatibility. This is a rather arbitrary wrapper method // that just calls `diffLines` with `ignoreWhitespace: true`. It's confusing to // have two ways to do exactly the same thing in the API, so we no longer // document this one (library users should explicitly use `diffLines` with // `ignoreWhitespace: true` instead) but we keep it around to maintain // compatibility with code that used old versions. function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value, options) { var undefinedReplacement = options.undefinedReplacement, _options$stringifyRep = options.stringifyReplacer, stringifyReplacer = _options$stringifyRep === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _options$stringifyRep; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right, options) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === Object.prototype.toString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(obj, _key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function unixToWin(patch) { if (Array.isArray(patch)) { return patch.map(unixToWin); } return _objectSpread2(_objectSpread2({}, patch), {}, { hunks: patch.hunks.map(function (hunk) { return _objectSpread2(_objectSpread2({}, hunk), {}, { lines: hunk.lines.map(function (line, i) { var _hunk$lines; return line.startsWith('\\') || line.endsWith('\r') || (_hunk$lines = hunk.lines[i + 1]) !== null && _hunk$lines !== void 0 && _hunk$lines.startsWith('\\') ? line : line + '\r'; }) }); }) }); } function winToUnix(patch) { if (Array.isArray(patch)) { return patch.map(winToUnix); } return _objectSpread2(_objectSpread2({}, patch), {}, { hunks: patch.hunks.map(function (hunk) { return _objectSpread2(_objectSpread2({}, hunk), {}, { lines: hunk.lines.map(function (line) { return line.endsWith('\r') ? line.substring(0, line.length - 1) : line; }) }); }) }); } /** * Returns true if the patch consistently uses Unix line endings (or only involves one line and has * no line endings). */ function isUnix(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return !patch.some(function (index) { return index.hunks.some(function (hunk) { return hunk.lines.some(function (line) { return !line.startsWith('\\') && line.endsWith('\r'); }); }); }); } /** * Returns true if the patch uses Windows line endings and only Windows line endings. */ function isWin(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return patch.some(function (index) { return index.hunks.some(function (hunk) { return hunk.lines.some(function (line) { return line.endsWith('\r'); }); }); }) && patch.every(function (index) { return index.hunks.every(function (hunk) { return hunk.lines.every(function (line, i) { var _hunk$lines2; return line.startsWith('\\') || line.endsWith('\r') || ((_hunk$lines2 = hunk.lines[i + 1]) === null || _hunk$lines2 === void 0 ? void 0 : _hunk$lines2.startsWith('\\')); }); }); }); } function parsePatch(uniDiff) { var diffstr = uniDiff.split(/\n/), list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:\s|diff\s|\-\-\-\s|\+\+\+\s|===================================================================)/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line) { throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], lines: [] }; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } var addCount = 0, removeCount = 0; for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || (_diffstr$i = diffstr[i]) !== null && _diffstr$i !== void 0 && _diffstr$i.startsWith('\\')); i++) { var _diffstr$i; var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { throw new Error("Hunk at line ".concat(chunkHeaderIndex + 1, " contained invalid line ").concat(diffstr[i])); } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform sanity checking if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return start + localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return start - localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { if (hasOnlyWinLineEndings(source) && isUnix(uniDiff)) { uniDiff = unixToWin(uniDiff); } else if (hasOnlyUnixLineEndings(source) && isWin(uniDiff)) { uniDiff = winToUnix(uniDiff); } } // Apply the diff to the input var lines = source.split('\n'), hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, fuzzFactor = options.fuzzFactor || 0, minLine = 0; if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { throw new Error('fuzzFactor must be a non-negative integer'); } // Special case for empty patch. if (!hunks.length) { return source; } // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a // newline that already exists - then we either return false and fail to apply the patch (if // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0). // If we do need to remove/add a newline at EOF, this will always be in the final hunk: var prevLine = '', removeEOFNL = false, addEOFNL = false; for (var i = 0; i < hunks[hunks.length - 1].lines.length; i++) { var line = hunks[hunks.length - 1].lines[i]; if (line[0] == '\\') { if (prevLine[0] == '+') { removeEOFNL = true; } else if (prevLine[0] == '-') { addEOFNL = true; } } prevLine = line; } if (removeEOFNL) { if (addEOFNL) { // This means the final line gets changed but doesn't have a trailing newline in either the // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if // fuzzFactor is 0, we simply validate that the source file has no trailing newline. if (!fuzzFactor && lines[lines.length - 1] == '') { return false; } } else if (lines[lines.length - 1] == '') { lines.pop(); } else if (!fuzzFactor) { return false; } } else if (addEOFNL) { if (lines[lines.length - 1] != '') { lines.push(''); } else if (!fuzzFactor) { return false; } } /** * Checks if the hunk can be made to fit at the provided location with at most `maxErrors` * insertions, substitutions, or deletions, while ensuring also that: * - lines deleted in the hunk match exactly, and * - wherever an insertion operation or block of insertion operations appears in the hunk, the * immediately preceding and following lines of context match exactly * * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0]. * * If the hunk can be applied, returns an object with properties `oldLineLastI` and * `replacementLines`. Otherwise, returns null. */ function applyHunk(hunkLines, toPos, maxErrors) { var hunkLinesI = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var lastContextLineMatched = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; var patchedLines = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; var patchedLinesLength = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; var nConsecutiveOldContextLines = 0; var nextContextLineMustMatch = false; for (; hunkLinesI < hunkLines.length; hunkLinesI++) { var hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : ' ', content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; if (operation === '-') { if (compareLine(toPos + 1, lines[toPos], operation, content)) { toPos++; nConsecutiveOldContextLines = 0; } else { if (!maxErrors || lines[toPos] == null) { return null; } patchedLines[patchedLinesLength] = lines[toPos]; return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); } } if (operation === '+') { if (!lastContextLineMatched) { return null; } patchedLines[patchedLinesLength] = content; patchedLinesLength++; nConsecutiveOldContextLines = 0; nextContextLineMustMatch = true; } if (operation === ' ') { nConsecutiveOldContextLines++; patchedLines[patchedLinesLength] = lines[toPos]; if (compareLine(toPos + 1, lines[toPos], operation, content)) { patchedLinesLength++; lastContextLineMatched = true; nextContextLineMustMatch = false; toPos++; } else { if (nextContextLineMustMatch || !maxErrors) { return null; } // Consider 3 possibilities in sequence: // 1. lines contains a *substitution* not included in the patch context, or // 2. lines contains an *insertion* not included in the patch context, or // 3. lines contains a *deletion* not included in the patch context // The first two options are of course only possible if the line from lines is non-null - // i.e. only option 3 is possible if we've overrun the end of the old file. return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); } } } // Before returning, trim any unmodified context lines off the end of patchedLines and reduce // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region // that starts in this hunk's trailing context. patchedLinesLength -= nConsecutiveOldContextLines; toPos -= nConsecutiveOldContextLines; patchedLines.length = patchedLinesLength; return { patchedLines: patchedLines, oldLineLastI: toPos - 1 }; } var resultLines = []; // Search best fit offsets for each hunk based on the previous ones var prevHunkOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var hunk = hunks[_i]; var hunkResult = void 0; var maxLine = lines.length - hunk.oldLines + fuzzFactor; var toPos = void 0; for (var maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { toPos = hunk.oldStart + prevHunkOffset - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; toPos !== undefined; toPos = iterator()) { hunkResult = applyHunk(hunk.lines, toPos, maxErrors); if (hunkResult) { break; } } if (hunkResult) { break; } } if (!hunkResult) { return false; } // Copy everything from the end of where we applied the last hunk to the start of this hunk for (var _i2 = minLine; _i2 < toPos; _i2++) { resultLines.push(lines[_i2]); } // Add the lines produced by applying the hunk: for (var _i3 = 0; _i3 < hunkResult.patchedLines.length; _i3++) { var _line = hunkResult.patchedLines[_i3]; resultLines.push(_line); } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunkResult.oldLineLastI + 1; // Note the offset between where the patch said the hunk should've applied and where we // applied it, so we can adjust future hunks accordingly: prevHunkOffset = toPos + 1 - hunk.oldStart; } // Copy over the rest of the lines from the old text for (var _i4 = minLine; _i4 < lines.length; _i4++) { resultLines.push(lines[_i4]); } return resultLines.join('\n'); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options === 'function') { options = { callback: options }; } if (typeof options.context === 'undefined') { options.context = 4; } if (options.newlineIsToken) { throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions'); } if (!options.callback) { return diffLinesResultToPatch(diffLines(oldStr, newStr, options)); } else { var _options = options, _callback = _options.callback; diffLines(oldStr, newStr, _objectSpread2(_objectSpread2({}, options), {}, { callback: function callback(diff) { var patch = diffLinesResultToPatch(diff); _callback(patch); } })); } function diffLinesResultToPatch(diff) { // STEP 1: Build up the patch with no "\ No newline at end of file" lines and with the arrays // of lines containing trailing newline characters. We'll tidy up later... if (!diff) { return; } diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop() { var current = diff[i], lines = current.lines || splitLines(current.value); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var _hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; hunks.push(_hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(); } // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add // "\ No newline at end of file". for (var _i = 0, _hunks = hunks; _i < _hunks.length; _i++) { var hunk = _hunks[_i]; for (var _i2 = 0; _i2 < hunk.lines.length; _i2++) { if (hunk.lines[_i2].endsWith('\n')) { hunk.lines[_i2] = hunk.lines[_i2].slice(0, -1); } else { hunk.lines.splice(_i2 + 1, 0, '\\ No newline at end of file'); _i2++; // Skip the line we just added, then continue iterating } } } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } } function formatPatch(diff) { if (Array.isArray(diff)) { return diff.map(formatPatch).join('\n'); } var ret = []; if (diff.oldFileName == diff.newFileName) { ret.push('Index: ' + diff.oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { var _options2; if (typeof options === 'function') { options = { callback: options }; } if (!((_options2 = options) !== null && _options2 !== void 0 && _options2.callback)) { var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); if (!patchObj) { return; } return formatPatch(patchObj); } else { var _options3 = options, _callback2 = _options3.callback; structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, _objectSpread2(_objectSpread2({}, options), {}, { callback: function callback(patchObj) { if (!patchObj) { _callback2(); } else { _callback2(formatPatch(patchObj)); } } })); } } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } /** * Split `text` into an array of lines, including the trailing newline character (where present) */ function splitLines(text) { var hasTrailingNl = text.endsWith('\n'); var result = text.split('\n').map(function (line) { return line + '\n'; }); if (hasTrailingNl) { result.pop(); } else { result.push(result.pop().slice(0, -1)); } return result; } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } function reversePatch(structuredPatch) { if (Array.isArray(structuredPatch)) { return structuredPatch.map(reversePatch).reverse(); } return _objectSpread2(_objectSpread2({}, structuredPatch), {}, { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(function (hunk) { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, lines: hunk.lines.map(function (l) { if (l.startsWith('-')) { return "+".concat(l.slice(1)); } if (l.startsWith('+')) { return "-".concat(l.slice(1)); } return l; }) }; }) }); } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } export { Diff, applyPatch, applyPatches, canonicalize, convertChangesToDMP, convertChangesToXML, createPatch, createTwoFilesPatch, diffArrays, diffChars, diffCss, diffJson, diffLines, diffSentences, diffTrimmedLines, diffWords, diffWordsWithSpace, formatPatch, merge, parsePatch, reversePatch, structuredPatch }; /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.applyPatch = applyPatch; exports.applyPatches = applyPatches; /*istanbul ignore end*/ var /*istanbul ignore start*/ _string = require("../util/string") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _lineEndings = require("./line-endings") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _parse = require("./parse") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _distanceIterator = _interopRequireDefault(require("../util/distance-iterator")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ function applyPatch(source, uniDiff) { /*istanbul ignore start*/ var /*istanbul ignore end*/ options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _parse /*istanbul ignore end*/ . /*istanbul ignore start*/ parsePatch) /*istanbul ignore end*/ (uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { if ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ hasOnlyWinLineEndings) /*istanbul ignore end*/ (source) && /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _lineEndings /*istanbul ignore end*/ . /*istanbul ignore start*/ isUnix) /*istanbul ignore end*/ (uniDiff)) { uniDiff = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _lineEndings /*istanbul ignore end*/ . /*istanbul ignore start*/ unixToWin) /*istanbul ignore end*/ (uniDiff); } else if ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _string /*istanbul ignore end*/ . /*istanbul ignore start*/ hasOnlyUnixLineEndings) /*istanbul ignore end*/ (source) && /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _lineEndings /*istanbul ignore end*/ . /*istanbul ignore start*/ isWin) /*istanbul ignore end*/ (uniDiff)) { uniDiff = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _lineEndings /*istanbul ignore end*/ . /*istanbul ignore start*/ winToUnix) /*istanbul ignore end*/ (uniDiff); } } // Apply the diff to the input var lines = source.split('\n'), hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ line === patchContent ); }, fuzzFactor = options.fuzzFactor || 0, minLine = 0; if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { throw new Error('fuzzFactor must be a non-negative integer'); } // Special case for empty patch. if (!hunks.length) { return source; } // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a // newline that already exists - then we either return false and fail to apply the patch (if // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0). // If we do need to remove/add a newline at EOF, this will always be in the final hunk: var prevLine = '', removeEOFNL = false, addEOFNL = false; for (var i = 0; i < hunks[hunks.length - 1].lines.length; i++) { var line = hunks[hunks.length - 1].lines[i]; if (line[0] == '\\') { if (prevLine[0] == '+') { removeEOFNL = true; } else if (prevLine[0] == '-') { addEOFNL = true; } } prevLine = line; } if (removeEOFNL) { if (addEOFNL) { // This means the final line gets changed but doesn't have a trailing newline in either the // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if // fuzzFactor is 0, we simply validate that the source file has no trailing newline. if (!fuzzFactor && lines[lines.length - 1] == '') { return false; } } else if (lines[lines.length - 1] == '') { lines.pop(); } else if (!fuzzFactor) { return false; } } else if (addEOFNL) { if (lines[lines.length - 1] != '') { lines.push(''); } else if (!fuzzFactor) { return false; } } /** * Checks if the hunk can be made to fit at the provided location with at most `maxErrors` * insertions, substitutions, or deletions, while ensuring also that: * - lines deleted in the hunk match exactly, and * - wherever an insertion operation or block of insertion operations appears in the hunk, the * immediately preceding and following lines of context match exactly * * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0]. * * If the hunk can be applied, returns an object with properties `oldLineLastI` and * `replacementLines`. Otherwise, returns null. */ function applyHunk(hunkLines, toPos, maxErrors) { /*istanbul ignore start*/ var /*istanbul ignore end*/ hunkLinesI = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; /*istanbul ignore start*/ var /*istanbul ignore end*/ lastContextLineMatched = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; /*istanbul ignore start*/ var /*istanbul ignore end*/ patchedLines = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; /*istanbul ignore start*/ var /*istanbul ignore end*/ patchedLinesLength = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; var nConsecutiveOldContextLines = 0; var nextContextLineMustMatch = false; for (; hunkLinesI < hunkLines.length; hunkLinesI++) { var hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : ' ', content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; if (operation === '-') { if (compareLine(toPos + 1, lines[toPos], operation, content)) { toPos++; nConsecutiveOldContextLines = 0; } else { if (!maxErrors || lines[toPos] == null) { return null; } patchedLines[patchedLinesLength] = lines[toPos]; return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); } } if (operation === '+') { if (!lastContextLineMatched) { return null; } patchedLines[patchedLinesLength] = content; patchedLinesLength++; nConsecutiveOldContextLines = 0; nextContextLineMustMatch = true; } if (operation === ' ') { nConsecutiveOldContextLines++; patchedLines[patchedLinesLength] = lines[toPos]; if (compareLine(toPos + 1, lines[toPos], operation, content)) { patchedLinesLength++; lastContextLineMatched = true; nextContextLineMustMatch = false; toPos++; } else { if (nextContextLineMustMatch || !maxErrors) { return null; } // Consider 3 possibilities in sequence: // 1. lines contains a *substitution* not included in the patch context, or // 2. lines contains an *insertion* not included in the patch context, or // 3. lines contains a *deletion* not included in the patch context // The first two options are of course only possible if the line from lines is non-null - // i.e. only option 3 is possible if we've overrun the end of the old file. return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); } } } // Before returning, trim any unmodified context lines off the end of patchedLines and reduce // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region // that starts in this hunk's trailing context. patchedLinesLength -= nConsecutiveOldContextLines; toPos -= nConsecutiveOldContextLines; patchedLines.length = patchedLinesLength; return { patchedLines: patchedLines, oldLineLastI: toPos - 1 }; } var resultLines = []; // Search best fit offsets for each hunk based on the previous ones var prevHunkOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var hunk = hunks[_i]; var hunkResult = /*istanbul ignore start*/ void 0 /*istanbul ignore end*/ ; var maxLine = lines.length - hunk.oldLines + fuzzFactor; var toPos = /*istanbul ignore start*/ void 0 /*istanbul ignore end*/ ; for (var maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { toPos = hunk.oldStart + prevHunkOffset - 1; var iterator = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _distanceIterator /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ])(toPos, minLine, maxLine); for (; toPos !== undefined; toPos = iterator()) { hunkResult = applyHunk(hunk.lines, toPos, maxErrors); if (hunkResult) { break; } } if (hunkResult) { break; } } if (!hunkResult) { return false; } // Copy everything from the end of where we applied the last hunk to the start of this hunk for (var _i2 = minLine; _i2 < toPos; _i2++) { resultLines.push(lines[_i2]); } // Add the lines produced by applying the hunk: for (var _i3 = 0; _i3 < hunkResult.patchedLines.length; _i3++) { var _line = hunkResult.patchedLines[_i3]; resultLines.push(_line); } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunkResult.oldLineLastI + 1; // Note the offset between where the patch said the hunk should've applied and where we // applied it, so we can adjust future hunks accordingly: prevHunkOffset = toPos + 1 - hunk.oldStart; } // Copy over the rest of the lines from the old text for (var _i4 = minLine; _i4 < lines.length; _i4++) { resultLines.push(lines[_i4]); } return resultLines.join('\n'); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _parse /*istanbul ignore end*/ . /*istanbul ignore start*/ parsePatch) /*istanbul ignore end*/ (uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfc3RyaW5nIiwicmVxdWlyZSIsIl9saW5lRW5kaW5ncyIsIl9wYXJzZSIsIl9kaXN0YW5jZUl0ZXJhdG9yIiwiX2ludGVyb3BSZXF1aXJlRGVmYXVsdCIsIm9iaiIsIl9fZXNNb2R1bGUiLCJhcHBseVBhdGNoIiwic291cmNlIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJhcmd1bWVudHMiLCJsZW5ndGgiLCJ1bmRlZmluZWQiLCJwYXJzZVBhdGNoIiwiQXJyYXkiLCJpc0FycmF5IiwiRXJyb3IiLCJhdXRvQ29udmVydExpbmVFbmRpbmdzIiwiaGFzT25seVdpbkxpbmVFbmRpbmdzIiwiaXNVbml4IiwidW5peFRvV2luIiwiaGFzT25seVVuaXhMaW5lRW5kaW5ncyIsImlzV2luIiwid2luVG9Vbml4IiwibGluZXMiLCJzcGxpdCIsImh1bmtzIiwiY29tcGFyZUxpbmUiLCJsaW5lTnVtYmVyIiwibGluZSIsIm9wZXJhdGlvbiIsInBhdGNoQ29udGVudCIsImZ1enpGYWN0b3IiLCJtaW5MaW5lIiwiTnVtYmVyIiwiaXNJbnRlZ2VyIiwicHJldkxpbmUiLCJyZW1vdmVFT0ZOTCIsImFkZEVPRk5MIiwiaSIsInBvcCIsInB1c2giLCJhcHBseUh1bmsiLCJodW5rTGluZXMiLCJ0b1BvcyIsIm1heEVycm9ycyIsImh1bmtMaW5lc0kiLCJsYXN0Q29udGV4dExpbmVNYXRjaGVkIiwicGF0Y2hlZExpbmVzIiwicGF0Y2hlZExpbmVzTGVuZ3RoIiwibkNvbnNlY3V0aXZlT2xkQ29udGV4dExpbmVzIiwibmV4dENvbnRleHRMaW5lTXVzdE1hdGNoIiwiaHVua0xpbmUiLCJjb250ZW50Iiwic3Vic3RyIiwib2xkTGluZUxhc3RJIiwicmVzdWx0TGluZXMiLCJwcmV2SHVua09mZnNldCIsImh1bmsiLCJodW5rUmVzdWx0IiwibWF4TGluZSIsIm9sZExpbmVzIiwib2xkU3RhcnQiLCJpdGVyYXRvciIsImRpc3RhbmNlSXRlcmF0b3IiLCJqb2luIiwiYXBwbHlQYXRjaGVzIiwiY3VycmVudEluZGV4IiwicHJvY2Vzc0luZGV4IiwiaW5kZXgiLCJjb21wbGV0ZSIsImxvYWRGaWxlIiwiZXJyIiwiZGF0YSIsInVwZGF0ZWRDb250ZW50IiwicGF0Y2hlZCJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9hcHBseS5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQge2hhc09ubHlXaW5MaW5lRW5kaW5ncywgaGFzT25seVVuaXhMaW5lRW5kaW5nc30gZnJvbSAnLi4vdXRpbC9zdHJpbmcnO1xuaW1wb3J0IHtpc1dpbiwgaXNVbml4LCB1bml4VG9XaW4sIHdpblRvVW5peH0gZnJvbSAnLi9saW5lLWVuZGluZ3MnO1xuaW1wb3J0IHtwYXJzZVBhdGNofSBmcm9tICcuL3BhcnNlJztcbmltcG9ydCBkaXN0YW5jZUl0ZXJhdG9yIGZyb20gJy4uL3V0aWwvZGlzdGFuY2UtaXRlcmF0b3InO1xuXG5leHBvcnQgZnVuY3Rpb24gYXBwbHlQYXRjaChzb3VyY2UsIHVuaURpZmYsIG9wdGlvbnMgPSB7fSkge1xuICBpZiAodHlwZW9mIHVuaURpZmYgPT09ICdzdHJpbmcnKSB7XG4gICAgdW5pRGlmZiA9IHBhcnNlUGF0Y2godW5pRGlmZik7XG4gIH1cblxuICBpZiAoQXJyYXkuaXNBcnJheSh1bmlEaWZmKSkge1xuICAgIGlmICh1bmlEaWZmLmxlbmd0aCA+IDEpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignYXBwbHlQYXRjaCBvbmx5IHdvcmtzIHdpdGggYSBzaW5nbGUgaW5wdXQuJyk7XG4gICAgfVxuXG4gICAgdW5pRGlmZiA9IHVuaURpZmZbMF07XG4gIH1cblxuICBpZiAob3B0aW9ucy5hdXRvQ29udmVydExpbmVFbmRpbmdzIHx8IG9wdGlvbnMuYXV0b0NvbnZlcnRMaW5lRW5kaW5ncyA9PSBudWxsKSB7XG4gICAgaWYgKGhhc09ubHlXaW5MaW5lRW5kaW5ncyhzb3VyY2UpICYmIGlzVW5peCh1bmlEaWZmKSkge1xuICAgICAgdW5pRGlmZiA9IHVuaXhUb1dpbih1bmlEaWZmKTtcbiAgICB9IGVsc2UgaWYgKGhhc09ubHlVbml4TGluZUVuZGluZ3Moc291cmNlKSAmJiBpc1dpbih1bmlEaWZmKSkge1xuICAgICAgdW5pRGlmZiA9IHdpblRvVW5peCh1bmlEaWZmKTtcbiAgICB9XG4gIH1cblxuICAvLyBBcHBseSB0aGUgZGlmZiB0byB0aGUgaW5wdXRcbiAgbGV0IGxpbmVzID0gc291cmNlLnNwbGl0KCdcXG4nKSxcbiAgICAgIGh1bmtzID0gdW5pRGlmZi5odW5rcyxcblxuICAgICAgY29tcGFyZUxpbmUgPSBvcHRpb25zLmNvbXBhcmVMaW5lIHx8ICgobGluZU51bWJlciwgbGluZSwgb3BlcmF0aW9uLCBwYXRjaENvbnRlbnQpID0+IGxpbmUgPT09IHBhdGNoQ29udGVudCksXG4gICAgICBmdXp6RmFjdG9yID0gb3B0aW9ucy5mdXp6RmFjdG9yIHx8IDAsXG4gICAgICBtaW5MaW5lID0gMDtcblxuICBpZiAoZnV6ekZhY3RvciA8IDAgfHwgIU51bWJlci5pc0ludGVnZXIoZnV6ekZhY3RvcikpIHtcbiAgICB0aHJvdyBuZXcgRXJyb3IoJ2Z1enpGYWN0b3IgbXVzdCBiZSBhIG5vbi1uZWdhdGl2ZSBpbnRlZ2VyJyk7XG4gIH1cblxuICAvLyBTcGVjaWFsIGNhc2UgZm9yIGVtcHR5IHBhdGNoLlxuICBpZiAoIWh1bmtzLmxlbmd0aCkge1xuICAgIHJldHVybiBzb3VyY2U7XG4gIH1cblxuICAvLyBCZWZvcmUgYW55dGhpbmcgZWxzZSwgaGFuZGxlIEVPRk5MIGluc2VydGlvbi9yZW1vdmFsLiBJZiB0aGUgcGF0Y2ggdGVsbHMgdXMgdG8gbWFrZSBhIGNoYW5nZVxuICAvLyB0byB0aGUgRU9GTkwgdGhhdCBpcyByZWR1bmRhbnQvaW1wb3NzaWJsZSAtIGkuZS4gdG8gcmVtb3ZlIGEgbmV3bGluZSB0aGF0J3Mgbm90IHRoZXJlLCBvciBhZGQgYVxuICAvLyBuZXdsaW5lIHRoYXQgYWxyZWFkeSBleGlzdHMgLSB0aGVuIHdlIGVpdGhlciByZXR1cm4gZmFsc2UgYW5kIGZhaWwgdG8gYXBwbHkgdGhlIHBhdGNoIChpZlxuICAvLyBmdXp6RmFjdG9yIGlzIDApIG9yIHNpbXBseSBpZ25vcmUgdGhlIHByb2JsZW0gYW5kIGRvIG5vdGhpbmcgKGlmIGZ1enpGYWN0b3IgaXMgPjApLlxuICAvLyBJZiB3ZSBkbyBuZWVkIHRvIHJlbW92ZS9hZGQgYSBuZXdsaW5lIGF0IEVPRiwgdGhpcyB3aWxsIGFsd2F5cyBiZSBpbiB0aGUgZmluYWwgaHVuazpcbiAgbGV0IHByZXZMaW5lID0gJycsXG4gICAgICByZW1vdmVFT0ZOTCA9IGZhbHNlLFxuICAgICAgYWRkRU9GTkwgPSBmYWxzZTtcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBodW5rc1todW5rcy5sZW5ndGggLSAxXS5saW5lcy5sZW5ndGg7IGkrKykge1xuICAgIGNvbnN0IGxpbmUgPSBodW5rc1todW5rcy5sZW5ndGggLSAxXS5saW5lc1tpXTtcbiAgICBpZiAobGluZVswXSA9PSAnXFxcXCcpIHtcbiAgICAgIGlmIChwcmV2TGluZVswXSA9PSAnKycpIHtcbiAgICAgICAgcmVtb3ZlRU9GTkwgPSB0cnVlO1xuICAgICAgfSBlbHNlIGlmIChwcmV2TGluZVswXSA9PSAnLScpIHtcbiAgICAgICAgYWRkRU9GTkwgPSB0cnVlO1xuICAgICAgfVxuICAgIH1cbiAgICBwcmV2TGluZSA9IGxpbmU7XG4gIH1cbiAgaWYgKHJlbW92ZUVPRk5MKSB7XG4gICAgaWYgKGFkZEVPRk5MKSB7XG4gICAgICAvLyBUaGlzIG1lYW5zIHRoZSBmaW5hbCBsaW5lIGdldHMgY2hhbmdlZCBidXQgZG9lc24ndCBoYXZlIGEgdHJhaWxpbmcgbmV3bGluZSBpbiBlaXRoZXIgdGhlXG4gICAgICAvLyBvcmlnaW5hbCBvciBwYXRjaGVkIHZlcnNpb24uIEluIHRoYXQgY2FzZSwgd2UgZG8gbm90aGluZyBpZiBmdXp6RmFjdG9yID4gMCwgYW5kIGlmXG4gICAgICAvLyBmdXp6RmFjdG9yIGlzIDAsIHdlIHNpbXBseSB2YWxpZGF0ZSB0aGF0IHRoZSBzb3VyY2UgZmlsZSBoYXMgbm8gdHJhaWxpbmcgbmV3bGluZS5cbiAgICAgIGlmICghZnV6ekZhY3RvciAmJiBsaW5lc1tsaW5lcy5sZW5ndGggLSAxXSA9PSAnJykge1xuICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICB9XG4gICAgfSBlbHNlIGlmIChsaW5lc1tsaW5lcy5sZW5ndGggLSAxXSA9PSAnJykge1xuICAgICAgbGluZXMucG9wKCk7XG4gICAgfSBlbHNlIGlmICghZnV6ekZhY3Rvcikge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfSBlbHNlIGlmIChhZGRFT0ZOTCkge1xuICAgIGlmIChsaW5lc1tsaW5lcy5sZW5ndGggLSAxXSAhPSAnJykge1xuICAgICAgbGluZXMucHVzaCgnJyk7XG4gICAgfSBlbHNlIGlmICghZnV6ekZhY3Rvcikge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIC8qKlxuICAgKiBDaGVja3MgaWYgdGhlIGh1bmsgY2FuIGJlIG1hZGUgdG8gZml0IGF0IHRoZSBwcm92aWRlZCBsb2NhdGlvbiB3aXRoIGF0IG1vc3QgYG1heEVycm9yc2BcbiAgICogaW5zZXJ0aW9ucywgc3Vic3RpdHV0aW9ucywgb3IgZGVsZXRpb25zLCB3aGlsZSBlbnN1cmluZyBhbHNvIHRoYXQ6XG4gICAqIC0gbGluZXMgZGVsZXRlZCBpbiB0aGUgaHVuayBtYXRjaCBleGFjdGx5LCBhbmRcbiAgICogLSB3aGVyZXZlciBhbiBpbnNlcnRpb24gb3BlcmF0aW9uIG9yIGJsb2NrIG9mIGluc2VydGlvbiBvcGVyYXRpb25zIGFwcGVhcnMgaW4gdGhlIGh1bmssIHRoZVxuICAgKiAgIGltbWVkaWF0ZWx5IHByZWNlZGluZyBhbmQgZm9sbG93aW5nIGxpbmVzIG9mIGNvbnRleHQgbWF0Y2ggZXhhY3RseVxuICAgKlxuICAgKiBgdG9Qb3NgIHNob3VsZCBiZSBzZXQgc3VjaCB0aGF0IGxpbmVzW3RvUG9zXSBpcyBtZWFudCB0byBtYXRjaCBodW5rTGluZXNbMF0uXG4gICAqXG4gICAqIElmIHRoZSBodW5rIGNhbiBiZSBhcHBsaWVkLCByZXR1cm5zIGFuIG9iamVjdCB3aXRoIHByb3BlcnRpZXMgYG9sZExpbmVMYXN0SWAgYW5kXG4gICAqIGByZXBsYWNlbWVudExpbmVzYC4gT3RoZXJ3aXNlLCByZXR1cm5zIG51bGwuXG4gICAqL1xuICBmdW5jdGlvbiBhcHBseUh1bmsoXG4gICAgaHVua0xpbmVzLFxuICAgIHRvUG9zLFxuICAgIG1heEVycm9ycyxcbiAgICBodW5rTGluZXNJID0gMCxcbiAgICBsYXN0Q29udGV4dExpbmVNYXRjaGVkID0gdHJ1ZSxcbiAgICBwYXRjaGVkTGluZXMgPSBbXSxcbiAgICBwYXRjaGVkTGluZXNMZW5ndGggPSAwLFxuICApIHtcbiAgICBsZXQgbkNvbnNlY3V0aXZlT2xkQ29udGV4dExpbmVzID0gMDtcbiAgICBsZXQgbmV4dENvbnRleHRMaW5lTXVzdE1hdGNoID0gZmFsc2U7XG4gICAgZm9yICg7IGh1bmtMaW5lc0kgPCBodW5rTGluZXMubGVuZ3RoOyBodW5rTGluZXNJKyspIHtcbiAgICAgIGxldCBodW5rTGluZSA9IGh1bmtMaW5lc1todW5rTGluZXNJXSxcbiAgICAgICAgICBvcGVyYXRpb24gPSAoaHVua0xpbmUubGVuZ3RoID4gMCA/IGh1bmtMaW5lWzBdIDogJyAnKSxcbiAgICAgICAgICBjb250ZW50ID0gKGh1bmtMaW5lLmxlbmd0aCA+IDAgPyBodW5rTGluZS5zdWJzdHIoMSkgOiBodW5rTGluZSk7XG5cbiAgICAgIGlmIChvcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICBpZiAoY29tcGFyZUxpbmUodG9Qb3MgKyAxLCBsaW5lc1t0b1Bvc10sIG9wZXJhdGlvbiwgY29udGVudCkpIHtcbiAgICAgICAgICB0b1BvcysrO1xuICAgICAgICAgIG5Db25zZWN1dGl2ZU9sZENvbnRleHRMaW5lcyA9IDA7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgaWYgKCFtYXhFcnJvcnMgfHwgbGluZXNbdG9Qb3NdID09IG51bGwpIHtcbiAgICAgICAgICAgIHJldHVybiBudWxsO1xuICAgICAgICAgIH1cbiAgICAgICAgICBwYXRjaGVkTGluZXNbcGF0Y2hlZExpbmVzTGVuZ3RoXSA9IGxpbmVzW3RvUG9zXTtcbiAgICAgICAgICByZXR1cm4gYXBwbHlIdW5rKFxuICAgICAgICAgICAgaHVua0xpbmVzLFxuICAgICAgICAgICAgdG9Qb3MgKyAxLFxuICAgICAgICAgICAgbWF4RXJyb3JzIC0gMSxcbiAgICAgICAgICAgIGh1bmtMaW5lc0ksXG4gICAgICAgICAgICBmYWxzZSxcbiAgICAgICAgICAgIHBhdGNoZWRMaW5lcyxcbiAgICAgICAgICAgIHBhdGNoZWRMaW5lc0xlbmd0aCArIDEsXG4gICAgICAgICAgKTtcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICBpZiAob3BlcmF0aW9uID09PSAnKycpIHtcbiAgICAgICAgaWYgKCFsYXN0Q29udGV4dExpbmVNYXRjaGVkKSB7XG4gICAgICAgICAgcmV0dXJuIG51bGw7XG4gICAgICAgIH1cbiAgICAgICAgcGF0Y2hlZExpbmVzW3BhdGNoZWRMaW5lc0xlbmd0aF0gPSBjb250ZW50O1xuICAgICAgICBwYXRjaGVkTGluZXNMZW5ndGgrKztcbiAgICAgICAgbkNvbnNlY3V0aXZlT2xkQ29udGV4dExpbmVzID0gMDtcbiAgICAgICAgbmV4dENvbnRleHRMaW5lTXVzdE1hdGNoID0gdHJ1ZTtcbiAgICAgIH1cblxuICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJyAnKSB7XG4gICAgICAgIG5Db25zZWN1dGl2ZU9sZENvbnRleHRMaW5lcysrO1xuICAgICAgICBwYXRjaGVkTGluZXNbcGF0Y2hlZExpbmVzTGVuZ3RoXSA9IGxpbmVzW3RvUG9zXTtcbiAgICAgICAgaWYgKGNvbXBhcmVMaW5lKHRvUG9zICsgMSwgbGluZXNbdG9Qb3NdLCBvcGVyYXRpb24sIGNvbnRlbnQpKSB7XG4gICAgICAgICAgcGF0Y2hlZExpbmVzTGVuZ3RoKys7XG4gICAgICAgICAgbGFzdENvbnRleHRMaW5lTWF0Y2hlZCA9IHRydWU7XG4gICAgICAgICAgbmV4dENvbnRleHRMaW5lTXVzdE1hdGNoID0gZmFsc2U7XG4gICAgICAgICAgdG9Qb3MrKztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBpZiAobmV4dENvbnRleHRMaW5lTXVzdE1hdGNoIHx8ICFtYXhFcnJvcnMpIHtcbiAgICAgICAgICAgIHJldHVybiBudWxsO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIC8vIENvbnNpZGVyIDMgcG9zc2liaWxpdGllcyBpbiBzZXF1ZW5jZTpcbiAgICAgICAgICAvLyAxLiBsaW5lcyBjb250YWlucyBhICpzdWJzdGl0dXRpb24qIG5vdCBpbmNsdWRlZCBpbiB0aGUgcGF0Y2ggY29udGV4dCwgb3JcbiAgICAgICAgICAvLyAyLiBsaW5lcyBjb250YWlucyBhbiAqaW5zZXJ0aW9uKiBub3QgaW5jbHVkZWQgaW4gdGhlIHBhdGNoIGNvbnRleHQsIG9yXG4gICAgICAgICAgLy8gMy4gbGluZXMgY29udGFpbnMgYSAqZGVsZXRpb24qIG5vdCBpbmNsdWRlZCBpbiB0aGUgcGF0Y2ggY29udGV4dFxuICAgICAgICAgIC8vIFRoZSBmaXJzdCB0d28gb3B0aW9ucyBhcmUgb2YgY291cnNlIG9ubHkgcG9zc2libGUgaWYgdGhlIGxpbmUgZnJvbSBsaW5lcyBpcyBub24tbnVsbCAtXG4gICAgICAgICAgLy8gaS5lLiBvbmx5IG9wdGlvbiAzIGlzIHBvc3NpYmxlIGlmIHdlJ3ZlIG92ZXJydW4gdGhlIGVuZCBvZiB0aGUgb2xkIGZpbGUuXG4gICAgICAgICAgcmV0dXJuIChcbiAgICAgICAgICAgIGxpbmVzW3RvUG9zXSAmJiAoXG4gICAgICAgICAgICAgIGFwcGx5SHVuayhcbiAgICAgICAgICAgICAgICBodW5rTGluZXMsXG4gICAgICAgICAgICAgICAgdG9Qb3MgKyAxLFxuICAgICAgICAgICAgICAgIG1heEVycm9ycyAtIDEsXG4gICAgICAgICAgICAgICAgaHVua0xpbmVzSSArIDEsXG4gICAgICAgICAgICAgICAgZmFsc2UsXG4gICAgICAgICAgICAgICAgcGF0Y2hlZExpbmVzLFxuICAgICAgICAgICAgICAgIHBhdGNoZWRMaW5lc0xlbmd0aCArIDFcbiAgICAgICAgICAgICAgKSB8fCBhcHBseUh1bmsoXG4gICAgICAgICAgICAgICAgaHVua0xpbmVzLFxuICAgICAgICAgICAgICAgIHRvUG9zICsgMSxcbiAgICAgICAgICAgICAgICBtYXhFcnJvcnMgLSAxLFxuICAgICAgICAgICAgICAgIGh1bmtMaW5lc0ksXG4gICAgICAgICAgICAgICAgZmFsc2UsXG4gICAgICAgICAgICAgICAgcGF0Y2hlZExpbmVzLFxuICAgICAgICAgICAgICAgIHBhdGNoZWRMaW5lc0xlbmd0aCArIDFcbiAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgKSB8fCBhcHBseUh1bmsoXG4gICAgICAgICAgICAgIGh1bmtMaW5lcyxcbiAgICAgICAgICAgICAgdG9Qb3MsXG4gICAgICAgICAgICAgIG1heEVycm9ycyAtIDEsXG4gICAgICAgICAgICAgIGh1bmtMaW5lc0kgKyAxLFxuICAgICAgICAgICAgICBmYWxzZSxcbiAgICAgICAgICAgICAgcGF0Y2hlZExpbmVzLFxuICAgICAgICAgICAgICBwYXRjaGVkTGluZXNMZW5ndGhcbiAgICAgICAgICAgIClcbiAgICAgICAgICApO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuXG4gICAgLy8gQmVmb3JlIHJldHVybmluZywgdHJpbSBhbnkgdW5tb2RpZmllZCBjb250ZXh0IGxpbmVzIG9mZiB0aGUgZW5kIG9mIHBhdGNoZWRMaW5lcyBhbmQgcmVkdWNlXG4gICAgLy8gdG9Qb3MgKGFuZCB0aHVzIG9sZExpbmVMYXN0SSkgYWNjb3JkaW5nbHkuIFRoaXMgYWxsb3dzIGxhdGVyIGh1bmtzIHRvIGJlIGFwcGxpZWQgdG8gYSByZWdpb25cbiAgICAvLyB0aGF0IHN0YXJ0cyBpbiB0aGlzIGh1bmsncyB0cmFpbGluZyBjb250ZXh0LlxuICAgIHBhdGNoZWRMaW5lc0xlbmd0aCAtPSBuQ29uc2VjdXRpdmVPbGRDb250ZXh0TGluZXM7XG4gICAgdG9Qb3MgLT0gbkNvbnNlY3V0aXZlT2xkQ29udGV4dExpbmVzO1xuICAgIHBhdGNoZWRMaW5lcy5sZW5ndGggPSBwYXRjaGVkTGluZXNMZW5ndGg7XG4gICAgcmV0dXJuIHtcbiAgICAgIHBhdGNoZWRMaW5lcyxcbiAgICAgIG9sZExpbmVMYXN0STogdG9Qb3MgLSAxXG4gICAgfTtcbiAgfVxuXG4gIGNvbnN0IHJlc3VsdExpbmVzID0gW107XG5cbiAgLy8gU2VhcmNoIGJlc3QgZml0IG9mZnNldHMgZm9yIGVhY2ggaHVuayBiYXNlZCBvbiB0aGUgcHJldmlvdXMgb25lc1xuICBsZXQgcHJldkh1bmtPZmZzZXQgPSAwO1xuICBmb3IgKGxldCBpID0gMDsgaSA8IGh1bmtzLmxlbmd0aDsgaSsrKSB7XG4gICAgY29uc3QgaHVuayA9IGh1bmtzW2ldO1xuICAgIGxldCBodW5rUmVzdWx0O1xuICAgIGxldCBtYXhMaW5lID0gbGluZXMubGVuZ3RoIC0gaHVuay5vbGRMaW5lcyArIGZ1enpGYWN0b3I7XG4gICAgbGV0IHRvUG9zO1xuICAgIGZvciAobGV0IG1heEVycm9ycyA9IDA7IG1heEVycm9ycyA8PSBmdXp6RmFjdG9yOyBtYXhFcnJvcnMrKykge1xuICAgICAgdG9Qb3MgPSBodW5rLm9sZFN0YXJ0ICsgcHJldkh1bmtPZmZzZXQgLSAxO1xuICAgICAgbGV0IGl0ZXJhdG9yID0gZGlzdGFuY2VJdGVyYXRvcih0b1BvcywgbWluTGluZSwgbWF4TGluZSk7XG4gICAgICBmb3IgKDsgdG9Qb3MgIT09IHVuZGVmaW5lZDsgdG9Qb3MgPSBpdGVyYXRvcigpKSB7XG4gICAgICAgIGh1bmtSZXN1bHQgPSBhcHBseUh1bmsoaHVuay5saW5lcywgdG9Qb3MsIG1heEVycm9ycyk7XG4gICAgICAgIGlmIChodW5rUmVzdWx0KSB7XG4gICAgICAgICAgYnJlYWs7XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIGlmIChodW5rUmVzdWx0KSB7XG4gICAgICAgIGJyZWFrO1xuICAgICAgfVxuICAgIH1cblxuICAgIGlmICghaHVua1Jlc3VsdCkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cblxuICAgIC8vIENvcHkgZXZlcnl0aGluZyBmcm9tIHRoZSBlbmQgb2Ygd2hlcmUgd2UgYXBwbGllZCB0aGUgbGFzdCBodW5rIHRvIHRoZSBzdGFydCBvZiB0aGlzIGh1bmtcbiAgICBmb3IgKGxldCBpID0gbWluTGluZTsgaSA8IHRvUG9zOyBpKyspIHtcbiAgICAgIHJlc3VsdExpbmVzLnB1c2gobGluZXNbaV0pO1xuICAgIH1cblxuICAgIC8vIEFkZCB0aGUgbGluZXMgcHJvZHVjZWQgYnkgYXBwbHlpbmcgdGhlIGh1bms6XG4gICAgZm9yIChsZXQgaSA9IDA7IGkgPCBodW5rUmVzdWx0LnBhdGNoZWRMaW5lcy5sZW5ndGg7IGkrKykge1xuICAgICAgY29uc3QgbGluZSA9IGh1bmtSZXN1bHQucGF0Y2hlZExpbmVzW2ldO1xuICAgICAgcmVzdWx0TGluZXMucHVzaChsaW5lKTtcbiAgICB9XG5cbiAgICAvLyBTZXQgbG93ZXIgdGV4dCBsaW1pdCB0byBlbmQgb2YgdGhlIGN1cnJlbnQgaHVuaywgc28gbmV4dCBvbmVzIGRvbid0IHRyeVxuICAgIC8vIHRvIGZpdCBvdmVyIGFscmVhZHkgcGF0Y2hlZCB0ZXh0XG4gICAgbWluTGluZSA9IGh1bmtSZXN1bHQub2xkTGluZUxhc3RJICsgMTtcblxuICAgIC8vIE5vdGUgdGhlIG9mZnNldCBiZXR3ZWVuIHdoZXJlIHRoZSBwYXRjaCBzYWlkIHRoZSBodW5rIHNob3VsZCd2ZSBhcHBsaWVkIGFuZCB3aGVyZSB3ZVxuICAgIC8vIGFwcGxpZWQgaXQsIHNvIHdlIGNhbiBhZGp1c3QgZnV0dXJlIGh1bmtzIGFjY29yZGluZ2x5OlxuICAgIHByZXZIdW5rT2Zmc2V0ID0gdG9Qb3MgKyAxIC0gaHVuay5vbGRTdGFydDtcbiAgfVxuXG4gIC8vIENvcHkgb3ZlciB0aGUgcmVzdCBvZiB0aGUgbGluZXMgZnJvbSB0aGUgb2xkIHRleHRcbiAgZm9yIChsZXQgaSA9IG1pbkxpbmU7IGkgPCBsaW5lcy5sZW5ndGg7IGkrKykge1xuICAgIHJlc3VsdExpbmVzLnB1c2gobGluZXNbaV0pO1xuICB9XG5cbiAgcmV0dXJuIHJlc3VsdExpbmVzLmpvaW4oJ1xcbicpO1xufVxuXG4vLyBXcmFwcGVyIHRoYXQgc3VwcG9ydHMgbXVsdGlwbGUgZmlsZSBwYXRjaGVzIHZpYSBjYWxsYmFja3MuXG5leHBvcnQgZnVuY3Rpb24gYXBwbHlQYXRjaGVzKHVuaURpZmYsIG9wdGlvbnMpIHtcbiAgaWYgKHR5cGVvZiB1bmlEaWZmID09PSAnc3RyaW5nJykge1xuICAgIHVuaURpZmYgPSBwYXJzZVBhdGNoKHVuaURpZmYpO1xuICB9XG5cbiAgbGV0IGN1cnJlbnRJbmRleCA9IDA7XG4gIGZ1bmN0aW9uIHByb2Nlc3NJbmRleCgpIHtcbiAgICBsZXQgaW5kZXggPSB1bmlEaWZmW2N1cnJlbnRJbmRleCsrXTtcbiAgICBpZiAoIWluZGV4KSB7XG4gICAgICByZXR1cm4gb3B0aW9ucy5jb21wbGV0ZSgpO1xuICAgIH1cblxuICAgIG9wdGlvbnMubG9hZEZpbGUoaW5kZXgsIGZ1bmN0aW9uKGVyciwgZGF0YSkge1xuICAgICAgaWYgKGVycikge1xuICAgICAgICByZXR1cm4gb3B0aW9ucy5jb21wbGV0ZShlcnIpO1xuICAgICAgfVxuXG4gICAgICBsZXQgdXBkYXRlZENvbnRlbnQgPSBhcHBseVBhdGNoKGRhdGEsIGluZGV4LCBvcHRpb25zKTtcbiAgICAgIG9wdGlvbnMucGF0Y2hlZChpbmRleCwgdXBkYXRlZENvbnRlbnQsIGZ1bmN0aW9uKGVycikge1xuICAgICAgICBpZiAoZXJyKSB7XG4gICAgICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoZXJyKTtcbiAgICAgICAgfVxuXG4gICAgICAgIHByb2Nlc3NJbmRleCgpO1xuICAgICAgfSk7XG4gICAgfSk7XG4gIH1cbiAgcHJvY2Vzc0luZGV4KCk7XG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQUE7QUFBQUEsT0FBQSxHQUFBQyxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQUMsWUFBQSxHQUFBRCxPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQUUsTUFBQSxHQUFBRixPQUFBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQUcsaUJBQUEsR0FBQUMsc0JBQUEsQ0FBQUosT0FBQTtBQUFBO0FBQUE7QUFBeUQsbUNBQUFJLHVCQUFBQyxHQUFBLFdBQUFBLEdBQUEsSUFBQUEsR0FBQSxDQUFBQyxVQUFBLEdBQUFELEdBQUEsZ0JBQUFBLEdBQUE7QUFBQTtBQUVsRCxTQUFTRSxVQUFVQSxDQUFDQyxNQUFNLEVBQUVDLE9BQU8sRUFBZ0I7RUFBQTtFQUFBO0VBQUE7RUFBZEMsT0FBTyxHQUFBQyxTQUFBLENBQUFDLE1BQUEsUUFBQUQsU0FBQSxRQUFBRSxTQUFBLEdBQUFGLFNBQUEsTUFBRyxDQUFDLENBQUM7RUFDdEQsSUFBSSxPQUFPRixPQUFPLEtBQUssUUFBUSxFQUFFO0lBQy9CQSxPQUFPO0lBQUc7SUFBQTtJQUFBO0lBQUFLO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBLFVBQVU7SUFBQTtJQUFBLENBQUNMLE9BQU8sQ0FBQztFQUMvQjtFQUVBLElBQUlNLEtBQUssQ0FBQ0MsT0FBTyxDQUFDUCxPQUFPLENBQUMsRUFBRTtJQUMxQixJQUFJQSxPQUFPLENBQUNHLE1BQU0sR0FBRyxDQUFDLEVBQUU7TUFDdEIsTUFBTSxJQUFJSyxLQUFLLENBQUMsNENBQTRDLENBQUM7SUFDL0Q7SUFFQVIsT0FBTyxHQUFHQSxPQUFPLENBQUMsQ0FBQyxDQUFDO0VBQ3RCO0VBRUEsSUFBSUMsT0FBTyxDQUFDUSxzQkFBc0IsSUFBSVIsT0FBTyxDQUFDUSxzQkFBc0IsSUFBSSxJQUFJLEVBQUU7SUFDNUU7SUFBSTtJQUFBO0lBQUE7SUFBQUM7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEscUJBQXFCO0lBQUE7SUFBQSxDQUFDWCxNQUFNLENBQUM7SUFBSTtJQUFBO0lBQUE7SUFBQVk7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsTUFBTTtJQUFBO0lBQUEsQ0FBQ1gsT0FBTyxDQUFDLEVBQUU7TUFDcERBLE9BQU87TUFBRztNQUFBO01BQUE7TUFBQVk7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUEsU0FBUztNQUFBO01BQUEsQ0FBQ1osT0FBTyxDQUFDO0lBQzlCLENBQUMsTUFBTTtJQUFJO0lBQUE7SUFBQTtJQUFBYTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQSxzQkFBc0I7SUFBQTtJQUFBLENBQUNkLE1BQU0sQ0FBQztJQUFJO0lBQUE7SUFBQTtJQUFBZTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQSxLQUFLO0lBQUE7SUFBQSxDQUFDZCxPQUFPLENBQUMsRUFBRTtNQUMzREEsT0FBTztNQUFHO01BQUE7TUFBQTtNQUFBZTtNQUFBQTtNQUFBQTtNQUFBQTtNQUFBQTtNQUFBQSxTQUFTO01BQUE7TUFBQSxDQUFDZixPQUFPLENBQUM7SUFDOUI7RUFDRjs7RUFFQTtFQUNBLElBQUlnQixLQUFLLEdBQUdqQixNQUFNLENBQUNrQixLQUFLLENBQUMsSUFBSSxDQUFDO0lBQzFCQyxLQUFLLEdBQUdsQixPQUFPLENBQUNrQixLQUFLO0lBRXJCQyxXQUFXLEdBQUdsQixPQUFPLENBQUNrQixXQUFXLElBQUssVUFBQ0MsVUFBVSxFQUFFQyxJQUFJLEVBQUVDLFNBQVMsRUFBRUMsWUFBWTtJQUFBO0lBQUE7TUFBQTtRQUFBO1FBQUtGLElBQUksS0FBS0U7TUFBWTtJQUFBLENBQUM7SUFDM0dDLFVBQVUsR0FBR3ZCLE9BQU8sQ0FBQ3VCLFVBQVUsSUFBSSxDQUFDO0lBQ3BDQyxPQUFPLEdBQUcsQ0FBQztFQUVmLElBQUlELFVBQVUsR0FBRyxDQUFDLElBQUksQ0FBQ0UsTUFBTSxDQUFDQyxTQUFTLENBQUNILFVBQVUsQ0FBQyxFQUFFO0lBQ25ELE1BQU0sSUFBSWhCLEtBQUssQ0FBQywyQ0FBMkMsQ0FBQztFQUM5RDs7RUFFQTtFQUNBLElBQUksQ0FBQ1UsS0FBSyxDQUFDZixNQUFNLEVBQUU7SUFDakIsT0FBT0osTUFBTTtFQUNmOztFQUVBO0VBQ0E7RUFDQTtFQUNBO0VBQ0E7RUFDQSxJQUFJNkIsUUFBUSxHQUFHLEVBQUU7SUFDYkMsV0FBVyxHQUFHLEtBQUs7SUFDbkJDLFFBQVEsR0FBRyxLQUFLO0VBQ3BCLEtBQUssSUFBSUMsQ0FBQyxHQUFHLENBQUMsRUFBRUEsQ0FBQyxHQUFHYixLQUFLLENBQUNBLEtBQUssQ0FBQ2YsTUFBTSxHQUFHLENBQUMsQ0FBQyxDQUFDYSxLQUFLLENBQUNiLE1BQU0sRUFBRTRCLENBQUMsRUFBRSxFQUFFO0lBQzdELElBQU1WLElBQUksR0FBR0gsS0FBSyxDQUFDQSxLQUFLLENBQUNmLE1BQU0sR0FBRyxDQUFDLENBQUMsQ0FBQ2EsS0FBSyxDQUFDZSxDQUFDLENBQUM7SUFDN0MsSUFBSVYsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLElBQUksRUFBRTtNQUNuQixJQUFJTyxRQUFRLENBQUMsQ0FBQyxDQUFDLElBQUksR0FBRyxFQUFFO1FBQ3RCQyxXQUFXLEdBQUcsSUFBSTtNQUNwQixDQUFDLE1BQU0sSUFBSUQsUUFBUSxDQUFDLENBQUMsQ0FBQyxJQUFJLEdBQUcsRUFBRTtRQUM3QkUsUUFBUSxHQUFHLElBQUk7TUFDakI7SUFDRjtJQUNBRixRQUFRLEdBQUdQLElBQUk7RUFDakI7RUFDQSxJQUFJUSxXQUFXLEVBQUU7SUFDZixJQUFJQyxRQUFRLEVBQUU7TUFDWjtNQUNBO01BQ0E7TUFDQSxJQUFJLENBQUNOLFVBQVUsSUFBSVIsS0FBSyxDQUFDQSxLQUFLLENBQUNiLE1BQU0sR0FBRyxDQUFDLENBQUMsSUFBSSxFQUFFLEVBQUU7UUFDaEQsT0FBTyxLQUFLO01BQ2Q7SUFDRixDQUFDLE1BQU0sSUFBSWEsS0FBSyxDQUFDQSxLQUFLLENBQUNiLE1BQU0sR0FBRyxDQUFDLENBQUMsSUFBSSxFQUFFLEVBQUU7TUFDeENhLEtBQUssQ0FBQ2dCLEdBQUcsQ0FBQyxDQUFDO0lBQ2IsQ0FBQyxNQUFNLElBQUksQ0FBQ1IsVUFBVSxFQUFFO01BQ3RCLE9BQU8sS0FBSztJQUNkO0VBQ0YsQ0FBQyxNQUFNLElBQUlNLFFBQVEsRUFBRTtJQUNuQixJQUFJZCxLQUFLLENBQUNBLEtBQUssQ0FBQ2IsTUFBTSxHQUFHLENBQUMsQ0FBQyxJQUFJLEVBQUUsRUFBRTtNQUNqQ2EsS0FBSyxDQUFDaUIsSUFBSSxDQUFDLEVBQUUsQ0FBQztJQUNoQixDQUFDLE1BQU0sSUFBSSxDQUFDVCxVQUFVLEVBQUU7TUFDdEIsT0FBTyxLQUFLO0lBQ2Q7RUFDRjs7RUFFQTtBQUNGO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7RUFDRSxTQUFTVSxTQUFTQSxDQUNoQkMsU0FBUyxFQUNUQyxLQUFLLEVBQ0xDLFNBQVMsRUFLVDtJQUFBO0lBQUE7SUFBQTtJQUpBQyxVQUFVLEdBQUFwQyxTQUFBLENBQUFDLE1BQUEsUUFBQUQsU0FBQSxRQUFBRSxTQUFBLEdBQUFGLFNBQUEsTUFBRyxDQUFDO0lBQUE7SUFBQTtJQUFBO0lBQ2RxQyxzQkFBc0IsR0FBQXJDLFNBQUEsQ0FBQUMsTUFBQSxRQUFBRCxTQUFBLFFBQUFFLFNBQUEsR0FBQUYsU0FBQSxNQUFHLElBQUk7SUFBQTtJQUFBO0lBQUE7SUFDN0JzQyxZQUFZLEdBQUF0QyxTQUFBLENBQUFDLE1BQUEsUUFBQUQsU0FBQSxRQUFBRSxTQUFBLEdBQUFGLFNBQUEsTUFBRyxFQUFFO0lBQUE7SUFBQTtJQUFBO0lBQ2pCdUMsa0JBQWtCLEdBQUF2QyxTQUFBLENBQUFDLE1BQUEsUUFBQUQsU0FBQSxRQUFBRSxTQUFBLEdBQUFGLFNBQUEsTUFBRyxDQUFDO0lBRXRCLElBQUl3QywyQkFBMkIsR0FBRyxDQUFDO0lBQ25DLElBQUlDLHdCQUF3QixHQUFHLEtBQUs7SUFDcEMsT0FBT0wsVUFBVSxHQUFHSCxTQUFTLENBQUNoQyxNQUFNLEVBQUVtQyxVQUFVLEVBQUUsRUFBRTtNQUNsRCxJQUFJTSxRQUFRLEdBQUdULFNBQVMsQ0FBQ0csVUFBVSxDQUFDO1FBQ2hDaEIsU0FBUyxHQUFJc0IsUUFBUSxDQUFDekMsTUFBTSxHQUFHLENBQUMsR0FBR3lDLFFBQVEsQ0FBQyxDQUFDLENBQUMsR0FBRyxHQUFJO1FBQ3JEQyxPQUFPLEdBQUlELFFBQVEsQ0FBQ3pDLE1BQU0sR0FBRyxDQUFDLEdBQUd5QyxRQUFRLENBQUNFLE1BQU0sQ0FBQyxDQUFDLENBQUMsR0FBR0YsUUFBUztNQUVuRSxJQUFJdEIsU0FBUyxLQUFLLEdBQUcsRUFBRTtRQUNyQixJQUFJSCxXQUFXLENBQUNpQixLQUFLLEdBQUcsQ0FBQyxFQUFFcEIsS0FBSyxDQUFDb0IsS0FBSyxDQUFDLEVBQUVkLFNBQVMsRUFBRXVCLE9BQU8sQ0FBQyxFQUFFO1VBQzVEVCxLQUFLLEVBQUU7VUFDUE0sMkJBQTJCLEdBQUcsQ0FBQztRQUNqQyxDQUFDLE1BQU07VUFDTCxJQUFJLENBQUNMLFNBQVMsSUFBSXJCLEtBQUssQ0FBQ29CLEtBQUssQ0FBQyxJQUFJLElBQUksRUFBRTtZQUN0QyxPQUFPLElBQUk7VUFDYjtVQUNBSSxZQUFZLENBQUNDLGtCQUFrQixDQUFDLEdBQUd6QixLQUFLLENBQUNvQixLQUFLLENBQUM7VUFDL0MsT0FBT0YsU0FBUyxDQUNkQyxTQUFTLEVBQ1RDLEtBQUssR0FBRyxDQUFDLEVBQ1RDLFNBQVMsR0FBRyxDQUFDLEVBQ2JDLFVBQVUsRUFDVixLQUFLLEVBQ0xFLFlBQVksRUFDWkMsa0JBQWtCLEdBQUcsQ0FDdkIsQ0FBQztRQUNIO01BQ0Y7TUFFQSxJQUFJbkIsU0FBUyxLQUFLLEdBQUcsRUFBRTtRQUNyQixJQUFJLENBQUNpQixzQkFBc0IsRUFBRTtVQUMzQixPQUFPLElBQUk7UUFDYjtRQUNBQyxZQUFZLENBQUNDLGtCQUFrQixDQUFDLEdBQUdJLE9BQU87UUFDMUNKLGtCQUFrQixFQUFFO1FBQ3BCQywyQkFBMkIsR0FBRyxDQUFDO1FBQy9CQyx3QkFBd0IsR0FBRyxJQUFJO01BQ2pDO01BRUEsSUFBSXJCLFNBQVMsS0FBSyxHQUFHLEVBQUU7UUFDckJvQiwyQkFBMkIsRUFBRTtRQUM3QkYsWUFBWSxDQUFDQyxrQkFBa0IsQ0FBQyxHQUFHekIsS0FBSyxDQUFDb0IsS0FBSyxDQUFDO1FBQy9DLElBQUlqQixXQUFXLENBQUNpQixLQUFLLEdBQUcsQ0FBQyxFQUFFcEIsS0FBSyxDQUFDb0IsS0FBSyxDQUFDLEVBQUVkLFNBQVMsRUFBRXVCLE9BQU8sQ0FBQyxFQUFFO1VBQzVESixrQkFBa0IsRUFBRTtVQUNwQkYsc0JBQXNCLEdBQUcsSUFBSTtVQUM3Qkksd0JBQXdCLEdBQUcsS0FBSztVQUNoQ1AsS0FBSyxFQUFFO1FBQ1QsQ0FBQyxNQUFNO1VBQ0wsSUFBSU8sd0JBQXdCLElBQUksQ0FBQ04sU0FBUyxFQUFFO1lBQzFDLE9BQU8sSUFBSTtVQUNiOztVQUVBO1VBQ0E7VUFDQTtVQUNBO1VBQ0E7VUFDQTtVQUNBLE9BQ0VyQixLQUFLLENBQUNvQixLQUFLLENBQUMsS0FDVkYsU0FBUyxDQUNQQyxTQUFTLEVBQ1RDLEtBQUssR0FBRyxDQUFDLEVBQ1RDLFNBQVMsR0FBRyxDQUFDLEVBQ2JDLFVBQVUsR0FBRyxDQUFDLEVBQ2QsS0FBSyxFQUNMRSxZQUFZLEVBQ1pDLGtCQUFrQixHQUFHLENBQ3ZCLENBQUMsSUFBSVAsU0FBUyxDQUNaQyxTQUFTLEVBQ1RDLEtBQUssR0FBRyxDQUFDLEVBQ1RDLFNBQVMsR0FBRyxDQUFDLEVBQ2JDLFVBQVUsRUFDVixLQUFLLEVBQ0xFLFlBQVksRUFDWkMsa0JBQWtCLEdBQUcsQ0FDdkIsQ0FBQyxDQUNGLElBQUlQLFNBQVMsQ0FDWkMsU0FBUyxFQUNUQyxLQUFLLEVBQ0xDLFNBQVMsR0FBRyxDQUFDLEVBQ2JDLFVBQVUsR0FBRyxDQUFDLEVBQ2QsS0FBSyxFQUNMRSxZQUFZLEVBQ1pDLGtCQUNGLENBQUM7UUFFTDtNQUNGO0lBQ0Y7O0lBRUE7SUFDQTtJQUNBO0lBQ0FBLGtCQUFrQixJQUFJQywyQkFBMkI7SUFDakROLEtBQUssSUFBSU0sMkJBQTJCO0lBQ3BDRixZQUFZLENBQUNyQyxNQUFNLEdBQUdzQyxrQkFBa0I7SUFDeEMsT0FBTztNQUNMRCxZQUFZLEVBQVpBLFlBQVk7TUFDWk8sWUFBWSxFQUFFWCxLQUFLLEdBQUc7SUFDeEIsQ0FBQztFQUNIO0VBRUEsSUFBTVksV0FBVyxHQUFHLEVBQUU7O0VBRXRCO0VBQ0EsSUFBSUMsY0FBYyxHQUFHLENBQUM7RUFDdEIsS0FBSyxJQUFJbEIsRUFBQyxHQUFHLENBQUMsRUFBRUEsRUFBQyxHQUFHYixLQUFLLENBQUNmLE1BQU0sRUFBRTRCLEVBQUMsRUFBRSxFQUFFO0lBQ3JDLElBQU1tQixJQUFJLEdBQUdoQyxLQUFLLENBQUNhLEVBQUMsQ0FBQztJQUNyQixJQUFJb0IsVUFBVTtJQUFBO0lBQUE7SUFBQTtJQUFBO0lBQ2QsSUFBSUMsT0FBTyxHQUFHcEMsS0FBSyxDQUFDYixNQUFNLEdBQUcrQyxJQUFJLENBQUNHLFFBQVEsR0FBRzdCLFVBQVU7SUFDdkQsSUFBSVksS0FBSztJQUFBO0lBQUE7SUFBQTtJQUFBO0lBQ1QsS0FBSyxJQUFJQyxTQUFTLEdBQUcsQ0FBQyxFQUFFQSxTQUFTLElBQUliLFVBQVUsRUFBRWEsU0FBUyxFQUFFLEVBQUU7TUFDNURELEtBQUssR0FBR2MsSUFBSSxDQUFDSSxRQUFRLEdBQUdMLGNBQWMsR0FBRyxDQUFDO01BQzFDLElBQUlNLFFBQVE7TUFBRztNQUFBO01BQUE7TUFBQUM7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUE7TUFBQUEsQ0FBZ0IsRUFBQ3BCLEtBQUssRUFBRVgsT0FBTyxFQUFFMkIsT0FBTyxDQUFDO01BQ3hELE9BQU9oQixLQUFLLEtBQUtoQyxTQUFTLEVBQUVnQyxLQUFLLEdBQUdtQixRQUFRLENBQUMsQ0FBQyxFQUFFO1FBQzlDSixVQUFVLEdBQUdqQixTQUFTLENBQUNnQixJQUFJLENBQUNsQyxLQUFLLEVBQUVvQixLQUFLLEVBQUVDLFNBQVMsQ0FBQztRQUNwRCxJQUFJYyxVQUFVLEVBQUU7VUFDZDtRQUNGO01BQ0Y7TUFDQSxJQUFJQSxVQUFVLEVBQUU7UUFDZDtNQUNGO0lBQ0Y7SUFFQSxJQUFJLENBQUNBLFVBQVUsRUFBRTtNQUNmLE9BQU8sS0FBSztJQUNkOztJQUVBO0lBQ0EsS0FBSyxJQUFJcEIsR0FBQyxHQUFHTixPQUFPLEVBQUVNLEdBQUMsR0FBR0ssS0FBSyxFQUFFTCxHQUFDLEVBQUUsRUFBRTtNQUNwQ2lCLFdBQVcsQ0FBQ2YsSUFBSSxDQUFDakIsS0FBSyxDQUFDZSxHQUFDLENBQUMsQ0FBQztJQUM1Qjs7SUFFQTtJQUNBLEtBQUssSUFBSUEsR0FBQyxHQUFHLENBQUMsRUFBRUEsR0FBQyxHQUFHb0IsVUFBVSxDQUFDWCxZQUFZLENBQUNyQyxNQUFNLEVBQUU0QixHQUFDLEVBQUUsRUFBRTtNQUN2RCxJQUFNVixLQUFJLEdBQUc4QixVQUFVLENBQUNYLFlBQVksQ0FBQ1QsR0FBQyxDQUFDO01BQ3ZDaUIsV0FBVyxDQUFDZixJQUFJLENBQUNaLEtBQUksQ0FBQztJQUN4Qjs7SUFFQTtJQUNBO0lBQ0FJLE9BQU8sR0FBRzBCLFVBQVUsQ0FBQ0osWUFBWSxHQUFHLENBQUM7O0lBRXJDO0lBQ0E7SUFDQUUsY0FBYyxHQUFHYixLQUFLLEdBQUcsQ0FBQyxHQUFHYyxJQUFJLENBQUNJLFFBQVE7RUFDNUM7O0VBRUE7RUFDQSxLQUFLLElBQUl2QixHQUFDLEdBQUdOLE9BQU8sRUFBRU0sR0FBQyxHQUFHZixLQUFLLENBQUNiLE1BQU0sRUFBRTRCLEdBQUMsRUFBRSxFQUFFO0lBQzNDaUIsV0FBVyxDQUFDZixJQUFJLENBQUNqQixLQUFLLENBQUNlLEdBQUMsQ0FBQyxDQUFDO0VBQzVCO0VBRUEsT0FBT2lCLFdBQVcsQ0FBQ1MsSUFBSSxDQUFDLElBQUksQ0FBQztBQUMvQjs7QUFFQTtBQUNPLFNBQVNDLFlBQVlBLENBQUMxRCxPQUFPLEVBQUVDLE9BQU8sRUFBRTtFQUM3QyxJQUFJLE9BQU9ELE9BQU8sS0FBSyxRQUFRLEVBQUU7SUFDL0JBLE9BQU87SUFBRztJQUFBO0lBQUE7SUFBQUs7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsVUFBVTtJQUFBO0lBQUEsQ0FBQ0wsT0FBTyxDQUFDO0VBQy9CO0VBRUEsSUFBSTJELFlBQVksR0FBRyxDQUFDO0VBQ3BCLFNBQVNDLFlBQVlBLENBQUEsRUFBRztJQUN0QixJQUFJQyxLQUFLLEdBQUc3RCxPQUFPLENBQUMyRCxZQUFZLEVBQUUsQ0FBQztJQUNuQyxJQUFJLENBQUNFLEtBQUssRUFBRTtNQUNWLE9BQU81RCxPQUFPLENBQUM2RCxRQUFRLENBQUMsQ0FBQztJQUMzQjtJQUVBN0QsT0FBTyxDQUFDOEQsUUFBUSxDQUFDRixLQUFLLEVBQUUsVUFBU0csR0FBRyxFQUFFQyxJQUFJLEVBQUU7TUFDMUMsSUFBSUQsR0FBRyxFQUFFO1FBQ1AsT0FBTy9ELE9BQU8sQ0FBQzZELFFBQVEsQ0FBQ0UsR0FBRyxDQUFDO01BQzlCO01BRUEsSUFBSUUsY0FBYyxHQUFHcEUsVUFBVSxDQUFDbUUsSUFBSSxFQUFFSixLQUFLLEVBQUU1RCxPQUFPLENBQUM7TUFDckRBLE9BQU8sQ0FBQ2tFLE9BQU8sQ0FBQ04sS0FBSyxFQUFFSyxjQUFjLEVBQUUsVUFBU0YsR0FBRyxFQUFFO1FBQ25ELElBQUlBLEdBQUcsRUFBRTtVQUNQLE9BQU8vRCxPQUFPLENBQUM2RCxRQUFRLENBQUNFLEdBQUcsQ0FBQztRQUM5QjtRQUVBSixZQUFZLENBQUMsQ0FBQztNQUNoQixDQUFDLENBQUM7SUFDSixDQUFDLENBQUM7RUFDSjtFQUNBQSxZQUFZLENBQUMsQ0FBQztBQUNoQiIsImlnbm9yZUxpc3QiOltdfQ== /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createPatch = createPatch; exports.createTwoFilesPatch = createTwoFilesPatch; exports.formatPatch = formatPatch; exports.structuredPatch = structuredPatch; /*istanbul ignore end*/ var /*istanbul ignore start*/ _line = require("../diff/line") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /*istanbul ignore end*/ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options === 'function') { options = { callback: options }; } if (typeof options.context === 'undefined') { options.context = 4; } if (options.newlineIsToken) { throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions'); } if (!options.callback) { return diffLinesResultToPatch( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _line /*istanbul ignore end*/ . /*istanbul ignore start*/ diffLines) /*istanbul ignore end*/ (oldStr, newStr, options)); } else { var /*istanbul ignore start*/ _options = /*istanbul ignore end*/ options, /*istanbul ignore start*/ /*istanbul ignore end*/ _callback = _options.callback; /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _line /*istanbul ignore end*/ . /*istanbul ignore start*/ diffLines) /*istanbul ignore end*/ (oldStr, newStr, /*istanbul ignore start*/ _objectSpread(_objectSpread({}, /*istanbul ignore end*/ options), {}, { callback: function /*istanbul ignore start*/ callback /*istanbul ignore end*/ (diff) { var patch = diffLinesResultToPatch(diff); _callback(patch); } })); } function diffLinesResultToPatch(diff) { // STEP 1: Build up the patch with no "\ No newline at end of file" lines and with the arrays // of lines containing trailing newline characters. We'll tidy up later... if (!diff) { return; } diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; /*istanbul ignore start*/ var _loop = function _loop() /*istanbul ignore end*/ { var current = diff[i], lines = current.lines || splitLines(current.value); current.lines = lines; if (current.added || current.removed) { /*istanbul ignore start*/ var _curRange; /*istanbul ignore end*/ // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_curRange = /*istanbul ignore end*/ curRange).push.apply( /*istanbul ignore start*/ _curRange /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { /*istanbul ignore start*/ var _curRange2; /*istanbul ignore end*/ // Overlapping /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_curRange2 = /*istanbul ignore end*/ curRange).push.apply( /*istanbul ignore start*/ _curRange2 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ contextLines(lines))); } else { /*istanbul ignore start*/ var _curRange3; /*istanbul ignore end*/ // end the range and output var contextSize = Math.min(lines.length, options.context); /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_curRange3 = /*istanbul ignore end*/ curRange).push.apply( /*istanbul ignore start*/ _curRange3 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ contextLines(lines.slice(0, contextSize)))); var _hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; hunks.push(_hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) /*istanbul ignore start*/ { _loop(); } // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add // "\ No newline at end of file". /*istanbul ignore end*/ for ( /*istanbul ignore start*/ var _i = 0, _hunks = /*istanbul ignore end*/ hunks; /*istanbul ignore start*/ _i < _hunks.length /*istanbul ignore end*/ ; /*istanbul ignore start*/ _i++ /*istanbul ignore end*/ ) { var hunk = /*istanbul ignore start*/ _hunks[_i] /*istanbul ignore end*/ ; for (var _i2 = 0; _i2 < hunk.lines.length; _i2++) { if (hunk.lines[_i2].endsWith('\n')) { hunk.lines[_i2] = hunk.lines[_i2].slice(0, -1); } else { hunk.lines.splice(_i2 + 1, 0, '\\ No newline at end of file'); _i2++; // Skip the line we just added, then continue iterating } } } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } } function formatPatch(diff) { if (Array.isArray(diff)) { return diff.map(formatPatch).join('\n'); } var ret = []; if (diff.oldFileName == diff.newFileName) { ret.push('Index: ' + diff.oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { /*istanbul ignore start*/ var _options2; /*istanbul ignore end*/ if (typeof options === 'function') { options = { callback: options }; } if (! /*istanbul ignore start*/ ((_options2 = /*istanbul ignore end*/ options) !== null && _options2 !== void 0 && /*istanbul ignore start*/ _options2 /*istanbul ignore end*/ .callback)) { var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); if (!patchObj) { return; } return formatPatch(patchObj); } else { var /*istanbul ignore start*/ _options3 = /*istanbul ignore end*/ options, /*istanbul ignore start*/ /*istanbul ignore end*/ _callback2 = _options3.callback; structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, /*istanbul ignore start*/ _objectSpread(_objectSpread({}, /*istanbul ignore end*/ options), {}, { callback: function /*istanbul ignore start*/ callback /*istanbul ignore end*/ (patchObj) { if (!patchObj) { _callback2(); } else { _callback2(formatPatch(patchObj)); } } })); } } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } /** * Split `text` into an array of lines, including the trailing newline character (where present) */ function splitLines(text) { var hasTrailingNl = text.endsWith('\n'); var result = text.split('\n').map(function (line) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ line + '\n' ); }); if (hasTrailingNl) { result.pop(); } else { result.push(result.pop().slice(0, -1)); } return result; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfbGluZSIsInJlcXVpcmUiLCJfdHlwZW9mIiwibyIsIlN5bWJvbCIsIml0ZXJhdG9yIiwiY29uc3RydWN0b3IiLCJwcm90b3R5cGUiLCJfdG9Db25zdW1hYmxlQXJyYXkiLCJhcnIiLCJfYXJyYXlXaXRob3V0SG9sZXMiLCJfaXRlcmFibGVUb0FycmF5IiwiX3Vuc3VwcG9ydGVkSXRlcmFibGVUb0FycmF5IiwiX25vbkl0ZXJhYmxlU3ByZWFkIiwiVHlwZUVycm9yIiwibWluTGVuIiwiX2FycmF5TGlrZVRvQXJyYXkiLCJuIiwiT2JqZWN0IiwidG9TdHJpbmciLCJjYWxsIiwic2xpY2UiLCJuYW1lIiwiQXJyYXkiLCJmcm9tIiwidGVzdCIsIml0ZXIiLCJpc0FycmF5IiwibGVuIiwibGVuZ3RoIiwiaSIsImFycjIiLCJvd25LZXlzIiwiZSIsInIiLCJ0Iiwia2V5cyIsImdldE93blByb3BlcnR5U3ltYm9scyIsImZpbHRlciIsImdldE93blByb3BlcnR5RGVzY3JpcHRvciIsImVudW1lcmFibGUiLCJwdXNoIiwiYXBwbHkiLCJfb2JqZWN0U3ByZWFkIiwiYXJndW1lbnRzIiwiZm9yRWFjaCIsIl9kZWZpbmVQcm9wZXJ0eSIsImdldE93blByb3BlcnR5RGVzY3JpcHRvcnMiLCJkZWZpbmVQcm9wZXJ0aWVzIiwiZGVmaW5lUHJvcGVydHkiLCJvYmoiLCJrZXkiLCJ2YWx1ZSIsIl90b1Byb3BlcnR5S2V5IiwiY29uZmlndXJhYmxlIiwid3JpdGFibGUiLCJfdG9QcmltaXRpdmUiLCJ0b1ByaW1pdGl2ZSIsIlN0cmluZyIsIk51bWJlciIsInN0cnVjdHVyZWRQYXRjaCIsIm9sZEZpbGVOYW1lIiwibmV3RmlsZU5hbWUiLCJvbGRTdHIiLCJuZXdTdHIiLCJvbGRIZWFkZXIiLCJuZXdIZWFkZXIiLCJvcHRpb25zIiwiY2FsbGJhY2siLCJjb250ZXh0IiwibmV3bGluZUlzVG9rZW4iLCJFcnJvciIsImRpZmZMaW5lc1Jlc3VsdFRvUGF0Y2giLCJkaWZmTGluZXMiLCJfb3B0aW9ucyIsImRpZmYiLCJwYXRjaCIsImxpbmVzIiwiY29udGV4dExpbmVzIiwibWFwIiwiZW50cnkiLCJodW5rcyIsIm9sZFJhbmdlU3RhcnQiLCJuZXdSYW5nZVN0YXJ0IiwiY3VyUmFuZ2UiLCJvbGRMaW5lIiwibmV3TGluZSIsIl9sb29wIiwiY3VycmVudCIsInNwbGl0TGluZXMiLCJhZGRlZCIsInJlbW92ZWQiLCJfY3VyUmFuZ2UiLCJwcmV2IiwiX2N1clJhbmdlMiIsIl9jdXJSYW5nZTMiLCJjb250ZXh0U2l6ZSIsIk1hdGgiLCJtaW4iLCJodW5rIiwib2xkU3RhcnQiLCJvbGRMaW5lcyIsIm5ld1N0YXJ0IiwibmV3TGluZXMiLCJfaSIsIl9odW5rcyIsImVuZHNXaXRoIiwic3BsaWNlIiwiZm9ybWF0UGF0Y2giLCJqb2luIiwicmV0IiwiY3JlYXRlVHdvRmlsZXNQYXRjaCIsIl9vcHRpb25zMiIsInBhdGNoT2JqIiwiX29wdGlvbnMzIiwiY3JlYXRlUGF0Y2giLCJmaWxlTmFtZSIsInRleHQiLCJoYXNUcmFpbGluZ05sIiwicmVzdWx0Iiwic3BsaXQiLCJsaW5lIiwicG9wIl0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL3BhdGNoL2NyZWF0ZS5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQge2RpZmZMaW5lc30gZnJvbSAnLi4vZGlmZi9saW5lJztcblxuZXhwb3J0IGZ1bmN0aW9uIHN0cnVjdHVyZWRQYXRjaChvbGRGaWxlTmFtZSwgbmV3RmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucykge1xuICBpZiAoIW9wdGlvbnMpIHtcbiAgICBvcHRpb25zID0ge307XG4gIH1cbiAgaWYgKHR5cGVvZiBvcHRpb25zID09PSAnZnVuY3Rpb24nKSB7XG4gICAgb3B0aW9ucyA9IHtjYWxsYmFjazogb3B0aW9uc307XG4gIH1cbiAgaWYgKHR5cGVvZiBvcHRpb25zLmNvbnRleHQgPT09ICd1bmRlZmluZWQnKSB7XG4gICAgb3B0aW9ucy5jb250ZXh0ID0gNDtcbiAgfVxuICBpZiAob3B0aW9ucy5uZXdsaW5lSXNUb2tlbikge1xuICAgIHRocm93IG5ldyBFcnJvcignbmV3bGluZUlzVG9rZW4gbWF5IG5vdCBiZSB1c2VkIHdpdGggcGF0Y2gtZ2VuZXJhdGlvbiBmdW5jdGlvbnMsIG9ubHkgd2l0aCBkaWZmaW5nIGZ1bmN0aW9ucycpO1xuICB9XG5cbiAgaWYgKCFvcHRpb25zLmNhbGxiYWNrKSB7XG4gICAgcmV0dXJuIGRpZmZMaW5lc1Jlc3VsdFRvUGF0Y2goZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKSk7XG4gIH0gZWxzZSB7XG4gICAgY29uc3Qge2NhbGxiYWNrfSA9IG9wdGlvbnM7XG4gICAgZGlmZkxpbmVzKFxuICAgICAgb2xkU3RyLFxuICAgICAgbmV3U3RyLFxuICAgICAge1xuICAgICAgICAuLi5vcHRpb25zLFxuICAgICAgICBjYWxsYmFjazogKGRpZmYpID0+IHtcbiAgICAgICAgICBjb25zdCBwYXRjaCA9IGRpZmZMaW5lc1Jlc3VsdFRvUGF0Y2goZGlmZik7XG4gICAgICAgICAgY2FsbGJhY2socGF0Y2gpO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgKTtcbiAgfVxuXG4gIGZ1bmN0aW9uIGRpZmZMaW5lc1Jlc3VsdFRvUGF0Y2goZGlmZikge1xuICAgIC8vIFNURVAgMTogQnVpbGQgdXAgdGhlIHBhdGNoIHdpdGggbm8gXCJcXCBObyBuZXdsaW5lIGF0IGVuZCBvZiBmaWxlXCIgbGluZXMgYW5kIHdpdGggdGhlIGFycmF5c1xuICAgIC8vICAgICAgICAgb2YgbGluZXMgY29udGFpbmluZyB0cmFpbGluZyBuZXdsaW5lIGNoYXJhY3RlcnMuIFdlJ2xsIHRpZHkgdXAgbGF0ZXIuLi5cblxuICAgIGlmKCFkaWZmKSB7XG4gICAgICByZXR1cm47XG4gICAgfVxuXG4gICAgZGlmZi5wdXNoKHt2YWx1ZTogJycsIGxpbmVzOiBbXX0pOyAvLyBBcHBlbmQgYW4gZW1wdHkgdmFsdWUgdG8gbWFrZSBjbGVhbnVwIGVhc2llclxuXG4gICAgZnVuY3Rpb24gY29udGV4dExpbmVzKGxpbmVzKSB7XG4gICAgICByZXR1cm4gbGluZXMubWFwKGZ1bmN0aW9uKGVudHJ5KSB7IHJldHVybiAnICcgKyBlbnRyeTsgfSk7XG4gICAgfVxuXG4gICAgbGV0IGh1bmtzID0gW107XG4gICAgbGV0IG9sZFJhbmdlU3RhcnQgPSAwLCBuZXdSYW5nZVN0YXJ0ID0gMCwgY3VyUmFuZ2UgPSBbXSxcbiAgICAgICAgb2xkTGluZSA9IDEsIG5ld0xpbmUgPSAxO1xuICAgIGZvciAobGV0IGkgPSAwOyBpIDwgZGlmZi5sZW5ndGg7IGkrKykge1xuICAgICAgY29uc3QgY3VycmVudCA9IGRpZmZbaV0sXG4gICAgICAgICAgICBsaW5lcyA9IGN1cnJlbnQubGluZXMgfHwgc3BsaXRMaW5lcyhjdXJyZW50LnZhbHVlKTtcbiAgICAgIGN1cnJlbnQubGluZXMgPSBsaW5lcztcblxuICAgICAgaWYgKGN1cnJlbnQuYWRkZWQgfHwgY3VycmVudC5yZW1vdmVkKSB7XG4gICAgICAgIC8vIElmIHdlIGhhdmUgcHJldmlvdXMgY29udGV4dCwgc3RhcnQgd2l0aCB0aGF0XG4gICAgICAgIGlmICghb2xkUmFuZ2VTdGFydCkge1xuICAgICAgICAgIGNvbnN0IHByZXYgPSBkaWZmW2kgLSAxXTtcbiAgICAgICAgICBvbGRSYW5nZVN0YXJ0ID0gb2xkTGluZTtcbiAgICAgICAgICBuZXdSYW5nZVN0YXJ0ID0gbmV3TGluZTtcblxuICAgICAgICAgIGlmIChwcmV2KSB7XG4gICAgICAgICAgICBjdXJSYW5nZSA9IG9wdGlvbnMuY29udGV4dCA+IDAgPyBjb250ZXh0TGluZXMocHJldi5saW5lcy5zbGljZSgtb3B0aW9ucy5jb250ZXh0KSkgOiBbXTtcbiAgICAgICAgICAgIG9sZFJhbmdlU3RhcnQgLT0gY3VyUmFuZ2UubGVuZ3RoO1xuICAgICAgICAgICAgbmV3UmFuZ2VTdGFydCAtPSBjdXJSYW5nZS5sZW5ndGg7XG4gICAgICAgICAgfVxuICAgICAgICB9XG5cbiAgICAgICAgLy8gT3V0cHV0IG91ciBjaGFuZ2VzXG4gICAgICAgIGN1clJhbmdlLnB1c2goLi4uIGxpbmVzLm1hcChmdW5jdGlvbihlbnRyeSkge1xuICAgICAgICAgIHJldHVybiAoY3VycmVudC5hZGRlZCA/ICcrJyA6ICctJykgKyBlbnRyeTtcbiAgICAgICAgfSkpO1xuXG4gICAgICAgIC8vIFRyYWNrIHRoZSB1cGRhdGVkIGZpbGUgcG9zaXRpb25cbiAgICAgICAgaWYgKGN1cnJlbnQuYWRkZWQpIHtcbiAgICAgICAgICBuZXdMaW5lICs9IGxpbmVzLmxlbmd0aDtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBvbGRMaW5lICs9IGxpbmVzLmxlbmd0aDtcbiAgICAgICAgfVxuICAgICAgfSBlbHNlIHtcbiAgICAgICAgLy8gSWRlbnRpY2FsIGNvbnRleHQgbGluZXMuIFRyYWNrIGxpbmUgY2hhbmdlc1xuICAgICAgICBpZiAob2xkUmFuZ2VTdGFydCkge1xuICAgICAgICAgIC8vIENsb3NlIG91dCBhbnkgY2hhbmdlcyB0aGF0IGhhdmUgYmVlbiBvdXRwdXQgKG9yIGpvaW4gb3ZlcmxhcHBpbmcpXG4gICAgICAgICAgaWYgKGxpbmVzLmxlbmd0aCA8PSBvcHRpb25zLmNvbnRleHQgKiAyICYmIGkgPCBkaWZmLmxlbmd0aCAtIDIpIHtcbiAgICAgICAgICAgIC8vIE92ZXJsYXBwaW5nXG4gICAgICAgICAgICBjdXJSYW5nZS5wdXNoKC4uLiBjb250ZXh0TGluZXMobGluZXMpKTtcbiAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgLy8gZW5kIHRoZSByYW5nZSBhbmQgb3V0cHV0XG4gICAgICAgICAgICBsZXQgY29udGV4dFNpemUgPSBNYXRoLm1pbihsaW5lcy5sZW5ndGgsIG9wdGlvbnMuY29udGV4dCk7XG4gICAgICAgICAgICBjdXJSYW5nZS5wdXNoKC4uLiBjb250ZXh0TGluZXMobGluZXMuc2xpY2UoMCwgY29udGV4dFNpemUpKSk7XG5cbiAgICAgICAgICAgIGxldCBodW5rID0ge1xuICAgICAgICAgICAgICBvbGRTdGFydDogb2xkUmFuZ2VTdGFydCxcbiAgICAgICAgICAgICAgb2xkTGluZXM6IChvbGRMaW5lIC0gb2xkUmFuZ2VTdGFydCArIGNvbnRleHRTaXplKSxcbiAgICAgICAgICAgICAgbmV3U3RhcnQ6IG5ld1JhbmdlU3RhcnQsXG4gICAgICAgICAgICAgIG5ld0xpbmVzOiAobmV3TGluZSAtIG5ld1JhbmdlU3RhcnQgKyBjb250ZXh0U2l6ZSksXG4gICAgICAgICAgICAgIGxpbmVzOiBjdXJSYW5nZVxuICAgICAgICAgICAgfTtcbiAgICAgICAgICAgIGh1bmtzLnB1c2goaHVuayk7XG5cbiAgICAgICAgICAgIG9sZFJhbmdlU3RhcnQgPSAwO1xuICAgICAgICAgICAgbmV3UmFuZ2VTdGFydCA9IDA7XG4gICAgICAgICAgICBjdXJSYW5nZSA9IFtdO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBvbGRMaW5lICs9IGxpbmVzLmxlbmd0aDtcbiAgICAgICAgbmV3TGluZSArPSBsaW5lcy5sZW5ndGg7XG4gICAgICB9XG4gICAgfVxuXG4gICAgLy8gU3RlcCAyOiBlbGltaW5hdGUgdGhlIHRyYWlsaW5nIGBcXG5gIGZyb20gZWFjaCBsaW5lIG9mIGVhY2ggaHVuaywgYW5kLCB3aGVyZSBuZWVkZWQsIGFkZFxuICAgIC8vICAgICAgICAgXCJcXCBObyBuZXdsaW5lIGF0IGVuZCBvZiBmaWxlXCIuXG4gICAgZm9yIChjb25zdCBodW5rIG9mIGh1bmtzKSB7XG4gICAgICBmb3IgKGxldCBpID0gMDsgaSA8IGh1bmsubGluZXMubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgaWYgKGh1bmsubGluZXNbaV0uZW5kc1dpdGgoJ1xcbicpKSB7XG4gICAgICAgICAgaHVuay5saW5lc1tpXSA9IGh1bmsubGluZXNbaV0uc2xpY2UoMCwgLTEpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIGh1bmsubGluZXMuc3BsaWNlKGkgKyAxLCAwLCAnXFxcXCBObyBuZXdsaW5lIGF0IGVuZCBvZiBmaWxlJyk7XG4gICAgICAgICAgaSsrOyAvLyBTa2lwIHRoZSBsaW5lIHdlIGp1c3QgYWRkZWQsIHRoZW4gY29udGludWUgaXRlcmF0aW5nXG4gICAgICAgIH1cbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4ge1xuICAgICAgb2xkRmlsZU5hbWU6IG9sZEZpbGVOYW1lLCBuZXdGaWxlTmFtZTogbmV3RmlsZU5hbWUsXG4gICAgICBvbGRIZWFkZXI6IG9sZEhlYWRlciwgbmV3SGVhZGVyOiBuZXdIZWFkZXIsXG4gICAgICBodW5rczogaHVua3NcbiAgICB9O1xuICB9XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBmb3JtYXRQYXRjaChkaWZmKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KGRpZmYpKSB7XG4gICAgcmV0dXJuIGRpZmYubWFwKGZvcm1hdFBhdGNoKS5qb2luKCdcXG4nKTtcbiAgfVxuXG4gIGNvbnN0IHJldCA9IFtdO1xuICBpZiAoZGlmZi5vbGRGaWxlTmFtZSA9PSBkaWZmLm5ld0ZpbGVOYW1lKSB7XG4gICAgcmV0LnB1c2goJ0luZGV4OiAnICsgZGlmZi5vbGRGaWxlTmFtZSk7XG4gIH1cbiAgcmV0LnB1c2goJz09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0nKTtcbiAgcmV0LnB1c2goJy0tLSAnICsgZGlmZi5vbGRGaWxlTmFtZSArICh0eXBlb2YgZGlmZi5vbGRIZWFkZXIgPT09ICd1bmRlZmluZWQnID8gJycgOiAnXFx0JyArIGRpZmYub2xkSGVhZGVyKSk7XG4gIHJldC5wdXNoKCcrKysgJyArIGRpZmYubmV3RmlsZU5hbWUgKyAodHlwZW9mIGRpZmYubmV3SGVhZGVyID09PSAndW5kZWZpbmVkJyA/ICcnIDogJ1xcdCcgKyBkaWZmLm5ld0hlYWRlcikpO1xuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgZGlmZi5odW5rcy5sZW5ndGg7IGkrKykge1xuICAgIGNvbnN0IGh1bmsgPSBkaWZmLmh1bmtzW2ldO1xuICAgIC8vIFVuaWZpZWQgRGlmZiBGb3JtYXQgcXVpcms6IElmIHRoZSBjaHVuayBzaXplIGlzIDAsXG4gICAgLy8gdGhlIGZpcnN0IG51bWJlciBpcyBvbmUgbG93ZXIgdGhhbiBvbmUgd291bGQgZXhwZWN0LlxuICAgIC8vIGh0dHBzOi8vd3d3LmFydGltYS5jb20vd2VibG9ncy92aWV3cG9zdC5qc3A/dGhyZWFkPTE2NDI5M1xuICAgIGlmIChodW5rLm9sZExpbmVzID09PSAwKSB7XG4gICAgICBodW5rLm9sZFN0YXJ0IC09IDE7XG4gICAgfVxuICAgIGlmIChodW5rLm5ld0xpbmVzID09PSAwKSB7XG4gICAgICBodW5rLm5ld1N0YXJ0IC09IDE7XG4gICAgfVxuICAgIHJldC5wdXNoKFxuICAgICAgJ0BAIC0nICsgaHVuay5vbGRTdGFydCArICcsJyArIGh1bmsub2xkTGluZXNcbiAgICAgICsgJyArJyArIGh1bmsubmV3U3RhcnQgKyAnLCcgKyBodW5rLm5ld0xpbmVzXG4gICAgICArICcgQEAnXG4gICAgKTtcbiAgICByZXQucHVzaC5hcHBseShyZXQsIGh1bmsubGluZXMpO1xuICB9XG5cbiAgcmV0dXJuIHJldC5qb2luKCdcXG4nKSArICdcXG4nO1xufVxuXG5leHBvcnQgZnVuY3Rpb24gY3JlYXRlVHdvRmlsZXNQYXRjaChvbGRGaWxlTmFtZSwgbmV3RmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucykge1xuICBpZiAodHlwZW9mIG9wdGlvbnMgPT09ICdmdW5jdGlvbicpIHtcbiAgICBvcHRpb25zID0ge2NhbGxiYWNrOiBvcHRpb25zfTtcbiAgfVxuXG4gIGlmICghb3B0aW9ucz8uY2FsbGJhY2spIHtcbiAgICBjb25zdCBwYXRjaE9iaiA9IHN0cnVjdHVyZWRQYXRjaChvbGRGaWxlTmFtZSwgbmV3RmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucyk7XG4gICAgaWYgKCFwYXRjaE9iaikge1xuICAgICAgcmV0dXJuO1xuICAgIH1cbiAgICByZXR1cm4gZm9ybWF0UGF0Y2gocGF0Y2hPYmopO1xuICB9IGVsc2Uge1xuICAgIGNvbnN0IHtjYWxsYmFja30gPSBvcHRpb25zO1xuICAgIHN0cnVjdHVyZWRQYXRjaChcbiAgICAgIG9sZEZpbGVOYW1lLFxuICAgICAgbmV3RmlsZU5hbWUsXG4gICAgICBvbGRTdHIsXG4gICAgICBuZXdTdHIsXG4gICAgICBvbGRIZWFkZXIsXG4gICAgICBuZXdIZWFkZXIsXG4gICAgICB7XG4gICAgICAgIC4uLm9wdGlvbnMsXG4gICAgICAgIGNhbGxiYWNrOiBwYXRjaE9iaiA9PiB7XG4gICAgICAgICAgaWYgKCFwYXRjaE9iaikge1xuICAgICAgICAgICAgY2FsbGJhY2soKTtcbiAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgY2FsbGJhY2soZm9ybWF0UGF0Y2gocGF0Y2hPYmopKTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICApO1xuICB9XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBjcmVhdGVQYXRjaChmaWxlTmFtZSwgb2xkU3RyLCBuZXdTdHIsIG9sZEhlYWRlciwgbmV3SGVhZGVyLCBvcHRpb25zKSB7XG4gIHJldHVybiBjcmVhdGVUd29GaWxlc1BhdGNoKGZpbGVOYW1lLCBmaWxlTmFtZSwgb2xkU3RyLCBuZXdTdHIsIG9sZEhlYWRlciwgbmV3SGVhZGVyLCBvcHRpb25zKTtcbn1cblxuLyoqXG4gKiBTcGxpdCBgdGV4dGAgaW50byBhbiBhcnJheSBvZiBsaW5lcywgaW5jbHVkaW5nIHRoZSB0cmFpbGluZyBuZXdsaW5lIGNoYXJhY3RlciAod2hlcmUgcHJlc2VudClcbiAqL1xuZnVuY3Rpb24gc3BsaXRMaW5lcyh0ZXh0KSB7XG4gIGNvbnN0IGhhc1RyYWlsaW5nTmwgPSB0ZXh0LmVuZHNXaXRoKCdcXG4nKTtcbiAgY29uc3QgcmVzdWx0ID0gdGV4dC5zcGxpdCgnXFxuJykubWFwKGxpbmUgPT4gbGluZSArICdcXG4nKTtcbiAgaWYgKGhhc1RyYWlsaW5nTmwpIHtcbiAgICByZXN1bHQucG9wKCk7XG4gIH0gZWxzZSB7XG4gICAgcmVzdWx0LnB1c2gocmVzdWx0LnBvcCgpLnNsaWNlKDAsIC0xKSk7XG4gIH1cbiAgcmV0dXJuIHJlc3VsdDtcbn1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUFBLEtBQUEsR0FBQUMsT0FBQTtBQUFBO0FBQUE7QUFBdUMsbUNBQUFDLFFBQUFDLENBQUEsc0NBQUFELE9BQUEsd0JBQUFFLE1BQUEsdUJBQUFBLE1BQUEsQ0FBQUMsUUFBQSxhQUFBRixDQUFBLGtCQUFBQSxDQUFBLGdCQUFBQSxDQUFBLFdBQUFBLENBQUEseUJBQUFDLE1BQUEsSUFBQUQsQ0FBQSxDQUFBRyxXQUFBLEtBQUFGLE1BQUEsSUFBQUQsQ0FBQSxLQUFBQyxNQUFBLENBQUFHLFNBQUEscUJBQUFKLENBQUEsS0FBQUQsT0FBQSxDQUFBQyxDQUFBO0FBQUEsU0FBQUssbUJBQUFDLEdBQUEsV0FBQUMsa0JBQUEsQ0FBQUQsR0FBQSxLQUFBRSxnQkFBQSxDQUFBRixHQUFBLEtBQUFHLDJCQUFBLENBQUFILEdBQUEsS0FBQUksa0JBQUE7QUFBQSxTQUFBQSxtQkFBQSxjQUFBQyxTQUFBO0FBQUEsU0FBQUYsNEJBQUFULENBQUEsRUFBQVksTUFBQSxTQUFBWixDQUFBLHFCQUFBQSxDQUFBLHNCQUFBYSxpQkFBQSxDQUFBYixDQUFBLEVBQUFZLE1BQUEsT0FBQUUsQ0FBQSxHQUFBQyxNQUFBLENBQUFYLFNBQUEsQ0FBQVksUUFBQSxDQUFBQyxJQUFBLENBQUFqQixDQUFBLEVBQUFrQixLQUFBLGFBQUFKLENBQUEsaUJBQUFkLENBQUEsQ0FBQUcsV0FBQSxFQUFBVyxDQUFBLEdBQUFkLENBQUEsQ0FBQUcsV0FBQSxDQUFBZ0IsSUFBQSxNQUFBTCxDQUFBLGNBQUFBLENBQUEsbUJBQUFNLEtBQUEsQ0FBQUMsSUFBQSxDQUFBckIsQ0FBQSxPQUFBYyxDQUFBLCtEQUFBUSxJQUFBLENBQUFSLENBQUEsVUFBQUQsaUJBQUEsQ0FBQWIsQ0FBQSxFQUFBWSxNQUFBO0FBQUEsU0FBQUosaUJBQUFlLElBQUEsZUFBQXRCLE1BQUEsb0JBQUFzQixJQUFBLENBQUF0QixNQUFBLENBQUFDLFFBQUEsYUFBQXFCLElBQUEsK0JBQUFILEtBQUEsQ0FBQUMsSUFBQSxDQUFBRSxJQUFBO0FBQUEsU0FBQWhCLG1CQUFBRCxHQUFBLFFBQUFjLEtBQUEsQ0FBQUksT0FBQSxDQUFBbEIsR0FBQSxVQUFBTyxpQkFBQSxDQUFBUCxHQUFBO0FBQUEsU0FBQU8sa0JBQUFQLEdBQUEsRUFBQW1CLEdBQUEsUUFBQUEsR0FBQSxZQUFBQSxHQUFBLEdBQUFuQixHQUFBLENBQUFvQixNQUFBLEVBQUFELEdBQUEsR0FBQW5CLEdBQUEsQ0FBQW9CLE1BQUEsV0FBQUMsQ0FBQSxNQUFBQyxJQUFBLE9BQUFSLEtBQUEsQ0FBQUssR0FBQSxHQUFBRSxDQUFBLEdBQUFGLEdBQUEsRUFBQUUsQ0FBQSxJQUFBQyxJQUFBLENBQUFELENBQUEsSUFBQXJCLEdBQUEsQ0FBQXFCLENBQUEsVUFBQUMsSUFBQTtBQUFBLFNBQUFDLFFBQUFDLENBQUEsRUFBQUMsQ0FBQSxRQUFBQyxDQUFBLEdBQUFqQixNQUFBLENBQUFrQixJQUFBLENBQUFILENBQUEsT0FBQWYsTUFBQSxDQUFBbUIscUJBQUEsUUFBQWxDLENBQUEsR0FBQWUsTUFBQSxDQUFBbUIscUJBQUEsQ0FBQUosQ0FBQSxHQUFBQyxDQUFBLEtBQUEvQixDQUFBLEdBQUFBLENBQUEsQ0FBQW1DLE1BQUEsV0FBQUosQ0FBQSxXQUFBaEIsTUFBQSxDQUFBcUIsd0JBQUEsQ0FBQU4sQ0FBQSxFQUFBQyxDQUFBLEVBQUFNLFVBQUEsT0FBQUwsQ0FBQSxDQUFBTSxJQUFBLENBQUFDLEtBQUEsQ0FBQVAsQ0FBQSxFQUFBaEMsQ0FBQSxZQUFBZ0MsQ0FBQTtBQUFBLFNBQUFRLGNBQUFWLENBQUEsYUFBQUMsQ0FBQSxNQUFBQSxDQUFBLEdBQUFVLFNBQUEsQ0FBQWYsTUFBQSxFQUFBSyxDQUFBLFVBQUFDLENBQUEsV0FBQVMsU0FBQSxDQUFBVixDQUFBLElBQUFVLFNBQUEsQ0FBQVYsQ0FBQSxRQUFBQSxDQUFBLE9BQUFGLE9BQUEsQ0FBQWQsTUFBQSxDQUFBaUIsQ0FBQSxPQUFBVSxPQUFBLFdBQUFYLENBQUEsSUFBQVksZUFBQSxDQUFBYixDQUFBLEVBQUFDLENBQUEsRUFBQUMsQ0FBQSxDQUFBRCxDQUFBLFNBQUFoQixNQUFBLENBQUE2Qix5QkFBQSxHQUFBN0IsTUFBQSxDQUFBOEIsZ0JBQUEsQ0FBQWYsQ0FBQSxFQUFBZixNQUFBLENBQUE2Qix5QkFBQSxDQUFBWixDQUFBLEtBQUFILE9BQUEsQ0FBQWQsTUFBQSxDQUFBaUIsQ0FBQSxHQUFBVSxPQUFBLFdBQUFYLENBQUEsSUFBQWhCLE1BQUEsQ0FBQStCLGNBQUEsQ0FBQWhCLENBQUEsRUFBQUMsQ0FBQSxFQUFBaEIsTUFBQSxDQUFBcUIsd0JBQUEsQ0FBQUosQ0FBQSxFQUFBRCxDQUFBLGlCQUFBRCxDQUFBO0FBQUEsU0FBQWEsZ0JBQUFJLEdBQUEsRUFBQUMsR0FBQSxFQUFBQyxLQUFBLElBQUFELEdBQUEsR0FBQUUsY0FBQSxDQUFBRixHQUFBLE9BQUFBLEdBQUEsSUFBQUQsR0FBQSxJQUFBaEMsTUFBQSxDQUFBK0IsY0FBQSxDQUFBQyxHQUFBLEVBQUFDLEdBQUEsSUFBQUMsS0FBQSxFQUFBQSxLQUFBLEVBQUFaLFVBQUEsUUFBQWMsWUFBQSxRQUFBQyxRQUFBLG9CQUFBTCxHQUFBLENBQUFDLEdBQUEsSUFBQUMsS0FBQSxXQUFBRixHQUFBO0FBQUEsU0FBQUcsZUFBQWxCLENBQUEsUUFBQUwsQ0FBQSxHQUFBMEIsWUFBQSxDQUFBckIsQ0FBQSxnQ0FBQWpDLE9BQUEsQ0FBQTRCLENBQUEsSUFBQUEsQ0FBQSxHQUFBQSxDQUFBO0FBQUEsU0FBQTBCLGFBQUFyQixDQUFBLEVBQUFELENBQUEsb0JBQUFoQyxPQUFBLENBQUFpQyxDQUFBLE1BQUFBLENBQUEsU0FBQUEsQ0FBQSxNQUFBRixDQUFBLEdBQUFFLENBQUEsQ0FBQS9CLE1BQUEsQ0FBQXFELFdBQUEsa0JBQUF4QixDQUFBLFFBQUFILENBQUEsR0FBQUcsQ0FBQSxDQUFBYixJQUFBLENBQUFlLENBQUEsRUFBQUQsQ0FBQSxnQ0FBQWhDLE9BQUEsQ0FBQTRCLENBQUEsVUFBQUEsQ0FBQSxZQUFBaEIsU0FBQSx5RUFBQW9CLENBQUEsR0FBQXdCLE1BQUEsR0FBQUMsTUFBQSxFQUFBeEIsQ0FBQTtBQUFBO0FBRWhDLFNBQVN5QixlQUFlQSxDQUFDQyxXQUFXLEVBQUVDLFdBQVcsRUFBRUMsTUFBTSxFQUFFQyxNQUFNLEVBQUVDLFNBQVMsRUFBRUMsU0FBUyxFQUFFQyxPQUFPLEVBQUU7RUFDdkcsSUFBSSxDQUFDQSxPQUFPLEVBQUU7SUFDWkEsT0FBTyxHQUFHLENBQUMsQ0FBQztFQUNkO0VBQ0EsSUFBSSxPQUFPQSxPQUFPLEtBQUssVUFBVSxFQUFFO0lBQ2pDQSxPQUFPLEdBQUc7TUFBQ0MsUUFBUSxFQUFFRDtJQUFPLENBQUM7RUFDL0I7RUFDQSxJQUFJLE9BQU9BLE9BQU8sQ0FBQ0UsT0FBTyxLQUFLLFdBQVcsRUFBRTtJQUMxQ0YsT0FBTyxDQUFDRSxPQUFPLEdBQUcsQ0FBQztFQUNyQjtFQUNBLElBQUlGLE9BQU8sQ0FBQ0csY0FBYyxFQUFFO0lBQzFCLE1BQU0sSUFBSUMsS0FBSyxDQUFDLDZGQUE2RixDQUFDO0VBQ2hIO0VBRUEsSUFBSSxDQUFDSixPQUFPLENBQUNDLFFBQVEsRUFBRTtJQUNyQixPQUFPSSxzQkFBc0I7SUFBQztJQUFBO0lBQUE7SUFBQUM7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsU0FBUztJQUFBO0lBQUEsQ0FBQ1YsTUFBTSxFQUFFQyxNQUFNLEVBQUVHLE9BQU8sQ0FBQyxDQUFDO0VBQ25FLENBQUMsTUFBTTtJQUNMO01BQUE7TUFBQU8sUUFBQTtNQUFBO01BQW1CUCxPQUFPO01BQUE7TUFBQTtNQUFuQkMsU0FBUSxHQUFBTSxRQUFBLENBQVJOLFFBQVE7SUFDZjtJQUFBO0lBQUE7SUFBQUs7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUE7SUFBQUEsU0FBUztJQUFBO0lBQUEsQ0FDUFYsTUFBTSxFQUNOQyxNQUFNO0lBQUE7SUFBQXJCLGFBQUEsQ0FBQUEsYUFBQTtJQUFBO0lBRUR3QixPQUFPO01BQ1ZDLFFBQVEsRUFBRTtNQUFBO01BQUFBO01BQUFBO01BQUEsQ0FBQ08sSUFBSSxFQUFLO1FBQ2xCLElBQU1DLEtBQUssR0FBR0osc0JBQXNCLENBQUNHLElBQUksQ0FBQztRQUMxQ1AsU0FBUSxDQUFDUSxLQUFLLENBQUM7TUFDakI7SUFBQyxFQUVMLENBQUM7RUFDSDtFQUVBLFNBQVNKLHNCQUFzQkEsQ0FBQ0csSUFBSSxFQUFFO0lBQ3BDO0lBQ0E7O0lBRUEsSUFBRyxDQUFDQSxJQUFJLEVBQUU7TUFDUjtJQUNGO0lBRUFBLElBQUksQ0FBQ2xDLElBQUksQ0FBQztNQUFDVyxLQUFLLEVBQUUsRUFBRTtNQUFFeUIsS0FBSyxFQUFFO0lBQUUsQ0FBQyxDQUFDLENBQUMsQ0FBQzs7SUFFbkMsU0FBU0MsWUFBWUEsQ0FBQ0QsS0FBSyxFQUFFO01BQzNCLE9BQU9BLEtBQUssQ0FBQ0UsR0FBRyxDQUFDLFVBQVNDLEtBQUssRUFBRTtRQUFFLE9BQU8sR0FBRyxHQUFHQSxLQUFLO01BQUUsQ0FBQyxDQUFDO0lBQzNEO0lBRUEsSUFBSUMsS0FBSyxHQUFHLEVBQUU7SUFDZCxJQUFJQyxhQUFhLEdBQUcsQ0FBQztNQUFFQyxhQUFhLEdBQUcsQ0FBQztNQUFFQyxRQUFRLEdBQUcsRUFBRTtNQUNuREMsT0FBTyxHQUFHLENBQUM7TUFBRUMsT0FBTyxHQUFHLENBQUM7SUFBQztJQUFBLElBQUFDLEtBQUEsWUFBQUEsTUFBQTtJQUFBO0lBQ1M7TUFDcEMsSUFBTUMsT0FBTyxHQUFHYixJQUFJLENBQUM3QyxDQUFDLENBQUM7UUFDakIrQyxLQUFLLEdBQUdXLE9BQU8sQ0FBQ1gsS0FBSyxJQUFJWSxVQUFVLENBQUNELE9BQU8sQ0FBQ3BDLEtBQUssQ0FBQztNQUN4RG9DLE9BQU8sQ0FBQ1gsS0FBSyxHQUFHQSxLQUFLO01BRXJCLElBQUlXLE9BQU8sQ0FBQ0UsS0FBSyxJQUFJRixPQUFPLENBQUNHLE9BQU8sRUFBRTtRQUFBO1FBQUEsSUFBQUMsU0FBQTtRQUFBO1FBQ3BDO1FBQ0EsSUFBSSxDQUFDVixhQUFhLEVBQUU7VUFDbEIsSUFBTVcsSUFBSSxHQUFHbEIsSUFBSSxDQUFDN0MsQ0FBQyxHQUFHLENBQUMsQ0FBQztVQUN4Qm9ELGFBQWEsR0FBR0csT0FBTztVQUN2QkYsYUFBYSxHQUFHRyxPQUFPO1VBRXZCLElBQUlPLElBQUksRUFBRTtZQUNSVCxRQUFRLEdBQUdqQixPQUFPLENBQUNFLE9BQU8sR0FBRyxDQUFDLEdBQUdTLFlBQVksQ0FBQ2UsSUFBSSxDQUFDaEIsS0FBSyxDQUFDeEQsS0FBSyxDQUFDLENBQUM4QyxPQUFPLENBQUNFLE9BQU8sQ0FBQyxDQUFDLEdBQUcsRUFBRTtZQUN0RmEsYUFBYSxJQUFJRSxRQUFRLENBQUN2RCxNQUFNO1lBQ2hDc0QsYUFBYSxJQUFJQyxRQUFRLENBQUN2RCxNQUFNO1VBQ2xDO1FBQ0Y7O1FBRUE7UUFDQTtRQUFBO1FBQUE7UUFBQSxDQUFBK0QsU0FBQTtRQUFBO1FBQUFSLFFBQVEsRUFBQzNDLElBQUksQ0FBQUMsS0FBQTtRQUFBO1FBQUFrRDtRQUFBO1FBQUE7UUFBQTtRQUFBcEYsa0JBQUE7UUFBQTtRQUFLcUUsS0FBSyxDQUFDRSxHQUFHLENBQUMsVUFBU0MsS0FBSyxFQUFFO1VBQzFDLE9BQU8sQ0FBQ1EsT0FBTyxDQUFDRSxLQUFLLEdBQUcsR0FBRyxHQUFHLEdBQUcsSUFBSVYsS0FBSztRQUM1QyxDQUFDLENBQUMsRUFBQzs7UUFFSDtRQUNBLElBQUlRLE9BQU8sQ0FBQ0UsS0FBSyxFQUFFO1VBQ2pCSixPQUFPLElBQUlULEtBQUssQ0FBQ2hELE1BQU07UUFDekIsQ0FBQyxNQUFNO1VBQ0x3RCxPQUFPLElBQUlSLEtBQUssQ0FBQ2hELE1BQU07UUFDekI7TUFDRixDQUFDLE1BQU07UUFDTDtRQUNBLElBQUlxRCxhQUFhLEVBQUU7VUFDakI7VUFDQSxJQUFJTCxLQUFLLENBQUNoRCxNQUFNLElBQUlzQyxPQUFPLENBQUNFLE9BQU8sR0FBRyxDQUFDLElBQUl2QyxDQUFDLEdBQUc2QyxJQUFJLENBQUM5QyxNQUFNLEdBQUcsQ0FBQyxFQUFFO1lBQUE7WUFBQSxJQUFBaUUsVUFBQTtZQUFBO1lBQzlEO1lBQ0E7WUFBQTtZQUFBO1lBQUEsQ0FBQUEsVUFBQTtZQUFBO1lBQUFWLFFBQVEsRUFBQzNDLElBQUksQ0FBQUMsS0FBQTtZQUFBO1lBQUFvRDtZQUFBO1lBQUE7WUFBQTtZQUFBdEYsa0JBQUE7WUFBQTtZQUFLc0UsWUFBWSxDQUFDRCxLQUFLLENBQUMsRUFBQztVQUN4QyxDQUFDLE1BQU07WUFBQTtZQUFBLElBQUFrQixVQUFBO1lBQUE7WUFDTDtZQUNBLElBQUlDLFdBQVcsR0FBR0MsSUFBSSxDQUFDQyxHQUFHLENBQUNyQixLQUFLLENBQUNoRCxNQUFNLEVBQUVzQyxPQUFPLENBQUNFLE9BQU8sQ0FBQztZQUN6RDtZQUFBO1lBQUE7WUFBQSxDQUFBMEIsVUFBQTtZQUFBO1lBQUFYLFFBQVEsRUFBQzNDLElBQUksQ0FBQUMsS0FBQTtZQUFBO1lBQUFxRDtZQUFBO1lBQUE7WUFBQTtZQUFBdkYsa0JBQUE7WUFBQTtZQUFLc0UsWUFBWSxDQUFDRCxLQUFLLENBQUN4RCxLQUFLLENBQUMsQ0FBQyxFQUFFMkUsV0FBVyxDQUFDLENBQUMsRUFBQztZQUU1RCxJQUFJRyxLQUFJLEdBQUc7Y0FDVEMsUUFBUSxFQUFFbEIsYUFBYTtjQUN2Qm1CLFFBQVEsRUFBR2hCLE9BQU8sR0FBR0gsYUFBYSxHQUFHYyxXQUFZO2NBQ2pETSxRQUFRLEVBQUVuQixhQUFhO2NBQ3ZCb0IsUUFBUSxFQUFHakIsT0FBTyxHQUFHSCxhQUFhLEdBQUdhLFdBQVk7Y0FDakRuQixLQUFLLEVBQUVPO1lBQ1QsQ0FBQztZQUNESCxLQUFLLENBQUN4QyxJQUFJLENBQUMwRCxLQUFJLENBQUM7WUFFaEJqQixhQUFhLEdBQUcsQ0FBQztZQUNqQkMsYUFBYSxHQUFHLENBQUM7WUFDakJDLFFBQVEsR0FBRyxFQUFFO1VBQ2Y7UUFDRjtRQUNBQyxPQUFPLElBQUlSLEtBQUssQ0FBQ2hELE1BQU07UUFDdkJ5RCxPQUFPLElBQUlULEtBQUssQ0FBQ2hELE1BQU07TUFDekI7SUFDRixDQUFDO0lBM0RELEtBQUssSUFBSUMsQ0FBQyxHQUFHLENBQUMsRUFBRUEsQ0FBQyxHQUFHNkMsSUFBSSxDQUFDOUMsTUFBTSxFQUFFQyxDQUFDLEVBQUU7SUFBQTtJQUFBO01BQUF5RCxLQUFBO0lBQUE7O0lBNkRwQztJQUNBO0lBQUE7SUFDQTtJQUFBO0lBQUEsSUFBQWlCLEVBQUEsTUFBQUMsTUFBQTtNQUFBO01BQW1CeEIsS0FBSztJQUFBO0lBQUF1QixFQUFBLEdBQUFDLE1BQUEsQ0FBQTVFO0lBQUE7SUFBQTtJQUFBO0lBQUEyRSxFQUFBO0lBQUE7SUFBQSxFQUFFO01BQXJCLElBQU1MLElBQUk7TUFBQTtNQUFBTSxNQUFBLENBQUFELEVBQUE7TUFBQTtNQUFBO01BQ2IsS0FBSyxJQUFJMUUsR0FBQyxHQUFHLENBQUMsRUFBRUEsR0FBQyxHQUFHcUUsSUFBSSxDQUFDdEIsS0FBSyxDQUFDaEQsTUFBTSxFQUFFQyxHQUFDLEVBQUUsRUFBRTtRQUMxQyxJQUFJcUUsSUFBSSxDQUFDdEIsS0FBSyxDQUFDL0MsR0FBQyxDQUFDLENBQUM0RSxRQUFRLENBQUMsSUFBSSxDQUFDLEVBQUU7VUFDaENQLElBQUksQ0FBQ3RCLEtBQUssQ0FBQy9DLEdBQUMsQ0FBQyxHQUFHcUUsSUFBSSxDQUFDdEIsS0FBSyxDQUFDL0MsR0FBQyxDQUFDLENBQUNULEtBQUssQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUM7UUFDNUMsQ0FBQyxNQUFNO1VBQ0w4RSxJQUFJLENBQUN0QixLQUFLLENBQUM4QixNQUFNLENBQUM3RSxHQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsRUFBRSw4QkFBOEIsQ0FBQztVQUMzREEsR0FBQyxFQUFFLENBQUMsQ0FBQztRQUNQO01BQ0Y7SUFDRjtJQUVBLE9BQU87TUFDTCtCLFdBQVcsRUFBRUEsV0FBVztNQUFFQyxXQUFXLEVBQUVBLFdBQVc7TUFDbERHLFNBQVMsRUFBRUEsU0FBUztNQUFFQyxTQUFTLEVBQUVBLFNBQVM7TUFDMUNlLEtBQUssRUFBRUE7SUFDVCxDQUFDO0VBQ0g7QUFDRjtBQUVPLFNBQVMyQixXQUFXQSxDQUFDakMsSUFBSSxFQUFFO0VBQ2hDLElBQUlwRCxLQUFLLENBQUNJLE9BQU8sQ0FBQ2dELElBQUksQ0FBQyxFQUFFO0lBQ3ZCLE9BQU9BLElBQUksQ0FBQ0ksR0FBRyxDQUFDNkIsV0FBVyxDQUFDLENBQUNDLElBQUksQ0FBQyxJQUFJLENBQUM7RUFDekM7RUFFQSxJQUFNQyxHQUFHLEdBQUcsRUFBRTtFQUNkLElBQUluQyxJQUFJLENBQUNkLFdBQVcsSUFBSWMsSUFBSSxDQUFDYixXQUFXLEVBQUU7SUFDeENnRCxHQUFHLENBQUNyRSxJQUFJLENBQUMsU0FBUyxHQUFHa0MsSUFBSSxDQUFDZCxXQUFXLENBQUM7RUFDeEM7RUFDQWlELEdBQUcsQ0FBQ3JFLElBQUksQ0FBQyxxRUFBcUUsQ0FBQztFQUMvRXFFLEdBQUcsQ0FBQ3JFLElBQUksQ0FBQyxNQUFNLEdBQUdrQyxJQUFJLENBQUNkLFdBQVcsSUFBSSxPQUFPYyxJQUFJLENBQUNWLFNBQVMsS0FBSyxXQUFXLEdBQUcsRUFBRSxHQUFHLElBQUksR0FBR1UsSUFBSSxDQUFDVixTQUFTLENBQUMsQ0FBQztFQUMxRzZDLEdBQUcsQ0FBQ3JFLElBQUksQ0FBQyxNQUFNLEdBQUdrQyxJQUFJLENBQUNiLFdBQVcsSUFBSSxPQUFPYSxJQUFJLENBQUNULFNBQVMsS0FBSyxXQUFXLEdBQUcsRUFBRSxHQUFHLElBQUksR0FBR1MsSUFBSSxDQUFDVCxTQUFTLENBQUMsQ0FBQztFQUUxRyxLQUFLLElBQUlwQyxDQUFDLEdBQUcsQ0FBQyxFQUFFQSxDQUFDLEdBQUc2QyxJQUFJLENBQUNNLEtBQUssQ0FBQ3BELE1BQU0sRUFBRUMsQ0FBQyxFQUFFLEVBQUU7SUFDMUMsSUFBTXFFLElBQUksR0FBR3hCLElBQUksQ0FBQ00sS0FBSyxDQUFDbkQsQ0FBQyxDQUFDO0lBQzFCO0lBQ0E7SUFDQTtJQUNBLElBQUlxRSxJQUFJLENBQUNFLFFBQVEsS0FBSyxDQUFDLEVBQUU7TUFDdkJGLElBQUksQ0FBQ0MsUUFBUSxJQUFJLENBQUM7SUFDcEI7SUFDQSxJQUFJRCxJQUFJLENBQUNJLFFBQVEsS0FBSyxDQUFDLEVBQUU7TUFDdkJKLElBQUksQ0FBQ0csUUFBUSxJQUFJLENBQUM7SUFDcEI7SUFDQVEsR0FBRyxDQUFDckUsSUFBSSxDQUNOLE1BQU0sR0FBRzBELElBQUksQ0FBQ0MsUUFBUSxHQUFHLEdBQUcsR0FBR0QsSUFBSSxDQUFDRSxRQUFRLEdBQzFDLElBQUksR0FBR0YsSUFBSSxDQUFDRyxRQUFRLEdBQUcsR0FBRyxHQUFHSCxJQUFJLENBQUNJLFFBQVEsR0FDMUMsS0FDSixDQUFDO0lBQ0RPLEdBQUcsQ0FBQ3JFLElBQUksQ0FBQ0MsS0FBSyxDQUFDb0UsR0FBRyxFQUFFWCxJQUFJLENBQUN0QixLQUFLLENBQUM7RUFDakM7RUFFQSxPQUFPaUMsR0FBRyxDQUFDRCxJQUFJLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSTtBQUM5QjtBQUVPLFNBQVNFLG1CQUFtQkEsQ0FBQ2xELFdBQVcsRUFBRUMsV0FBVyxFQUFFQyxNQUFNLEVBQUVDLE1BQU0sRUFBRUMsU0FBUyxFQUFFQyxTQUFTLEVBQUVDLE9BQU8sRUFBRTtFQUFBO0VBQUEsSUFBQTZDLFNBQUE7RUFBQTtFQUMzRyxJQUFJLE9BQU83QyxPQUFPLEtBQUssVUFBVSxFQUFFO0lBQ2pDQSxPQUFPLEdBQUc7TUFBQ0MsUUFBUSxFQUFFRDtJQUFPLENBQUM7RUFDL0I7RUFFQSxJQUFJO0VBQUE7RUFBQSxFQUFBNkMsU0FBQTtFQUFBO0VBQUM3QyxPQUFPLGNBQUE2QyxTQUFBO0VBQVA7RUFBQUE7RUFBQTtFQUFBLENBQVM1QyxRQUFRLEdBQUU7SUFDdEIsSUFBTTZDLFFBQVEsR0FBR3JELGVBQWUsQ0FBQ0MsV0FBVyxFQUFFQyxXQUFXLEVBQUVDLE1BQU0sRUFBRUMsTUFBTSxFQUFFQyxTQUFTLEVBQUVDLFNBQVMsRUFBRUMsT0FBTyxDQUFDO0lBQ3pHLElBQUksQ0FBQzhDLFFBQVEsRUFBRTtNQUNiO0lBQ0Y7SUFDQSxPQUFPTCxXQUFXLENBQUNLLFFBQVEsQ0FBQztFQUM5QixDQUFDLE1BQU07SUFDTDtNQUFBO01BQUFDLFNBQUE7TUFBQTtNQUFtQi9DLE9BQU87TUFBQTtNQUFBO01BQW5CQyxVQUFRLEdBQUE4QyxTQUFBLENBQVI5QyxRQUFRO0lBQ2ZSLGVBQWUsQ0FDYkMsV0FBVyxFQUNYQyxXQUFXLEVBQ1hDLE1BQU0sRUFDTkMsTUFBTSxFQUNOQyxTQUFTLEVBQ1RDLFNBQVM7SUFBQTtJQUFBdkIsYUFBQSxDQUFBQSxhQUFBO0lBQUE7SUFFSndCLE9BQU87TUFDVkMsUUFBUSxFQUFFO01BQUE7TUFBQUE7TUFBQUE7TUFBQSxDQUFBNkMsUUFBUSxFQUFJO1FBQ3BCLElBQUksQ0FBQ0EsUUFBUSxFQUFFO1VBQ2I3QyxVQUFRLENBQUMsQ0FBQztRQUNaLENBQUMsTUFBTTtVQUNMQSxVQUFRLENBQUN3QyxXQUFXLENBQUNLLFFBQVEsQ0FBQyxDQUFDO1FBQ2pDO01BQ0Y7SUFBQyxFQUVMLENBQUM7RUFDSDtBQUNGO0FBRU8sU0FBU0UsV0FBV0EsQ0FBQ0MsUUFBUSxFQUFFckQsTUFBTSxFQUFFQyxNQUFNLEVBQUVDLFNBQVMsRUFBRUMsU0FBUyxFQUFFQyxPQUFPLEVBQUU7RUFDbkYsT0FBTzRDLG1CQUFtQixDQUFDSyxRQUFRLEVBQUVBLFFBQVEsRUFBRXJELE1BQU0sRUFBRUMsTUFBTSxFQUFFQyxTQUFTLEVBQUVDLFNBQVMsRUFBRUMsT0FBTyxDQUFDO0FBQy9GOztBQUVBO0FBQ0E7QUFDQTtBQUNBLFNBQVNzQixVQUFVQSxDQUFDNEIsSUFBSSxFQUFFO0VBQ3hCLElBQU1DLGFBQWEsR0FBR0QsSUFBSSxDQUFDWCxRQUFRLENBQUMsSUFBSSxDQUFDO0VBQ3pDLElBQU1hLE1BQU0sR0FBR0YsSUFBSSxDQUFDRyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUN6QyxHQUFHLENBQUMsVUFBQTBDLElBQUk7RUFBQTtFQUFBO0lBQUE7TUFBQTtNQUFJQSxJQUFJLEdBQUc7SUFBSTtFQUFBLEVBQUM7RUFDeEQsSUFBSUgsYUFBYSxFQUFFO0lBQ2pCQyxNQUFNLENBQUNHLEdBQUcsQ0FBQyxDQUFDO0VBQ2QsQ0FBQyxNQUFNO0lBQ0xILE1BQU0sQ0FBQzlFLElBQUksQ0FBQzhFLE1BQU0sQ0FBQ0csR0FBRyxDQUFDLENBQUMsQ0FBQ3JHLEtBQUssQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUMsQ0FBQztFQUN4QztFQUNBLE9BQU9rRyxNQUFNO0FBQ2YiLCJpZ25vcmVMaXN0IjpbXX0= /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isUnix = isUnix; exports.isWin = isWin; exports.unixToWin = unixToWin; exports.winToUnix = winToUnix; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /*istanbul ignore end*/ function unixToWin(patch) { if (Array.isArray(patch)) { return patch.map(unixToWin); } return ( /*istanbul ignore start*/ _objectSpread(_objectSpread({}, /*istanbul ignore end*/ patch), {}, { hunks: patch.hunks.map(function (hunk) /*istanbul ignore start*/ { return _objectSpread(_objectSpread({}, /*istanbul ignore end*/ hunk), {}, { lines: hunk.lines.map(function (line, i) /*istanbul ignore start*/ { var _hunk$lines; return ( /*istanbul ignore end*/ line.startsWith('\\') || line.endsWith('\r') || /*istanbul ignore start*/ (_hunk$lines = /*istanbul ignore end*/ hunk.lines[i + 1]) !== null && _hunk$lines !== void 0 && /*istanbul ignore start*/ _hunk$lines /*istanbul ignore end*/ .startsWith('\\') ? line : line + '\r' ); }) }); }) }) ); } function winToUnix(patch) { if (Array.isArray(patch)) { return patch.map(winToUnix); } return ( /*istanbul ignore start*/ _objectSpread(_objectSpread({}, /*istanbul ignore end*/ patch), {}, { hunks: patch.hunks.map(function (hunk) /*istanbul ignore start*/ { return _objectSpread(_objectSpread({}, /*istanbul ignore end*/ hunk), {}, { lines: hunk.lines.map(function (line) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ line.endsWith('\r') ? line.substring(0, line.length - 1) : line ); }) }); }) }) ); } /** * Returns true if the patch consistently uses Unix line endings (or only involves one line and has * no line endings). */ function isUnix(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return !patch.some(function (index) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ index.hunks.some(function (hunk) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ hunk.lines.some(function (line) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ !line.startsWith('\\') && line.endsWith('\r') ); }) ); }) ); }); } /** * Returns true if the patch uses Windows line endings and only Windows line endings. */ function isWin(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return patch.some(function (index) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ index.hunks.some(function (hunk) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ hunk.lines.some(function (line) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ line.endsWith('\r') ); }) ); }) ); }) && patch.every(function (index) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ index.hunks.every(function (hunk) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ hunk.lines.every(function (line, i) /*istanbul ignore start*/ { var _hunk$lines2; return ( /*istanbul ignore end*/ line.startsWith('\\') || line.endsWith('\r') || /*istanbul ignore start*/ ((_hunk$lines2 = /*istanbul ignore end*/ hunk.lines[i + 1]) === null || _hunk$lines2 === void 0 ? void 0 : /*istanbul ignore start*/ _hunk$lines2 /*istanbul ignore end*/ .startsWith('\\')) ); }) ); }) ); }); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ1bml4VG9XaW4iLCJwYXRjaCIsIkFycmF5IiwiaXNBcnJheSIsIm1hcCIsIl9vYmplY3RTcHJlYWQiLCJodW5rcyIsImh1bmsiLCJsaW5lcyIsImxpbmUiLCJpIiwiX2h1bmskbGluZXMiLCJzdGFydHNXaXRoIiwiZW5kc1dpdGgiLCJ3aW5Ub1VuaXgiLCJzdWJzdHJpbmciLCJsZW5ndGgiLCJpc1VuaXgiLCJzb21lIiwiaW5kZXgiLCJpc1dpbiIsImV2ZXJ5IiwiX2h1bmskbGluZXMyIl0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL3BhdGNoL2xpbmUtZW5kaW5ncy5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gdW5peFRvV2luKHBhdGNoKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KHBhdGNoKSkge1xuICAgIHJldHVybiBwYXRjaC5tYXAodW5peFRvV2luKTtcbiAgfVxuXG4gIHJldHVybiB7XG4gICAgLi4ucGF0Y2gsXG4gICAgaHVua3M6IHBhdGNoLmh1bmtzLm1hcChodW5rID0+ICh7XG4gICAgICAuLi5odW5rLFxuICAgICAgbGluZXM6IGh1bmsubGluZXMubWFwKFxuICAgICAgICAobGluZSwgaSkgPT5cbiAgICAgICAgICAobGluZS5zdGFydHNXaXRoKCdcXFxcJykgfHwgbGluZS5lbmRzV2l0aCgnXFxyJykgfHwgaHVuay5saW5lc1tpICsgMV0/LnN0YXJ0c1dpdGgoJ1xcXFwnKSlcbiAgICAgICAgICAgID8gbGluZVxuICAgICAgICAgICAgOiBsaW5lICsgJ1xccidcbiAgICAgIClcbiAgICB9KSlcbiAgfTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIHdpblRvVW5peChwYXRjaCkge1xuICBpZiAoQXJyYXkuaXNBcnJheShwYXRjaCkpIHtcbiAgICByZXR1cm4gcGF0Y2gubWFwKHdpblRvVW5peCk7XG4gIH1cblxuICByZXR1cm4ge1xuICAgIC4uLnBhdGNoLFxuICAgIGh1bmtzOiBwYXRjaC5odW5rcy5tYXAoaHVuayA9PiAoe1xuICAgICAgLi4uaHVuayxcbiAgICAgIGxpbmVzOiBodW5rLmxpbmVzLm1hcChsaW5lID0+IGxpbmUuZW5kc1dpdGgoJ1xccicpID8gbGluZS5zdWJzdHJpbmcoMCwgbGluZS5sZW5ndGggLSAxKSA6IGxpbmUpXG4gICAgfSkpXG4gIH07XG59XG5cbi8qKlxuICogUmV0dXJucyB0cnVlIGlmIHRoZSBwYXRjaCBjb25zaXN0ZW50bHkgdXNlcyBVbml4IGxpbmUgZW5kaW5ncyAob3Igb25seSBpbnZvbHZlcyBvbmUgbGluZSBhbmQgaGFzXG4gKiBubyBsaW5lIGVuZGluZ3MpLlxuICovXG5leHBvcnQgZnVuY3Rpb24gaXNVbml4KHBhdGNoKSB7XG4gIGlmICghQXJyYXkuaXNBcnJheShwYXRjaCkpIHsgcGF0Y2ggPSBbcGF0Y2hdOyB9XG4gIHJldHVybiAhcGF0Y2guc29tZShcbiAgICBpbmRleCA9PiBpbmRleC5odW5rcy5zb21lKFxuICAgICAgaHVuayA9PiBodW5rLmxpbmVzLnNvbWUoXG4gICAgICAgIGxpbmUgPT4gIWxpbmUuc3RhcnRzV2l0aCgnXFxcXCcpICYmIGxpbmUuZW5kc1dpdGgoJ1xccicpXG4gICAgICApXG4gICAgKVxuICApO1xufVxuXG4vKipcbiAqIFJldHVybnMgdHJ1ZSBpZiB0aGUgcGF0Y2ggdXNlcyBXaW5kb3dzIGxpbmUgZW5kaW5ncyBhbmQgb25seSBXaW5kb3dzIGxpbmUgZW5kaW5ncy5cbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIGlzV2luKHBhdGNoKSB7XG4gIGlmICghQXJyYXkuaXNBcnJheShwYXRjaCkpIHsgcGF0Y2ggPSBbcGF0Y2hdOyB9XG4gIHJldHVybiBwYXRjaC5zb21lKGluZGV4ID0+IGluZGV4Lmh1bmtzLnNvbWUoaHVuayA9PiBodW5rLmxpbmVzLnNvbWUobGluZSA9PiBsaW5lLmVuZHNXaXRoKCdcXHInKSkpKVxuICAgICYmIHBhdGNoLmV2ZXJ5KFxuICAgICAgaW5kZXggPT4gaW5kZXguaHVua3MuZXZlcnkoXG4gICAgICAgIGh1bmsgPT4gaHVuay5saW5lcy5ldmVyeShcbiAgICAgICAgICAobGluZSwgaSkgPT4gbGluZS5zdGFydHNXaXRoKCdcXFxcJykgfHwgbGluZS5lbmRzV2l0aCgnXFxyJykgfHwgaHVuay5saW5lc1tpICsgMV0/LnN0YXJ0c1dpdGgoJ1xcXFwnKVxuICAgICAgICApXG4gICAgICApXG4gICAgKTtcbn1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFBTyxTQUFTQSxTQUFTQSxDQUFDQyxLQUFLLEVBQUU7RUFDL0IsSUFBSUMsS0FBSyxDQUFDQyxPQUFPLENBQUNGLEtBQUssQ0FBQyxFQUFFO0lBQ3hCLE9BQU9BLEtBQUssQ0FBQ0csR0FBRyxDQUFDSixTQUFTLENBQUM7RUFDN0I7RUFFQTtJQUFBO0lBQUFLLGFBQUEsQ0FBQUEsYUFBQTtJQUFBO0lBQ0tKLEtBQUs7TUFDUkssS0FBSyxFQUFFTCxLQUFLLENBQUNLLEtBQUssQ0FBQ0YsR0FBRyxDQUFDLFVBQUFHLElBQUk7TUFBQTtNQUFBO1FBQUEsT0FBQUYsYUFBQSxDQUFBQSxhQUFBO1FBQUE7UUFDdEJFLElBQUk7VUFDUEMsS0FBSyxFQUFFRCxJQUFJLENBQUNDLEtBQUssQ0FBQ0osR0FBRyxDQUNuQixVQUFDSyxJQUFJLEVBQUVDLENBQUM7VUFBQTtVQUFBO1lBQUEsSUFBQUMsV0FBQTtZQUFBO2NBQUE7Y0FDTEYsSUFBSSxDQUFDRyxVQUFVLENBQUMsSUFBSSxDQUFDLElBQUlILElBQUksQ0FBQ0ksUUFBUSxDQUFDLElBQUksQ0FBQztjQUFBO2NBQUEsQ0FBQUYsV0FBQTtjQUFBO2NBQUlKLElBQUksQ0FBQ0MsS0FBSyxDQUFDRSxDQUFDLEdBQUcsQ0FBQyxDQUFDLGNBQUFDLFdBQUE7Y0FBakI7Y0FBQUE7Y0FBQTtjQUFBLENBQW1CQyxVQUFVLENBQUMsSUFBSSxDQUFDLEdBQ2hGSCxJQUFJLEdBQ0pBLElBQUksR0FBRztZQUFJO1VBQUEsQ0FDbkI7UUFBQztNQUFBLENBQ0Q7SUFBQztFQUFBO0FBRVA7QUFFTyxTQUFTSyxTQUFTQSxDQUFDYixLQUFLLEVBQUU7RUFDL0IsSUFBSUMsS0FBSyxDQUFDQyxPQUFPLENBQUNGLEtBQUssQ0FBQyxFQUFFO0lBQ3hCLE9BQU9BLEtBQUssQ0FBQ0csR0FBRyxDQUFDVSxTQUFTLENBQUM7RUFDN0I7RUFFQTtJQUFBO0lBQUFULGFBQUEsQ0FBQUEsYUFBQTtJQUFBO0lBQ0tKLEtBQUs7TUFDUkssS0FBSyxFQUFFTCxLQUFLLENBQUNLLEtBQUssQ0FBQ0YsR0FBRyxDQUFDLFVBQUFHLElBQUk7TUFBQTtNQUFBO1FBQUEsT0FBQUYsYUFBQSxDQUFBQSxhQUFBO1FBQUE7UUFDdEJFLElBQUk7VUFDUEMsS0FBSyxFQUFFRCxJQUFJLENBQUNDLEtBQUssQ0FBQ0osR0FBRyxDQUFDLFVBQUFLLElBQUk7VUFBQTtVQUFBO1lBQUE7Y0FBQTtjQUFJQSxJQUFJLENBQUNJLFFBQVEsQ0FBQyxJQUFJLENBQUMsR0FBR0osSUFBSSxDQUFDTSxTQUFTLENBQUMsQ0FBQyxFQUFFTixJQUFJLENBQUNPLE1BQU0sR0FBRyxDQUFDLENBQUMsR0FBR1A7WUFBSTtVQUFBO1FBQUM7TUFBQSxDQUM5RjtJQUFDO0VBQUE7QUFFUDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNPLFNBQVNRLE1BQU1BLENBQUNoQixLQUFLLEVBQUU7RUFDNUIsSUFBSSxDQUFDQyxLQUFLLENBQUNDLE9BQU8sQ0FBQ0YsS0FBSyxDQUFDLEVBQUU7SUFBRUEsS0FBSyxHQUFHLENBQUNBLEtBQUssQ0FBQztFQUFFO0VBQzlDLE9BQU8sQ0FBQ0EsS0FBSyxDQUFDaUIsSUFBSSxDQUNoQixVQUFBQyxLQUFLO0VBQUE7RUFBQTtJQUFBO01BQUE7TUFBSUEsS0FBSyxDQUFDYixLQUFLLENBQUNZLElBQUksQ0FDdkIsVUFBQVgsSUFBSTtNQUFBO01BQUE7UUFBQTtVQUFBO1VBQUlBLElBQUksQ0FBQ0MsS0FBSyxDQUFDVSxJQUFJLENBQ3JCLFVBQUFULElBQUk7VUFBQTtVQUFBO1lBQUE7Y0FBQTtjQUFJLENBQUNBLElBQUksQ0FBQ0csVUFBVSxDQUFDLElBQUksQ0FBQyxJQUFJSCxJQUFJLENBQUNJLFFBQVEsQ0FBQyxJQUFJO1lBQUM7VUFBQSxDQUN2RDtRQUFDO01BQUEsQ0FDSDtJQUFDO0VBQUEsQ0FDSCxDQUFDO0FBQ0g7O0FBRUE7QUFDQTtBQUNBO0FBQ08sU0FBU08sS0FBS0EsQ0FBQ25CLEtBQUssRUFBRTtFQUMzQixJQUFJLENBQUNDLEtBQUssQ0FBQ0MsT0FBTyxDQUFDRixLQUFLLENBQUMsRUFBRTtJQUFFQSxLQUFLLEdBQUcsQ0FBQ0EsS0FBSyxDQUFDO0VBQUU7RUFDOUMsT0FBT0EsS0FBSyxDQUFDaUIsSUFBSSxDQUFDLFVBQUFDLEtBQUs7RUFBQTtFQUFBO0lBQUE7TUFBQTtNQUFJQSxLQUFLLENBQUNiLEtBQUssQ0FBQ1ksSUFBSSxDQUFDLFVBQUFYLElBQUk7TUFBQTtNQUFBO1FBQUE7VUFBQTtVQUFJQSxJQUFJLENBQUNDLEtBQUssQ0FBQ1UsSUFBSSxDQUFDLFVBQUFULElBQUk7VUFBQTtVQUFBO1lBQUE7Y0FBQTtjQUFJQSxJQUFJLENBQUNJLFFBQVEsQ0FBQyxJQUFJO1lBQUM7VUFBQTtRQUFDO01BQUE7SUFBQztFQUFBLEVBQUMsSUFDN0ZaLEtBQUssQ0FBQ29CLEtBQUssQ0FDWixVQUFBRixLQUFLO0VBQUE7RUFBQTtJQUFBO01BQUE7TUFBSUEsS0FBSyxDQUFDYixLQUFLLENBQUNlLEtBQUssQ0FDeEIsVUFBQWQsSUFBSTtNQUFBO01BQUE7UUFBQTtVQUFBO1VBQUlBLElBQUksQ0FBQ0MsS0FBSyxDQUFDYSxLQUFLLENBQ3RCLFVBQUNaLElBQUksRUFBRUMsQ0FBQztVQUFBO1VBQUE7WUFBQSxJQUFBWSxZQUFBO1lBQUE7Y0FBQTtjQUFLYixJQUFJLENBQUNHLFVBQVUsQ0FBQyxJQUFJLENBQUMsSUFBSUgsSUFBSSxDQUFDSSxRQUFRLENBQUMsSUFBSSxDQUFDO2NBQUE7Y0FBQSxFQUFBUyxZQUFBO2NBQUE7Y0FBSWYsSUFBSSxDQUFDQyxLQUFLLENBQUNFLENBQUMsR0FBRyxDQUFDLENBQUMsY0FBQVksWUFBQTtjQUFqQjtjQUFBQTtjQUFBO2NBQUEsQ0FBbUJWLFVBQVUsQ0FBQyxJQUFJLENBQUM7WUFBQTtVQUFBLENBQ2xHO1FBQUM7TUFBQSxDQUNIO0lBQUM7RUFBQSxDQUNILENBQUM7QUFDTCIsImlnbm9yZUxpc3QiOltdfQ== /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calcLineCount = calcLineCount; exports.merge = merge; /*istanbul ignore end*/ var /*istanbul ignore start*/ _create = require("./create") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _parse = require("./parse") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _array = require("../util/array") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } /*istanbul ignore end*/ function calcLineCount(hunk) { var /*istanbul ignore start*/ _calcOldNewLineCount = /*istanbul ignore end*/ calcOldNewLineCount(hunk.lines), /*istanbul ignore start*/ /*istanbul ignore end*/ oldLines = _calcOldNewLineCount.oldLines, /*istanbul ignore start*/ /*istanbul ignore end*/ newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _parse /*istanbul ignore end*/ . /*istanbul ignore start*/ parsePatch) /*istanbul ignore end*/ (param)[0] ); } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _create /*istanbul ignore end*/ . /*istanbul ignore start*/ structuredPatch) /*istanbul ignore end*/ (undefined, undefined, base, param) ); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { /*istanbul ignore start*/ var _hunk$lines; /*istanbul ignore end*/ // Mine inserted /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { /*istanbul ignore start*/ var _hunk$lines2; /*istanbul ignore end*/ // Theirs inserted /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines2 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines2 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _array /*istanbul ignore end*/ . /*istanbul ignore start*/ arrayStartsWith) /*istanbul ignore end*/ (myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { /*istanbul ignore start*/ var _hunk$lines3; /*istanbul ignore end*/ /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines3 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines3 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ myChanges)); return; } else if ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _array /*istanbul ignore end*/ . /*istanbul ignore start*/ arrayStartsWith) /*istanbul ignore end*/ (theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { /*istanbul ignore start*/ var _hunk$lines4; /*istanbul ignore end*/ /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines4 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines4 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ theirChanges)); return; } } else if ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _array /*istanbul ignore end*/ . /*istanbul ignore start*/ arrayEqual) /*istanbul ignore end*/ (myChanges, theirChanges)) { /*istanbul ignore start*/ var _hunk$lines5; /*istanbul ignore end*/ /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines5 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines5 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { /*istanbul ignore start*/ var _hunk$lines6; /*istanbul ignore end*/ /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines6 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines6 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfY3JlYXRlIiwicmVxdWlyZSIsIl9wYXJzZSIsIl9hcnJheSIsIl90b0NvbnN1bWFibGVBcnJheSIsImFyciIsIl9hcnJheVdpdGhvdXRIb2xlcyIsIl9pdGVyYWJsZVRvQXJyYXkiLCJfdW5zdXBwb3J0ZWRJdGVyYWJsZVRvQXJyYXkiLCJfbm9uSXRlcmFibGVTcHJlYWQiLCJUeXBlRXJyb3IiLCJvIiwibWluTGVuIiwiX2FycmF5TGlrZVRvQXJyYXkiLCJuIiwiT2JqZWN0IiwicHJvdG90eXBlIiwidG9TdHJpbmciLCJjYWxsIiwic2xpY2UiLCJjb25zdHJ1Y3RvciIsIm5hbWUiLCJBcnJheSIsImZyb20iLCJ0ZXN0IiwiaXRlciIsIlN5bWJvbCIsIml0ZXJhdG9yIiwiaXNBcnJheSIsImxlbiIsImxlbmd0aCIsImkiLCJhcnIyIiwiY2FsY0xpbmVDb3VudCIsImh1bmsiLCJfY2FsY09sZE5ld0xpbmVDb3VudCIsImNhbGNPbGROZXdMaW5lQ291bnQiLCJsaW5lcyIsIm9sZExpbmVzIiwibmV3TGluZXMiLCJ1bmRlZmluZWQiLCJtZXJnZSIsIm1pbmUiLCJ0aGVpcnMiLCJiYXNlIiwibG9hZFBhdGNoIiwicmV0IiwiaW5kZXgiLCJuZXdGaWxlTmFtZSIsImZpbGVOYW1lQ2hhbmdlZCIsIm9sZEZpbGVOYW1lIiwib2xkSGVhZGVyIiwibmV3SGVhZGVyIiwic2VsZWN0RmllbGQiLCJodW5rcyIsIm1pbmVJbmRleCIsInRoZWlyc0luZGV4IiwibWluZU9mZnNldCIsInRoZWlyc09mZnNldCIsIm1pbmVDdXJyZW50Iiwib2xkU3RhcnQiLCJJbmZpbml0eSIsInRoZWlyc0N1cnJlbnQiLCJodW5rQmVmb3JlIiwicHVzaCIsImNsb25lSHVuayIsIm1lcmdlZEh1bmsiLCJNYXRoIiwibWluIiwibmV3U3RhcnQiLCJtZXJnZUxpbmVzIiwicGFyYW0iLCJwYXJzZVBhdGNoIiwiRXJyb3IiLCJzdHJ1Y3R1cmVkUGF0Y2giLCJwYXRjaCIsImNvbmZsaWN0IiwiY2hlY2siLCJvZmZzZXQiLCJtaW5lTGluZXMiLCJ0aGVpck9mZnNldCIsInRoZWlyTGluZXMiLCJ0aGVpciIsImluc2VydExlYWRpbmciLCJ0aGVpckN1cnJlbnQiLCJtdXR1YWxDaGFuZ2UiLCJfaHVuayRsaW5lcyIsImFwcGx5IiwiY29sbGVjdENoYW5nZSIsIl9odW5rJGxpbmVzMiIsInJlbW92YWwiLCJpbnNlcnRUcmFpbGluZyIsIm15Q2hhbmdlcyIsInRoZWlyQ2hhbmdlcyIsImFsbFJlbW92ZXMiLCJhcnJheVN0YXJ0c1dpdGgiLCJza2lwUmVtb3ZlU3VwZXJzZXQiLCJfaHVuayRsaW5lczMiLCJfaHVuayRsaW5lczQiLCJhcnJheUVxdWFsIiwiX2h1bmskbGluZXM1Iiwic3dhcCIsImNvbGxlY3RDb250ZXh0IiwibWVyZ2VkIiwiX2h1bmskbGluZXM2IiwiaW5zZXJ0IiwibGluZSIsInN0YXRlIiwib3BlcmF0aW9uIiwibWF0Y2hDaGFuZ2VzIiwiY2hhbmdlcyIsIm1hdGNoSW5kZXgiLCJjb250ZXh0Q2hhbmdlcyIsImNvbmZsaWN0ZWQiLCJjaGFuZ2UiLCJtYXRjaCIsInN1YnN0ciIsInJlZHVjZSIsInByZXYiLCJyZW1vdmVDaGFuZ2VzIiwiZGVsdGEiLCJjaGFuZ2VDb250ZW50IiwiZm9yRWFjaCIsIm15Q291bnQiLCJ0aGVpckNvdW50Il0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL3BhdGNoL21lcmdlLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7c3RydWN0dXJlZFBhdGNofSBmcm9tICcuL2NyZWF0ZSc7XG5pbXBvcnQge3BhcnNlUGF0Y2h9IGZyb20gJy4vcGFyc2UnO1xuXG5pbXBvcnQge2FycmF5RXF1YWwsIGFycmF5U3RhcnRzV2l0aH0gZnJvbSAnLi4vdXRpbC9hcnJheSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBjYWxjTGluZUNvdW50KGh1bmspIHtcbiAgY29uc3Qge29sZExpbmVzLCBuZXdMaW5lc30gPSBjYWxjT2xkTmV3TGluZUNvdW50KGh1bmsubGluZXMpO1xuXG4gIGlmIChvbGRMaW5lcyAhPT0gdW5kZWZpbmVkKSB7XG4gICAgaHVuay5vbGRMaW5lcyA9IG9sZExpbmVzO1xuICB9IGVsc2Uge1xuICAgIGRlbGV0ZSBodW5rLm9sZExpbmVzO1xuICB9XG5cbiAgaWYgKG5ld0xpbmVzICE9PSB1bmRlZmluZWQpIHtcbiAgICBodW5rLm5ld0xpbmVzID0gbmV3TGluZXM7XG4gIH0gZWxzZSB7XG4gICAgZGVsZXRlIGh1bmsubmV3TGluZXM7XG4gIH1cbn1cblxuZXhwb3J0IGZ1bmN0aW9uIG1lcmdlKG1pbmUsIHRoZWlycywgYmFzZSkge1xuICBtaW5lID0gbG9hZFBhdGNoKG1pbmUsIGJhc2UpO1xuICB0aGVpcnMgPSBsb2FkUGF0Y2godGhlaXJzLCBiYXNlKTtcblxuICBsZXQgcmV0ID0ge307XG5cbiAgLy8gRm9yIGluZGV4IHdlIGp1c3QgbGV0IGl0IHBhc3MgdGhyb3VnaCBhcyBpdCBkb2Vzbid0IGhhdmUgYW55IG5lY2Vzc2FyeSBtZWFuaW5nLlxuICAvLyBMZWF2aW5nIHNhbml0eSBjaGVja3Mgb24gdGhpcyB0byB0aGUgQVBJIGNvbnN1bWVyIHRoYXQgbWF5IGtub3cgbW9yZSBhYm91dCB0aGVcbiAgLy8gbWVhbmluZyBpbiB0aGVpciBvd24gY29udGV4dC5cbiAgaWYgKG1pbmUuaW5kZXggfHwgdGhlaXJzLmluZGV4KSB7XG4gICAgcmV0LmluZGV4ID0gbWluZS5pbmRleCB8fCB0aGVpcnMuaW5kZXg7XG4gIH1cblxuICBpZiAobWluZS5uZXdGaWxlTmFtZSB8fCB0aGVpcnMubmV3RmlsZU5hbWUpIHtcbiAgICBpZiAoIWZpbGVOYW1lQ2hhbmdlZChtaW5lKSkge1xuICAgICAgLy8gTm8gaGVhZGVyIG9yIG5vIGNoYW5nZSBpbiBvdXJzLCB1c2UgdGhlaXJzIChhbmQgb3VycyBpZiB0aGVpcnMgZG9lcyBub3QgZXhpc3QpXG4gICAgICByZXQub2xkRmlsZU5hbWUgPSB0aGVpcnMub2xkRmlsZU5hbWUgfHwgbWluZS5vbGRGaWxlTmFtZTtcbiAgICAgIHJldC5uZXdGaWxlTmFtZSA9IHRoZWlycy5uZXdGaWxlTmFtZSB8fCBtaW5lLm5ld0ZpbGVOYW1lO1xuICAgICAgcmV0Lm9sZEhlYWRlciA9IHRoZWlycy5vbGRIZWFkZXIgfHwgbWluZS5vbGRIZWFkZXI7XG4gICAgICByZXQubmV3SGVhZGVyID0gdGhlaXJzLm5ld0hlYWRlciB8fCBtaW5lLm5ld0hlYWRlcjtcbiAgICB9IGVsc2UgaWYgKCFmaWxlTmFtZUNoYW5nZWQodGhlaXJzKSkge1xuICAgICAgLy8gTm8gaGVhZGVyIG9yIG5vIGNoYW5nZSBpbiB0aGVpcnMsIHVzZSBvdXJzXG4gICAgICByZXQub2xkRmlsZU5hbWUgPSBtaW5lLm9sZEZpbGVOYW1lO1xuICAgICAgcmV0Lm5ld0ZpbGVOYW1lID0gbWluZS5uZXdGaWxlTmFtZTtcbiAgICAgIHJldC5vbGRIZWFkZXIgPSBtaW5lLm9sZEhlYWRlcjtcbiAgICAgIHJldC5uZXdIZWFkZXIgPSBtaW5lLm5ld0hlYWRlcjtcbiAgICB9IGVsc2Uge1xuICAgICAgLy8gQm90aCBjaGFuZ2VkLi4uIGZpZ3VyZSBpdCBvdXRcbiAgICAgIHJldC5vbGRGaWxlTmFtZSA9IHNlbGVjdEZpZWxkKHJldCwgbWluZS5vbGRGaWxlTmFtZSwgdGhlaXJzLm9sZEZpbGVOYW1lKTtcbiAgICAgIHJldC5uZXdGaWxlTmFtZSA9IHNlbGVjdEZpZWxkKHJldCwgbWluZS5uZXdGaWxlTmFtZSwgdGhlaXJzLm5ld0ZpbGVOYW1lKTtcbiAgICAgIHJldC5vbGRIZWFkZXIgPSBzZWxlY3RGaWVsZChyZXQsIG1pbmUub2xkSGVhZGVyLCB0aGVpcnMub2xkSGVhZGVyKTtcbiAgICAgIHJldC5uZXdIZWFkZXIgPSBzZWxlY3RGaWVsZChyZXQsIG1pbmUubmV3SGVhZGVyLCB0aGVpcnMubmV3SGVhZGVyKTtcbiAgICB9XG4gIH1cblxuICByZXQuaHVua3MgPSBbXTtcblxuICBsZXQgbWluZUluZGV4ID0gMCxcbiAgICAgIHRoZWlyc0luZGV4ID0gMCxcbiAgICAgIG1pbmVPZmZzZXQgPSAwLFxuICAgICAgdGhlaXJzT2Zmc2V0ID0gMDtcblxuICB3aGlsZSAobWluZUluZGV4IDwgbWluZS5odW5rcy5sZW5ndGggfHwgdGhlaXJzSW5kZXggPCB0aGVpcnMuaHVua3MubGVuZ3RoKSB7XG4gICAgbGV0IG1pbmVDdXJyZW50ID0gbWluZS5odW5rc1ttaW5lSW5kZXhdIHx8IHtvbGRTdGFydDogSW5maW5pdHl9LFxuICAgICAgICB0aGVpcnNDdXJyZW50ID0gdGhlaXJzLmh1bmtzW3RoZWlyc0luZGV4XSB8fCB7b2xkU3RhcnQ6IEluZmluaXR5fTtcblxuICAgIGlmIChodW5rQmVmb3JlKG1pbmVDdXJyZW50LCB0aGVpcnNDdXJyZW50KSkge1xuICAgICAgLy8gVGhpcyBwYXRjaCBkb2VzIG5vdCBvdmVybGFwIHdpdGggYW55IG9mIHRoZSBvdGhlcnMsIHlheS5cbiAgICAgIHJldC5odW5rcy5wdXNoKGNsb25lSHVuayhtaW5lQ3VycmVudCwgbWluZU9mZnNldCkpO1xuICAgICAgbWluZUluZGV4Kys7XG4gICAgICB0aGVpcnNPZmZzZXQgKz0gbWluZUN1cnJlbnQubmV3TGluZXMgLSBtaW5lQ3VycmVudC5vbGRMaW5lcztcbiAgICB9IGVsc2UgaWYgKGh1bmtCZWZvcmUodGhlaXJzQ3VycmVudCwgbWluZUN1cnJlbnQpKSB7XG4gICAgICAvLyBUaGlzIHBhdGNoIGRvZXMgbm90IG92ZXJsYXAgd2l0aCBhbnkgb2YgdGhlIG90aGVycywgeWF5LlxuICAgICAgcmV0Lmh1bmtzLnB1c2goY2xvbmVIdW5rKHRoZWlyc0N1cnJlbnQsIHRoZWlyc09mZnNldCkpO1xuICAgICAgdGhlaXJzSW5kZXgrKztcbiAgICAgIG1pbmVPZmZzZXQgKz0gdGhlaXJzQ3VycmVudC5uZXdMaW5lcyAtIHRoZWlyc0N1cnJlbnQub2xkTGluZXM7XG4gICAgfSBlbHNlIHtcbiAgICAgIC8vIE92ZXJsYXAsIG1lcmdlIGFzIGJlc3Qgd2UgY2FuXG4gICAgICBsZXQgbWVyZ2VkSHVuayA9IHtcbiAgICAgICAgb2xkU3RhcnQ6IE1hdGgubWluKG1pbmVDdXJyZW50Lm9sZFN0YXJ0LCB0aGVpcnNDdXJyZW50Lm9sZFN0YXJ0KSxcbiAgICAgICAgb2xkTGluZXM6IDAsXG4gICAgICAgIG5ld1N0YXJ0OiBNYXRoLm1pbihtaW5lQ3VycmVudC5uZXdTdGFydCArIG1pbmVPZmZzZXQsIHRoZWlyc0N1cnJlbnQub2xkU3RhcnQgKyB0aGVpcnNPZmZzZXQpLFxuICAgICAgICBuZXdMaW5lczogMCxcbiAgICAgICAgbGluZXM6IFtdXG4gICAgICB9O1xuICAgICAgbWVyZ2VMaW5lcyhtZXJnZWRIdW5rLCBtaW5lQ3VycmVudC5vbGRTdGFydCwgbWluZUN1cnJlbnQubGluZXMsIHRoZWlyc0N1cnJlbnQub2xkU3RhcnQsIHRoZWlyc0N1cnJlbnQubGluZXMpO1xuICAgICAgdGhlaXJzSW5kZXgrKztcbiAgICAgIG1pbmVJbmRleCsrO1xuXG4gICAgICByZXQuaHVua3MucHVzaChtZXJnZWRIdW5rKTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmV0O1xufVxuXG5mdW5jdGlvbiBsb2FkUGF0Y2gocGFyYW0sIGJhc2UpIHtcbiAgaWYgKHR5cGVvZiBwYXJhbSA9PT0gJ3N0cmluZycpIHtcbiAgICBpZiAoKC9eQEAvbSkudGVzdChwYXJhbSkgfHwgKCgvXkluZGV4Oi9tKS50ZXN0KHBhcmFtKSkpIHtcbiAgICAgIHJldHVybiBwYXJzZVBhdGNoKHBhcmFtKVswXTtcbiAgICB9XG5cbiAgICBpZiAoIWJhc2UpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignTXVzdCBwcm92aWRlIGEgYmFzZSByZWZlcmVuY2Ugb3IgcGFzcyBpbiBhIHBhdGNoJyk7XG4gICAgfVxuICAgIHJldHVybiBzdHJ1Y3R1cmVkUGF0Y2godW5kZWZpbmVkLCB1bmRlZmluZWQsIGJhc2UsIHBhcmFtKTtcbiAgfVxuXG4gIHJldHVybiBwYXJhbTtcbn1cblxuZnVuY3Rpb24gZmlsZU5hbWVDaGFuZ2VkKHBhdGNoKSB7XG4gIHJldHVybiBwYXRjaC5uZXdGaWxlTmFtZSAmJiBwYXRjaC5uZXdGaWxlTmFtZSAhPT0gcGF0Y2gub2xkRmlsZU5hbWU7XG59XG5cbmZ1bmN0aW9uIHNlbGVjdEZpZWxkKGluZGV4LCBtaW5lLCB0aGVpcnMpIHtcbiAgaWYgKG1pbmUgPT09IHRoZWlycykge1xuICAgIHJldHVybiBtaW5lO1xuICB9IGVsc2Uge1xuICAgIGluZGV4LmNvbmZsaWN0ID0gdHJ1ZTtcbiAgICByZXR1cm4ge21pbmUsIHRoZWlyc307XG4gIH1cbn1cblxuZnVuY3Rpb24gaHVua0JlZm9yZSh0ZXN0LCBjaGVjaykge1xuICByZXR1cm4gdGVzdC5vbGRTdGFydCA8IGNoZWNrLm9sZFN0YXJ0XG4gICAgJiYgKHRlc3Qub2xkU3RhcnQgKyB0ZXN0Lm9sZExpbmVzKSA8IGNoZWNrLm9sZFN0YXJ0O1xufVxuXG5mdW5jdGlvbiBjbG9uZUh1bmsoaHVuaywgb2Zmc2V0KSB7XG4gIHJldHVybiB7XG4gICAgb2xkU3RhcnQ6IGh1bmsub2xkU3RhcnQsIG9sZExpbmVzOiBodW5rLm9sZExpbmVzLFxuICAgIG5ld1N0YXJ0OiBodW5rLm5ld1N0YXJ0ICsgb2Zmc2V0LCBuZXdMaW5lczogaHVuay5uZXdMaW5lcyxcbiAgICBsaW5lczogaHVuay5saW5lc1xuICB9O1xufVxuXG5mdW5jdGlvbiBtZXJnZUxpbmVzKGh1bmssIG1pbmVPZmZzZXQsIG1pbmVMaW5lcywgdGhlaXJPZmZzZXQsIHRoZWlyTGluZXMpIHtcbiAgLy8gVGhpcyB3aWxsIGdlbmVyYWxseSByZXN1bHQgaW4gYSBjb25mbGljdGVkIGh1bmssIGJ1dCB0aGVyZSBhcmUgY2FzZXMgd2hlcmUgdGhlIGNvbnRleHRcbiAgLy8gaXMgdGhlIG9ubHkgb3ZlcmxhcCB3aGVyZSB3ZSBjYW4gc3VjY2Vzc2Z1bGx5IG1lcmdlIHRoZSBjb250ZW50IGhlcmUuXG4gIGxldCBtaW5lID0ge29mZnNldDogbWluZU9mZnNldCwgbGluZXM6IG1pbmVMaW5lcywgaW5kZXg6IDB9LFxuICAgICAgdGhlaXIgPSB7b2Zmc2V0OiB0aGVpck9mZnNldCwgbGluZXM6IHRoZWlyTGluZXMsIGluZGV4OiAwfTtcblxuICAvLyBIYW5kbGUgYW55IGxlYWRpbmcgY29udGVudFxuICBpbnNlcnRMZWFkaW5nKGh1bmssIG1pbmUsIHRoZWlyKTtcbiAgaW5zZXJ0TGVhZGluZyhodW5rLCB0aGVpciwgbWluZSk7XG5cbiAgLy8gTm93IGluIHRoZSBvdmVybGFwIGNvbnRlbnQuIFNjYW4gdGhyb3VnaCBhbmQgc2VsZWN0IHRoZSBiZXN0IGNoYW5nZXMgZnJvbSBlYWNoLlxuICB3aGlsZSAobWluZS5pbmRleCA8IG1pbmUubGluZXMubGVuZ3RoICYmIHRoZWlyLmluZGV4IDwgdGhlaXIubGluZXMubGVuZ3RoKSB7XG4gICAgbGV0IG1pbmVDdXJyZW50ID0gbWluZS5saW5lc1ttaW5lLmluZGV4XSxcbiAgICAgICAgdGhlaXJDdXJyZW50ID0gdGhlaXIubGluZXNbdGhlaXIuaW5kZXhdO1xuXG4gICAgaWYgKChtaW5lQ3VycmVudFswXSA9PT0gJy0nIHx8IG1pbmVDdXJyZW50WzBdID09PSAnKycpXG4gICAgICAgICYmICh0aGVpckN1cnJlbnRbMF0gPT09ICctJyB8fCB0aGVpckN1cnJlbnRbMF0gPT09ICcrJykpIHtcbiAgICAgIC8vIEJvdGggbW9kaWZpZWQgLi4uXG4gICAgICBtdXR1YWxDaGFuZ2UoaHVuaywgbWluZSwgdGhlaXIpO1xuICAgIH0gZWxzZSBpZiAobWluZUN1cnJlbnRbMF0gPT09ICcrJyAmJiB0aGVpckN1cnJlbnRbMF0gPT09ICcgJykge1xuICAgICAgLy8gTWluZSBpbnNlcnRlZFxuICAgICAgaHVuay5saW5lcy5wdXNoKC4uLiBjb2xsZWN0Q2hhbmdlKG1pbmUpKTtcbiAgICB9IGVsc2UgaWYgKHRoZWlyQ3VycmVudFswXSA9PT0gJysnICYmIG1pbmVDdXJyZW50WzBdID09PSAnICcpIHtcbiAgICAgIC8vIFRoZWlycyBpbnNlcnRlZFxuICAgICAgaHVuay5saW5lcy5wdXNoKC4uLiBjb2xsZWN0Q2hhbmdlKHRoZWlyKSk7XG4gICAgfSBlbHNlIGlmIChtaW5lQ3VycmVudFswXSA9PT0gJy0nICYmIHRoZWlyQ3VycmVudFswXSA9PT0gJyAnKSB7XG4gICAgICAvLyBNaW5lIHJlbW92ZWQgb3IgZWRpdGVkXG4gICAgICByZW1vdmFsKGh1bmssIG1pbmUsIHRoZWlyKTtcbiAgICB9IGVsc2UgaWYgKHRoZWlyQ3VycmVudFswXSA9PT0gJy0nICYmIG1pbmVDdXJyZW50WzBdID09PSAnICcpIHtcbiAgICAgIC8vIFRoZWlyIHJlbW92ZWQgb3IgZWRpdGVkXG4gICAgICByZW1vdmFsKGh1bmssIHRoZWlyLCBtaW5lLCB0cnVlKTtcbiAgICB9IGVsc2UgaWYgKG1pbmVDdXJyZW50ID09PSB0aGVpckN1cnJlbnQpIHtcbiAgICAgIC8vIENvbnRleHQgaWRlbnRpdHlcbiAgICAgIGh1bmsubGluZXMucHVzaChtaW5lQ3VycmVudCk7XG4gICAgICBtaW5lLmluZGV4Kys7XG4gICAgICB0aGVpci5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICAvLyBDb250ZXh0IG1pc21hdGNoXG4gICAgICBjb25mbGljdChodW5rLCBjb2xsZWN0Q2hhbmdlKG1pbmUpLCBjb2xsZWN0Q2hhbmdlKHRoZWlyKSk7XG4gICAgfVxuICB9XG5cbiAgLy8gTm93IHB1c2ggYW55dGhpbmcgdGhhdCBtYXkgYmUgcmVtYWluaW5nXG4gIGluc2VydFRyYWlsaW5nKGh1bmssIG1pbmUpO1xuICBpbnNlcnRUcmFpbGluZyhodW5rLCB0aGVpcik7XG5cbiAgY2FsY0xpbmVDb3VudChodW5rKTtcbn1cblxuZnVuY3Rpb24gbXV0dWFsQ2hhbmdlKGh1bmssIG1pbmUsIHRoZWlyKSB7XG4gIGxldCBteUNoYW5nZXMgPSBjb2xsZWN0Q2hhbmdlKG1pbmUpLFxuICAgICAgdGhlaXJDaGFuZ2VzID0gY29sbGVjdENoYW5nZSh0aGVpcik7XG5cbiAgaWYgKGFsbFJlbW92ZXMobXlDaGFuZ2VzKSAmJiBhbGxSZW1vdmVzKHRoZWlyQ2hhbmdlcykpIHtcbiAgICAvLyBTcGVjaWFsIGNhc2UgZm9yIHJlbW92ZSBjaGFuZ2VzIHRoYXQgYXJlIHN1cGVyc2V0cyBvZiBvbmUgYW5vdGhlclxuICAgIGlmIChhcnJheVN0YXJ0c1dpdGgobXlDaGFuZ2VzLCB0aGVpckNoYW5nZXMpXG4gICAgICAgICYmIHNraXBSZW1vdmVTdXBlcnNldCh0aGVpciwgbXlDaGFuZ2VzLCBteUNoYW5nZXMubGVuZ3RoIC0gdGhlaXJDaGFuZ2VzLmxlbmd0aCkpIHtcbiAgICAgIGh1bmsubGluZXMucHVzaCguLi4gbXlDaGFuZ2VzKTtcbiAgICAgIHJldHVybjtcbiAgICB9IGVsc2UgaWYgKGFycmF5U3RhcnRzV2l0aCh0aGVpckNoYW5nZXMsIG15Q2hhbmdlcylcbiAgICAgICAgJiYgc2tpcFJlbW92ZVN1cGVyc2V0KG1pbmUsIHRoZWlyQ2hhbmdlcywgdGhlaXJDaGFuZ2VzLmxlbmd0aCAtIG15Q2hhbmdlcy5sZW5ndGgpKSB7XG4gICAgICBodW5rLmxpbmVzLnB1c2goLi4uIHRoZWlyQ2hhbmdlcyk7XG4gICAgICByZXR1cm47XG4gICAgfVxuICB9IGVsc2UgaWYgKGFycmF5RXF1YWwobXlDaGFuZ2VzLCB0aGVpckNoYW5nZXMpKSB7XG4gICAgaHVuay5saW5lcy5wdXNoKC4uLiBteUNoYW5nZXMpO1xuICAgIHJldHVybjtcbiAgfVxuXG4gIGNvbmZsaWN0KGh1bmssIG15Q2hhbmdlcywgdGhlaXJDaGFuZ2VzKTtcbn1cblxuZnVuY3Rpb24gcmVtb3ZhbChodW5rLCBtaW5lLCB0aGVpciwgc3dhcCkge1xuICBsZXQgbXlDaGFuZ2VzID0gY29sbGVjdENoYW5nZShtaW5lKSxcbiAgICAgIHRoZWlyQ2hhbmdlcyA9IGNvbGxlY3RDb250ZXh0KHRoZWlyLCBteUNoYW5nZXMpO1xuICBpZiAodGhlaXJDaGFuZ2VzLm1lcmdlZCkge1xuICAgIGh1bmsubGluZXMucHVzaCguLi4gdGhlaXJDaGFuZ2VzLm1lcmdlZCk7XG4gIH0gZWxzZSB7XG4gICAgY29uZmxpY3QoaHVuaywgc3dhcCA/IHRoZWlyQ2hhbmdlcyA6IG15Q2hhbmdlcywgc3dhcCA/IG15Q2hhbmdlcyA6IHRoZWlyQ2hhbmdlcyk7XG4gIH1cbn1cblxuZnVuY3Rpb24gY29uZmxpY3QoaHVuaywgbWluZSwgdGhlaXIpIHtcbiAgaHVuay5jb25mbGljdCA9IHRydWU7XG4gIGh1bmsubGluZXMucHVzaCh7XG4gICAgY29uZmxpY3Q6IHRydWUsXG4gICAgbWluZTogbWluZSxcbiAgICB0aGVpcnM6IHRoZWlyXG4gIH0pO1xufVxuXG5mdW5jdGlvbiBpbnNlcnRMZWFkaW5nKGh1bmssIGluc2VydCwgdGhlaXIpIHtcbiAgd2hpbGUgKGluc2VydC5vZmZzZXQgPCB0aGVpci5vZmZzZXQgJiYgaW5zZXJ0LmluZGV4IDwgaW5zZXJ0LmxpbmVzLmxlbmd0aCkge1xuICAgIGxldCBsaW5lID0gaW5zZXJ0LmxpbmVzW2luc2VydC5pbmRleCsrXTtcbiAgICBodW5rLmxpbmVzLnB1c2gobGluZSk7XG4gICAgaW5zZXJ0Lm9mZnNldCsrO1xuICB9XG59XG5mdW5jdGlvbiBpbnNlcnRUcmFpbGluZyhodW5rLCBpbnNlcnQpIHtcbiAgd2hpbGUgKGluc2VydC5pbmRleCA8IGluc2VydC5saW5lcy5sZW5ndGgpIHtcbiAgICBsZXQgbGluZSA9IGluc2VydC5saW5lc1tpbnNlcnQuaW5kZXgrK107XG4gICAgaHVuay5saW5lcy5wdXNoKGxpbmUpO1xuICB9XG59XG5cbmZ1bmN0aW9uIGNvbGxlY3RDaGFuZ2Uoc3RhdGUpIHtcbiAgbGV0IHJldCA9IFtdLFxuICAgICAgb3BlcmF0aW9uID0gc3RhdGUubGluZXNbc3RhdGUuaW5kZXhdWzBdO1xuICB3aGlsZSAoc3RhdGUuaW5kZXggPCBzdGF0ZS5saW5lcy5sZW5ndGgpIHtcbiAgICBsZXQgbGluZSA9IHN0YXRlLmxpbmVzW3N0YXRlLmluZGV4XTtcblxuICAgIC8vIEdyb3VwIGFkZGl0aW9ucyB0aGF0IGFyZSBpbW1lZGlhdGVseSBhZnRlciBzdWJ0cmFjdGlvbnMgYW5kIHRyZWF0IHRoZW0gYXMgb25lIFwiYXRvbWljXCIgbW9kaWZ5IGNoYW5nZS5cbiAgICBpZiAob3BlcmF0aW9uID09PSAnLScgJiYgbGluZVswXSA9PT0gJysnKSB7XG4gICAgICBvcGVyYXRpb24gPSAnKyc7XG4gICAgfVxuXG4gICAgaWYgKG9wZXJhdGlvbiA9PT0gbGluZVswXSkge1xuICAgICAgcmV0LnB1c2gobGluZSk7XG4gICAgICBzdGF0ZS5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICBicmVhaztcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmV0O1xufVxuZnVuY3Rpb24gY29sbGVjdENvbnRleHQoc3RhdGUsIG1hdGNoQ2hhbmdlcykge1xuICBsZXQgY2hhbmdlcyA9IFtdLFxuICAgICAgbWVyZ2VkID0gW10sXG4gICAgICBtYXRjaEluZGV4ID0gMCxcbiAgICAgIGNvbnRleHRDaGFuZ2VzID0gZmFsc2UsXG4gICAgICBjb25mbGljdGVkID0gZmFsc2U7XG4gIHdoaWxlIChtYXRjaEluZGV4IDwgbWF0Y2hDaGFuZ2VzLmxlbmd0aFxuICAgICAgICAmJiBzdGF0ZS5pbmRleCA8IHN0YXRlLmxpbmVzLmxlbmd0aCkge1xuICAgIGxldCBjaGFuZ2UgPSBzdGF0ZS5saW5lc1tzdGF0ZS5pbmRleF0sXG4gICAgICAgIG1hdGNoID0gbWF0Y2hDaGFuZ2VzW21hdGNoSW5kZXhdO1xuXG4gICAgLy8gT25jZSB3ZSd2ZSBoaXQgb3VyIGFkZCwgdGhlbiB3ZSBhcmUgZG9uZVxuICAgIGlmIChtYXRjaFswXSA9PT0gJysnKSB7XG4gICAgICBicmVhaztcbiAgICB9XG5cbiAgICBjb250ZXh0Q2hhbmdlcyA9IGNvbnRleHRDaGFuZ2VzIHx8IGNoYW5nZVswXSAhPT0gJyAnO1xuXG4gICAgbWVyZ2VkLnB1c2gobWF0Y2gpO1xuICAgIG1hdGNoSW5kZXgrKztcblxuICAgIC8vIENvbnN1bWUgYW55IGFkZGl0aW9ucyBpbiB0aGUgb3RoZXIgYmxvY2sgYXMgYSBjb25mbGljdCB0byBhdHRlbXB0XG4gICAgLy8gdG8gcHVsbCBpbiB0aGUgcmVtYWluaW5nIGNvbnRleHQgYWZ0ZXIgdGhpc1xuICAgIGlmIChjaGFuZ2VbMF0gPT09ICcrJykge1xuICAgICAgY29uZmxpY3RlZCA9IHRydWU7XG5cbiAgICAgIHdoaWxlIChjaGFuZ2VbMF0gPT09ICcrJykge1xuICAgICAgICBjaGFuZ2VzLnB1c2goY2hhbmdlKTtcbiAgICAgICAgY2hhbmdlID0gc3RhdGUubGluZXNbKytzdGF0ZS5pbmRleF07XG4gICAgICB9XG4gICAgfVxuXG4gICAgaWYgKG1hdGNoLnN1YnN0cigxKSA9PT0gY2hhbmdlLnN1YnN0cigxKSkge1xuICAgICAgY2hhbmdlcy5wdXNoKGNoYW5nZSk7XG4gICAgICBzdGF0ZS5pbmRleCsrO1xuICAgIH0gZWxzZSB7XG4gICAgICBjb25mbGljdGVkID0gdHJ1ZTtcbiAgICB9XG4gIH1cblxuICBpZiAoKG1hdGNoQ2hhbmdlc1ttYXRjaEluZGV4XSB8fCAnJylbMF0gPT09ICcrJ1xuICAgICAgJiYgY29udGV4dENoYW5nZXMpIHtcbiAgICBjb25mbGljdGVkID0gdHJ1ZTtcbiAgfVxuXG4gIGlmIChjb25mbGljdGVkKSB7XG4gICAgcmV0dXJuIGNoYW5nZXM7XG4gIH1cblxuICB3aGlsZSAobWF0Y2hJbmRleCA8IG1hdGNoQ2hhbmdlcy5sZW5ndGgpIHtcbiAgICBtZXJnZWQucHVzaChtYXRjaENoYW5nZXNbbWF0Y2hJbmRleCsrXSk7XG4gIH1cblxuICByZXR1cm4ge1xuICAgIG1lcmdlZCxcbiAgICBjaGFuZ2VzXG4gIH07XG59XG5cbmZ1bmN0aW9uIGFsbFJlbW92ZXMoY2hhbmdlcykge1xuICByZXR1cm4gY2hhbmdlcy5yZWR1Y2UoZnVuY3Rpb24ocHJldiwgY2hhbmdlKSB7XG4gICAgcmV0dXJuIHByZXYgJiYgY2hhbmdlWzBdID09PSAnLSc7XG4gIH0sIHRydWUpO1xufVxuZnVuY3Rpb24gc2tpcFJlbW92ZVN1cGVyc2V0KHN0YXRlLCByZW1vdmVDaGFuZ2VzLCBkZWx0YSkge1xuICBmb3IgKGxldCBpID0gMDsgaSA8IGRlbHRhOyBpKyspIHtcbiAgICBsZXQgY2hhbmdlQ29udGVudCA9IHJlbW92ZUNoYW5nZXNbcmVtb3ZlQ2hhbmdlcy5sZW5ndGggLSBkZWx0YSArIGldLnN1YnN0cigxKTtcbiAgICBpZiAoc3RhdGUubGluZXNbc3RhdGUuaW5kZXggKyBpXSAhPT0gJyAnICsgY2hhbmdlQ29udGVudCkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHN0YXRlLmluZGV4ICs9IGRlbHRhO1xuICByZXR1cm4gdHJ1ZTtcbn1cblxuZnVuY3Rpb24gY2FsY09sZE5ld0xpbmVDb3VudChsaW5lcykge1xuICBsZXQgb2xkTGluZXMgPSAwO1xuICBsZXQgbmV3TGluZXMgPSAwO1xuXG4gIGxpbmVzLmZvckVhY2goZnVuY3Rpb24obGluZSkge1xuICAgIGlmICh0eXBlb2YgbGluZSAhPT0gJ3N0cmluZycpIHtcbiAgICAgIGxldCBteUNvdW50ID0gY2FsY09sZE5ld0xpbmVDb3VudChsaW5lLm1pbmUpO1xuICAgICAgbGV0IHRoZWlyQ291bnQgPSBjYWxjT2xkTmV3TGluZUNvdW50KGxpbmUudGhlaXJzKTtcblxuICAgICAgaWYgKG9sZExpbmVzICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgaWYgKG15Q291bnQub2xkTGluZXMgPT09IHRoZWlyQ291bnQub2xkTGluZXMpIHtcbiAgICAgICAgICBvbGRMaW5lcyArPSBteUNvdW50Lm9sZExpbmVzO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIG9sZExpbmVzID0gdW5kZWZpbmVkO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIGlmIChuZXdMaW5lcyAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIGlmIChteUNvdW50Lm5ld0xpbmVzID09PSB0aGVpckNvdW50Lm5ld0xpbmVzKSB7XG4gICAgICAgICAgbmV3TGluZXMgKz0gbXlDb3VudC5uZXdMaW5lcztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBuZXdMaW5lcyA9IHVuZGVmaW5lZDtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH0gZWxzZSB7XG4gICAgICBpZiAobmV3TGluZXMgIT09IHVuZGVmaW5lZCAmJiAobGluZVswXSA9PT0gJysnIHx8IGxpbmVbMF0gPT09ICcgJykpIHtcbiAgICAgICAgbmV3TGluZXMrKztcbiAgICAgIH1cbiAgICAgIGlmIChvbGRMaW5lcyAhPT0gdW5kZWZpbmVkICYmIChsaW5lWzBdID09PSAnLScgfHwgbGluZVswXSA9PT0gJyAnKSkge1xuICAgICAgICBvbGRMaW5lcysrO1xuICAgICAgfVxuICAgIH1cbiAgfSk7XG5cbiAgcmV0dXJuIHtvbGRMaW5lcywgbmV3TGluZXN9O1xufVxuIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUFBLE9BQUEsR0FBQUMsT0FBQTtBQUFBO0FBQUE7QUFDQTtBQUFBO0FBQUFDLE1BQUEsR0FBQUQsT0FBQTtBQUFBO0FBQUE7QUFFQTtBQUFBO0FBQUFFLE1BQUEsR0FBQUYsT0FBQTtBQUFBO0FBQUE7QUFBMEQsbUNBQUFHLG1CQUFBQyxHQUFBLFdBQUFDLGtCQUFBLENBQUFELEdBQUEsS0FBQUUsZ0JBQUEsQ0FBQUYsR0FBQSxLQUFBRywyQkFBQSxDQUFBSCxHQUFBLEtBQUFJLGtCQUFBO0FBQUEsU0FBQUEsbUJBQUEsY0FBQUMsU0FBQTtBQUFBLFNBQUFGLDRCQUFBRyxDQUFBLEVBQUFDLE1BQUEsU0FBQUQsQ0FBQSxxQkFBQUEsQ0FBQSxzQkFBQUUsaUJBQUEsQ0FBQUYsQ0FBQSxFQUFBQyxNQUFBLE9BQUFFLENBQUEsR0FBQUMsTUFBQSxDQUFBQyxTQUFBLENBQUFDLFFBQUEsQ0FBQUMsSUFBQSxDQUFBUCxDQUFBLEVBQUFRLEtBQUEsYUFBQUwsQ0FBQSxpQkFBQUgsQ0FBQSxDQUFBUyxXQUFBLEVBQUFOLENBQUEsR0FBQUgsQ0FBQSxDQUFBUyxXQUFBLENBQUFDLElBQUEsTUFBQVAsQ0FBQSxjQUFBQSxDQUFBLG1CQUFBUSxLQUFBLENBQUFDLElBQUEsQ0FBQVosQ0FBQSxPQUFBRyxDQUFBLCtEQUFBVSxJQUFBLENBQUFWLENBQUEsVUFBQUQsaUJBQUEsQ0FBQUYsQ0FBQSxFQUFBQyxNQUFBO0FBQUEsU0FBQUwsaUJBQUFrQixJQUFBLGVBQUFDLE1BQUEsb0JBQUFELElBQUEsQ0FBQUMsTUFBQSxDQUFBQyxRQUFBLGFBQUFGLElBQUEsK0JBQUFILEtBQUEsQ0FBQUMsSUFBQSxDQUFBRSxJQUFBO0FBQUEsU0FBQW5CLG1CQUFBRCxHQUFBLFFBQUFpQixLQUFBLENBQUFNLE9BQUEsQ0FBQXZCLEdBQUEsVUFBQVEsaUJBQUEsQ0FBQVIsR0FBQTtBQUFBLFNBQUFRLGtCQUFBUixHQUFBLEVBQUF3QixHQUFBLFFBQUFBLEdBQUEsWUFBQUEsR0FBQSxHQUFBeEIsR0FBQSxDQUFBeUIsTUFBQSxFQUFBRCxHQUFBLEdBQUF4QixHQUFBLENBQUF5QixNQUFBLFdBQUFDLENBQUEsTUFBQUMsSUFBQSxPQUFBVixLQUFBLENBQUFPLEdBQUEsR0FBQUUsQ0FBQSxHQUFBRixHQUFBLEVBQUFFLENBQUEsSUFBQUMsSUFBQSxDQUFBRCxDQUFBLElBQUExQixHQUFBLENBQUEwQixDQUFBLFVBQUFDLElBQUE7QUFBQTtBQUVuRCxTQUFTQyxhQUFhQSxDQUFDQyxJQUFJLEVBQUU7RUFDbEM7SUFBQTtJQUFBQyxvQkFBQTtJQUFBO0lBQTZCQyxtQkFBbUIsQ0FBQ0YsSUFBSSxDQUFDRyxLQUFLLENBQUM7SUFBQTtJQUFBO0lBQXJEQyxRQUFRLEdBQUFILG9CQUFBLENBQVJHLFFBQVE7SUFBQTtJQUFBO0lBQUVDLFFBQVEsR0FBQUosb0JBQUEsQ0FBUkksUUFBUTtFQUV6QixJQUFJRCxRQUFRLEtBQUtFLFNBQVMsRUFBRTtJQUMxQk4sSUFBSSxDQUFDSSxRQUFRLEdBQUdBLFFBQVE7RUFDMUIsQ0FBQyxNQUFNO0lBQ0wsT0FBT0osSUFBSSxDQUFDSSxRQUFRO0VBQ3RCO0VBRUEsSUFBSUMsUUFBUSxLQUFLQyxTQUFTLEVBQUU7SUFDMUJOLElBQUksQ0FBQ0ssUUFBUSxHQUFHQSxRQUFRO0VBQzFCLENBQUMsTUFBTTtJQUNMLE9BQU9MLElBQUksQ0FBQ0ssUUFBUTtFQUN0QjtBQUNGO0FBRU8sU0FBU0UsS0FBS0EsQ0FBQ0MsSUFBSSxFQUFFQyxNQUFNLEVBQUVDLElBQUksRUFBRTtFQUN4Q0YsSUFBSSxHQUFHRyxTQUFTLENBQUNILElBQUksRUFBRUUsSUFBSSxDQUFDO0VBQzVCRCxNQUFNLEdBQUdFLFNBQVMsQ0FBQ0YsTUFBTSxFQUFFQyxJQUFJLENBQUM7RUFFaEMsSUFBSUUsR0FBRyxHQUFHLENBQUMsQ0FBQzs7RUFFWjtFQUNBO0VBQ0E7RUFDQSxJQUFJSixJQUFJLENBQUNLLEtBQUssSUFBSUosTUFBTSxDQUFDSSxLQUFLLEVBQUU7SUFDOUJELEdBQUcsQ0FBQ0MsS0FBSyxHQUFHTCxJQUFJLENBQUNLLEtBQUssSUFBSUosTUFBTSxDQUFDSSxLQUFLO0VBQ3hDO0VBRUEsSUFBSUwsSUFBSSxDQUFDTSxXQUFXLElBQUlMLE1BQU0sQ0FBQ0ssV0FBVyxFQUFFO0lBQzFDLElBQUksQ0FBQ0MsZUFBZSxDQUFDUCxJQUFJLENBQUMsRUFBRTtNQUMxQjtNQUNBSSxHQUFHLENBQUNJLFdBQVcsR0FBR1AsTUFBTSxDQUFDTyxXQUFXLElBQUlSLElBQUksQ0FBQ1EsV0FBVztNQUN4REosR0FBRyxDQUFDRSxXQUFXLEdBQUdMLE1BQU0sQ0FBQ0ssV0FBVyxJQUFJTixJQUFJLENBQUNNLFdBQVc7TUFDeERGLEdBQUcsQ0FBQ0ssU0FBUyxHQUFHUixNQUFNLENBQUNRLFNBQVMsSUFBSVQsSUFBSSxDQUFDUyxTQUFTO01BQ2xETCxHQUFHLENBQUNNLFNBQVMsR0FBR1QsTUFBTSxDQUFDUyxTQUFTLElBQUlWLElBQUksQ0FBQ1UsU0FBUztJQUNwRCxDQUFDLE1BQU0sSUFBSSxDQUFDSCxlQUFlLENBQUNOLE1BQU0sQ0FBQyxFQUFFO01BQ25DO01BQ0FHLEdBQUcsQ0FBQ0ksV0FBVyxHQUFHUixJQUFJLENBQUNRLFdBQVc7TUFDbENKLEdBQUcsQ0FBQ0UsV0FBVyxHQUFHTixJQUFJLENBQUNNLFdBQVc7TUFDbENGLEdBQUcsQ0FBQ0ssU0FBUyxHQUFHVCxJQUFJLENBQUNTLFNBQVM7TUFDOUJMLEdBQUcsQ0FBQ00sU0FBUyxHQUFHVixJQUFJLENBQUNVLFNBQVM7SUFDaEMsQ0FBQyxNQUFNO01BQ0w7TUFDQU4sR0FBRyxDQUFDSSxXQUFXLEdBQUdHLFdBQVcsQ0FBQ1AsR0FBRyxFQUFFSixJQUFJLENBQUNRLFdBQVcsRUFBRVAsTUFBTSxDQUFDTyxXQUFXLENBQUM7TUFDeEVKLEdBQUcsQ0FBQ0UsV0FBVyxHQUFHSyxXQUFXLENBQUNQLEdBQUcsRUFBRUosSUFBSSxDQUFDTSxXQUFXLEVBQUVMLE1BQU0sQ0FBQ0ssV0FBVyxDQUFDO01BQ3hFRixHQUFHLENBQUNLLFNBQVMsR0FBR0UsV0FBVyxDQUFDUCxHQUFHLEVBQUVKLElBQUksQ0FBQ1MsU0FBUyxFQUFFUixNQUFNLENBQUNRLFNBQVMsQ0FBQztNQUNsRUwsR0FBRyxDQUFDTSxTQUFTLEdBQUdDLFdBQVcsQ0FBQ1AsR0FBRyxFQUFFSixJQUFJLENBQUNVLFNBQVMsRUFBRVQsTUFBTSxDQUFDUyxTQUFTLENBQUM7SUFDcEU7RUFDRjtFQUVBTixHQUFHLENBQUNRLEtBQUssR0FBRyxFQUFFO0VBRWQsSUFBSUMsU0FBUyxHQUFHLENBQUM7SUFDYkMsV0FBVyxHQUFHLENBQUM7SUFDZkMsVUFBVSxHQUFHLENBQUM7SUFDZEMsWUFBWSxHQUFHLENBQUM7RUFFcEIsT0FBT0gsU0FBUyxHQUFHYixJQUFJLENBQUNZLEtBQUssQ0FBQ3hCLE1BQU0sSUFBSTBCLFdBQVcsR0FBR2IsTUFBTSxDQUFDVyxLQUFLLENBQUN4QixNQUFNLEVBQUU7SUFDekUsSUFBSTZCLFdBQVcsR0FBR2pCLElBQUksQ0FBQ1ksS0FBSyxDQUFDQyxTQUFTLENBQUMsSUFBSTtRQUFDSyxRQUFRLEVBQUVDO01BQVEsQ0FBQztNQUMzREMsYUFBYSxHQUFHbkIsTUFBTSxDQUFDVyxLQUFLLENBQUNFLFdBQVcsQ0FBQyxJQUFJO1FBQUNJLFFBQVEsRUFBRUM7TUFBUSxDQUFDO0lBRXJFLElBQUlFLFVBQVUsQ0FBQ0osV0FBVyxFQUFFRyxhQUFhLENBQUMsRUFBRTtNQUMxQztNQUNBaEIsR0FBRyxDQUFDUSxLQUFLLENBQUNVLElBQUksQ0FBQ0MsU0FBUyxDQUFDTixXQUFXLEVBQUVGLFVBQVUsQ0FBQyxDQUFDO01BQ2xERixTQUFTLEVBQUU7TUFDWEcsWUFBWSxJQUFJQyxXQUFXLENBQUNwQixRQUFRLEdBQUdvQixXQUFXLENBQUNyQixRQUFRO0lBQzdELENBQUMsTUFBTSxJQUFJeUIsVUFBVSxDQUFDRCxhQUFhLEVBQUVILFdBQVcsQ0FBQyxFQUFFO01BQ2pEO01BQ0FiLEdBQUcsQ0FBQ1EsS0FBSyxDQUFDVSxJQUFJLENBQUNDLFNBQVMsQ0FBQ0gsYUFBYSxFQUFFSixZQUFZLENBQUMsQ0FBQztNQUN0REYsV0FBVyxFQUFFO01BQ2JDLFVBQVUsSUFBSUssYUFBYSxDQUFDdkIsUUFBUSxHQUFHdUIsYUFBYSxDQUFDeEIsUUFBUTtJQUMvRCxDQUFDLE1BQU07TUFDTDtNQUNBLElBQUk0QixVQUFVLEdBQUc7UUFDZk4sUUFBUSxFQUFFTyxJQUFJLENBQUNDLEdBQUcsQ0FBQ1QsV0FBVyxDQUFDQyxRQUFRLEVBQUVFLGFBQWEsQ0FBQ0YsUUFBUSxDQUFDO1FBQ2hFdEIsUUFBUSxFQUFFLENBQUM7UUFDWCtCLFFBQVEsRUFBRUYsSUFBSSxDQUFDQyxHQUFHLENBQUNULFdBQVcsQ0FBQ1UsUUFBUSxHQUFHWixVQUFVLEVBQUVLLGFBQWEsQ0FBQ0YsUUFBUSxHQUFHRixZQUFZLENBQUM7UUFDNUZuQixRQUFRLEVBQUUsQ0FBQztRQUNYRixLQUFLLEVBQUU7TUFDVCxDQUFDO01BQ0RpQyxVQUFVLENBQUNKLFVBQVUsRUFBRVAsV0FBVyxDQUFDQyxRQUFRLEVBQUVELFdBQVcsQ0FBQ3RCLEtBQUssRUFBRXlCLGFBQWEsQ0FBQ0YsUUFBUSxFQUFFRSxhQUFhLENBQUN6QixLQUFLLENBQUM7TUFDNUdtQixXQUFXLEVBQUU7TUFDYkQsU0FBUyxFQUFFO01BRVhULEdBQUcsQ0FBQ1EsS0FBSyxDQUFDVSxJQUFJLENBQUNFLFVBQVUsQ0FBQztJQUM1QjtFQUNGO0VBRUEsT0FBT3BCLEdBQUc7QUFDWjtBQUVBLFNBQVNELFNBQVNBLENBQUMwQixLQUFLLEVBQUUzQixJQUFJLEVBQUU7RUFDOUIsSUFBSSxPQUFPMkIsS0FBSyxLQUFLLFFBQVEsRUFBRTtJQUM3QixJQUFLLE1BQU0sQ0FBRS9DLElBQUksQ0FBQytDLEtBQUssQ0FBQyxJQUFNLFVBQVUsQ0FBRS9DLElBQUksQ0FBQytDLEtBQUssQ0FBRSxFQUFFO01BQ3RELE9BQU87UUFBQTtRQUFBO1FBQUE7UUFBQUM7UUFBQUE7UUFBQUE7UUFBQUE7UUFBQUE7UUFBQUEsVUFBVTtRQUFBO1FBQUEsQ0FBQ0QsS0FBSyxDQUFDLENBQUMsQ0FBQztNQUFDO0lBQzdCO0lBRUEsSUFBSSxDQUFDM0IsSUFBSSxFQUFFO01BQ1QsTUFBTSxJQUFJNkIsS0FBSyxDQUFDLGtEQUFrRCxDQUFDO0lBQ3JFO0lBQ0EsT0FBTztNQUFBO01BQUE7TUFBQTtNQUFBQztNQUFBQTtNQUFBQTtNQUFBQTtNQUFBQTtNQUFBQSxlQUFlO01BQUE7TUFBQSxDQUFDbEMsU0FBUyxFQUFFQSxTQUFTLEVBQUVJLElBQUksRUFBRTJCLEtBQUs7SUFBQztFQUMzRDtFQUVBLE9BQU9BLEtBQUs7QUFDZDtBQUVBLFNBQVN0QixlQUFlQSxDQUFDMEIsS0FBSyxFQUFFO0VBQzlCLE9BQU9BLEtBQUssQ0FBQzNCLFdBQVcsSUFBSTJCLEtBQUssQ0FBQzNCLFdBQVcsS0FBSzJCLEtBQUssQ0FBQ3pCLFdBQVc7QUFDckU7QUFFQSxTQUFTRyxXQUFXQSxDQUFDTixLQUFLLEVBQUVMLElBQUksRUFBRUMsTUFBTSxFQUFFO0VBQ3hDLElBQUlELElBQUksS0FBS0MsTUFBTSxFQUFFO0lBQ25CLE9BQU9ELElBQUk7RUFDYixDQUFDLE1BQU07SUFDTEssS0FBSyxDQUFDNkIsUUFBUSxHQUFHLElBQUk7SUFDckIsT0FBTztNQUFDbEMsSUFBSSxFQUFKQSxJQUFJO01BQUVDLE1BQU0sRUFBTkE7SUFBTSxDQUFDO0VBQ3ZCO0FBQ0Y7QUFFQSxTQUFTb0IsVUFBVUEsQ0FBQ3ZDLElBQUksRUFBRXFELEtBQUssRUFBRTtFQUMvQixPQUFPckQsSUFBSSxDQUFDb0MsUUFBUSxHQUFHaUIsS0FBSyxDQUFDakIsUUFBUSxJQUMvQnBDLElBQUksQ0FBQ29DLFFBQVEsR0FBR3BDLElBQUksQ0FBQ2MsUUFBUSxHQUFJdUMsS0FBSyxDQUFDakIsUUFBUTtBQUN2RDtBQUVBLFNBQVNLLFNBQVNBLENBQUMvQixJQUFJLEVBQUU0QyxNQUFNLEVBQUU7RUFDL0IsT0FBTztJQUNMbEIsUUFBUSxFQUFFMUIsSUFBSSxDQUFDMEIsUUFBUTtJQUFFdEIsUUFBUSxFQUFFSixJQUFJLENBQUNJLFFBQVE7SUFDaEQrQixRQUFRLEVBQUVuQyxJQUFJLENBQUNtQyxRQUFRLEdBQUdTLE1BQU07SUFBRXZDLFFBQVEsRUFBRUwsSUFBSSxDQUFDSyxRQUFRO0lBQ3pERixLQUFLLEVBQUVILElBQUksQ0FBQ0c7RUFDZCxDQUFDO0FBQ0g7QUFFQSxTQUFTaUMsVUFBVUEsQ0FBQ3BDLElBQUksRUFBRXVCLFVBQVUsRUFBRXNCLFNBQVMsRUFBRUMsV0FBVyxFQUFFQyxVQUFVLEVBQUU7RUFDeEU7RUFDQTtFQUNBLElBQUl2QyxJQUFJLEdBQUc7TUFBQ29DLE1BQU0sRUFBRXJCLFVBQVU7TUFBRXBCLEtBQUssRUFBRTBDLFNBQVM7TUFBRWhDLEtBQUssRUFBRTtJQUFDLENBQUM7SUFDdkRtQyxLQUFLLEdBQUc7TUFBQ0osTUFBTSxFQUFFRSxXQUFXO01BQUUzQyxLQUFLLEVBQUU0QyxVQUFVO01BQUVsQyxLQUFLLEVBQUU7SUFBQyxDQUFDOztFQUU5RDtFQUNBb0MsYUFBYSxDQUFDakQsSUFBSSxFQUFFUSxJQUFJLEVBQUV3QyxLQUFLLENBQUM7RUFDaENDLGFBQWEsQ0FBQ2pELElBQUksRUFBRWdELEtBQUssRUFBRXhDLElBQUksQ0FBQzs7RUFFaEM7RUFDQSxPQUFPQSxJQUFJLENBQUNLLEtBQUssR0FBR0wsSUFBSSxDQUFDTCxLQUFLLENBQUNQLE1BQU0sSUFBSW9ELEtBQUssQ0FBQ25DLEtBQUssR0FBR21DLEtBQUssQ0FBQzdDLEtBQUssQ0FBQ1AsTUFBTSxFQUFFO0lBQ3pFLElBQUk2QixXQUFXLEdBQUdqQixJQUFJLENBQUNMLEtBQUssQ0FBQ0ssSUFBSSxDQUFDSyxLQUFLLENBQUM7TUFDcENxQyxZQUFZLEdBQUdGLEtBQUssQ0FBQzdDLEtBQUssQ0FBQzZDLEtBQUssQ0FBQ25DLEtBQUssQ0FBQztJQUUzQyxJQUFJLENBQUNZLFdBQVcsQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLElBQUlBLFdBQVcsQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLE1BQzdDeUIsWUFBWSxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsSUFBSUEsWUFBWSxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsQ0FBQyxFQUFFO01BQzNEO01BQ0FDLFlBQVksQ0FBQ25ELElBQUksRUFBRVEsSUFBSSxFQUFFd0MsS0FBSyxDQUFDO0lBQ2pDLENBQUMsTUFBTSxJQUFJdkIsV0FBVyxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsSUFBSXlCLFlBQVksQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLEVBQUU7TUFBQTtNQUFBLElBQUFFLFdBQUE7TUFBQTtNQUM1RDtNQUNBO01BQUE7TUFBQTtNQUFBLENBQUFBLFdBQUE7TUFBQTtNQUFBcEQsSUFBSSxDQUFDRyxLQUFLLEVBQUMyQixJQUFJLENBQUF1QixLQUFBO01BQUE7TUFBQUQ7TUFBQTtNQUFBO01BQUE7TUFBQWxGLGtCQUFBO01BQUE7TUFBS29GLGFBQWEsQ0FBQzlDLElBQUksQ0FBQyxFQUFDO0lBQzFDLENBQUMsTUFBTSxJQUFJMEMsWUFBWSxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsSUFBSXpCLFdBQVcsQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLEVBQUU7TUFBQTtNQUFBLElBQUE4QixZQUFBO01BQUE7TUFDNUQ7TUFDQTtNQUFBO01BQUE7TUFBQSxDQUFBQSxZQUFBO01BQUE7TUFBQXZELElBQUksQ0FBQ0csS0FBSyxFQUFDMkIsSUFBSSxDQUFBdUIsS0FBQTtNQUFBO01BQUFFO01BQUE7TUFBQTtNQUFBO01BQUFyRixrQkFBQTtNQUFBO01BQUtvRixhQUFhLENBQUNOLEtBQUssQ0FBQyxFQUFDO0lBQzNDLENBQUMsTUFBTSxJQUFJdkIsV0FBVyxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsSUFBSXlCLFlBQVksQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLEVBQUU7TUFDNUQ7TUFDQU0sT0FBTyxDQUFDeEQsSUFBSSxFQUFFUSxJQUFJLEVBQUV3QyxLQUFLLENBQUM7SUFDNUIsQ0FBQyxNQUFNLElBQUlFLFlBQVksQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLElBQUl6QixXQUFXLENBQUMsQ0FBQyxDQUFDLEtBQUssR0FBRyxFQUFFO01BQzVEO01BQ0ErQixPQUFPLENBQUN4RCxJQUFJLEVBQUVnRCxLQUFLLEVBQUV4QyxJQUFJLEVBQUUsSUFBSSxDQUFDO0lBQ2xDLENBQUMsTUFBTSxJQUFJaUIsV0FBVyxLQUFLeUIsWUFBWSxFQUFFO01BQ3ZDO01BQ0FsRCxJQUFJLENBQUNHLEtBQUssQ0FBQzJCLElBQUksQ0FBQ0wsV0FBVyxDQUFDO01BQzVCakIsSUFBSSxDQUFDSyxLQUFLLEVBQUU7TUFDWm1DLEtBQUssQ0FBQ25DLEtBQUssRUFBRTtJQUNmLENBQUMsTUFBTTtNQUNMO01BQ0E2QixRQUFRLENBQUMxQyxJQUFJLEVBQUVzRCxhQUFhLENBQUM5QyxJQUFJLENBQUMsRUFBRThDLGFBQWEsQ0FBQ04sS0FBSyxDQUFDLENBQUM7SUFDM0Q7RUFDRjs7RUFFQTtFQUNBUyxjQUFjLENBQUN6RCxJQUFJLEVBQUVRLElBQUksQ0FBQztFQUMxQmlELGNBQWMsQ0FBQ3pELElBQUksRUFBRWdELEtBQUssQ0FBQztFQUUzQmpELGFBQWEsQ0FBQ0MsSUFBSSxDQUFDO0FBQ3JCO0FBRUEsU0FBU21ELFlBQVlBLENBQUNuRCxJQUFJLEVBQUVRLElBQUksRUFBRXdDLEtBQUssRUFBRTtFQUN2QyxJQUFJVSxTQUFTLEdBQUdKLGFBQWEsQ0FBQzlDLElBQUksQ0FBQztJQUMvQm1ELFlBQVksR0FBR0wsYUFBYSxDQUFDTixLQUFLLENBQUM7RUFFdkMsSUFBSVksVUFBVSxDQUFDRixTQUFTLENBQUMsSUFBSUUsVUFBVSxDQUFDRCxZQUFZLENBQUMsRUFBRTtJQUNyRDtJQUNBO0lBQUk7SUFBQTtJQUFBO0lBQUFFO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBO0lBQUFBLGVBQWU7SUFBQTtJQUFBLENBQUNILFNBQVMsRUFBRUMsWUFBWSxDQUFDLElBQ3JDRyxrQkFBa0IsQ0FBQ2QsS0FBSyxFQUFFVSxTQUFTLEVBQUVBLFNBQVMsQ0FBQzlELE1BQU0sR0FBRytELFlBQVksQ0FBQy9ELE1BQU0sQ0FBQyxFQUFFO01BQUE7TUFBQSxJQUFBbUUsWUFBQTtNQUFBO01BQ25GO01BQUE7TUFBQTtNQUFBLENBQUFBLFlBQUE7TUFBQTtNQUFBL0QsSUFBSSxDQUFDRyxLQUFLLEVBQUMyQixJQUFJLENBQUF1QixLQUFBO01BQUE7TUFBQVU7TUFBQTtNQUFBO01BQUE7TUFBQTdGLGtCQUFBO01BQUE7TUFBS3dGLFNBQVMsRUFBQztNQUM5QjtJQUNGLENBQUMsTUFBTTtJQUFJO0lBQUE7SUFBQTtJQUFBRztJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQTtJQUFBQSxlQUFlO0lBQUE7SUFBQSxDQUFDRixZQUFZLEVBQUVELFNBQVMsQ0FBQyxJQUM1Q0ksa0JBQWtCLENBQUN0RCxJQUFJLEVBQUVtRCxZQUFZLEVBQUVBLFlBQVksQ0FBQy9ELE1BQU0sR0FBRzhELFNBQVMsQ0FBQzlELE1BQU0sQ0FBQyxFQUFFO01BQUE7TUFBQSxJQUFBb0UsWUFBQTtNQUFBO01BQ3JGO01BQUE7TUFBQTtNQUFBLENBQUFBLFlBQUE7TUFBQTtNQUFBaEUsSUFBSSxDQUFDRyxLQUFLLEVBQUMyQixJQUFJLENBQUF1QixLQUFBO01BQUE7TUFBQVc7TUFBQTtNQUFBO01BQUE7TUFBQTlGLGtCQUFBO01BQUE7TUFBS3lGLFlBQVksRUFBQztNQUNqQztJQUNGO0VBQ0YsQ0FBQyxNQUFNO0VBQUk7RUFBQTtFQUFBO0VBQUFNO0VBQUFBO0VBQUFBO0VBQUFBO0VBQUFBO0VBQUFBLFVBQVU7RUFBQTtFQUFBLENBQUNQLFNBQVMsRUFBRUMsWUFBWSxDQUFDLEVBQUU7SUFBQTtJQUFBLElBQUFPLFlBQUE7SUFBQTtJQUM5QztJQUFBO0lBQUE7SUFBQSxDQUFBQSxZQUFBO0lBQUE7SUFBQWxFLElBQUksQ0FBQ0csS0FBSyxFQUFDMkIsSUFBSSxDQUFBdUIsS0FBQTtJQUFBO0lBQUFhO0lBQUE7SUFBQTtJQUFBO0lBQUFoRyxrQkFBQTtJQUFBO0lBQUt3RixTQUFTLEVBQUM7SUFDOUI7RUFDRjtFQUVBaEIsUUFBUSxDQUFDMUMsSUFBSSxFQUFFMEQsU0FBUyxFQUFFQyxZQUFZLENBQUM7QUFDekM7QUFFQSxTQUFTSCxPQUFPQSxDQUFDeEQsSUFBSSxFQUFFUSxJQUFJLEVBQUV3QyxLQUFLLEVBQUVtQixJQUFJLEVBQUU7RUFDeEMsSUFBSVQsU0FBUyxHQUFHSixhQUFhLENBQUM5QyxJQUFJLENBQUM7SUFDL0JtRCxZQUFZLEdBQUdTLGNBQWMsQ0FBQ3BCLEtBQUssRUFBRVUsU0FBUyxDQUFDO0VBQ25ELElBQUlDLFlBQVksQ0FBQ1UsTUFBTSxFQUFFO0lBQUE7SUFBQSxJQUFBQyxZQUFBO0lBQUE7SUFDdkI7SUFBQTtJQUFBO0lBQUEsQ0FBQUEsWUFBQTtJQUFBO0lBQUF0RSxJQUFJLENBQUNHLEtBQUssRUFBQzJCLElBQUksQ0FBQXVCLEtBQUE7SUFBQTtJQUFBaUI7SUFBQTtJQUFBO0lBQUE7SUFBQXBHLGtCQUFBO0lBQUE7SUFBS3lGLFlBQVksQ0FBQ1UsTUFBTSxFQUFDO0VBQzFDLENBQUMsTUFBTTtJQUNMM0IsUUFBUSxDQUFDMUMsSUFBSSxFQUFFbUUsSUFBSSxHQUFHUixZQUFZLEdBQUdELFNBQVMsRUFBRVMsSUFBSSxHQUFHVCxTQUFTLEdBQUdDLFlBQVksQ0FBQztFQUNsRjtBQUNGO0FBRUEsU0FBU2pCLFFBQVFBLENBQUMxQyxJQUFJLEVBQUVRLElBQUksRUFBRXdDLEtBQUssRUFBRTtFQUNuQ2hELElBQUksQ0FBQzBDLFFBQVEsR0FBRyxJQUFJO0VBQ3BCMUMsSUFBSSxDQUFDRyxLQUFLLENBQUMyQixJQUFJLENBQUM7SUFDZFksUUFBUSxFQUFFLElBQUk7SUFDZGxDLElBQUksRUFBRUEsSUFBSTtJQUNWQyxNQUFNLEVBQUV1QztFQUNWLENBQUMsQ0FBQztBQUNKO0FBRUEsU0FBU0MsYUFBYUEsQ0FBQ2pELElBQUksRUFBRXVFLE1BQU0sRUFBRXZCLEtBQUssRUFBRTtFQUMxQyxPQUFPdUIsTUFBTSxDQUFDM0IsTUFBTSxHQUFHSSxLQUFLLENBQUNKLE1BQU0sSUFBSTJCLE1BQU0sQ0FBQzFELEtBQUssR0FBRzBELE1BQU0sQ0FBQ3BFLEtBQUssQ0FBQ1AsTUFBTSxFQUFFO0lBQ3pFLElBQUk0RSxJQUFJLEdBQUdELE1BQU0sQ0FBQ3BFLEtBQUssQ0FBQ29FLE1BQU0sQ0FBQzFELEtBQUssRUFBRSxDQUFDO0lBQ3ZDYixJQUFJLENBQUNHLEtBQUssQ0FBQzJCLElBQUksQ0FBQzBDLElBQUksQ0FBQztJQUNyQkQsTUFBTSxDQUFDM0IsTUFBTSxFQUFFO0VBQ2pCO0FBQ0Y7QUFDQSxTQUFTYSxjQUFjQSxDQUFDekQsSUFBSSxFQUFFdUUsTUFBTSxFQUFFO0VBQ3BDLE9BQU9BLE1BQU0sQ0FBQzFELEtBQUssR0FBRzBELE1BQU0sQ0FBQ3BFLEtBQUssQ0FBQ1AsTUFBTSxFQUFFO0lBQ3pDLElBQUk0RSxJQUFJLEdBQUdELE1BQU0sQ0FBQ3BFLEtBQUssQ0FBQ29FLE1BQU0sQ0FBQzFELEtBQUssRUFBRSxDQUFDO0lBQ3ZDYixJQUFJLENBQUNHLEtBQUssQ0FBQzJCLElBQUksQ0FBQzBDLElBQUksQ0FBQztFQUN2QjtBQUNGO0FBRUEsU0FBU2xCLGFBQWFBLENBQUNtQixLQUFLLEVBQUU7RUFDNUIsSUFBSTdELEdBQUcsR0FBRyxFQUFFO0lBQ1I4RCxTQUFTLEdBQUdELEtBQUssQ0FBQ3RFLEtBQUssQ0FBQ3NFLEtBQUssQ0FBQzVELEtBQUssQ0FBQyxDQUFDLENBQUMsQ0FBQztFQUMzQyxPQUFPNEQsS0FBSyxDQUFDNUQsS0FBSyxHQUFHNEQsS0FBSyxDQUFDdEUsS0FBSyxDQUFDUCxNQUFNLEVBQUU7SUFDdkMsSUFBSTRFLElBQUksR0FBR0MsS0FBSyxDQUFDdEUsS0FBSyxDQUFDc0UsS0FBSyxDQUFDNUQsS0FBSyxDQUFDOztJQUVuQztJQUNBLElBQUk2RCxTQUFTLEtBQUssR0FBRyxJQUFJRixJQUFJLENBQUMsQ0FBQyxDQUFDLEtBQUssR0FBRyxFQUFFO01BQ3hDRSxTQUFTLEdBQUcsR0FBRztJQUNqQjtJQUVBLElBQUlBLFNBQVMsS0FBS0YsSUFBSSxDQUFDLENBQUMsQ0FBQyxFQUFFO01BQ3pCNUQsR0FBRyxDQUFDa0IsSUFBSSxDQUFDMEMsSUFBSSxDQUFDO01BQ2RDLEtBQUssQ0FBQzVELEtBQUssRUFBRTtJQUNmLENBQUMsTUFBTTtNQUNMO0lBQ0Y7RUFDRjtFQUVBLE9BQU9ELEdBQUc7QUFDWjtBQUNBLFNBQVN3RCxjQUFjQSxDQUFDSyxLQUFLLEVBQUVFLFlBQVksRUFBRTtFQUMzQyxJQUFJQyxPQUFPLEdBQUcsRUFBRTtJQUNaUCxNQUFNLEdBQUcsRUFBRTtJQUNYUSxVQUFVLEdBQUcsQ0FBQztJQUNkQyxjQUFjLEdBQUcsS0FBSztJQUN0QkMsVUFBVSxHQUFHLEtBQUs7RUFDdEIsT0FBT0YsVUFBVSxHQUFHRixZQUFZLENBQUMvRSxNQUFNLElBQzlCNkUsS0FBSyxDQUFDNUQsS0FBSyxHQUFHNEQsS0FBSyxDQUFDdEUsS0FBSyxDQUFDUCxNQUFNLEVBQUU7SUFDekMsSUFBSW9GLE1BQU0sR0FBR1AsS0FBSyxDQUFDdEUsS0FBSyxDQUFDc0UsS0FBSyxDQUFDNUQsS0FBSyxDQUFDO01BQ2pDb0UsS0FBSyxHQUFHTixZQUFZLENBQUNFLFVBQVUsQ0FBQzs7SUFFcEM7SUFDQSxJQUFJSSxLQUFLLENBQUMsQ0FBQyxDQUFDLEtBQUssR0FBRyxFQUFFO01BQ3BCO0lBQ0Y7SUFFQUgsY0FBYyxHQUFHQSxjQUFjLElBQUlFLE1BQU0sQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHO0lBRXBEWCxNQUFNLENBQUN2QyxJQUFJLENBQUNtRCxLQUFLLENBQUM7SUFDbEJKLFVBQVUsRUFBRTs7SUFFWjtJQUNBO0lBQ0EsSUFBSUcsTUFBTSxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsRUFBRTtNQUNyQkQsVUFBVSxHQUFHLElBQUk7TUFFakIsT0FBT0MsTUFBTSxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsRUFBRTtRQUN4QkosT0FBTyxDQUFDOUMsSUFBSSxDQUFDa0QsTUFBTSxDQUFDO1FBQ3BCQSxNQUFNLEdBQUdQLEtBQUssQ0FBQ3RFLEtBQUssQ0FBQyxFQUFFc0UsS0FBSyxDQUFDNUQsS0FBSyxDQUFDO01BQ3JDO0lBQ0Y7SUFFQSxJQUFJb0UsS0FBSyxDQUFDQyxNQUFNLENBQUMsQ0FBQyxDQUFDLEtBQUtGLE1BQU0sQ0FBQ0UsTUFBTSxDQUFDLENBQUMsQ0FBQyxFQUFFO01BQ3hDTixPQUFPLENBQUM5QyxJQUFJLENBQUNrRCxNQUFNLENBQUM7TUFDcEJQLEtBQUssQ0FBQzVELEtBQUssRUFBRTtJQUNmLENBQUMsTUFBTTtNQUNMa0UsVUFBVSxHQUFHLElBQUk7SUFDbkI7RUFDRjtFQUVBLElBQUksQ0FBQ0osWUFBWSxDQUFDRSxVQUFVLENBQUMsSUFBSSxFQUFFLEVBQUUsQ0FBQyxDQUFDLEtBQUssR0FBRyxJQUN4Q0MsY0FBYyxFQUFFO0lBQ3JCQyxVQUFVLEdBQUcsSUFBSTtFQUNuQjtFQUVBLElBQUlBLFVBQVUsRUFBRTtJQUNkLE9BQU9ILE9BQU87RUFDaEI7RUFFQSxPQUFPQyxVQUFVLEdBQUdGLFlBQVksQ0FBQy9FLE1BQU0sRUFBRTtJQUN2Q3lFLE1BQU0sQ0FBQ3ZDLElBQUksQ0FBQzZDLFlBQVksQ0FBQ0UsVUFBVSxFQUFFLENBQUMsQ0FBQztFQUN6QztFQUVBLE9BQU87SUFDTFIsTUFBTSxFQUFOQSxNQUFNO0lBQ05PLE9BQU8sRUFBUEE7RUFDRixDQUFDO0FBQ0g7QUFFQSxTQUFTaEIsVUFBVUEsQ0FBQ2dCLE9BQU8sRUFBRTtFQUMzQixPQUFPQSxPQUFPLENBQUNPLE1BQU0sQ0FBQyxVQUFTQyxJQUFJLEVBQUVKLE1BQU0sRUFBRTtJQUMzQyxPQUFPSSxJQUFJLElBQUlKLE1BQU0sQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHO0VBQ2xDLENBQUMsRUFBRSxJQUFJLENBQUM7QUFDVjtBQUNBLFNBQVNsQixrQkFBa0JBLENBQUNXLEtBQUssRUFBRVksYUFBYSxFQUFFQyxLQUFLLEVBQUU7RUFDdkQsS0FBSyxJQUFJekYsQ0FBQyxHQUFHLENBQUMsRUFBRUEsQ0FBQyxHQUFHeUYsS0FBSyxFQUFFekYsQ0FBQyxFQUFFLEVBQUU7SUFDOUIsSUFBSTBGLGFBQWEsR0FBR0YsYUFBYSxDQUFDQSxhQUFhLENBQUN6RixNQUFNLEdBQUcwRixLQUFLLEdBQUd6RixDQUFDLENBQUMsQ0FBQ3FGLE1BQU0sQ0FBQyxDQUFDLENBQUM7SUFDN0UsSUFBSVQsS0FBSyxDQUFDdEUsS0FBSyxDQUFDc0UsS0FBSyxDQUFDNUQsS0FBSyxHQUFHaEIsQ0FBQyxDQUFDLEtBQUssR0FBRyxHQUFHMEYsYUFBYSxFQUFFO01BQ3hELE9BQU8sS0FBSztJQUNkO0VBQ0Y7RUFFQWQsS0FBSyxDQUFDNUQsS0FBSyxJQUFJeUUsS0FBSztFQUNwQixPQUFPLElBQUk7QUFDYjtBQUVBLFNBQVNwRixtQkFBbUJBLENBQUNDLEtBQUssRUFBRTtFQUNsQyxJQUFJQyxRQUFRLEdBQUcsQ0FBQztFQUNoQixJQUFJQyxRQUFRLEdBQUcsQ0FBQztFQUVoQkYsS0FBSyxDQUFDcUYsT0FBTyxDQUFDLFVBQVNoQixJQUFJLEVBQUU7SUFDM0IsSUFBSSxPQUFPQSxJQUFJLEtBQUssUUFBUSxFQUFFO01BQzVCLElBQUlpQixPQUFPLEdBQUd2RixtQkFBbUIsQ0FBQ3NFLElBQUksQ0FBQ2hFLElBQUksQ0FBQztNQUM1QyxJQUFJa0YsVUFBVSxHQUFHeEYsbUJBQW1CLENBQUNzRSxJQUFJLENBQUMvRCxNQUFNLENBQUM7TUFFakQsSUFBSUwsUUFBUSxLQUFLRSxTQUFTLEVBQUU7UUFDMUIsSUFBSW1GLE9BQU8sQ0FBQ3JGLFFBQVEsS0FBS3NGLFVBQVUsQ0FBQ3RGLFFBQVEsRUFBRTtVQUM1Q0EsUUFBUSxJQUFJcUYsT0FBTyxDQUFDckYsUUFBUTtRQUM5QixDQUFDLE1BQU07VUFDTEEsUUFBUSxHQUFHRSxTQUFTO1FBQ3RCO01BQ0Y7TUFFQSxJQUFJRCxRQUFRLEtBQUtDLFNBQVMsRUFBRTtRQUMxQixJQUFJbUYsT0FBTyxDQUFDcEYsUUFBUSxLQUFLcUYsVUFBVSxDQUFDckYsUUFBUSxFQUFFO1VBQzVDQSxRQUFRLElBQUlvRixPQUFPLENBQUNwRixRQUFRO1FBQzlCLENBQUMsTUFBTTtVQUNMQSxRQUFRLEdBQUdDLFNBQVM7UUFDdEI7TUFDRjtJQUNGLENBQUMsTUFBTTtNQUNMLElBQUlELFFBQVEsS0FBS0MsU0FBUyxLQUFLa0UsSUFBSSxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsSUFBSUEsSUFBSSxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsQ0FBQyxFQUFFO1FBQ2xFbkUsUUFBUSxFQUFFO01BQ1o7TUFDQSxJQUFJRCxRQUFRLEtBQUtFLFNBQVMsS0FBS2tFLElBQUksQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLElBQUlBLElBQUksQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLENBQUMsRUFBRTtRQUNsRXBFLFFBQVEsRUFBRTtNQUNaO0lBQ0Y7RUFDRixDQUFDLENBQUM7RUFFRixPQUFPO0lBQUNBLFFBQVEsRUFBUkEsUUFBUTtJQUFFQyxRQUFRLEVBQVJBO0VBQVEsQ0FBQztBQUM3QiIsImlnbm9yZUxpc3QiOltdfQ== /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parsePatch = parsePatch; /*istanbul ignore end*/ function parsePatch(uniDiff) { var diffstr = uniDiff.split(/\n/), list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:\s|diff\s|\-\-\-\s|\+\+\+\s|===================================================================)/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line) { throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], lines: [] }; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } var addCount = 0, removeCount = 0; for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || /*istanbul ignore start*/ (_diffstr$i = /*istanbul ignore end*/ diffstr[i]) !== null && _diffstr$i !== void 0 && /*istanbul ignore start*/ _diffstr$i /*istanbul ignore end*/ .startsWith('\\')); i++) { /*istanbul ignore start*/ var _diffstr$i; /*istanbul ignore end*/ var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { throw new Error( /*istanbul ignore start*/ "Hunk at line ".concat( /*istanbul ignore end*/ chunkHeaderIndex + 1, " contained invalid line ").concat(diffstr[i])); } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform sanity checking if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJwYXJzZVBhdGNoIiwidW5pRGlmZiIsImRpZmZzdHIiLCJzcGxpdCIsImxpc3QiLCJpIiwicGFyc2VJbmRleCIsImluZGV4IiwicHVzaCIsImxlbmd0aCIsImxpbmUiLCJ0ZXN0IiwiaGVhZGVyIiwiZXhlYyIsInBhcnNlRmlsZUhlYWRlciIsImh1bmtzIiwicGFyc2VIdW5rIiwiRXJyb3IiLCJKU09OIiwic3RyaW5naWZ5IiwiZmlsZUhlYWRlciIsImtleVByZWZpeCIsImRhdGEiLCJmaWxlTmFtZSIsInJlcGxhY2UiLCJzdWJzdHIiLCJ0cmltIiwiY2h1bmtIZWFkZXJJbmRleCIsImNodW5rSGVhZGVyTGluZSIsImNodW5rSGVhZGVyIiwiaHVuayIsIm9sZFN0YXJ0Iiwib2xkTGluZXMiLCJuZXdTdGFydCIsIm5ld0xpbmVzIiwibGluZXMiLCJhZGRDb3VudCIsInJlbW92ZUNvdW50IiwiX2RpZmZzdHIkaSIsInN0YXJ0c1dpdGgiLCJvcGVyYXRpb24iLCJjb25jYXQiXSwic291cmNlcyI6WyIuLi8uLi9zcmMvcGF0Y2gvcGFyc2UuanMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGZ1bmN0aW9uIHBhcnNlUGF0Y2godW5pRGlmZikge1xuICBsZXQgZGlmZnN0ciA9IHVuaURpZmYuc3BsaXQoL1xcbi8pLFxuICAgICAgbGlzdCA9IFtdLFxuICAgICAgaSA9IDA7XG5cbiAgZnVuY3Rpb24gcGFyc2VJbmRleCgpIHtcbiAgICBsZXQgaW5kZXggPSB7fTtcbiAgICBsaXN0LnB1c2goaW5kZXgpO1xuXG4gICAgLy8gUGFyc2UgZGlmZiBtZXRhZGF0YVxuICAgIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICAgIGxldCBsaW5lID0gZGlmZnN0cltpXTtcblxuICAgICAgLy8gRmlsZSBoZWFkZXIgZm91bmQsIGVuZCBwYXJzaW5nIGRpZmYgbWV0YWRhdGFcbiAgICAgIGlmICgoL14oXFwtXFwtXFwtfFxcK1xcK1xcK3xAQClcXHMvKS50ZXN0KGxpbmUpKSB7XG4gICAgICAgIGJyZWFrO1xuICAgICAgfVxuXG4gICAgICAvLyBEaWZmIGluZGV4XG4gICAgICBsZXQgaGVhZGVyID0gKC9eKD86SW5kZXg6fGRpZmYoPzogLXIgXFx3KykrKVxccysoLis/KVxccyokLykuZXhlYyhsaW5lKTtcbiAgICAgIGlmIChoZWFkZXIpIHtcbiAgICAgICAgaW5kZXguaW5kZXggPSBoZWFkZXJbMV07XG4gICAgICB9XG5cbiAgICAgIGkrKztcbiAgICB9XG5cbiAgICAvLyBQYXJzZSBmaWxlIGhlYWRlcnMgaWYgdGhleSBhcmUgZGVmaW5lZC4gVW5pZmllZCBkaWZmIHJlcXVpcmVzIHRoZW0sIGJ1dFxuICAgIC8vIHRoZXJlJ3Mgbm8gdGVjaG5pY2FsIGlzc3VlcyB0byBoYXZlIGFuIGlzb2xhdGVkIGh1bmsgd2l0aG91dCBmaWxlIGhlYWRlclxuICAgIHBhcnNlRmlsZUhlYWRlcihpbmRleCk7XG4gICAgcGFyc2VGaWxlSGVhZGVyKGluZGV4KTtcblxuICAgIC8vIFBhcnNlIGh1bmtzXG4gICAgaW5kZXguaHVua3MgPSBbXTtcblxuICAgIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICAgIGxldCBsaW5lID0gZGlmZnN0cltpXTtcbiAgICAgIGlmICgoL14oSW5kZXg6XFxzfGRpZmZcXHN8XFwtXFwtXFwtXFxzfFxcK1xcK1xcK1xcc3w9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09KS8pLnRlc3QobGluZSkpIHtcbiAgICAgICAgYnJlYWs7XG4gICAgICB9IGVsc2UgaWYgKCgvXkBALykudGVzdChsaW5lKSkge1xuICAgICAgICBpbmRleC5odW5rcy5wdXNoKHBhcnNlSHVuaygpKTtcbiAgICAgIH0gZWxzZSBpZiAobGluZSkge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1Vua25vd24gbGluZSAnICsgKGkgKyAxKSArICcgJyArIEpTT04uc3RyaW5naWZ5KGxpbmUpKTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIGkrKztcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICAvLyBQYXJzZXMgdGhlIC0tLSBhbmQgKysrIGhlYWRlcnMsIGlmIG5vbmUgYXJlIGZvdW5kLCBubyBsaW5lc1xuICAvLyBhcmUgY29uc3VtZWQuXG4gIGZ1bmN0aW9uIHBhcnNlRmlsZUhlYWRlcihpbmRleCkge1xuICAgIGNvbnN0IGZpbGVIZWFkZXIgPSAoL14oLS0tfFxcK1xcK1xcKylcXHMrKC4qKVxccj8kLykuZXhlYyhkaWZmc3RyW2ldKTtcbiAgICBpZiAoZmlsZUhlYWRlcikge1xuICAgICAgbGV0IGtleVByZWZpeCA9IGZpbGVIZWFkZXJbMV0gPT09ICctLS0nID8gJ29sZCcgOiAnbmV3JztcbiAgICAgIGNvbnN0IGRhdGEgPSBmaWxlSGVhZGVyWzJdLnNwbGl0KCdcXHQnLCAyKTtcbiAgICAgIGxldCBmaWxlTmFtZSA9IGRhdGFbMF0ucmVwbGFjZSgvXFxcXFxcXFwvZywgJ1xcXFwnKTtcbiAgICAgIGlmICgoL15cIi4qXCIkLykudGVzdChmaWxlTmFtZSkpIHtcbiAgICAgICAgZmlsZU5hbWUgPSBmaWxlTmFtZS5zdWJzdHIoMSwgZmlsZU5hbWUubGVuZ3RoIC0gMik7XG4gICAgICB9XG4gICAgICBpbmRleFtrZXlQcmVmaXggKyAnRmlsZU5hbWUnXSA9IGZpbGVOYW1lO1xuICAgICAgaW5kZXhba2V5UHJlZml4ICsgJ0hlYWRlciddID0gKGRhdGFbMV0gfHwgJycpLnRyaW0oKTtcblxuICAgICAgaSsrO1xuICAgIH1cbiAgfVxuXG4gIC8vIFBhcnNlcyBhIGh1bmtcbiAgLy8gVGhpcyBhc3N1bWVzIHRoYXQgd2UgYXJlIGF0IHRoZSBzdGFydCBvZiBhIGh1bmsuXG4gIGZ1bmN0aW9uIHBhcnNlSHVuaygpIHtcbiAgICBsZXQgY2h1bmtIZWFkZXJJbmRleCA9IGksXG4gICAgICAgIGNodW5rSGVhZGVyTGluZSA9IGRpZmZzdHJbaSsrXSxcbiAgICAgICAgY2h1bmtIZWFkZXIgPSBjaHVua0hlYWRlckxpbmUuc3BsaXQoL0BAIC0oXFxkKykoPzosKFxcZCspKT8gXFwrKFxcZCspKD86LChcXGQrKSk/IEBALyk7XG5cbiAgICBsZXQgaHVuayA9IHtcbiAgICAgIG9sZFN0YXJ0OiArY2h1bmtIZWFkZXJbMV0sXG4gICAgICBvbGRMaW5lczogdHlwZW9mIGNodW5rSGVhZGVyWzJdID09PSAndW5kZWZpbmVkJyA/IDEgOiArY2h1bmtIZWFkZXJbMl0sXG4gICAgICBuZXdTdGFydDogK2NodW5rSGVhZGVyWzNdLFxuICAgICAgbmV3TGluZXM6IHR5cGVvZiBjaHVua0hlYWRlcls0XSA9PT0gJ3VuZGVmaW5lZCcgPyAxIDogK2NodW5rSGVhZGVyWzRdLFxuICAgICAgbGluZXM6IFtdXG4gICAgfTtcblxuICAgIC8vIFVuaWZpZWQgRGlmZiBGb3JtYXQgcXVpcms6IElmIHRoZSBjaHVuayBzaXplIGlzIDAsXG4gICAgLy8gdGhlIGZpcnN0IG51bWJlciBpcyBvbmUgbG93ZXIgdGhhbiBvbmUgd291bGQgZXhwZWN0LlxuICAgIC8vIGh0dHBzOi8vd3d3LmFydGltYS5jb20vd2VibG9ncy92aWV3cG9zdC5qc3A/dGhyZWFkPTE2NDI5M1xuICAgIGlmIChodW5rLm9sZExpbmVzID09PSAwKSB7XG4gICAgICBodW5rLm9sZFN0YXJ0ICs9IDE7XG4gICAgfVxuICAgIGlmIChodW5rLm5ld0xpbmVzID09PSAwKSB7XG4gICAgICBodW5rLm5ld1N0YXJ0ICs9IDE7XG4gICAgfVxuXG4gICAgbGV0IGFkZENvdW50ID0gMCxcbiAgICAgICAgcmVtb3ZlQ291bnQgPSAwO1xuICAgIGZvciAoXG4gICAgICA7XG4gICAgICBpIDwgZGlmZnN0ci5sZW5ndGggJiYgKHJlbW92ZUNvdW50IDwgaHVuay5vbGRMaW5lcyB8fCBhZGRDb3VudCA8IGh1bmsubmV3TGluZXMgfHwgZGlmZnN0cltpXT8uc3RhcnRzV2l0aCgnXFxcXCcpKTtcbiAgICAgIGkrK1xuICAgICkge1xuICAgICAgbGV0IG9wZXJhdGlvbiA9IChkaWZmc3RyW2ldLmxlbmd0aCA9PSAwICYmIGkgIT0gKGRpZmZzdHIubGVuZ3RoIC0gMSkpID8gJyAnIDogZGlmZnN0cltpXVswXTtcbiAgICAgIGlmIChvcGVyYXRpb24gPT09ICcrJyB8fCBvcGVyYXRpb24gPT09ICctJyB8fCBvcGVyYXRpb24gPT09ICcgJyB8fCBvcGVyYXRpb24gPT09ICdcXFxcJykge1xuICAgICAgICBodW5rLmxpbmVzLnB1c2goZGlmZnN0cltpXSk7XG5cbiAgICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJysnKSB7XG4gICAgICAgICAgYWRkQ291bnQrKztcbiAgICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICAgIHJlbW92ZUNvdW50Kys7XG4gICAgICAgIH0gZWxzZSBpZiAob3BlcmF0aW9uID09PSAnICcpIHtcbiAgICAgICAgICBhZGRDb3VudCsrO1xuICAgICAgICAgIHJlbW92ZUNvdW50Kys7XG4gICAgICAgIH1cbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIHRocm93IG5ldyBFcnJvcihgSHVuayBhdCBsaW5lICR7Y2h1bmtIZWFkZXJJbmRleCArIDF9IGNvbnRhaW5lZCBpbnZhbGlkIGxpbmUgJHtkaWZmc3RyW2ldfWApO1xuICAgICAgfVxuICAgIH1cblxuICAgIC8vIEhhbmRsZSB0aGUgZW1wdHkgYmxvY2sgY291bnQgY2FzZVxuICAgIGlmICghYWRkQ291bnQgJiYgaHVuay5uZXdMaW5lcyA9PT0gMSkge1xuICAgICAgaHVuay5uZXdMaW5lcyA9IDA7XG4gICAgfVxuICAgIGlmICghcmVtb3ZlQ291bnQgJiYgaHVuay5vbGRMaW5lcyA9PT0gMSkge1xuICAgICAgaHVuay5vbGRMaW5lcyA9IDA7XG4gICAgfVxuXG4gICAgLy8gUGVyZm9ybSBzYW5pdHkgY2hlY2tpbmdcbiAgICBpZiAoYWRkQ291bnQgIT09IGh1bmsubmV3TGluZXMpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignQWRkZWQgbGluZSBjb3VudCBkaWQgbm90IG1hdGNoIGZvciBodW5rIGF0IGxpbmUgJyArIChjaHVua0hlYWRlckluZGV4ICsgMSkpO1xuICAgIH1cbiAgICBpZiAocmVtb3ZlQ291bnQgIT09IGh1bmsub2xkTGluZXMpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignUmVtb3ZlZCBsaW5lIGNvdW50IGRpZCBub3QgbWF0Y2ggZm9yIGh1bmsgYXQgbGluZSAnICsgKGNodW5rSGVhZGVySW5kZXggKyAxKSk7XG4gICAgfVxuXG4gICAgcmV0dXJuIGh1bms7XG4gIH1cblxuICB3aGlsZSAoaSA8IGRpZmZzdHIubGVuZ3RoKSB7XG4gICAgcGFyc2VJbmRleCgpO1xuICB9XG5cbiAgcmV0dXJuIGxpc3Q7XG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBQU8sU0FBU0EsVUFBVUEsQ0FBQ0MsT0FBTyxFQUFFO0VBQ2xDLElBQUlDLE9BQU8sR0FBR0QsT0FBTyxDQUFDRSxLQUFLLENBQUMsSUFBSSxDQUFDO0lBQzdCQyxJQUFJLEdBQUcsRUFBRTtJQUNUQyxDQUFDLEdBQUcsQ0FBQztFQUVULFNBQVNDLFVBQVVBLENBQUEsRUFBRztJQUNwQixJQUFJQyxLQUFLLEdBQUcsQ0FBQyxDQUFDO0lBQ2RILElBQUksQ0FBQ0ksSUFBSSxDQUFDRCxLQUFLLENBQUM7O0lBRWhCO0lBQ0EsT0FBT0YsQ0FBQyxHQUFHSCxPQUFPLENBQUNPLE1BQU0sRUFBRTtNQUN6QixJQUFJQyxJQUFJLEdBQUdSLE9BQU8sQ0FBQ0csQ0FBQyxDQUFDOztNQUVyQjtNQUNBLElBQUssdUJBQXVCLENBQUVNLElBQUksQ0FBQ0QsSUFBSSxDQUFDLEVBQUU7UUFDeEM7TUFDRjs7TUFFQTtNQUNBLElBQUlFLE1BQU0sR0FBSSwwQ0FBMEMsQ0FBRUMsSUFBSSxDQUFDSCxJQUFJLENBQUM7TUFDcEUsSUFBSUUsTUFBTSxFQUFFO1FBQ1ZMLEtBQUssQ0FBQ0EsS0FBSyxHQUFHSyxNQUFNLENBQUMsQ0FBQyxDQUFDO01BQ3pCO01BRUFQLENBQUMsRUFBRTtJQUNMOztJQUVBO0lBQ0E7SUFDQVMsZUFBZSxDQUFDUCxLQUFLLENBQUM7SUFDdEJPLGVBQWUsQ0FBQ1AsS0FBSyxDQUFDOztJQUV0QjtJQUNBQSxLQUFLLENBQUNRLEtBQUssR0FBRyxFQUFFO0lBRWhCLE9BQU9WLENBQUMsR0FBR0gsT0FBTyxDQUFDTyxNQUFNLEVBQUU7TUFDekIsSUFBSUMsS0FBSSxHQUFHUixPQUFPLENBQUNHLENBQUMsQ0FBQztNQUNyQixJQUFLLDBHQUEwRyxDQUFFTSxJQUFJLENBQUNELEtBQUksQ0FBQyxFQUFFO1FBQzNIO01BQ0YsQ0FBQyxNQUFNLElBQUssS0FBSyxDQUFFQyxJQUFJLENBQUNELEtBQUksQ0FBQyxFQUFFO1FBQzdCSCxLQUFLLENBQUNRLEtBQUssQ0FBQ1AsSUFBSSxDQUFDUSxTQUFTLENBQUMsQ0FBQyxDQUFDO01BQy9CLENBQUMsTUFBTSxJQUFJTixLQUFJLEVBQUU7UUFDZixNQUFNLElBQUlPLEtBQUssQ0FBQyxlQUFlLElBQUlaLENBQUMsR0FBRyxDQUFDLENBQUMsR0FBRyxHQUFHLEdBQUdhLElBQUksQ0FBQ0MsU0FBUyxDQUFDVCxLQUFJLENBQUMsQ0FBQztNQUN6RSxDQUFDLE1BQU07UUFDTEwsQ0FBQyxFQUFFO01BQ0w7SUFDRjtFQUNGOztFQUVBO0VBQ0E7RUFDQSxTQUFTUyxlQUFlQSxDQUFDUCxLQUFLLEVBQUU7SUFDOUIsSUFBTWEsVUFBVSxHQUFJLDBCQUEwQixDQUFFUCxJQUFJLENBQUNYLE9BQU8sQ0FBQ0csQ0FBQyxDQUFDLENBQUM7SUFDaEUsSUFBSWUsVUFBVSxFQUFFO01BQ2QsSUFBSUMsU0FBUyxHQUFHRCxVQUFVLENBQUMsQ0FBQyxDQUFDLEtBQUssS0FBSyxHQUFHLEtBQUssR0FBRyxLQUFLO01BQ3ZELElBQU1FLElBQUksR0FBR0YsVUFBVSxDQUFDLENBQUMsQ0FBQyxDQUFDakIsS0FBSyxDQUFDLElBQUksRUFBRSxDQUFDLENBQUM7TUFDekMsSUFBSW9CLFFBQVEsR0FBR0QsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDRSxPQUFPLENBQUMsT0FBTyxFQUFFLElBQUksQ0FBQztNQUM3QyxJQUFLLFFBQVEsQ0FBRWIsSUFBSSxDQUFDWSxRQUFRLENBQUMsRUFBRTtRQUM3QkEsUUFBUSxHQUFHQSxRQUFRLENBQUNFLE1BQU0sQ0FBQyxDQUFDLEVBQUVGLFFBQVEsQ0FBQ2QsTUFBTSxHQUFHLENBQUMsQ0FBQztNQUNwRDtNQUNBRixLQUFLLENBQUNjLFNBQVMsR0FBRyxVQUFVLENBQUMsR0FBR0UsUUFBUTtNQUN4Q2hCLEtBQUssQ0FBQ2MsU0FBUyxHQUFHLFFBQVEsQ0FBQyxHQUFHLENBQUNDLElBQUksQ0FBQyxDQUFDLENBQUMsSUFBSSxFQUFFLEVBQUVJLElBQUksQ0FBQyxDQUFDO01BRXBEckIsQ0FBQyxFQUFFO0lBQ0w7RUFDRjs7RUFFQTtFQUNBO0VBQ0EsU0FBU1csU0FBU0EsQ0FBQSxFQUFHO0lBQ25CLElBQUlXLGdCQUFnQixHQUFHdEIsQ0FBQztNQUNwQnVCLGVBQWUsR0FBRzFCLE9BQU8sQ0FBQ0csQ0FBQyxFQUFFLENBQUM7TUFDOUJ3QixXQUFXLEdBQUdELGVBQWUsQ0FBQ3pCLEtBQUssQ0FBQyw0Q0FBNEMsQ0FBQztJQUVyRixJQUFJMkIsSUFBSSxHQUFHO01BQ1RDLFFBQVEsRUFBRSxDQUFDRixXQUFXLENBQUMsQ0FBQyxDQUFDO01BQ3pCRyxRQUFRLEVBQUUsT0FBT0gsV0FBVyxDQUFDLENBQUMsQ0FBQyxLQUFLLFdBQVcsR0FBRyxDQUFDLEdBQUcsQ0FBQ0EsV0FBVyxDQUFDLENBQUMsQ0FBQztNQUNyRUksUUFBUSxFQUFFLENBQUNKLFdBQVcsQ0FBQyxDQUFDLENBQUM7TUFDekJLLFFBQVEsRUFBRSxPQUFPTCxXQUFXLENBQUMsQ0FBQyxDQUFDLEtBQUssV0FBVyxHQUFHLENBQUMsR0FBRyxDQUFDQSxXQUFXLENBQUMsQ0FBQyxDQUFDO01BQ3JFTSxLQUFLLEVBQUU7SUFDVCxDQUFDOztJQUVEO0lBQ0E7SUFDQTtJQUNBLElBQUlMLElBQUksQ0FBQ0UsUUFBUSxLQUFLLENBQUMsRUFBRTtNQUN2QkYsSUFBSSxDQUFDQyxRQUFRLElBQUksQ0FBQztJQUNwQjtJQUNBLElBQUlELElBQUksQ0FBQ0ksUUFBUSxLQUFLLENBQUMsRUFBRTtNQUN2QkosSUFBSSxDQUFDRyxRQUFRLElBQUksQ0FBQztJQUNwQjtJQUVBLElBQUlHLFFBQVEsR0FBRyxDQUFDO01BQ1pDLFdBQVcsR0FBRyxDQUFDO0lBQ25CLE9BRUVoQyxDQUFDLEdBQUdILE9BQU8sQ0FBQ08sTUFBTSxLQUFLNEIsV0FBVyxHQUFHUCxJQUFJLENBQUNFLFFBQVEsSUFBSUksUUFBUSxHQUFHTixJQUFJLENBQUNJLFFBQVE7SUFBQTtJQUFBLENBQUFJLFVBQUE7SUFBQTtJQUFJcEMsT0FBTyxDQUFDRyxDQUFDLENBQUMsY0FBQWlDLFVBQUE7SUFBVjtJQUFBQTtJQUFBO0lBQUEsQ0FBWUMsVUFBVSxDQUFDLElBQUksQ0FBQyxDQUFDLEVBQy9HbEMsQ0FBQyxFQUFFLEVBQ0g7TUFBQTtNQUFBLElBQUFpQyxVQUFBO01BQUE7TUFDQSxJQUFJRSxTQUFTLEdBQUl0QyxPQUFPLENBQUNHLENBQUMsQ0FBQyxDQUFDSSxNQUFNLElBQUksQ0FBQyxJQUFJSixDQUFDLElBQUtILE9BQU8sQ0FBQ08sTUFBTSxHQUFHLENBQUUsR0FBSSxHQUFHLEdBQUdQLE9BQU8sQ0FBQ0csQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO01BQzNGLElBQUltQyxTQUFTLEtBQUssR0FBRyxJQUFJQSxTQUFTLEtBQUssR0FBRyxJQUFJQSxTQUFTLEtBQUssR0FBRyxJQUFJQSxTQUFTLEtBQUssSUFBSSxFQUFFO1FBQ3JGVixJQUFJLENBQUNLLEtBQUssQ0FBQzNCLElBQUksQ0FBQ04sT0FBTyxDQUFDRyxDQUFDLENBQUMsQ0FBQztRQUUzQixJQUFJbUMsU0FBUyxLQUFLLEdBQUcsRUFBRTtVQUNyQkosUUFBUSxFQUFFO1FBQ1osQ0FBQyxNQUFNLElBQUlJLFNBQVMsS0FBSyxHQUFHLEVBQUU7VUFDNUJILFdBQVcsRUFBRTtRQUNmLENBQUMsTUFBTSxJQUFJRyxTQUFTLEtBQUssR0FBRyxFQUFFO1VBQzVCSixRQUFRLEVBQUU7VUFDVkMsV0FBVyxFQUFFO1FBQ2Y7TUFDRixDQUFDLE1BQU07UUFDTCxNQUFNLElBQUlwQixLQUFLO1FBQUE7UUFBQSxnQkFBQXdCLE1BQUE7UUFBQTtRQUFpQmQsZ0JBQWdCLEdBQUcsQ0FBQyw4QkFBQWMsTUFBQSxDQUEyQnZDLE9BQU8sQ0FBQ0csQ0FBQyxDQUFDLENBQUUsQ0FBQztNQUM5RjtJQUNGOztJQUVBO0lBQ0EsSUFBSSxDQUFDK0IsUUFBUSxJQUFJTixJQUFJLENBQUNJLFFBQVEsS0FBSyxDQUFDLEVBQUU7TUFDcENKLElBQUksQ0FBQ0ksUUFBUSxHQUFHLENBQUM7SUFDbkI7SUFDQSxJQUFJLENBQUNHLFdBQVcsSUFBSVAsSUFBSSxDQUFDRSxRQUFRLEtBQUssQ0FBQyxFQUFFO01BQ3ZDRixJQUFJLENBQUNFLFFBQVEsR0FBRyxDQUFDO0lBQ25COztJQUVBO0lBQ0EsSUFBSUksUUFBUSxLQUFLTixJQUFJLENBQUNJLFFBQVEsRUFBRTtNQUM5QixNQUFNLElBQUlqQixLQUFLLENBQUMsa0RBQWtELElBQUlVLGdCQUFnQixHQUFHLENBQUMsQ0FBQyxDQUFDO0lBQzlGO0lBQ0EsSUFBSVUsV0FBVyxLQUFLUCxJQUFJLENBQUNFLFFBQVEsRUFBRTtNQUNqQyxNQUFNLElBQUlmLEtBQUssQ0FBQyxvREFBb0QsSUFBSVUsZ0JBQWdCLEdBQUcsQ0FBQyxDQUFDLENBQUM7SUFDaEc7SUFFQSxPQUFPRyxJQUFJO0VBQ2I7RUFFQSxPQUFPekIsQ0FBQyxHQUFHSCxPQUFPLENBQUNPLE1BQU0sRUFBRTtJQUN6QkgsVUFBVSxDQUFDLENBQUM7RUFDZDtFQUVBLE9BQU9GLElBQUk7QUFDYiIsImlnbm9yZUxpc3QiOltdfQ== /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reversePatch = reversePatch; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /*istanbul ignore end*/ function reversePatch(structuredPatch) { if (Array.isArray(structuredPatch)) { return structuredPatch.map(reversePatch).reverse(); } return ( /*istanbul ignore start*/ _objectSpread(_objectSpread({}, /*istanbul ignore end*/ structuredPatch), {}, { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(function (hunk) { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, lines: hunk.lines.map(function (l) { if (l.startsWith('-')) { return ( /*istanbul ignore start*/ "+".concat( /*istanbul ignore end*/ l.slice(1)) ); } if (l.startsWith('+')) { return ( /*istanbul ignore start*/ "-".concat( /*istanbul ignore end*/ l.slice(1)) ); } return l; }) }; }) }) ); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyZXZlcnNlUGF0Y2giLCJzdHJ1Y3R1cmVkUGF0Y2giLCJBcnJheSIsImlzQXJyYXkiLCJtYXAiLCJyZXZlcnNlIiwiX29iamVjdFNwcmVhZCIsIm9sZEZpbGVOYW1lIiwibmV3RmlsZU5hbWUiLCJvbGRIZWFkZXIiLCJuZXdIZWFkZXIiLCJodW5rcyIsImh1bmsiLCJvbGRMaW5lcyIsIm5ld0xpbmVzIiwib2xkU3RhcnQiLCJuZXdTdGFydCIsImxpbmVzIiwibCIsInN0YXJ0c1dpdGgiLCJjb25jYXQiLCJzbGljZSJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9yZXZlcnNlLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBmdW5jdGlvbiByZXZlcnNlUGF0Y2goc3RydWN0dXJlZFBhdGNoKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KHN0cnVjdHVyZWRQYXRjaCkpIHtcbiAgICByZXR1cm4gc3RydWN0dXJlZFBhdGNoLm1hcChyZXZlcnNlUGF0Y2gpLnJldmVyc2UoKTtcbiAgfVxuXG4gIHJldHVybiB7XG4gICAgLi4uc3RydWN0dXJlZFBhdGNoLFxuICAgIG9sZEZpbGVOYW1lOiBzdHJ1Y3R1cmVkUGF0Y2gubmV3RmlsZU5hbWUsXG4gICAgb2xkSGVhZGVyOiBzdHJ1Y3R1cmVkUGF0Y2gubmV3SGVhZGVyLFxuICAgIG5ld0ZpbGVOYW1lOiBzdHJ1Y3R1cmVkUGF0Y2gub2xkRmlsZU5hbWUsXG4gICAgbmV3SGVhZGVyOiBzdHJ1Y3R1cmVkUGF0Y2gub2xkSGVhZGVyLFxuICAgIGh1bmtzOiBzdHJ1Y3R1cmVkUGF0Y2guaHVua3MubWFwKGh1bmsgPT4ge1xuICAgICAgcmV0dXJuIHtcbiAgICAgICAgb2xkTGluZXM6IGh1bmsubmV3TGluZXMsXG4gICAgICAgIG9sZFN0YXJ0OiBodW5rLm5ld1N0YXJ0LFxuICAgICAgICBuZXdMaW5lczogaHVuay5vbGRMaW5lcyxcbiAgICAgICAgbmV3U3RhcnQ6IGh1bmsub2xkU3RhcnQsXG4gICAgICAgIGxpbmVzOiBodW5rLmxpbmVzLm1hcChsID0+IHtcbiAgICAgICAgICBpZiAobC5zdGFydHNXaXRoKCctJykpIHsgcmV0dXJuIGArJHtsLnNsaWNlKDEpfWA7IH1cbiAgICAgICAgICBpZiAobC5zdGFydHNXaXRoKCcrJykpIHsgcmV0dXJuIGAtJHtsLnNsaWNlKDEpfWA7IH1cbiAgICAgICAgICByZXR1cm4gbDtcbiAgICAgICAgfSlcbiAgICAgIH07XG4gICAgfSlcbiAgfTtcbn1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7QUFBTyxTQUFTQSxZQUFZQSxDQUFDQyxlQUFlLEVBQUU7RUFDNUMsSUFBSUMsS0FBSyxDQUFDQyxPQUFPLENBQUNGLGVBQWUsQ0FBQyxFQUFFO0lBQ2xDLE9BQU9BLGVBQWUsQ0FBQ0csR0FBRyxDQUFDSixZQUFZLENBQUMsQ0FBQ0ssT0FBTyxDQUFDLENBQUM7RUFDcEQ7RUFFQTtJQUFBO0lBQUFDLGFBQUEsQ0FBQUEsYUFBQTtJQUFBO0lBQ0tMLGVBQWU7TUFDbEJNLFdBQVcsRUFBRU4sZUFBZSxDQUFDTyxXQUFXO01BQ3hDQyxTQUFTLEVBQUVSLGVBQWUsQ0FBQ1MsU0FBUztNQUNwQ0YsV0FBVyxFQUFFUCxlQUFlLENBQUNNLFdBQVc7TUFDeENHLFNBQVMsRUFBRVQsZUFBZSxDQUFDUSxTQUFTO01BQ3BDRSxLQUFLLEVBQUVWLGVBQWUsQ0FBQ1UsS0FBSyxDQUFDUCxHQUFHLENBQUMsVUFBQVEsSUFBSSxFQUFJO1FBQ3ZDLE9BQU87VUFDTEMsUUFBUSxFQUFFRCxJQUFJLENBQUNFLFFBQVE7VUFDdkJDLFFBQVEsRUFBRUgsSUFBSSxDQUFDSSxRQUFRO1VBQ3ZCRixRQUFRLEVBQUVGLElBQUksQ0FBQ0MsUUFBUTtVQUN2QkcsUUFBUSxFQUFFSixJQUFJLENBQUNHLFFBQVE7VUFDdkJFLEtBQUssRUFBRUwsSUFBSSxDQUFDSyxLQUFLLENBQUNiLEdBQUcsQ0FBQyxVQUFBYyxDQUFDLEVBQUk7WUFDekIsSUFBSUEsQ0FBQyxDQUFDQyxVQUFVLENBQUMsR0FBRyxDQUFDLEVBQUU7Y0FBRTtnQkFBQTtnQkFBQSxJQUFBQyxNQUFBO2dCQUFBO2dCQUFXRixDQUFDLENBQUNHLEtBQUssQ0FBQyxDQUFDLENBQUM7Y0FBQTtZQUFJO1lBQ2xELElBQUlILENBQUMsQ0FBQ0MsVUFBVSxDQUFDLEdBQUcsQ0FBQyxFQUFFO2NBQUU7Z0JBQUE7Z0JBQUEsSUFBQUMsTUFBQTtnQkFBQTtnQkFBV0YsQ0FBQyxDQUFDRyxLQUFLLENBQUMsQ0FBQyxDQUFDO2NBQUE7WUFBSTtZQUNsRCxPQUFPSCxDQUFDO1VBQ1YsQ0FBQztRQUNILENBQUM7TUFDSCxDQUFDO0lBQUM7RUFBQTtBQUVOIiwiaWdub3JlTGlzdCI6W119 /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayEqual = arrayEqual; exports.arrayStartsWith = arrayStartsWith; /*istanbul ignore end*/ function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJhcnJheUVxdWFsIiwiYSIsImIiLCJsZW5ndGgiLCJhcnJheVN0YXJ0c1dpdGgiLCJhcnJheSIsInN0YXJ0IiwiaSJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2FycmF5LmpzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBmdW5jdGlvbiBhcnJheUVxdWFsKGEsIGIpIHtcbiAgaWYgKGEubGVuZ3RoICE9PSBiLmxlbmd0aCkge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIHJldHVybiBhcnJheVN0YXJ0c1dpdGgoYSwgYik7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBhcnJheVN0YXJ0c1dpdGgoYXJyYXksIHN0YXJ0KSB7XG4gIGlmIChzdGFydC5sZW5ndGggPiBhcnJheS5sZW5ndGgpIHtcbiAgICByZXR1cm4gZmFsc2U7XG4gIH1cblxuICBmb3IgKGxldCBpID0gMDsgaSA8IHN0YXJ0Lmxlbmd0aDsgaSsrKSB7XG4gICAgaWYgKHN0YXJ0W2ldICE9PSBhcnJheVtpXSkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFBTyxTQUFTQSxVQUFVQSxDQUFDQyxDQUFDLEVBQUVDLENBQUMsRUFBRTtFQUMvQixJQUFJRCxDQUFDLENBQUNFLE1BQU0sS0FBS0QsQ0FBQyxDQUFDQyxNQUFNLEVBQUU7SUFDekIsT0FBTyxLQUFLO0VBQ2Q7RUFFQSxPQUFPQyxlQUFlLENBQUNILENBQUMsRUFBRUMsQ0FBQyxDQUFDO0FBQzlCO0FBRU8sU0FBU0UsZUFBZUEsQ0FBQ0MsS0FBSyxFQUFFQyxLQUFLLEVBQUU7RUFDNUMsSUFBSUEsS0FBSyxDQUFDSCxNQUFNLEdBQUdFLEtBQUssQ0FBQ0YsTUFBTSxFQUFFO0lBQy9CLE9BQU8sS0FBSztFQUNkO0VBRUEsS0FBSyxJQUFJSSxDQUFDLEdBQUcsQ0FBQyxFQUFFQSxDQUFDLEdBQUdELEtBQUssQ0FBQ0gsTUFBTSxFQUFFSSxDQUFDLEVBQUUsRUFBRTtJQUNyQyxJQUFJRCxLQUFLLENBQUNDLENBQUMsQ0FBQyxLQUFLRixLQUFLLENBQUNFLENBQUMsQ0FBQyxFQUFFO01BQ3pCLE9BQU8sS0FBSztJQUNkO0VBQ0Y7RUFFQSxPQUFPLElBQUk7QUFDYiIsImlnbm9yZUxpc3QiOltdfQ== /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = _default; /*istanbul ignore end*/ // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function /*istanbul ignore start*/ _default /*istanbul ignore end*/ (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return start + localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return start - localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfZGVmYXVsdCIsInN0YXJ0IiwibWluTGluZSIsIm1heExpbmUiLCJ3YW50Rm9yd2FyZCIsImJhY2t3YXJkRXhoYXVzdGVkIiwiZm9yd2FyZEV4aGF1c3RlZCIsImxvY2FsT2Zmc2V0IiwiaXRlcmF0b3IiXSwic291cmNlcyI6WyIuLi8uLi9zcmMvdXRpbC9kaXN0YW5jZS1pdGVyYXRvci5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyIvLyBJdGVyYXRvciB0aGF0IHRyYXZlcnNlcyBpbiB0aGUgcmFuZ2Ugb2YgW21pbiwgbWF4XSwgc3RlcHBpbmdcbi8vIGJ5IGRpc3RhbmNlIGZyb20gYSBnaXZlbiBzdGFydCBwb3NpdGlvbi4gSS5lLiBmb3IgWzAsIDRdLCB3aXRoXG4vLyBzdGFydCBvZiAyLCB0aGlzIHdpbGwgaXRlcmF0ZSAyLCAzLCAxLCA0LCAwLlxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24oc3RhcnQsIG1pbkxpbmUsIG1heExpbmUpIHtcbiAgbGV0IHdhbnRGb3J3YXJkID0gdHJ1ZSxcbiAgICAgIGJhY2t3YXJkRXhoYXVzdGVkID0gZmFsc2UsXG4gICAgICBmb3J3YXJkRXhoYXVzdGVkID0gZmFsc2UsXG4gICAgICBsb2NhbE9mZnNldCA9IDE7XG5cbiAgcmV0dXJuIGZ1bmN0aW9uIGl0ZXJhdG9yKCkge1xuICAgIGlmICh3YW50Rm9yd2FyZCAmJiAhZm9yd2FyZEV4aGF1c3RlZCkge1xuICAgICAgaWYgKGJhY2t3YXJkRXhoYXVzdGVkKSB7XG4gICAgICAgIGxvY2FsT2Zmc2V0Kys7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICB3YW50Rm9yd2FyZCA9IGZhbHNlO1xuICAgICAgfVxuXG4gICAgICAvLyBDaGVjayBpZiB0cnlpbmcgdG8gZml0IGJleW9uZCB0ZXh0IGxlbmd0aCwgYW5kIGlmIG5vdCwgY2hlY2sgaXQgZml0c1xuICAgICAgLy8gYWZ0ZXIgb2Zmc2V0IGxvY2F0aW9uIChvciBkZXNpcmVkIGxvY2F0aW9uIG9uIGZpcnN0IGl0ZXJhdGlvbilcbiAgICAgIGlmIChzdGFydCArIGxvY2FsT2Zmc2V0IDw9IG1heExpbmUpIHtcbiAgICAgICAgcmV0dXJuIHN0YXJ0ICsgbG9jYWxPZmZzZXQ7XG4gICAgICB9XG5cbiAgICAgIGZvcndhcmRFeGhhdXN0ZWQgPSB0cnVlO1xuICAgIH1cblxuICAgIGlmICghYmFja3dhcmRFeGhhdXN0ZWQpIHtcbiAgICAgIGlmICghZm9yd2FyZEV4aGF1c3RlZCkge1xuICAgICAgICB3YW50Rm9yd2FyZCA9IHRydWU7XG4gICAgICB9XG5cbiAgICAgIC8vIENoZWNrIGlmIHRyeWluZyB0byBmaXQgYmVmb3JlIHRleHQgYmVnaW5uaW5nLCBhbmQgaWYgbm90LCBjaGVjayBpdCBmaXRzXG4gICAgICAvLyBiZWZvcmUgb2Zmc2V0IGxvY2F0aW9uXG4gICAgICBpZiAobWluTGluZSA8PSBzdGFydCAtIGxvY2FsT2Zmc2V0KSB7XG4gICAgICAgIHJldHVybiBzdGFydCAtIGxvY2FsT2Zmc2V0Kys7XG4gICAgICB9XG5cbiAgICAgIGJhY2t3YXJkRXhoYXVzdGVkID0gdHJ1ZTtcbiAgICAgIHJldHVybiBpdGVyYXRvcigpO1xuICAgIH1cblxuICAgIC8vIFdlIHRyaWVkIHRvIGZpdCBodW5rIGJlZm9yZSB0ZXh0IGJlZ2lubmluZyBhbmQgYmV5b25kIHRleHQgbGVuZ3RoLCB0aGVuXG4gICAgLy8gaHVuayBjYW4ndCBmaXQgb24gdGhlIHRleHQuIFJldHVybiB1bmRlZmluZWRcbiAgfTtcbn1cbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7QUFBQTtBQUNBO0FBQ0E7QUFDZTtBQUFBO0FBQUFBO0FBQUFBO0FBQUEsQ0FBU0MsS0FBSyxFQUFFQyxPQUFPLEVBQUVDLE9BQU8sRUFBRTtFQUMvQyxJQUFJQyxXQUFXLEdBQUcsSUFBSTtJQUNsQkMsaUJBQWlCLEdBQUcsS0FBSztJQUN6QkMsZ0JBQWdCLEdBQUcsS0FBSztJQUN4QkMsV0FBVyxHQUFHLENBQUM7RUFFbkIsT0FBTyxTQUFTQyxRQUFRQSxDQUFBLEVBQUc7SUFDekIsSUFBSUosV0FBVyxJQUFJLENBQUNFLGdCQUFnQixFQUFFO01BQ3BDLElBQUlELGlCQUFpQixFQUFFO1FBQ3JCRSxXQUFXLEVBQUU7TUFDZixDQUFDLE1BQU07UUFDTEgsV0FBVyxHQUFHLEtBQUs7TUFDckI7O01BRUE7TUFDQTtNQUNBLElBQUlILEtBQUssR0FBR00sV0FBVyxJQUFJSixPQUFPLEVBQUU7UUFDbEMsT0FBT0YsS0FBSyxHQUFHTSxXQUFXO01BQzVCO01BRUFELGdCQUFnQixHQUFHLElBQUk7SUFDekI7SUFFQSxJQUFJLENBQUNELGlCQUFpQixFQUFFO01BQ3RCLElBQUksQ0FBQ0MsZ0JBQWdCLEVBQUU7UUFDckJGLFdBQVcsR0FBRyxJQUFJO01BQ3BCOztNQUVBO01BQ0E7TUFDQSxJQUFJRixPQUFPLElBQUlELEtBQUssR0FBR00sV0FBVyxFQUFFO1FBQ2xDLE9BQU9OLEtBQUssR0FBR00sV0FBVyxFQUFFO01BQzlCO01BRUFGLGlCQUFpQixHQUFHLElBQUk7TUFDeEIsT0FBT0csUUFBUSxDQUFDLENBQUM7SUFDbkI7O0lBRUE7SUFDQTtFQUNGLENBQUM7QUFDSCIsImlnbm9yZUxpc3QiOltdfQ== /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateOptions = generateOptions; /*istanbul ignore end*/ function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJnZW5lcmF0ZU9wdGlvbnMiLCJvcHRpb25zIiwiZGVmYXVsdHMiLCJjYWxsYmFjayIsIm5hbWUiLCJoYXNPd25Qcm9wZXJ0eSJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3BhcmFtcy5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIGRlZmF1bHRzKSB7XG4gIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGRlZmF1bHRzLmNhbGxiYWNrID0gb3B0aW9ucztcbiAgfSBlbHNlIGlmIChvcHRpb25zKSB7XG4gICAgZm9yIChsZXQgbmFtZSBpbiBvcHRpb25zKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9wdGlvbnMuaGFzT3duUHJvcGVydHkobmFtZSkpIHtcbiAgICAgICAgZGVmYXVsdHNbbmFtZV0gPSBvcHRpb25zW25hbWVdO1xuICAgICAgfVxuICAgIH1cbiAgfVxuICByZXR1cm4gZGVmYXVsdHM7XG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBQU8sU0FBU0EsZUFBZUEsQ0FBQ0MsT0FBTyxFQUFFQyxRQUFRLEVBQUU7RUFDakQsSUFBSSxPQUFPRCxPQUFPLEtBQUssVUFBVSxFQUFFO0lBQ2pDQyxRQUFRLENBQUNDLFFBQVEsR0FBR0YsT0FBTztFQUM3QixDQUFDLE1BQU0sSUFBSUEsT0FBTyxFQUFFO0lBQ2xCLEtBQUssSUFBSUcsSUFBSSxJQUFJSCxPQUFPLEVBQUU7TUFDeEI7TUFDQSxJQUFJQSxPQUFPLENBQUNJLGNBQWMsQ0FBQ0QsSUFBSSxDQUFDLEVBQUU7UUFDaENGLFFBQVEsQ0FBQ0UsSUFBSSxDQUFDLEdBQUdILE9BQU8sQ0FBQ0csSUFBSSxDQUFDO01BQ2hDO0lBQ0Y7RUFDRjtFQUNBLE9BQU9GLFFBQVE7QUFDakIiLCJpZ25vcmVMaXN0IjpbXX0= /*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hasOnlyUnixLineEndings = hasOnlyUnixLineEndings; exports.hasOnlyWinLineEndings = hasOnlyWinLineEndings; exports.longestCommonPrefix = longestCommonPrefix; exports.longestCommonSuffix = longestCommonSuffix; exports.maximumOverlap = maximumOverlap; exports.removePrefix = removePrefix; exports.removeSuffix = removeSuffix; exports.replacePrefix = replacePrefix; exports.replaceSuffix = replaceSuffix; /*istanbul ignore end*/ function longestCommonPrefix(str1, str2) { var i; for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[i] != str2[i]) { return str1.slice(0, i); } } return str1.slice(0, i); } function longestCommonSuffix(str1, str2) { var i; // Unlike longestCommonPrefix, we need a special case to handle all scenarios // where we return the empty string since str1.slice(-0) will return the // entire string. if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) { return ''; } for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) { return str1.slice(-i); } } return str1.slice(-i); } function replacePrefix(string, oldPrefix, newPrefix) { if (string.slice(0, oldPrefix.length) != oldPrefix) { throw Error( /*istanbul ignore start*/ "string ".concat( /*istanbul ignore end*/ JSON.stringify(string), " doesn't start with prefix ").concat(JSON.stringify(oldPrefix), "; this is a bug")); } return newPrefix + string.slice(oldPrefix.length); } function replaceSuffix(string, oldSuffix, newSuffix) { if (!oldSuffix) { return string + newSuffix; } if (string.slice(-oldSuffix.length) != oldSuffix) { throw Error( /*istanbul ignore start*/ "string ".concat( /*istanbul ignore end*/ JSON.stringify(string), " doesn't end with suffix ").concat(JSON.stringify(oldSuffix), "; this is a bug")); } return string.slice(0, -oldSuffix.length) + newSuffix; } function removePrefix(string, oldPrefix) { return replacePrefix(string, oldPrefix, ''); } function removeSuffix(string, oldSuffix) { return replaceSuffix(string, oldSuffix, ''); } function maximumOverlap(string1, string2) { return string2.slice(0, overlapCount(string1, string2)); } // Nicked from https://stackoverflow.com/a/60422853/1709587 function overlapCount(a, b) { // Deal with cases where the strings differ in length var startA = 0; if (a.length > b.length) { startA = a.length - b.length; } var endB = b.length; if (a.length < b.length) { endB = a.length; } // Create a back-reference for each index // that should be followed in case of a mismatch. // We only need B to make these references: var map = Array(endB); var k = 0; // Index that lags behind j map[0] = 0; for (var j = 1; j < endB; j++) { if (b[j] == b[k]) { map[j] = map[k]; // skip over the same character (optional optimisation) } else { map[j] = k; } while (k > 0 && b[j] != b[k]) { k = map[k]; } if (b[j] == b[k]) { k++; } } // Phase 2: use these references while iterating over A k = 0; for (var i = startA; i < a.length; i++) { while (k > 0 && a[i] != b[k]) { k = map[k]; } if (a[i] == b[k]) { k++; } } return k; } /** * Returns true if the string consistently uses Windows line endings. */ function hasOnlyWinLineEndings(string) { return string.includes('\r\n') && !string.startsWith('\n') && !string.match(/[^\r]\n/); } /** * Returns true if the string consistently uses Unix line endings. */ function hasOnlyUnixLineEndings(string) { return !string.includes('\r\n') && string.includes('\n'); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJsb25nZXN0Q29tbW9uUHJlZml4Iiwic3RyMSIsInN0cjIiLCJpIiwibGVuZ3RoIiwic2xpY2UiLCJsb25nZXN0Q29tbW9uU3VmZml4IiwicmVwbGFjZVByZWZpeCIsInN0cmluZyIsIm9sZFByZWZpeCIsIm5ld1ByZWZpeCIsIkVycm9yIiwiY29uY2F0IiwiSlNPTiIsInN0cmluZ2lmeSIsInJlcGxhY2VTdWZmaXgiLCJvbGRTdWZmaXgiLCJuZXdTdWZmaXgiLCJyZW1vdmVQcmVmaXgiLCJyZW1vdmVTdWZmaXgiLCJtYXhpbXVtT3ZlcmxhcCIsInN0cmluZzEiLCJzdHJpbmcyIiwib3ZlcmxhcENvdW50IiwiYSIsImIiLCJzdGFydEEiLCJlbmRCIiwibWFwIiwiQXJyYXkiLCJrIiwiaiIsImhhc09ubHlXaW5MaW5lRW5kaW5ncyIsImluY2x1ZGVzIiwic3RhcnRzV2l0aCIsIm1hdGNoIiwiaGFzT25seVVuaXhMaW5lRW5kaW5ncyJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3N0cmluZy5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gbG9uZ2VzdENvbW1vblByZWZpeChzdHIxLCBzdHIyKSB7XG4gIGxldCBpO1xuICBmb3IgKGkgPSAwOyBpIDwgc3RyMS5sZW5ndGggJiYgaSA8IHN0cjIubGVuZ3RoOyBpKyspIHtcbiAgICBpZiAoc3RyMVtpXSAhPSBzdHIyW2ldKSB7XG4gICAgICByZXR1cm4gc3RyMS5zbGljZSgwLCBpKTtcbiAgICB9XG4gIH1cbiAgcmV0dXJuIHN0cjEuc2xpY2UoMCwgaSk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBsb25nZXN0Q29tbW9uU3VmZml4KHN0cjEsIHN0cjIpIHtcbiAgbGV0IGk7XG5cbiAgLy8gVW5saWtlIGxvbmdlc3RDb21tb25QcmVmaXgsIHdlIG5lZWQgYSBzcGVjaWFsIGNhc2UgdG8gaGFuZGxlIGFsbCBzY2VuYXJpb3NcbiAgLy8gd2hlcmUgd2UgcmV0dXJuIHRoZSBlbXB0eSBzdHJpbmcgc2luY2Ugc3RyMS5zbGljZSgtMCkgd2lsbCByZXR1cm4gdGhlXG4gIC8vIGVudGlyZSBzdHJpbmcuXG4gIGlmICghc3RyMSB8fCAhc3RyMiB8fCBzdHIxW3N0cjEubGVuZ3RoIC0gMV0gIT0gc3RyMltzdHIyLmxlbmd0aCAtIDFdKSB7XG4gICAgcmV0dXJuICcnO1xuICB9XG5cbiAgZm9yIChpID0gMDsgaSA8IHN0cjEubGVuZ3RoICYmIGkgPCBzdHIyLmxlbmd0aDsgaSsrKSB7XG4gICAgaWYgKHN0cjFbc3RyMS5sZW5ndGggLSAoaSArIDEpXSAhPSBzdHIyW3N0cjIubGVuZ3RoIC0gKGkgKyAxKV0pIHtcbiAgICAgIHJldHVybiBzdHIxLnNsaWNlKC1pKTtcbiAgICB9XG4gIH1cbiAgcmV0dXJuIHN0cjEuc2xpY2UoLWkpO1xufVxuXG5leHBvcnQgZnVuY3Rpb24gcmVwbGFjZVByZWZpeChzdHJpbmcsIG9sZFByZWZpeCwgbmV3UHJlZml4KSB7XG4gIGlmIChzdHJpbmcuc2xpY2UoMCwgb2xkUHJlZml4Lmxlbmd0aCkgIT0gb2xkUHJlZml4KSB7XG4gICAgdGhyb3cgRXJyb3IoYHN0cmluZyAke0pTT04uc3RyaW5naWZ5KHN0cmluZyl9IGRvZXNuJ3Qgc3RhcnQgd2l0aCBwcmVmaXggJHtKU09OLnN0cmluZ2lmeShvbGRQcmVmaXgpfTsgdGhpcyBpcyBhIGJ1Z2ApO1xuICB9XG4gIHJldHVybiBuZXdQcmVmaXggKyBzdHJpbmcuc2xpY2Uob2xkUHJlZml4Lmxlbmd0aCk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiByZXBsYWNlU3VmZml4KHN0cmluZywgb2xkU3VmZml4LCBuZXdTdWZmaXgpIHtcbiAgaWYgKCFvbGRTdWZmaXgpIHtcbiAgICByZXR1cm4gc3RyaW5nICsgbmV3U3VmZml4O1xuICB9XG5cbiAgaWYgKHN0cmluZy5zbGljZSgtb2xkU3VmZml4Lmxlbmd0aCkgIT0gb2xkU3VmZml4KSB7XG4gICAgdGhyb3cgRXJyb3IoYHN0cmluZyAke0pTT04uc3RyaW5naWZ5KHN0cmluZyl9IGRvZXNuJ3QgZW5kIHdpdGggc3VmZml4ICR7SlNPTi5zdHJpbmdpZnkob2xkU3VmZml4KX07IHRoaXMgaXMgYSBidWdgKTtcbiAgfVxuICByZXR1cm4gc3RyaW5nLnNsaWNlKDAsIC1vbGRTdWZmaXgubGVuZ3RoKSArIG5ld1N1ZmZpeDtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIHJlbW92ZVByZWZpeChzdHJpbmcsIG9sZFByZWZpeCkge1xuICByZXR1cm4gcmVwbGFjZVByZWZpeChzdHJpbmcsIG9sZFByZWZpeCwgJycpO1xufVxuXG5leHBvcnQgZnVuY3Rpb24gcmVtb3ZlU3VmZml4KHN0cmluZywgb2xkU3VmZml4KSB7XG4gIHJldHVybiByZXBsYWNlU3VmZml4KHN0cmluZywgb2xkU3VmZml4LCAnJyk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBtYXhpbXVtT3ZlcmxhcChzdHJpbmcxLCBzdHJpbmcyKSB7XG4gIHJldHVybiBzdHJpbmcyLnNsaWNlKDAsIG92ZXJsYXBDb3VudChzdHJpbmcxLCBzdHJpbmcyKSk7XG59XG5cbi8vIE5pY2tlZCBmcm9tIGh0dHBzOi8vc3RhY2tvdmVyZmxvdy5jb20vYS82MDQyMjg1My8xNzA5NTg3XG5mdW5jdGlvbiBvdmVybGFwQ291bnQoYSwgYikge1xuICAvLyBEZWFsIHdpdGggY2FzZXMgd2hlcmUgdGhlIHN0cmluZ3MgZGlmZmVyIGluIGxlbmd0aFxuICBsZXQgc3RhcnRBID0gMDtcbiAgaWYgKGEubGVuZ3RoID4gYi5sZW5ndGgpIHsgc3RhcnRBID0gYS5sZW5ndGggLSBiLmxlbmd0aDsgfVxuICBsZXQgZW5kQiA9IGIubGVuZ3RoO1xuICBpZiAoYS5sZW5ndGggPCBiLmxlbmd0aCkgeyBlbmRCID0gYS5sZW5ndGg7IH1cbiAgLy8gQ3JlYXRlIGEgYmFjay1yZWZlcmVuY2UgZm9yIGVhY2ggaW5kZXhcbiAgLy8gICB0aGF0IHNob3VsZCBiZSBmb2xsb3dlZCBpbiBjYXNlIG9mIGEgbWlzbWF0Y2guXG4gIC8vICAgV2Ugb25seSBuZWVkIEIgdG8gbWFrZSB0aGVzZSByZWZlcmVuY2VzOlxuICBsZXQgbWFwID0gQXJyYXkoZW5kQik7XG4gIGxldCBrID0gMDsgLy8gSW5kZXggdGhhdCBsYWdzIGJlaGluZCBqXG4gIG1hcFswXSA9IDA7XG4gIGZvciAobGV0IGogPSAxOyBqIDwgZW5kQjsgaisrKSB7XG4gICAgICBpZiAoYltqXSA9PSBiW2tdKSB7XG4gICAgICAgICAgbWFwW2pdID0gbWFwW2tdOyAvLyBza2lwIG92ZXIgdGhlIHNhbWUgY2hhcmFjdGVyIChvcHRpb25hbCBvcHRpbWlzYXRpb24pXG4gICAgICB9IGVsc2Uge1xuICAgICAgICAgIG1hcFtqXSA9IGs7XG4gICAgICB9XG4gICAgICB3aGlsZSAoayA+IDAgJiYgYltqXSAhPSBiW2tdKSB7IGsgPSBtYXBba107IH1cbiAgICAgIGlmIChiW2pdID09IGJba10pIHsgaysrOyB9XG4gIH1cbiAgLy8gUGhhc2UgMjogdXNlIHRoZXNlIHJlZmVyZW5jZXMgd2hpbGUgaXRlcmF0aW5nIG92ZXIgQVxuICBrID0gMDtcbiAgZm9yIChsZXQgaSA9IHN0YXJ0QTsgaSA8IGEubGVuZ3RoOyBpKyspIHtcbiAgICAgIHdoaWxlIChrID4gMCAmJiBhW2ldICE9IGJba10pIHsgayA9IG1hcFtrXTsgfVxuICAgICAgaWYgKGFbaV0gPT0gYltrXSkgeyBrKys7IH1cbiAgfVxuICByZXR1cm4gaztcbn1cblxuXG4vKipcbiAqIFJldHVybnMgdHJ1ZSBpZiB0aGUgc3RyaW5nIGNvbnNpc3RlbnRseSB1c2VzIFdpbmRvd3MgbGluZSBlbmRpbmdzLlxuICovXG5leHBvcnQgZnVuY3Rpb24gaGFzT25seVdpbkxpbmVFbmRpbmdzKHN0cmluZykge1xuICByZXR1cm4gc3RyaW5nLmluY2x1ZGVzKCdcXHJcXG4nKSAmJiAhc3RyaW5nLnN0YXJ0c1dpdGgoJ1xcbicpICYmICFzdHJpbmcubWF0Y2goL1teXFxyXVxcbi8pO1xufVxuXG4vKipcbiAqIFJldHVybnMgdHJ1ZSBpZiB0aGUgc3RyaW5nIGNvbnNpc3RlbnRseSB1c2VzIFVuaXggbGluZSBlbmRpbmdzLlxuICovXG5leHBvcnQgZnVuY3Rpb24gaGFzT25seVVuaXhMaW5lRW5kaW5ncyhzdHJpbmcpIHtcbiAgcmV0dXJuICFzdHJpbmcuaW5jbHVkZXMoJ1xcclxcbicpICYmIHN0cmluZy5pbmNsdWRlcygnXFxuJyk7XG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7QUFBTyxTQUFTQSxtQkFBbUJBLENBQUNDLElBQUksRUFBRUMsSUFBSSxFQUFFO0VBQzlDLElBQUlDLENBQUM7RUFDTCxLQUFLQSxDQUFDLEdBQUcsQ0FBQyxFQUFFQSxDQUFDLEdBQUdGLElBQUksQ0FBQ0csTUFBTSxJQUFJRCxDQUFDLEdBQUdELElBQUksQ0FBQ0UsTUFBTSxFQUFFRCxDQUFDLEVBQUUsRUFBRTtJQUNuRCxJQUFJRixJQUFJLENBQUNFLENBQUMsQ0FBQyxJQUFJRCxJQUFJLENBQUNDLENBQUMsQ0FBQyxFQUFFO01BQ3RCLE9BQU9GLElBQUksQ0FBQ0ksS0FBSyxDQUFDLENBQUMsRUFBRUYsQ0FBQyxDQUFDO0lBQ3pCO0VBQ0Y7RUFDQSxPQUFPRixJQUFJLENBQUNJLEtBQUssQ0FBQyxDQUFDLEVBQUVGLENBQUMsQ0FBQztBQUN6QjtBQUVPLFNBQVNHLG1CQUFtQkEsQ0FBQ0wsSUFBSSxFQUFFQyxJQUFJLEVBQUU7RUFDOUMsSUFBSUMsQ0FBQzs7RUFFTDtFQUNBO0VBQ0E7RUFDQSxJQUFJLENBQUNGLElBQUksSUFBSSxDQUFDQyxJQUFJLElBQUlELElBQUksQ0FBQ0EsSUFBSSxDQUFDRyxNQUFNLEdBQUcsQ0FBQyxDQUFDLElBQUlGLElBQUksQ0FBQ0EsSUFBSSxDQUFDRSxNQUFNLEdBQUcsQ0FBQyxDQUFDLEVBQUU7SUFDcEUsT0FBTyxFQUFFO0VBQ1g7RUFFQSxLQUFLRCxDQUFDLEdBQUcsQ0FBQyxFQUFFQSxDQUFDLEdBQUdGLElBQUksQ0FBQ0csTUFBTSxJQUFJRCxDQUFDLEdBQUdELElBQUksQ0FBQ0UsTUFBTSxFQUFFRCxDQUFDLEVBQUUsRUFBRTtJQUNuRCxJQUFJRixJQUFJLENBQUNBLElBQUksQ0FBQ0csTUFBTSxJQUFJRCxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsSUFBSUQsSUFBSSxDQUFDQSxJQUFJLENBQUNFLE1BQU0sSUFBSUQsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLEVBQUU7TUFDOUQsT0FBT0YsSUFBSSxDQUFDSSxLQUFLLENBQUMsQ0FBQ0YsQ0FBQyxDQUFDO0lBQ3ZCO0VBQ0Y7RUFDQSxPQUFPRixJQUFJLENBQUNJLEtBQUssQ0FBQyxDQUFDRixDQUFDLENBQUM7QUFDdkI7QUFFTyxTQUFTSSxhQUFhQSxDQUFDQyxNQUFNLEVBQUVDLFNBQVMsRUFBRUMsU0FBUyxFQUFFO0VBQzFELElBQUlGLE1BQU0sQ0FBQ0gsS0FBSyxDQUFDLENBQUMsRUFBRUksU0FBUyxDQUFDTCxNQUFNLENBQUMsSUFBSUssU0FBUyxFQUFFO0lBQ2xELE1BQU1FLEtBQUs7SUFBQTtJQUFBLFVBQUFDLE1BQUE7SUFBQTtJQUFXQyxJQUFJLENBQUNDLFNBQVMsQ0FBQ04sTUFBTSxDQUFDLGlDQUFBSSxNQUFBLENBQThCQyxJQUFJLENBQUNDLFNBQVMsQ0FBQ0wsU0FBUyxDQUFDLG9CQUFpQixDQUFDO0VBQ3ZIO0VBQ0EsT0FBT0MsU0FBUyxHQUFHRixNQUFNLENBQUNILEtBQUssQ0FBQ0ksU0FBUyxDQUFDTCxNQUFNLENBQUM7QUFDbkQ7QUFFTyxTQUFTVyxhQUFhQSxDQUFDUCxNQUFNLEVBQUVRLFNBQVMsRUFBRUMsU0FBUyxFQUFFO0VBQzFELElBQUksQ0FBQ0QsU0FBUyxFQUFFO0lBQ2QsT0FBT1IsTUFBTSxHQUFHUyxTQUFTO0VBQzNCO0VBRUEsSUFBSVQsTUFBTSxDQUFDSCxLQUFLLENBQUMsQ0FBQ1csU0FBUyxDQUFDWixNQUFNLENBQUMsSUFBSVksU0FBUyxFQUFFO0lBQ2hELE1BQU1MLEtBQUs7SUFBQTtJQUFBLFVBQUFDLE1BQUE7SUFBQTtJQUFXQyxJQUFJLENBQUNDLFNBQVMsQ0FBQ04sTUFBTSxDQUFDLCtCQUFBSSxNQUFBLENBQTRCQyxJQUFJLENBQUNDLFNBQVMsQ0FBQ0UsU0FBUyxDQUFDLG9CQUFpQixDQUFDO0VBQ3JIO0VBQ0EsT0FBT1IsTUFBTSxDQUFDSCxLQUFLLENBQUMsQ0FBQyxFQUFFLENBQUNXLFNBQVMsQ0FBQ1osTUFBTSxDQUFDLEdBQUdhLFNBQVM7QUFDdkQ7QUFFTyxTQUFTQyxZQUFZQSxDQUFDVixNQUFNLEVBQUVDLFNBQVMsRUFBRTtFQUM5QyxPQUFPRixhQUFhLENBQUNDLE1BQU0sRUFBRUMsU0FBUyxFQUFFLEVBQUUsQ0FBQztBQUM3QztBQUVPLFNBQVNVLFlBQVlBLENBQUNYLE1BQU0sRUFBRVEsU0FBUyxFQUFFO0VBQzlDLE9BQU9ELGFBQWEsQ0FBQ1AsTUFBTSxFQUFFUSxTQUFTLEVBQUUsRUFBRSxDQUFDO0FBQzdDO0FBRU8sU0FBU0ksY0FBY0EsQ0FBQ0MsT0FBTyxFQUFFQyxPQUFPLEVBQUU7RUFDL0MsT0FBT0EsT0FBTyxDQUFDakIsS0FBSyxDQUFDLENBQUMsRUFBRWtCLFlBQVksQ0FBQ0YsT0FBTyxFQUFFQyxPQUFPLENBQUMsQ0FBQztBQUN6RDs7QUFFQTtBQUNBLFNBQVNDLFlBQVlBLENBQUNDLENBQUMsRUFBRUMsQ0FBQyxFQUFFO0VBQzFCO0VBQ0EsSUFBSUMsTUFBTSxHQUFHLENBQUM7RUFDZCxJQUFJRixDQUFDLENBQUNwQixNQUFNLEdBQUdxQixDQUFDLENBQUNyQixNQUFNLEVBQUU7SUFBRXNCLE1BQU0sR0FBR0YsQ0FBQyxDQUFDcEIsTUFBTSxHQUFHcUIsQ0FBQyxDQUFDckIsTUFBTTtFQUFFO0VBQ3pELElBQUl1QixJQUFJLEdBQUdGLENBQUMsQ0FBQ3JCLE1BQU07RUFDbkIsSUFBSW9CLENBQUMsQ0FBQ3BCLE1BQU0sR0FBR3FCLENBQUMsQ0FBQ3JCLE1BQU0sRUFBRTtJQUFFdUIsSUFBSSxHQUFHSCxDQUFDLENBQUNwQixNQUFNO0VBQUU7RUFDNUM7RUFDQTtFQUNBO0VBQ0EsSUFBSXdCLEdBQUcsR0FBR0MsS0FBSyxDQUFDRixJQUFJLENBQUM7RUFDckIsSUFBSUcsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDO0VBQ1hGLEdBQUcsQ0FBQyxDQUFDLENBQUMsR0FBRyxDQUFDO0VBQ1YsS0FBSyxJQUFJRyxDQUFDLEdBQUcsQ0FBQyxFQUFFQSxDQUFDLEdBQUdKLElBQUksRUFBRUksQ0FBQyxFQUFFLEVBQUU7SUFDM0IsSUFBSU4sQ0FBQyxDQUFDTSxDQUFDLENBQUMsSUFBSU4sQ0FBQyxDQUFDSyxDQUFDLENBQUMsRUFBRTtNQUNkRixHQUFHLENBQUNHLENBQUMsQ0FBQyxHQUFHSCxHQUFHLENBQUNFLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDckIsQ0FBQyxNQUFNO01BQ0hGLEdBQUcsQ0FBQ0csQ0FBQyxDQUFDLEdBQUdELENBQUM7SUFDZDtJQUNBLE9BQU9BLENBQUMsR0FBRyxDQUFDLElBQUlMLENBQUMsQ0FBQ00sQ0FBQyxDQUFDLElBQUlOLENBQUMsQ0FBQ0ssQ0FBQyxDQUFDLEVBQUU7TUFBRUEsQ0FBQyxHQUFHRixHQUFHLENBQUNFLENBQUMsQ0FBQztJQUFFO0lBQzVDLElBQUlMLENBQUMsQ0FBQ00sQ0FBQyxDQUFDLElBQUlOLENBQUMsQ0FBQ0ssQ0FBQyxDQUFDLEVBQUU7TUFBRUEsQ0FBQyxFQUFFO0lBQUU7RUFDN0I7RUFDQTtFQUNBQSxDQUFDLEdBQUcsQ0FBQztFQUNMLEtBQUssSUFBSTNCLENBQUMsR0FBR3VCLE1BQU0sRUFBRXZCLENBQUMsR0FBR3FCLENBQUMsQ0FBQ3BCLE1BQU0sRUFBRUQsQ0FBQyxFQUFFLEVBQUU7SUFDcEMsT0FBTzJCLENBQUMsR0FBRyxDQUFDLElBQUlOLENBQUMsQ0FBQ3JCLENBQUMsQ0FBQyxJQUFJc0IsQ0FBQyxDQUFDSyxDQUFDLENBQUMsRUFBRTtNQUFFQSxDQUFDLEdBQUdGLEdBQUcsQ0FBQ0UsQ0FBQyxDQUFDO0lBQUU7SUFDNUMsSUFBSU4sQ0FBQyxDQUFDckIsQ0FBQyxDQUFDLElBQUlzQixDQUFDLENBQUNLLENBQUMsQ0FBQyxFQUFFO01BQUVBLENBQUMsRUFBRTtJQUFFO0VBQzdCO0VBQ0EsT0FBT0EsQ0FBQztBQUNWOztBQUdBO0FBQ0E7QUFDQTtBQUNPLFNBQVNFLHFCQUFxQkEsQ0FBQ3hCLE1BQU0sRUFBRTtFQUM1QyxPQUFPQSxNQUFNLENBQUN5QixRQUFRLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQ3pCLE1BQU0sQ0FBQzBCLFVBQVUsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDMUIsTUFBTSxDQUFDMkIsS0FBSyxDQUFDLFNBQVMsQ0FBQztBQUN4Rjs7QUFFQTtBQUNBO0FBQ0E7QUFDTyxTQUFTQyxzQkFBc0JBLENBQUM1QixNQUFNLEVBQUU7RUFDN0MsT0FBTyxDQUFDQSxNQUFNLENBQUN5QixRQUFRLENBQUMsTUFBTSxDQUFDLElBQUl6QixNQUFNLENBQUN5QixRQUFRLENBQUMsSUFBSSxDQUFDO0FBQzFEIiwiaWdub3JlTGlzdCI6W119 { "name": "diff", "version": "7.0.0", "description": "A JavaScript text diff implementation.", "keywords": [ "diff", "jsdiff", "compare", "patch", "text", "json", "css", "javascript" ], "maintainers": [ "Kevin Decker (http://incaseofstairs.com)", "Mark Amery " ], "bugs": { "email": "kpdecker@gmail.com", "url": "http://github.com/kpdecker/jsdiff/issues" }, "license": "BSD-3-Clause", "repository": { "type": "git", "url": "git://github.com/kpdecker/jsdiff.git" }, "engines": { "node": ">=0.3.1" }, "main": "./lib/index.js", "module": "./lib/index.es6.js", "browser": "./dist/diff.js", "unpkg": "./dist/diff.js", "exports": { ".": { "import": "./lib/index.mjs", "require": "./lib/index.js" }, "./package.json": "./package.json", "./": "./", "./*": "./*" }, "scripts": { "clean": "rm -rf lib/ dist/", "build:node": "yarn babel --out-dir lib --source-maps=inline src", "test": "grunt" }, "devDependencies": { "@babel/cli": "^7.24.1", "@babel/core": "^7.24.1", "@babel/plugin-transform-modules-commonjs": "^7.24.1", "@babel/preset-env": "^7.24.1", "@babel/register": "^7.23.7", "@colors/colors": "^1.6.0", "babel-eslint": "^10.0.1", "babel-loader": "^9.1.3", "chai": "^4.2.0", "eslint": "^5.12.0", "grunt": "^1.6.1", "grunt-babel": "^8.0.0", "grunt-cli": "^1.4.3", "grunt-contrib-clean": "^2.0.1", "grunt-contrib-copy": "^1.0.0", "grunt-contrib-uglify": "^5.2.2", "grunt-contrib-watch": "^1.1.0", "grunt-eslint": "^24.3.0", "grunt-exec": "^3.0.0", "grunt-karma": "^4.0.2", "grunt-mocha-istanbul": "^5.0.2", "grunt-mocha-test": "^0.13.3", "grunt-webpack": "^6.0.0", "istanbul": "github:kpdecker/istanbul", "karma": "^6.4.3", "karma-chrome-launcher": "^3.2.0", "karma-mocha": "^2.0.1", "karma-mocha-reporter": "^2.2.5", "karma-sourcemap-loader": "^0.4.0", "karma-webpack": "^5.0.1", "mocha": "^7.0.0", "rollup": "^4.13.0", "rollup-plugin-babel": "^4.2.0", "semver": "^7.6.0", "webpack": "^5.90.3", "webpack-dev-server": "^5.0.3" }, "optionalDependencies": {} } # Release Notes ## 7.0.0 Just a single (breaking) bugfix, undoing a behaviour change introduced accidentally in 6.0.0: - [#554](https://github.com/kpdecker/jsdiff/pull/554) **`diffWords` treats numbers and underscores as word characters again.** This behaviour was broken in v6.0.0. ## 6.0.0 This is a release containing many, *many* breaking changes. The objective of this release was to carry out a mass fix, in one go, of all the open bugs and design problems that required breaking changes to fix. A substantial, but exhaustive, changelog is below. [Commits](https://github.com/kpdecker/jsdiff/compare/v5.2.0...v6.0.0) - [#497](https://github.com/kpdecker/jsdiff/pull/497) **`diffWords` behavior has been radically changed.** Previously, even with `ignoreWhitespace: true`, runs of whitespace were tokens, which led to unhelpful and unintuitive diffing behavior in typical texts. Specifically, even when two texts contained overlapping passages, `diffWords` would sometimes choose to delete all the words from the old text and insert them anew in their new positions in order to avoid having to delete or insert whitespace tokens. Whitespace sequences are no longer tokens as of this release, which affects both the generated diffs and the `count`s. Runs of whitespace are still tokens in `diffWordsWithSpace`. As part of the changes to `diffWords`, **a new `.postProcess` method has been added on the base `Diff` type**, which can be overridden in custom `Diff` implementations. **`diffLines` with `ignoreWhitespace: true` will no longer ignore the insertion or deletion of entire extra lines of whitespace at the end of the text**. Previously, these would not show up as insertions or deletions, as a side effect of a hack in the base diffing algorithm meant to help ignore whitespace in `diffWords`. More generally, **the undocumented special handling in the core algorithm for ignored terminals has been removed entirely.** (This special case behavior used to rewrite the final two change objects in a scenario where the final change object was an addition or deletion and its `value` was treated as equal to the empty string when compared using the diff object's `.equals` method.) - [#500](https://github.com/kpdecker/jsdiff/pull/500) **`diffChars` now diffs Unicode code points** instead of UTF-16 code units. - [#508](https://github.com/kpdecker/jsdiff/pull/508) **`parsePatch` now always runs in what was previously "strict" mode; the undocumented `strict` option has been removed.** Previously, by default, `parsePatch` (and other patch functions that use it under the hood to parse patches) would accept a patch where the line counts in the headers were inconsistent with the actual patch content - e.g. where a hunk started with the header `@@ -1,3 +1,6 @@`, indicating that the content below spanned 3 lines in the old file and 6 lines in the new file, but then the actual content below the header consisted of some different number of lines, say 10 lines of context, 5 deletions, and 1 insertion. Actually trying to work with these patches using `applyPatch` or `merge`, however, would produce incorrect results instead of just ignoring the incorrect headers, making this "feature" more of a trap than something actually useful. It's been ripped out, and now we are always "strict" and will reject patches where the line counts in the headers aren't consistent with the actual patch content. - [#435](https://github.com/kpdecker/jsdiff/pull/435) **Fix `parsePatch` handling of control characters.** `parsePatch` used to interpret various unusual control characters - namely vertical tabs, form feeds, lone carriage returns without a line feed, and EBCDIC NELs - as line breaks when parsing a patch file. This was inconsistent with the behavior of both JsDiff's own `diffLines` method and also the Unix `diff` and `patch` utils, which all simply treat those control characters as ordinary characters. The result of this discrepancy was that some well-formed patches - produced either by `diff` or by JsDiff itself and handled properly by the `patch` util - would be wrongly parsed by `parsePatch`, with the effect that it would disregard the remainder of a hunk after encountering one of these control characters. - [#439](https://github.com/kpdecker/jsdiff/pull/439) **Prefer diffs that order deletions before insertions.** When faced with a choice between two diffs with an equal total edit distance, the Myers diff algorithm generally prefers one that does deletions before insertions rather than insertions before deletions. For instance, when diffing `abcd` against `acbd`, it will prefer a diff that says to delete the `b` and then insert a new `b` after the `c`, over a diff that says to insert a `c` before the `b` and then delete the existing `c`. JsDiff deviated from the published Myers algorithm in a way that led to it having the opposite preference in many cases, including that example. This is now fixed, meaning diffs output by JsDiff will more accurately reflect what the published Myers diff algorithm would output. - [#455](https://github.com/kpdecker/jsdiff/pull/455) **The `added` and `removed` properties of change objects are now guaranteed to be set to a boolean value.** (Previously, they would be set to `undefined` or omitted entirely instead of setting them to false.) - [#464](https://github.com/kpdecker/jsdiff/pull/464) Specifying `{maxEditLength: 0}` now sets a max edit length of 0 instead of no maximum. - [#460](https://github.com/kpdecker/jsdiff/pull/460) **Added `oneChangePerToken` option.** - [#467](https://github.com/kpdecker/jsdiff/pull/467) **Consistent ordering of arguments to `comparator(left, right)`.** Values from the old array will now consistently be passed as the first argument (`left`) and values from the new array as the second argument (`right`). Previously this was almost (but not quite) always the other way round. - [#480](https://github.com/kpdecker/jsdiff/pull/480) **Passing `maxEditLength` to `createPatch` & `createTwoFilesPatch` now works properly** (i.e. returns undefined if the max edit distance is exceeded; previous behavior was to crash with a `TypeError` if the edit distance was exceeded). - [#486](https://github.com/kpdecker/jsdiff/pull/486) **The `ignoreWhitespace` option of `diffLines` behaves more sensibly now.** `value`s in returned change objects now include leading/trailing whitespace even when `ignoreWhitespace` is used, just like how with `ignoreCase` the `value`s still reflect the case of one of the original texts instead of being all-lowercase. `ignoreWhitespace` is also now compatible with `newlineIsToken`. Finally, **`diffTrimmedLines` is deprecated** (and removed from the docs) in favour of using `diffLines` with `ignoreWhitespace: true`; the two are, and always have been, equivalent. - [#490](https://github.com/kpdecker/jsdiff/pull/490) **When calling diffing functions in async mode by passing a `callback` option, the diff result will now be passed as the *first* argument to the callback instead of the second.** (Previously, the first argument was never used at all and would always have value `undefined`.) - [#489](github.com/kpdecker/jsdiff/pull/489) **`this.options` no longer exists on `Diff` objects.** Instead, `options` is now passed as an argument to methods that rely on options, like `equals(left, right, options)`. This fixes a race condition in async mode, where diffing behaviour could be changed mid-execution if a concurrent usage of the same `Diff` instances overwrote its `options`. - [#518](https://github.com/kpdecker/jsdiff/pull/518) **`linedelimiters` no longer exists** on patch objects; instead, when a patch with Windows-style CRLF line endings is parsed, **the lines in `lines` will end with `\r`**. There is now a **new `autoConvertLineEndings` option, on by default**, which makes it so that when a patch with Windows-style line endings is applied to a source file with Unix style line endings, the patch gets autoconverted to use Unix-style line endings, and when a patch with Unix-style line endings is applied to a source file with Windows-style line endings, it gets autoconverted to use Windows-style line endings. - [#521](https://github.com/kpdecker/jsdiff/pull/521) **the `callback` option is now supported by `structuredPatch`, `createPatch - [#529](https://github.com/kpdecker/jsdiff/pull/529) **`parsePatch` can now parse patches where lines starting with `--` or `++` are deleted/inserted**; previously, there were edge cases where the parser would choke on valid patches or give wrong results. - [#530](https://github.com/kpdecker/jsdiff/pull/530) **Added `ignoreNewlineAtEof` option` to `diffLines`** - [#533](https://github.com/kpdecker/jsdiff/pull/533) **`applyPatch` uses an entirely new algorithm for fuzzy matching.** Differences between the old and new algorithm are as follows: * The `fuzzFactor` now indicates the maximum [*Levenshtein* distance](https://en.wikipedia.org/wiki/Levenshtein_distance) that there can be between the context shown in a hunk and the actual file content at a location where we try to apply the hunk. (Previously, it represented a maximum [*Hamming* distance](https://en.wikipedia.org/wiki/Hamming_distance), meaning that a single insertion or deletion in the source file could stop a hunk from applying even with a high `fuzzFactor`.) * A hunk containing a deletion can now only be applied in a context where the line to be deleted actually appears verbatim. (Previously, as long as enough context lines in the hunk matched, `applyPatch` would apply the hunk anyway and delete a completely different line.) * The context line immediately before and immediately after an insertion must match exactly between the hunk and the file for a hunk to apply. (Previously this was not required.) - [#535](https://github.com/kpdecker/jsdiff/pull/535) **A bug in patch generation functions is now fixed** that would sometimes previously cause `\ No newline at end of file` to appear in the wrong place in the generated patch, resulting in the patch being invalid. - [#535](https://github.com/kpdecker/jsdiff/pull/535) **Passing `newlineIsToken: true` to *patch*-generation functions is no longer allowed.** (Passing it to `diffLines` is still supported - it's only functions like `createPatch` where passing `newlineIsToken` is now an error.) Allowing it to be passed never really made sense, since in cases where the option had any effect on the output at all, the effect tended to be causing a garbled patch to be created that couldn't actually be applied to the source file. - [#539](https://github.com/kpdecker/jsdiff/pull/539) **`diffWords` now takes an optional `intlSegmenter` option** which should be an `Intl.Segmenter` with word-level granularity. This provides better tokenization of text into words than the default behaviour, even for English but especially for some other languages for which the default behaviour is poor. ## v5.2.0 [Commits](https://github.com/kpdecker/jsdiff/compare/v5.1.0...v5.2.0) - [#411](https://github.com/kpdecker/jsdiff/pull/411) Big performance improvement. Previously an O(n) array-copying operation inside the innermost loop of jsdiff's base diffing code increased the overall worst-case time complexity of computing a diff from O(n²) to O(n³). This is now fixed, bringing the worst-case time complexity down to what it theoretically should be for a Myers diff implementation. - [#448](https://github.com/kpdecker/jsdiff/pull/411) Performance improvement. Diagonals whose furthest-reaching D-path would go off the edge of the edit graph are now skipped, rather than being pointlessly considered as called for by the original Myers diff algorithm. This dramatically speeds up computing diffs where the new text just appends or truncates content at the end of the old text. - [#351](https://github.com/kpdecker/jsdiff/issues/351) Importing from the lib folder - e.g. `require("diff/lib/diff/word.js")` - will work again now. This had been broken for users on the latest version of Node since Node 17.5.0, which changed how Node interprets the `exports` property in jsdiff's `package.json` file. - [#344](https://github.com/kpdecker/jsdiff/issues/344) `diffLines`, `createTwoFilesPatch`, and other patch-creation methods now take an optional `stripTrailingCr: true` option which causes Windows-style `\r\n` line endings to be replaced with Unix-style `\n` line endings before calculating the diff, just like GNU `diff`'s `--strip-trailing-cr` flag. - [#451](https://github.com/kpdecker/jsdiff/pull/451) Added `diff.formatPatch`. - [#450](https://github.com/kpdecker/jsdiff/pull/450) Added `diff.reversePatch`. - [#478](https://github.com/kpdecker/jsdiff/pull/478) Added `timeout` option. ## v5.1.0 - [#365](https://github.com/kpdecker/jsdiff/issues/365) Allow early termination to limit execution time with degenerate cases [Commits](https://github.com/kpdecker/jsdiff/compare/v5.0.0...v5.1.0) ## v5.0.0 - Breaking: UMD export renamed from `JsDiff` to `Diff`. - Breaking: Newlines separated into separate tokens for word diff. - Breaking: Unified diffs now match ["quirks"](https://www.artima.com/weblogs/viewpost.jsp?thread=164293) [Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.1...v5.0.0) ## v4.0.1 - January 6th, 2019 - Fix main reference path - b826104 [Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.0...v4.0.1) ## v4.0.0 - January 5th, 2019 - [#94](https://github.com/kpdecker/jsdiff/issues/94) - Missing "No newline at end of file" when comparing two texts that do not end in newlines ([@federicotdn](https://api.github.com/users/federicotdn)) - [#227](https://github.com/kpdecker/jsdiff/issues/227) - Licence - [#199](https://github.com/kpdecker/jsdiff/issues/199) - Import statement for jsdiff - [#159](https://github.com/kpdecker/jsdiff/issues/159) - applyPatch affecting wrong line number with with new lines - [#8](https://github.com/kpdecker/jsdiff/issues/8) - A new state "replace" - Drop ie9 from karma targets - 79c31bd - Upgrade deps. Convert from webpack to rollup - 2c1a29c - Make ()[]"' as word boundaries between each other - f27b899 - jsdiff: Replaced phantomJS by chrome - ec3114e - Add yarn.lock to .npmignore - 29466d8 Compatibility notes: - Bower and Component packages no longer supported [Commits](https://github.com/kpdecker/jsdiff/compare/v3.5.0...v4.0.0) ## v3.5.0 - March 4th, 2018 - Omit redundant slice in join method of diffArrays - 1023590 - Support patches with empty lines - fb0f208 - Accept a custom JSON replacer function for JSON diffing - 69c7f0a - Optimize parch header parser - 2aec429 - Fix typos - e89c832 [Commits](https://github.com/kpdecker/jsdiff/compare/v3.4.0...v3.5.0) ## v3.4.0 - October 7th, 2017 - [#183](https://github.com/kpdecker/jsdiff/issues/183) - Feature request: ability to specify a custom equality checker for `diffArrays` - [#173](https://github.com/kpdecker/jsdiff/issues/173) - Bug: diffArrays gives wrong result on array of booleans - [#158](https://github.com/kpdecker/jsdiff/issues/158) - diffArrays will not compare the empty string in array? - comparator for custom equality checks - 30e141e - count oldLines and newLines when there are conflicts - 53bf384 - Fix: diffArrays can compare falsey items - 9e24284 - Docs: Replace grunt with npm test - 00e2f94 [Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.1...v3.4.0) ## v3.3.1 - September 3rd, 2017 - [#141](https://github.com/kpdecker/jsdiff/issues/141) - Cannot apply patch because my file delimiter is "/r/n" instead of "/n" - [#192](https://github.com/kpdecker/jsdiff/pull/192) - Fix: Bad merge when adding new files (#189) - correct spelling mistake - 21fa478 [Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.0...v3.3.1) ## v3.3.0 - July 5th, 2017 - [#114](https://github.com/kpdecker/jsdiff/issues/114) - /patch/merge not exported - Gracefully accept invalid newStart in hunks, same as patch(1) does. - d8a3635 - Use regex rather than starts/ends with for parsePatch - 6cab62c - Add browser flag - e64f674 - refactor: simplified code a bit more - 8f8e0f2 - refactor: simplified code a bit - b094a6f - fix: some corrections re ignoreCase option - 3c78fd0 - ignoreCase option - 3cbfbb5 - Sanitize filename while parsing patches - 2fe8129 - Added better installation methods - aced50b - Simple export of functionality - 8690f31 [Commits](https://github.com/kpdecker/jsdiff/compare/v3.2.0...v3.3.0) ## v3.2.0 - December 26th, 2016 - [#156](https://github.com/kpdecker/jsdiff/pull/156) - Add `undefinedReplacement` option to `diffJson` ([@ewnd9](https://api.github.com/users/ewnd9)) - [#154](https://github.com/kpdecker/jsdiff/pull/154) - Add `examples` and `images` to `.npmignore`. ([@wtgtybhertgeghgtwtg](https://api.github.com/users/wtgtybhertgeghgtwtg)) - [#153](https://github.com/kpdecker/jsdiff/pull/153) - feat(structuredPatch): Pass options to diffLines ([@Kiougar](https://api.github.com/users/Kiougar)) [Commits](https://github.com/kpdecker/jsdiff/compare/v3.1.0...v3.2.0) ## v3.1.0 - November 27th, 2016 - [#146](https://github.com/kpdecker/jsdiff/pull/146) - JsDiff.diffArrays to compare arrays ([@wvanderdeijl](https://api.github.com/users/wvanderdeijl)) - [#144](https://github.com/kpdecker/jsdiff/pull/144) - Split file using all possible line delimiter instead of hard-coded "/n" and join lines back using the original delimiters ([@soulbeing](https://api.github.com/users/soulbeing)) [Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.1...v3.1.0) ## v3.0.1 - October 9th, 2016 - [#139](https://github.com/kpdecker/jsdiff/pull/139) - Make README.md look nicer in npmjs.com ([@takenspc](https://api.github.com/users/takenspc)) - [#135](https://github.com/kpdecker/jsdiff/issues/135) - parsePatch combines patches from multiple files into a single IUniDiff when there is no "Index" line ([@ramya-rao-a](https://api.github.com/users/ramya-rao-a)) - [#124](https://github.com/kpdecker/jsdiff/issues/124) - IE7/IE8 failure since 2.0.0 ([@boneskull](https://api.github.com/users/boneskull)) [Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.0...v3.0.1) ## v3.0.0 - August 23rd, 2016 - [#130](https://github.com/kpdecker/jsdiff/pull/130) - Add callback argument to applyPatches `patched` option ([@piranna](https://api.github.com/users/piranna)) - [#120](https://github.com/kpdecker/jsdiff/pull/120) - Correctly handle file names containing spaces ([@adius](https://api.github.com/users/adius)) - [#119](https://github.com/kpdecker/jsdiff/pull/119) - Do single reflow ([@wifiextender](https://api.github.com/users/wifiextender)) - [#117](https://github.com/kpdecker/jsdiff/pull/117) - Make more usable with long strings. ([@abnbgist](https://api.github.com/users/abnbgist)) Compatibility notes: - applyPatches patch callback now is async and requires the callback be called to continue operation [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.3...v3.0.0) ## v2.2.3 - May 31st, 2016 - [#118](https://github.com/kpdecker/jsdiff/pull/118) - Add a fix for applying 0-length destination patches ([@chaaz](https://api.github.com/users/chaaz)) - [#115](https://github.com/kpdecker/jsdiff/pull/115) - Fixed grammar in README ([@krizalys](https://api.github.com/users/krizalys)) - [#113](https://github.com/kpdecker/jsdiff/pull/113) - fix typo ([@vmazare](https://api.github.com/users/vmazare)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.2...v2.2.3) ## v2.2.2 - March 13th, 2016 - [#102](https://github.com/kpdecker/jsdiff/issues/102) - diffJson with dates, returns empty curly braces ([@dr-dimitru](https://api.github.com/users/dr-dimitru)) - [#97](https://github.com/kpdecker/jsdiff/issues/97) - Whitespaces & diffWords ([@faiwer](https://api.github.com/users/faiwer)) - [#92](https://github.com/kpdecker/jsdiff/pull/92) - Fixes typo in the readme ([@bg451](https://api.github.com/users/bg451)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.1...v2.2.2) ## v2.2.1 - November 12th, 2015 - [#89](https://github.com/kpdecker/jsdiff/pull/89) - add in display selector to readme ([@FranDias](https://api.github.com/users/FranDias)) - [#88](https://github.com/kpdecker/jsdiff/pull/88) - Split diffs based on file headers instead of 'Index:' metadata ([@piranna](https://api.github.com/users/piranna)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.1) ## v2.2.0 - October 29th, 2015 - [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu)) - [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.0) ## v2.2.0 - October 29th, 2015 - [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu)) - [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.3...v2.2.0) ## v2.1.3 - September 30th, 2015 - [#78](https://github.com/kpdecker/jsdiff/pull/78) - fix: error throwing when apply patch to empty string ([@21paradox](https://api.github.com/users/21paradox)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.2...v2.1.3) ## v2.1.2 - September 23rd, 2015 - [#76](https://github.com/kpdecker/jsdiff/issues/76) - diff headers give error ([@piranna](https://api.github.com/users/piranna)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.1...v2.1.2) ## v2.1.1 - September 9th, 2015 - [#73](https://github.com/kpdecker/jsdiff/issues/73) - Is applyPatches() exposed in the API? ([@davidparsson](https://api.github.com/users/davidparsson)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.0...v2.1.1) ## v2.1.0 - August 27th, 2015 - [#72](https://github.com/kpdecker/jsdiff/issues/72) - Consider using options object API for flag permutations ([@kpdecker](https://api.github.com/users/kpdecker)) - [#70](https://github.com/kpdecker/jsdiff/issues/70) - diffWords treats \n at the end as significant whitespace ([@nesQuick](https://api.github.com/users/nesQuick)) - [#69](https://github.com/kpdecker/jsdiff/issues/69) - Missing count ([@wfalkwallace](https://api.github.com/users/wfalkwallace)) - [#68](https://github.com/kpdecker/jsdiff/issues/68) - diffLines seems broken ([@wfalkwallace](https://api.github.com/users/wfalkwallace)) - [#60](https://github.com/kpdecker/jsdiff/issues/60) - Support multiple diff hunks ([@piranna](https://api.github.com/users/piranna)) - [#54](https://github.com/kpdecker/jsdiff/issues/54) - Feature Request: 3-way merge ([@mog422](https://api.github.com/users/mog422)) - [#42](https://github.com/kpdecker/jsdiff/issues/42) - Fuzz factor for applyPatch ([@stuartpb](https://api.github.com/users/stuartpb)) - Move whitespace ignore out of equals method - 542063c - Include source maps in babel output - 7f7ab21 - Merge diff/line and diff/patch implementations - 1597705 - Drop map utility method - 1ddc939 - Documentation for parsePatch and applyPatches - 27c4b77 Compatibility notes: - The undocumented ignoreWhitespace flag has been removed from the Diff equality check directly. This implementation may be copied to diff utilities if dependencies existed on this functionality. [Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.2...v2.1.0) ## v2.0.2 - August 8th, 2015 - [#67](https://github.com/kpdecker/jsdiff/issues/67) - cannot require from npm module in node ([@commenthol](https://api.github.com/users/commenthol)) - Convert to chai since we don’t support IE8 - a96bbad [Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.1...v2.0.2) ## v2.0.1 - August 7th, 2015 - Add release build at proper step - 57542fd [Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.0...v2.0.1) ## v2.0.0 - August 7th, 2015 - [#66](https://github.com/kpdecker/jsdiff/issues/66) - Add karma and sauce tests ([@kpdecker](https://api.github.com/users/kpdecker)) - [#65](https://github.com/kpdecker/jsdiff/issues/65) - Create component repository for bower ([@kpdecker](https://api.github.com/users/kpdecker)) - [#64](https://github.com/kpdecker/jsdiff/issues/64) - Automatically call removeEmpty for all tokenizer calls ([@kpdecker](https://api.github.com/users/kpdecker)) - [#62](https://github.com/kpdecker/jsdiff/pull/62) - Allow access to structured object representation of patch data ([@bittrance](https://api.github.com/users/bittrance)) - [#61](https://github.com/kpdecker/jsdiff/pull/61) - Use svg instead of png to get better image quality ([@PeterDaveHello](https://api.github.com/users/PeterDaveHello)) - [#29](https://github.com/kpdecker/jsdiff/issues/29) - word tokenizer works only for 7 bit ascii ([@plasmagunman](https://api.github.com/users/plasmagunman)) Compatibility notes: - `this.removeEmpty` is now called automatically for all instances. If this is not desired, this may be overridden on a per instance basis. - The library has been refactored to use some ES6 features. The external APIs should remain the same, but bower projects that directly referenced the repository will now have to point to the [components/jsdiff](https://github.com/components/jsdiff) repository. [Commits](https://github.com/kpdecker/jsdiff/compare/v1.4.0...v2.0.0) ## v1.4.0 - May 6th, 2015 - [#57](https://github.com/kpdecker/jsdiff/issues/57) - createPatch -> applyPatch failed. ([@mog422](https://api.github.com/users/mog422)) - [#56](https://github.com/kpdecker/jsdiff/pull/56) - Two files patch ([@rgeissert](https://api.github.com/users/rgeissert)) - [#14](https://github.com/kpdecker/jsdiff/issues/14) - Flip added and removed order? ([@jakesandlund](https://api.github.com/users/jakesandlund)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.2...v1.4.0) ## v1.3.2 - March 30th, 2015 - [#53](https://github.com/kpdecker/jsdiff/pull/53) - Updated README.MD with Bower installation instructions ([@ofbriggs](https://api.github.com/users/ofbriggs)) - [#49](https://github.com/kpdecker/jsdiff/issues/49) - Cannot read property 'oldlines' of undefined ([@nwtn](https://api.github.com/users/nwtn)) - [#44](https://github.com/kpdecker/jsdiff/issues/44) - invalid-meta jsdiff is missing "main" entry in bower.json [Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.1...v1.3.2) ## v1.3.1 - March 13th, 2015 - [#52](https://github.com/kpdecker/jsdiff/pull/52) - Fix for #51 Wrong result of JsDiff.diffLines ([@felicienfrancois](https://api.github.com/users/felicienfrancois)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.0...v1.3.1) ## v1.3.0 - March 2nd, 2015 - [#47](https://github.com/kpdecker/jsdiff/pull/47) - Adding Diff Trimmed Lines ([@JamesGould123](https://api.github.com/users/JamesGould123)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.2...v1.3.0) ## v1.2.2 - January 26th, 2015 - [#45](https://github.com/kpdecker/jsdiff/pull/45) - Fix AMD module loading ([@pedrocarrico](https://api.github.com/users/pedrocarrico)) - [#43](https://github.com/kpdecker/jsdiff/pull/43) - added a bower file ([@nbrustein](https://api.github.com/users/nbrustein)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.1...v1.2.2) ## v1.2.1 - December 26th, 2014 - [#41](https://github.com/kpdecker/jsdiff/pull/41) - change condition of using node export system. ([@ironhee](https://api.github.com/users/ironhee)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.0...v1.2.1) ## v1.2.0 - November 29th, 2014 - [#37](https://github.com/kpdecker/jsdiff/pull/37) - Add support for sentences. ([@vmariano](https://api.github.com/users/vmariano)) - [#28](https://github.com/kpdecker/jsdiff/pull/28) - Implemented diffJson ([@papandreou](https://api.github.com/users/papandreou)) - [#27](https://github.com/kpdecker/jsdiff/issues/27) - Slow to execute over diffs with a large number of changes ([@termi](https://api.github.com/users/termi)) - Allow for optional async diffing - 19385b9 - Fix diffChars implementation - eaa44ed [Commits](https://github.com/kpdecker/jsdiff/compare/v1.1.0...v1.2.0) ## v1.1.0 - November 25th, 2014 - [#33](https://github.com/kpdecker/jsdiff/pull/33) - AMD and global exports ([@ovcharik](https://api.github.com/users/ovcharik)) - [#32](https://github.com/kpdecker/jsdiff/pull/32) - Add support for component ([@vmariano](https://api.github.com/users/vmariano)) - [#31](https://github.com/kpdecker/jsdiff/pull/31) - Don't rely on Array.prototype.map ([@papandreou](https://api.github.com/users/papandreou)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.8...v1.1.0) ## v1.0.8 - December 22nd, 2013 - [#24](https://github.com/kpdecker/jsdiff/pull/24) - Handle windows newlines on non windows machines. ([@benogle](https://api.github.com/users/benogle)) - [#23](https://github.com/kpdecker/jsdiff/pull/23) - Prettied up the API formatting a little, and added basic node and web examples ([@airportyh](https://api.github.com/users/airportyh)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.7...v1.0.8) ## v1.0.7 - September 11th, 2013 - [#22](https://github.com/kpdecker/jsdiff/pull/22) - Added variant of WordDiff that doesn't ignore whitespace differences ([@papandreou](https://api.github.com/users/papandreou) - Add 0.10 to travis tests - 243a526 [Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.6...v1.0.7) ## v1.0.6 - August 30th, 2013 - [#19](https://github.com/kpdecker/jsdiff/pull/19) - Explicitly define contents of npm package ([@sindresorhus](https://api.github.com/users/sindresorhus) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.5...v1.0.6) require('@babel/register')({ ignore: ['lib', 'node_modules'] }); var eaw = {}; if ('undefined' == typeof module) { window.eastasianwidth = eaw; } else { module.exports = eaw; } eaw.eastAsianWidth = function(character) { var x = character.charCodeAt(0); var y = (character.length == 2) ? character.charCodeAt(1) : 0; var codePoint = x; if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) { x &= 0x3FF; y &= 0x3FF; codePoint = (x << 10) | y; codePoint += 0x10000; } if ((0x3000 == codePoint) || (0xFF01 <= codePoint && codePoint <= 0xFF60) || (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) { return 'F'; } if ((0x20A9 == codePoint) || (0xFF61 <= codePoint && codePoint <= 0xFFBE) || (0xFFC2 <= codePoint && codePoint <= 0xFFC7) || (0xFFCA <= codePoint && codePoint <= 0xFFCF) || (0xFFD2 <= codePoint && codePoint <= 0xFFD7) || (0xFFDA <= codePoint && codePoint <= 0xFFDC) || (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) { return 'H'; } if ((0x1100 <= codePoint && codePoint <= 0x115F) || (0x11A3 <= codePoint && codePoint <= 0x11A7) || (0x11FA <= codePoint && codePoint <= 0x11FF) || (0x2329 <= codePoint && codePoint <= 0x232A) || (0x2E80 <= codePoint && codePoint <= 0x2E99) || (0x2E9B <= codePoint && codePoint <= 0x2EF3) || (0x2F00 <= codePoint && codePoint <= 0x2FD5) || (0x2FF0 <= codePoint && codePoint <= 0x2FFB) || (0x3001 <= codePoint && codePoint <= 0x303E) || (0x3041 <= codePoint && codePoint <= 0x3096) || (0x3099 <= codePoint && codePoint <= 0x30FF) || (0x3105 <= codePoint && codePoint <= 0x312D) || (0x3131 <= codePoint && codePoint <= 0x318E) || (0x3190 <= codePoint && codePoint <= 0x31BA) || (0x31C0 <= codePoint && codePoint <= 0x31E3) || (0x31F0 <= codePoint && codePoint <= 0x321E) || (0x3220 <= codePoint && codePoint <= 0x3247) || (0x3250 <= codePoint && codePoint <= 0x32FE) || (0x3300 <= codePoint && codePoint <= 0x4DBF) || (0x4E00 <= codePoint && codePoint <= 0xA48C) || (0xA490 <= codePoint && codePoint <= 0xA4C6) || (0xA960 <= codePoint && codePoint <= 0xA97C) || (0xAC00 <= codePoint && codePoint <= 0xD7A3) || (0xD7B0 <= codePoint && codePoint <= 0xD7C6) || (0xD7CB <= codePoint && codePoint <= 0xD7FB) || (0xF900 <= codePoint && codePoint <= 0xFAFF) || (0xFE10 <= codePoint && codePoint <= 0xFE19) || (0xFE30 <= codePoint && codePoint <= 0xFE52) || (0xFE54 <= codePoint && codePoint <= 0xFE66) || (0xFE68 <= codePoint && codePoint <= 0xFE6B) || (0x1B000 <= codePoint && codePoint <= 0x1B001) || (0x1F200 <= codePoint && codePoint <= 0x1F202) || (0x1F210 <= codePoint && codePoint <= 0x1F23A) || (0x1F240 <= codePoint && codePoint <= 0x1F248) || (0x1F250 <= codePoint && codePoint <= 0x1F251) || (0x20000 <= codePoint && codePoint <= 0x2F73F) || (0x2B740 <= codePoint && codePoint <= 0x2FFFD) || (0x30000 <= codePoint && codePoint <= 0x3FFFD)) { return 'W'; } if ((0x0020 <= codePoint && codePoint <= 0x007E) || (0x00A2 <= codePoint && codePoint <= 0x00A3) || (0x00A5 <= codePoint && codePoint <= 0x00A6) || (0x00AC == codePoint) || (0x00AF == codePoint) || (0x27E6 <= codePoint && codePoint <= 0x27ED) || (0x2985 <= codePoint && codePoint <= 0x2986)) { return 'Na'; } if ((0x00A1 == codePoint) || (0x00A4 == codePoint) || (0x00A7 <= codePoint && codePoint <= 0x00A8) || (0x00AA == codePoint) || (0x00AD <= codePoint && codePoint <= 0x00AE) || (0x00B0 <= codePoint && codePoint <= 0x00B4) || (0x00B6 <= codePoint && codePoint <= 0x00BA) || (0x00BC <= codePoint && codePoint <= 0x00BF) || (0x00C6 == codePoint) || (0x00D0 == codePoint) || (0x00D7 <= codePoint && codePoint <= 0x00D8) || (0x00DE <= codePoint && codePoint <= 0x00E1) || (0x00E6 == codePoint) || (0x00E8 <= codePoint && codePoint <= 0x00EA) || (0x00EC <= codePoint && codePoint <= 0x00ED) || (0x00F0 == codePoint) || (0x00F2 <= codePoint && codePoint <= 0x00F3) || (0x00F7 <= codePoint && codePoint <= 0x00FA) || (0x00FC == codePoint) || (0x00FE == codePoint) || (0x0101 == codePoint) || (0x0111 == codePoint) || (0x0113 == codePoint) || (0x011B == codePoint) || (0x0126 <= codePoint && codePoint <= 0x0127) || (0x012B == codePoint) || (0x0131 <= codePoint && codePoint <= 0x0133) || (0x0138 == codePoint) || (0x013F <= codePoint && codePoint <= 0x0142) || (0x0144 == codePoint) || (0x0148 <= codePoint && codePoint <= 0x014B) || (0x014D == codePoint) || (0x0152 <= codePoint && codePoint <= 0x0153) || (0x0166 <= codePoint && codePoint <= 0x0167) || (0x016B == codePoint) || (0x01CE == codePoint) || (0x01D0 == codePoint) || (0x01D2 == codePoint) || (0x01D4 == codePoint) || (0x01D6 == codePoint) || (0x01D8 == codePoint) || (0x01DA == codePoint) || (0x01DC == codePoint) || (0x0251 == codePoint) || (0x0261 == codePoint) || (0x02C4 == codePoint) || (0x02C7 == codePoint) || (0x02C9 <= codePoint && codePoint <= 0x02CB) || (0x02CD == codePoint) || (0x02D0 == codePoint) || (0x02D8 <= codePoint && codePoint <= 0x02DB) || (0x02DD == codePoint) || (0x02DF == codePoint) || (0x0300 <= codePoint && codePoint <= 0x036F) || (0x0391 <= codePoint && codePoint <= 0x03A1) || (0x03A3 <= codePoint && codePoint <= 0x03A9) || (0x03B1 <= codePoint && codePoint <= 0x03C1) || (0x03C3 <= codePoint && codePoint <= 0x03C9) || (0x0401 == codePoint) || (0x0410 <= codePoint && codePoint <= 0x044F) || (0x0451 == codePoint) || (0x2010 == codePoint) || (0x2013 <= codePoint && codePoint <= 0x2016) || (0x2018 <= codePoint && codePoint <= 0x2019) || (0x201C <= codePoint && codePoint <= 0x201D) || (0x2020 <= codePoint && codePoint <= 0x2022) || (0x2024 <= codePoint && codePoint <= 0x2027) || (0x2030 == codePoint) || (0x2032 <= codePoint && codePoint <= 0x2033) || (0x2035 == codePoint) || (0x203B == codePoint) || (0x203E == codePoint) || (0x2074 == codePoint) || (0x207F == codePoint) || (0x2081 <= codePoint && codePoint <= 0x2084) || (0x20AC == codePoint) || (0x2103 == codePoint) || (0x2105 == codePoint) || (0x2109 == codePoint) || (0x2113 == codePoint) || (0x2116 == codePoint) || (0x2121 <= codePoint && codePoint <= 0x2122) || (0x2126 == codePoint) || (0x212B == codePoint) || (0x2153 <= codePoint && codePoint <= 0x2154) || (0x215B <= codePoint && codePoint <= 0x215E) || (0x2160 <= codePoint && codePoint <= 0x216B) || (0x2170 <= codePoint && codePoint <= 0x2179) || (0x2189 == codePoint) || (0x2190 <= codePoint && codePoint <= 0x2199) || (0x21B8 <= codePoint && codePoint <= 0x21B9) || (0x21D2 == codePoint) || (0x21D4 == codePoint) || (0x21E7 == codePoint) || (0x2200 == codePoint) || (0x2202 <= codePoint && codePoint <= 0x2203) || (0x2207 <= codePoint && codePoint <= 0x2208) || (0x220B == codePoint) || (0x220F == codePoint) || (0x2211 == codePoint) || (0x2215 == codePoint) || (0x221A == codePoint) || (0x221D <= codePoint && codePoint <= 0x2220) || (0x2223 == codePoint) || (0x2225 == codePoint) || (0x2227 <= codePoint && codePoint <= 0x222C) || (0x222E == codePoint) || (0x2234 <= codePoint && codePoint <= 0x2237) || (0x223C <= codePoint && codePoint <= 0x223D) || (0x2248 == codePoint) || (0x224C == codePoint) || (0x2252 == codePoint) || (0x2260 <= codePoint && codePoint <= 0x2261) || (0x2264 <= codePoint && codePoint <= 0x2267) || (0x226A <= codePoint && codePoint <= 0x226B) || (0x226E <= codePoint && codePoint <= 0x226F) || (0x2282 <= codePoint && codePoint <= 0x2283) || (0x2286 <= codePoint && codePoint <= 0x2287) || (0x2295 == codePoint) || (0x2299 == codePoint) || (0x22A5 == codePoint) || (0x22BF == codePoint) || (0x2312 == codePoint) || (0x2460 <= codePoint && codePoint <= 0x24E9) || (0x24EB <= codePoint && codePoint <= 0x254B) || (0x2550 <= codePoint && codePoint <= 0x2573) || (0x2580 <= codePoint && codePoint <= 0x258F) || (0x2592 <= codePoint && codePoint <= 0x2595) || (0x25A0 <= codePoint && codePoint <= 0x25A1) || (0x25A3 <= codePoint && codePoint <= 0x25A9) || (0x25B2 <= codePoint && codePoint <= 0x25B3) || (0x25B6 <= codePoint && codePoint <= 0x25B7) || (0x25BC <= codePoint && codePoint <= 0x25BD) || (0x25C0 <= codePoint && codePoint <= 0x25C1) || (0x25C6 <= codePoint && codePoint <= 0x25C8) || (0x25CB == codePoint) || (0x25CE <= codePoint && codePoint <= 0x25D1) || (0x25E2 <= codePoint && codePoint <= 0x25E5) || (0x25EF == codePoint) || (0x2605 <= codePoint && codePoint <= 0x2606) || (0x2609 == codePoint) || (0x260E <= codePoint && codePoint <= 0x260F) || (0x2614 <= codePoint && codePoint <= 0x2615) || (0x261C == codePoint) || (0x261E == codePoint) || (0x2640 == codePoint) || (0x2642 == codePoint) || (0x2660 <= codePoint && codePoint <= 0x2661) || (0x2663 <= codePoint && codePoint <= 0x2665) || (0x2667 <= codePoint && codePoint <= 0x266A) || (0x266C <= codePoint && codePoint <= 0x266D) || (0x266F == codePoint) || (0x269E <= codePoint && codePoint <= 0x269F) || (0x26BE <= codePoint && codePoint <= 0x26BF) || (0x26C4 <= codePoint && codePoint <= 0x26CD) || (0x26CF <= codePoint && codePoint <= 0x26E1) || (0x26E3 == codePoint) || (0x26E8 <= codePoint && codePoint <= 0x26FF) || (0x273D == codePoint) || (0x2757 == codePoint) || (0x2776 <= codePoint && codePoint <= 0x277F) || (0x2B55 <= codePoint && codePoint <= 0x2B59) || (0x3248 <= codePoint && codePoint <= 0x324F) || (0xE000 <= codePoint && codePoint <= 0xF8FF) || (0xFE00 <= codePoint && codePoint <= 0xFE0F) || (0xFFFD == codePoint) || (0x1F100 <= codePoint && codePoint <= 0x1F10A) || (0x1F110 <= codePoint && codePoint <= 0x1F12D) || (0x1F130 <= codePoint && codePoint <= 0x1F169) || (0x1F170 <= codePoint && codePoint <= 0x1F19A) || (0xE0100 <= codePoint && codePoint <= 0xE01EF) || (0xF0000 <= codePoint && codePoint <= 0xFFFFD) || (0x100000 <= codePoint && codePoint <= 0x10FFFD)) { return 'A'; } return 'N'; }; eaw.characterLength = function(character) { var code = this.eastAsianWidth(character); if (code == 'F' || code == 'W' || code == 'A') { return 2; } else { return 1; } }; // Split a string considering surrogate-pairs. function stringToArray(string) { return string.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || []; } eaw.length = function(string) { var characters = stringToArray(string); var len = 0; for (var i = 0; i < characters.length; i++) { len = len + this.characterLength(characters[i]); } return len; }; eaw.slice = function(text, start, end) { textLen = eaw.length(text) start = start ? start : 0; end = end ? end : 1; if (start < 0) { start = textLen + start; } if (end < 0) { end = textLen + end; } var result = ''; var eawLen = 0; var chars = stringToArray(text); for (var i = 0; i < chars.length; i++) { var char = chars[i]; var charLen = eaw.length(char); if (eawLen >= start - (charLen == 2 ? 1 : 0)) { if (eawLen + charLen <= end) { result += char; } else { break; } } eawLen += charLen; } return result; }; { "name": "eastasianwidth", "version": "0.2.0", "description": "Get East Asian Width from a character.", "main": "eastasianwidth.js", "files": [ "eastasianwidth.js" ], "scripts": { "test": "mocha" }, "repository": "git://github.com/komagata/eastasianwidth.git", "author": "Masaki Komagata", "license": "MIT", "devDependencies": { "mocha": "~1.9.0" } } Copyright Mathias Bynens 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. "use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}-\u{1F1FA}]|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u{1F1F7}[\u{1F1EA}\u{1F1F4}\u{1F1F8}\u{1F1FA}\u{1F1FC}]|\u{1F469}[\u{1F3FB}-\u{1F3FF}]|\u{1F1F2}[\u{1F1E6}\u{1F1E8}-\u{1F1ED}\u{1F1F0}-\u{1F1FF}]|\u{1F1E6}[\u{1F1E8}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F2}\u{1F1F4}\u{1F1F6}-\u{1F1FA}\u{1F1FC}\u{1F1FD}\u{1F1FF}]|\u{1F1F0}[\u{1F1EA}\u{1F1EC}-\u{1F1EE}\u{1F1F2}\u{1F1F3}\u{1F1F5}\u{1F1F7}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1ED}[\u{1F1F0}\u{1F1F2}\u{1F1F3}\u{1F1F7}\u{1F1F9}\u{1F1FA}]|\u{1F1E9}[\u{1F1EA}\u{1F1EC}\u{1F1EF}\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1FF}]|\u{1F1FE}[\u{1F1EA}\u{1F1F9}]|\u{1F1EC}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EE}\u{1F1F1}-\u{1F1F3}\u{1F1F5}-\u{1F1FA}\u{1F1FC}\u{1F1FE}]|\u{1F1F8}[\u{1F1E6}-\u{1F1EA}\u{1F1EC}-\u{1F1F4}\u{1F1F7}-\u{1F1F9}\u{1F1FB}\u{1F1FD}-\u{1F1FF}]|\u{1F1EB}[\u{1F1EE}-\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1F7}]|\u{1F1F5}[\u{1F1E6}\u{1F1EA}-\u{1F1ED}\u{1F1F0}-\u{1F1F3}\u{1F1F7}-\u{1F1F9}\u{1F1FC}\u{1F1FE}]|\u{1F1FB}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1EE}\u{1F1F3}\u{1F1FA}]|\u{1F1F3}[\u{1F1E6}\u{1F1E8}\u{1F1EA}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F4}\u{1F1F5}\u{1F1F7}\u{1F1FA}\u{1F1FF}]|\u{1F1E8}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1EE}\u{1F1F0}-\u{1F1F5}\u{1F1F7}\u{1F1FA}-\u{1F1FF}]|\u{1F1F1}[\u{1F1E6}-\u{1F1E8}\u{1F1EE}\u{1F1F0}\u{1F1F7}-\u{1F1FB}\u{1F1FE}]|\u{1F1FF}[\u{1F1E6}\u{1F1F2}\u{1F1FC}]|\u{1F1FC}[\u{1F1EB}\u{1F1F8}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; "use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}-\u{1F1FA}]|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u{1F1F7}[\u{1F1EA}\u{1F1F4}\u{1F1F8}\u{1F1FA}\u{1F1FC}]|\u{1F469}[\u{1F3FB}-\u{1F3FF}]|\u{1F1F2}[\u{1F1E6}\u{1F1E8}-\u{1F1ED}\u{1F1F0}-\u{1F1FF}]|\u{1F1E6}[\u{1F1E8}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F2}\u{1F1F4}\u{1F1F6}-\u{1F1FA}\u{1F1FC}\u{1F1FD}\u{1F1FF}]|\u{1F1F0}[\u{1F1EA}\u{1F1EC}-\u{1F1EE}\u{1F1F2}\u{1F1F3}\u{1F1F5}\u{1F1F7}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1ED}[\u{1F1F0}\u{1F1F2}\u{1F1F3}\u{1F1F7}\u{1F1F9}\u{1F1FA}]|\u{1F1E9}[\u{1F1EA}\u{1F1EC}\u{1F1EF}\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1FF}]|\u{1F1FE}[\u{1F1EA}\u{1F1F9}]|\u{1F1EC}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EE}\u{1F1F1}-\u{1F1F3}\u{1F1F5}-\u{1F1FA}\u{1F1FC}\u{1F1FE}]|\u{1F1F8}[\u{1F1E6}-\u{1F1EA}\u{1F1EC}-\u{1F1F4}\u{1F1F7}-\u{1F1F9}\u{1F1FB}\u{1F1FD}-\u{1F1FF}]|\u{1F1EB}[\u{1F1EE}-\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1F7}]|\u{1F1F5}[\u{1F1E6}\u{1F1EA}-\u{1F1ED}\u{1F1F0}-\u{1F1F3}\u{1F1F7}-\u{1F1F9}\u{1F1FC}\u{1F1FE}]|\u{1F1FB}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1EE}\u{1F1F3}\u{1F1FA}]|\u{1F1F3}[\u{1F1E6}\u{1F1E8}\u{1F1EA}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F4}\u{1F1F5}\u{1F1F7}\u{1F1FA}\u{1F1FF}]|\u{1F1E8}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1EE}\u{1F1F0}-\u{1F1F5}\u{1F1F7}\u{1F1FA}-\u{1F1FF}]|\u{1F1F1}[\u{1F1E6}-\u{1F1E8}\u{1F1EE}\u{1F1F0}\u{1F1F7}-\u{1F1FB}\u{1F1FE}]|\u{1F1FF}[\u{1F1E6}\u{1F1F2}\u{1F1FC}]|\u{1F1FC}[\u{1F1EB}\u{1F1F8}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; "use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; { "name": "emoji-regex", "version": "8.0.0", "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", "homepage": "https://mths.be/emoji-regex", "main": "index.js", "types": "index.d.ts", "keywords": [ "unicode", "regex", "regexp", "regular expressions", "code points", "symbols", "characters", "emoji" ], "license": "MIT", "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "repository": { "type": "git", "url": "https://github.com/mathiasbynens/emoji-regex.git" }, "bugs": "https://github.com/mathiasbynens/emoji-regex/issues", "files": [ "LICENSE-MIT.txt", "index.js", "index.d.ts", "text.js", "es2015/index.js", "es2015/text.js" ], "scripts": { "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js", "test": "mocha", "test:watch": "npm run test -- --watch" }, "devDependencies": { "@babel/cli": "^7.2.3", "@babel/core": "^7.3.4", "@babel/plugin-proposal-unicode-property-regex": "^7.2.0", "@babel/preset-env": "^7.3.4", "mocha": "^6.0.2", "regexgen": "^1.3.0", "unicode-12.0.0": "^0.7.9" } } "use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; Copyright (c) 2012-2014 Andris Reinman 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 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. 'use strict'; var iconvLite = require('iconv-lite'); // Expose to the world module.exports.convert = convert; /** * Convert encoding of an UTF-8 string or a buffer * * @param {String|Buffer} str String to be converted * @param {String} to Encoding to be converted to * @param {String} [from='UTF-8'] Encoding to be converted from * @return {Buffer} Encoded string */ function convert(str, to, from) { from = checkEncoding(from || 'UTF-8'); to = checkEncoding(to || 'UTF-8'); str = str || ''; var result; if (from !== 'UTF-8' && typeof str === 'string') { str = Buffer.from(str, 'binary'); } if (from === to) { if (typeof str === 'string') { result = Buffer.from(str); } else { result = str; } } else { try { result = convertIconvLite(str, to, from); } catch (E) { console.error(E); result = str; } } if (typeof result === 'string') { result = Buffer.from(result, 'utf-8'); } return result; } /** * Convert encoding of astring with iconv-lite * * @param {String|Buffer} str String to be converted * @param {String} to Encoding to be converted to * @param {String} [from='UTF-8'] Encoding to be converted from * @return {Buffer} Encoded string */ function convertIconvLite(str, to, from) { if (to === 'UTF-8') { return iconvLite.decode(str, from); } else if (from === 'UTF-8') { return iconvLite.encode(str, to); } else { return iconvLite.encode(iconvLite.decode(str, from), to); } } /** * Converts charset name if needed * * @param {String} name Character set * @return {String} Character set name */ function checkEncoding(name) { return (name || '') .toString() .trim() .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1') .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1') .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1') .replace(/^ks_c_5601\-1987$/i, 'CP949') .replace(/^us[\-_]?ascii$/i, 'ASCII') .toUpperCase(); } { "name": "encoding", "version": "0.1.13", "description": "Convert encodings, uses iconv-lite", "main": "lib/encoding.js", "scripts": { "test": "nodeunit test" }, "repository": "https://github.com/andris9/encoding.git", "author": "Andris Reinman", "license": "MIT", "dependencies": { "iconv-lite": "^0.6.2" }, "devDependencies": { "nodeunit": "0.11.3" } } 'use strict'; var encoding = require('../lib/encoding'); exports['General tests'] = { 'From UTF-8 to Latin_1': function (test) { var input = 'ÕÄÖÜ', expected = Buffer.from([0xd5, 0xc4, 0xd6, 0xdc]); test.deepEqual(encoding.convert(input, 'latin1'), expected); test.done(); }, 'From Latin_1 to UTF-8': function (test) { var input = Buffer.from([0xd5, 0xc4, 0xd6, 0xdc]), expected = 'ÕÄÖÜ'; test.deepEqual(encoding.convert(input, 'utf-8', 'latin1').toString(), expected); test.done(); }, 'From UTF-8 to UTF-8': function (test) { var input = 'ÕÄÖÜ', expected = Buffer.from('ÕÄÖÜ'); test.deepEqual(encoding.convert(input, 'utf-8', 'utf-8'), expected); test.done(); }, 'From Latin_13 to Latin_15': function (test) { var input = Buffer.from([0xd5, 0xc4, 0xd6, 0xdc, 0xd0]), expected = Buffer.from([0xd5, 0xc4, 0xd6, 0xdc, 0xa6]); test.deepEqual(encoding.convert(input, 'latin_15', 'latin13'), expected); test.done(); } /* // ISO-2022-JP is not supported by iconv-lite "From ISO-2022-JP to UTF-8 with Iconv": function (test) { var input = Buffer.from( "GyRCM1g5OzU7PVEwdzgmPSQ4IUYkMnFKczlwGyhC", "base64" ), expected = Buffer.from( "5a2m5qCh5oqA6KGT5ZOh56CU5L+u5qSc6KiO5Lya5aCx5ZGK", "base64" ); test.deepEqual(encoding.convert(input, "utf-8", "ISO-2022-JP"), expected); test.done(); }, */ }; 'use strict'; const path = require('path'); const os = require('os'); const homedir = os.homedir(); const tmpdir = os.tmpdir(); const {env} = process; const macos = name => { const library = path.join(homedir, 'Library'); return { data: path.join(library, 'Application Support', name), config: path.join(library, 'Preferences', name), cache: path.join(library, 'Caches', name), log: path.join(library, 'Logs', name), temp: path.join(tmpdir, name) }; }; const windows = name => { const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming'); const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local'); return { // Data/config/cache/log are invented by me as Windows isn't opinionated about this data: path.join(localAppData, name, 'Data'), config: path.join(appData, name, 'Config'), cache: path.join(localAppData, name, 'Cache'), log: path.join(localAppData, name, 'Log'), temp: path.join(tmpdir, name) }; }; // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html const linux = name => { const username = path.basename(homedir); return { data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name), config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name), cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name), // https://wiki.debian.org/XDGBaseDirectorySpecification#state log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name), temp: path.join(tmpdir, username, name) }; }; const envPaths = (name, options) => { if (typeof name !== 'string') { throw new TypeError(`Expected string, got ${typeof name}`); } options = Object.assign({suffix: 'nodejs'}, options); if (options.suffix) { // Add suffix to prevent possible conflict with native apps name += `-${options.suffix}`; } if (process.platform === 'darwin') { return macos(name); } if (process.platform === 'win32') { return windows(name); } return linux(name); }; module.exports = envPaths; // TODO: Remove this for the next major release module.exports.default = envPaths; MIT License Copyright (c) Sindre Sorhus (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. { "name": "env-paths", "version": "2.2.1", "description": "Get paths for storing things like data, config, cache, etc", "license": "MIT", "repository": "sindresorhus/env-paths", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=6" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "common", "user", "paths", "env", "environment", "directory", "dir", "appdir", "path", "data", "config", "cache", "logs", "temp", "linux", "unix" ], "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.1", "xo": "^0.24.0" } } { "name": "err-code", "version": "1.1.1", "description": "Create new error instances with a code and additional properties", "main": "index.umd.js", "homepage": "https://github.com/IndigoUnited/js-err-code", "authors": [ "IndigoUnited (http://indigounited.com)" ], "moduleType": [ "amd", "globals", "node" ], "keywords": [ "error", "err", "code", "properties", "property" ], "license": "MIT", "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ] } 'use strict'; function assign(obj, props) { for (const key in props) { Object.defineProperty(obj, key, { value: props[key], enumerable: true, configurable: true, }); } return obj; } function createError(err, code, props) { if (!err || typeof err === 'string') { throw new TypeError('Please pass an Error to err-code'); } if (!props) { props = {}; } if (typeof code === 'object') { props = code; code = undefined; } if (code != null) { props.code = code; } try { return assign(err, props); } catch (_) { props.message = err.message; props.stack = err.stack; const ErrClass = function () {}; ErrClass.prototype = Object.create(Object.getPrototypeOf(err)); return assign(new ErrClass(), props); } } module.exports = createError; (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.errCode = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i index.umd.js" }, "bugs": { "url": "https://github.com/IndigoUnited/js-err-code/issues/" }, "repository": { "type": "git", "url": "git://github.com/IndigoUnited/js-err-code.git" }, "keywords": [ "error", "err", "code", "properties", "property" ], "author": "IndigoUnited (http://indigounited.com)", "license": "MIT", "devDependencies": { "@satazor/eslint-config": "^3.0.0", "browserify": "^16.5.1", "eslint": "^7.2.0", "expect.js": "^0.3.1", "mocha": "^8.0.1" } } 'use strict'; const errcode = require('../index'); const expect = require('expect.js'); describe('errcode', () => { describe('string as first argument', () => { it('should throw an error', () => { expect(() => { errcode('my message'); }).to.throwError((err) => { expect(err).to.be.a(TypeError); }); }); }); describe('error as first argument', () => { it('should accept an error and do nothing', () => { const myErr = new Error('my message'); const err = errcode(myErr); expect(err).to.be(myErr); expect(err.hasOwnProperty(err.code)).to.be(false); }); it('should accept an error and add a code', () => { const myErr = new Error('my message'); const err = errcode(myErr, 'ESOME'); expect(err).to.be(myErr); expect(err.code).to.be('ESOME'); }); it('should accept an error object and add code & properties', () => { const myErr = new Error('my message'); const err = errcode(myErr, 'ESOME', { foo: 'bar', bar: 'foo' }); expect(err).to.be.an(Error); expect(err.code).to.be('ESOME'); expect(err.foo).to.be('bar'); expect(err.bar).to.be('foo'); }); it('should create an error object without code but with properties', () => { const myErr = new Error('my message'); const err = errcode(myErr, { foo: 'bar', bar: 'foo' }); expect(err).to.be.an(Error); expect(err.code).to.be(undefined); expect(err.foo).to.be('bar'); expect(err.bar).to.be('foo'); }); it('should set a non-writable field', () => { const myErr = new Error('my message'); Object.defineProperty(myErr, 'code', { value: 'derp', writable: false, }); const err = errcode(myErr, 'ERR_WAT'); expect(err).to.be.an(Error); expect(err.stack).to.equal(myErr.stack); expect(err.code).to.be('ERR_WAT'); }); it('should add a code to frozen object', () => { const myErr = new Error('my message'); const err = errcode(Object.freeze(myErr), 'ERR_WAT'); expect(err).to.be.an(Error); expect(err.stack).to.equal(myErr.stack); expect(err.code).to.be('ERR_WAT'); }); it('should to set a field that throws at assignment time', () => { const myErr = new Error('my message'); Object.defineProperty(myErr, 'code', { enumerable: true, set() { throw new Error('Nope!'); }, get() { return 'derp'; }, }); const err = errcode(myErr, 'ERR_WAT'); expect(err).to.be.an(Error); expect(err.stack).to.equal(myErr.stack); expect(err.code).to.be('ERR_WAT'); }); it('should retain error type', () => { const myErr = new TypeError('my message'); Object.defineProperty(myErr, 'code', { value: 'derp', writable: false, }); const err = errcode(myErr, 'ERR_WAT'); expect(err).to.be.a(TypeError); expect(err.stack).to.equal(myErr.stack); expect(err.code).to.be('ERR_WAT'); }); it('should add a code to a class that extends Error', () => { class CustomError extends Error { set code(val) { throw new Error('Nope!'); } } const myErr = new CustomError('my message'); Object.defineProperty(myErr, 'code', { value: 'derp', writable: false, configurable: false, }); const err = errcode(myErr, 'ERR_WAT'); expect(err).to.be.a(CustomError); expect(err.stack).to.equal(myErr.stack); expect(err.code).to.be('ERR_WAT'); // original prototype chain should be intact expect(() => { const otherErr = new CustomError('my message'); otherErr.code = 'derp'; }).to.throwError(); }); it('should support errors that are not Errors', () => { const err = errcode({ message: 'Oh noes!', }, 'ERR_WAT'); expect(err.message).to.be('Oh noes!'); expect(err.code).to.be('ERR_WAT'); }); }); describe('falsy first arguments', () => { it('should not allow passing null as the first argument', () => { expect(() => { errcode(null); }).to.throwError((err) => { expect(err).to.be.a(TypeError); }); }); it('should not allow passing undefined as the first argument', () => { expect(() => { errcode(undefined); }).to.throwError((err) => { expect(err).to.be.a(TypeError); }); }); }); }); Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 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 (50%) 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (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-2.0 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."use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var options_1 = require("./options"); var delay_factory_1 = require("./delay/delay.factory"); function backOff(request, options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var sanitizedOptions, backOff; return __generator(this, function (_a) { switch (_a.label) { case 0: sanitizedOptions = options_1.getSanitizedOptions(options); backOff = new BackOff(request, sanitizedOptions); return [4 /*yield*/, backOff.execute()]; case 1: return [2 /*return*/, _a.sent()]; } }); }); } exports.backOff = backOff; var BackOff = /** @class */ (function () { function BackOff(request, options) { this.request = request; this.options = options; this.attemptNumber = 0; } BackOff.prototype.execute = function () { return __awaiter(this, void 0, void 0, function () { var e_1, shouldRetry; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!!this.attemptLimitReached) return [3 /*break*/, 7]; _a.label = 1; case 1: _a.trys.push([1, 4, , 6]); return [4 /*yield*/, this.applyDelay()]; case 2: _a.sent(); return [4 /*yield*/, this.request()]; case 3: return [2 /*return*/, _a.sent()]; case 4: e_1 = _a.sent(); this.attemptNumber++; return [4 /*yield*/, this.options.retry(e_1, this.attemptNumber)]; case 5: shouldRetry = _a.sent(); if (!shouldRetry || this.attemptLimitReached) { throw e_1; } return [3 /*break*/, 6]; case 6: return [3 /*break*/, 0]; case 7: throw new Error("Something went wrong."); } }); }); }; Object.defineProperty(BackOff.prototype, "attemptLimitReached", { get: function () { return this.attemptNumber >= this.options.numOfAttempts; }, enumerable: true, configurable: true }); BackOff.prototype.applyDelay = function () { return __awaiter(this, void 0, void 0, function () { var delay; return __generator(this, function (_a) { switch (_a.label) { case 0: delay = delay_factory_1.DelayFactory(this.options, this.attemptNumber); return [4 /*yield*/, delay.apply()]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; return BackOff; }()); //# sourceMappingURL=backoff.js.map"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var delay_base_1 = require("../delay.base"); var AlwaysDelay = /** @class */ (function (_super) { __extends(AlwaysDelay, _super); function AlwaysDelay() { return _super !== null && _super.apply(this, arguments) || this; } return AlwaysDelay; }(delay_base_1.Delay)); exports.AlwaysDelay = AlwaysDelay; //# sourceMappingURL=always.delay.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var jitter_factory_1 = require("../jitter/jitter.factory"); var Delay = /** @class */ (function () { function Delay(options) { this.options = options; this.attempt = 0; } Delay.prototype.apply = function () { var _this = this; return new Promise(function (resolve) { return setTimeout(resolve, _this.jitteredDelay); }); }; Delay.prototype.setAttemptNumber = function (attempt) { this.attempt = attempt; }; Object.defineProperty(Delay.prototype, "jitteredDelay", { get: function () { var jitter = jitter_factory_1.JitterFactory(this.options); return jitter(this.delay); }, enumerable: true, configurable: true }); Object.defineProperty(Delay.prototype, "delay", { get: function () { var constant = this.options.startingDelay; var base = this.options.timeMultiple; var power = this.numOfDelayedAttempts; var delay = constant * Math.pow(base, power); return Math.min(delay, this.options.maxDelay); }, enumerable: true, configurable: true }); Object.defineProperty(Delay.prototype, "numOfDelayedAttempts", { get: function () { return this.attempt; }, enumerable: true, configurable: true }); return Delay; }()); exports.Delay = Delay; //# sourceMappingURL=delay.base.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var skip_first_delay_1 = require("./skip-first/skip-first.delay"); var always_delay_1 = require("./always/always.delay"); function DelayFactory(options, attempt) { var delay = initDelayClass(options); delay.setAttemptNumber(attempt); return delay; } exports.DelayFactory = DelayFactory; function initDelayClass(options) { if (!options.delayFirstAttempt) { return new skip_first_delay_1.SkipFirstDelay(options); } return new always_delay_1.AlwaysDelay(options); } //# sourceMappingURL=delay.factory.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=delay.interface.js.map"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var delay_base_1 = require("../delay.base"); var SkipFirstDelay = /** @class */ (function (_super) { __extends(SkipFirstDelay, _super); function SkipFirstDelay() { return _super !== null && _super.apply(this, arguments) || this; } SkipFirstDelay.prototype.apply = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.isFirstAttempt ? true : _super.prototype.apply.call(this)]; }); }); }; Object.defineProperty(SkipFirstDelay.prototype, "isFirstAttempt", { get: function () { return this.attempt === 0; }, enumerable: true, configurable: true }); Object.defineProperty(SkipFirstDelay.prototype, "numOfDelayedAttempts", { get: function () { return this.attempt - 1; }, enumerable: true, configurable: true }); return SkipFirstDelay; }(delay_base_1.Delay)); exports.SkipFirstDelay = SkipFirstDelay; //# sourceMappingURL=skip-first.delay.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function fullJitter(delay) { var jitteredDelay = Math.random() * delay; return Math.round(jitteredDelay); } exports.fullJitter = fullJitter; //# sourceMappingURL=full.jitter.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var full_jitter_1 = require("./full/full.jitter"); var no_jitter_1 = require("./no/no.jitter"); function JitterFactory(options) { switch (options.jitter) { case "full": return full_jitter_1.fullJitter; case "none": default: return no_jitter_1.noJitter; } } exports.JitterFactory = JitterFactory; //# sourceMappingURL=jitter.factory.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function noJitter(delay) { return delay; } exports.noJitter = noJitter; //# sourceMappingURL=no.jitter.js.map"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); var defaultOptions = { delayFirstAttempt: false, jitter: "none", maxDelay: Infinity, numOfAttempts: 10, retry: function () { return true; }, startingDelay: 100, timeMultiple: 2 }; function getSanitizedOptions(options) { var sanitized = __assign(__assign({}, defaultOptions), options); if (sanitized.numOfAttempts < 1) { sanitized.numOfAttempts = 1; } return sanitized; } exports.getSanitizedOptions = getSanitizedOptions; //# sourceMappingURL=options.js.map{ "name": "exponential-backoff", "version": "3.1.1", "description": "A utility that allows retrying a function with an exponential delay between attempts.", "files": [ "dist/" ], "main": "dist/backoff.js", "types": "dist/backoff.d.ts", "scripts": { "build": "tsc", "test": "jest", "test:watch": "jest --watch" }, "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "*.{ts,json,md}": [ "prettier --write", "git add" ] }, "jest": { "transform": { "^.+\\.ts$": "ts-jest" }, "testRegex": "\\.spec\\.ts$", "moduleFileExtensions": [ "ts", "js" ] }, "repository": { "type": "git", "url": "git+https://github.com/coveo/exponential-backoff.git" }, "keywords": [ "exponential", "backoff", "retry" ], "author": "Sami Sayegh", "license": "Apache-2.0", "bugs": { "url": "https://github.com/coveo/exponential-backoff/issues" }, "homepage": "https://github.com/coveo/exponential-backoff#readme", "devDependencies": { "@types/jest": "^24.0.18", "@types/node": "^10.14.21", "husky": "^3.0.9", "jest": "^24.9.0", "lint-staged": "^9.4.2", "prettier": "^1.18.2", "ts-jest": "^24.1.0", "typescript": "^3.6.4" } } MIT License Copyright (c) 2020 Kasper Unn Weihe 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."use strict"; exports.__esModule = true; /* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable no-console */ var Benchmark = require("benchmark"); var mod_js_1 = require("./mod.js"); var fast_levenshtein_1 = require("fast-levenshtein"); var fs = require("fs"); var jslevenshtein = require("js-levenshtein"); var leven = require("leven"); var levenshteinEditDistance = require("levenshtein-edit-distance"); var suite = new Benchmark.Suite(); var randomstring = function (length) { var result = ""; var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }; var randomstringArr = function (stringSize, arraySize) { var i = 0; var arr = []; for (i = 0; i < arraySize; i++) { arr.push(randomstring(stringSize)); } return arr; }; var arrSize = 1000; if (!fs.existsSync("data.json")) { var data_1 = [ randomstringArr(4, arrSize), randomstringArr(8, arrSize), randomstringArr(16, arrSize), randomstringArr(32, arrSize), randomstringArr(64, arrSize), randomstringArr(128, arrSize), randomstringArr(256, arrSize), randomstringArr(512, arrSize), randomstringArr(1024, arrSize), ]; fs.writeFileSync("data.json", JSON.stringify(data_1)); } var data = JSON.parse(fs.readFileSync("data.json", "utf8")); var _loop_1 = function (i) { var datapick = data[i]; if (process.argv[2] !== "no") { suite .add("".concat(i, " - js-levenshtein"), function () { for (var j = 0; j < arrSize - 1; j += 2) { jslevenshtein(datapick[j], datapick[j + 1]); } }) .add("".concat(i, " - leven"), function () { for (var j = 0; j < arrSize - 1; j += 2) { leven(datapick[j], datapick[j + 1]); } }) .add("".concat(i, " - fast-levenshtein"), function () { for (var j = 0; j < arrSize - 1; j += 2) { (0, fast_levenshtein_1.get)(datapick[j], datapick[j + 1]); } }) .add("".concat(i, " - levenshtein-edit-distance"), function () { for (var j = 0; j < arrSize - 1; j += 2) { levenshteinEditDistance(datapick[j], datapick[j + 1]); } }); } suite.add("".concat(i, " - fastest-levenshtein"), function () { for (var j = 0; j < arrSize - 1; j += 2) { (0, mod_js_1.distance)(datapick[j], datapick[j + 1]); } }); }; // BENCHMARKS for (var i = 0; i < 9; i++) { _loop_1(i); } var results = new Map(); suite .on("cycle", function (event) { console.log(String(event.target)); if (results.has(event.target.name[0])) { results.get(event.target.name[0]).push(event.target.hz); } else { results.set(event.target.name[0], [event.target.hz]); } }) .on("complete", function () { console.log(results); }) // run async .run({ async: true }); const peq = new Uint32Array(0x10000); const myers_32 = (a, b) => { const n = a.length; const m = b.length; const lst = 1 << (n - 1); let pv = -1; let mv = 0; let sc = n; let i = n; while (i--) { peq[a.charCodeAt(i)] |= 1 << i; } for (i = 0; i < m; i++) { let eq = peq[b.charCodeAt(i)]; const xv = eq | mv; eq |= ((eq & pv) + pv) ^ pv; mv |= ~(eq | pv); pv &= eq; if (mv & lst) { sc++; } if (pv & lst) { sc--; } mv = (mv << 1) | 1; pv = (pv << 1) | ~(xv | mv); mv &= xv; } i = n; while (i--) { peq[a.charCodeAt(i)] = 0; } return sc; }; const myers_x = (b, a) => { const n = a.length; const m = b.length; const mhc = []; const phc = []; const hsize = Math.ceil(n / 32); const vsize = Math.ceil(m / 32); for (let i = 0; i < hsize; i++) { phc[i] = -1; mhc[i] = 0; } let j = 0; for (; j < vsize - 1; j++) { let mv = 0; let pv = -1; const start = j * 32; const vlen = Math.min(32, m) + start; for (let k = start; k < vlen; k++) { peq[b.charCodeAt(k)] |= 1 << k; } for (let i = 0; i < n; i++) { const eq = peq[a.charCodeAt(i)]; const pb = (phc[(i / 32) | 0] >>> i) & 1; const mb = (mhc[(i / 32) | 0] >>> i) & 1; const xv = eq | mv; const xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb; let ph = mv | ~(xh | pv); let mh = pv & xh; if ((ph >>> 31) ^ pb) { phc[(i / 32) | 0] ^= 1 << i; } if ((mh >>> 31) ^ mb) { mhc[(i / 32) | 0] ^= 1 << i; } ph = (ph << 1) | pb; mh = (mh << 1) | mb; pv = mh | ~(xv | ph); mv = ph & xv; } for (let k = start; k < vlen; k++) { peq[b.charCodeAt(k)] = 0; } } let mv = 0; let pv = -1; const start = j * 32; const vlen = Math.min(32, m - start) + start; for (let k = start; k < vlen; k++) { peq[b.charCodeAt(k)] |= 1 << k; } let score = m; for (let i = 0; i < n; i++) { const eq = peq[a.charCodeAt(i)]; const pb = (phc[(i / 32) | 0] >>> i) & 1; const mb = (mhc[(i / 32) | 0] >>> i) & 1; const xv = eq | mv; const xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb; let ph = mv | ~(xh | pv); let mh = pv & xh; score += (ph >>> (m - 1)) & 1; score -= (mh >>> (m - 1)) & 1; if ((ph >>> 31) ^ pb) { phc[(i / 32) | 0] ^= 1 << i; } if ((mh >>> 31) ^ mb) { mhc[(i / 32) | 0] ^= 1 << i; } ph = (ph << 1) | pb; mh = (mh << 1) | mb; pv = mh | ~(xv | ph); mv = ph & xv; } for (let k = start; k < vlen; k++) { peq[b.charCodeAt(k)] = 0; } return score; }; const distance = (a, b) => { if (a.length < b.length) { const tmp = b; b = a; a = tmp; } if (b.length === 0) { return a.length; } if (a.length <= 32) { return myers_32(a, b); } return myers_x(a, b); }; const closest = (str, arr) => { let min_distance = Infinity; let min_index = 0; for (let i = 0; i < arr.length; i++) { const dist = distance(str, arr[i]); if (dist < min_distance) { min_distance = dist; min_index = i; } } return arr[min_index]; }; export { closest, distance }; "use strict"; exports.__esModule = true; exports.distance = exports.closest = void 0; var peq = new Uint32Array(0x10000); var myers_32 = function (a, b) { var n = a.length; var m = b.length; var lst = 1 << (n - 1); var pv = -1; var mv = 0; var sc = n; var i = n; while (i--) { peq[a.charCodeAt(i)] |= 1 << i; } for (i = 0; i < m; i++) { var eq = peq[b.charCodeAt(i)]; var xv = eq | mv; eq |= ((eq & pv) + pv) ^ pv; mv |= ~(eq | pv); pv &= eq; if (mv & lst) { sc++; } if (pv & lst) { sc--; } mv = (mv << 1) | 1; pv = (pv << 1) | ~(xv | mv); mv &= xv; } i = n; while (i--) { peq[a.charCodeAt(i)] = 0; } return sc; }; var myers_x = function (b, a) { var n = a.length; var m = b.length; var mhc = []; var phc = []; var hsize = Math.ceil(n / 32); var vsize = Math.ceil(m / 32); for (var i = 0; i < hsize; i++) { phc[i] = -1; mhc[i] = 0; } var j = 0; for (; j < vsize - 1; j++) { var mv_1 = 0; var pv_1 = -1; var start_1 = j * 32; var vlen_1 = Math.min(32, m) + start_1; for (var k = start_1; k < vlen_1; k++) { peq[b.charCodeAt(k)] |= 1 << k; } for (var i = 0; i < n; i++) { var eq = peq[a.charCodeAt(i)]; var pb = (phc[(i / 32) | 0] >>> i) & 1; var mb = (mhc[(i / 32) | 0] >>> i) & 1; var xv = eq | mv_1; var xh = ((((eq | mb) & pv_1) + pv_1) ^ pv_1) | eq | mb; var ph = mv_1 | ~(xh | pv_1); var mh = pv_1 & xh; if ((ph >>> 31) ^ pb) { phc[(i / 32) | 0] ^= 1 << i; } if ((mh >>> 31) ^ mb) { mhc[(i / 32) | 0] ^= 1 << i; } ph = (ph << 1) | pb; mh = (mh << 1) | mb; pv_1 = mh | ~(xv | ph); mv_1 = ph & xv; } for (var k = start_1; k < vlen_1; k++) { peq[b.charCodeAt(k)] = 0; } } var mv = 0; var pv = -1; var start = j * 32; var vlen = Math.min(32, m - start) + start; for (var k = start; k < vlen; k++) { peq[b.charCodeAt(k)] |= 1 << k; } var score = m; for (var i = 0; i < n; i++) { var eq = peq[a.charCodeAt(i)]; var pb = (phc[(i / 32) | 0] >>> i) & 1; var mb = (mhc[(i / 32) | 0] >>> i) & 1; var xv = eq | mv; var xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb; var ph = mv | ~(xh | pv); var mh = pv & xh; score += (ph >>> (m - 1)) & 1; score -= (mh >>> (m - 1)) & 1; if ((ph >>> 31) ^ pb) { phc[(i / 32) | 0] ^= 1 << i; } if ((mh >>> 31) ^ mb) { mhc[(i / 32) | 0] ^= 1 << i; } ph = (ph << 1) | pb; mh = (mh << 1) | mb; pv = mh | ~(xv | ph); mv = ph & xv; } for (var k = start; k < vlen; k++) { peq[b.charCodeAt(k)] = 0; } return score; }; var distance = function (a, b) { if (a.length < b.length) { var tmp = b; b = a; a = tmp; } if (b.length === 0) { return a.length; } if (a.length <= 32) { return myers_32(a, b); } return myers_x(a, b); }; exports.distance = distance; var closest = function (str, arr) { var min_distance = Infinity; var min_index = 0; for (var i = 0; i < arr.length; i++) { var dist = distance(str, arr[i]); if (dist < min_distance) { min_distance = dist; min_index = i; } } return arr[min_index]; }; exports.closest = closest; { "name": "fastest-levenshtein", "version": "1.0.16", "description": "Fastest Levenshtein distance implementation in JS.", "main": "mod.js", "types": "mod.d.ts", "module": "./esm/mod.js", "repository": { "type": "git", "url": "git+https://github.com/ka-weihe/fastest-levenshtein.git" }, "keywords": [ "levenshtein", "distance", "fast", "fastest", "edit", "string", "similarity", "algorithm", "match", "comparison", "fuzzy", "search", "string", "matching", "similar", "node", "difference" ], "author": "Kasper U. Weihe", "license": "MIT", "bugs": { "url": "https://github.com/ka-weihe/fastest-levenshtein/issues" }, "homepage": "https://github.com/ka-weihe/fastest-levenshtein#README", "scripts": { "build": "tsc mod.ts --declaration", "build:esm": "tsc --declaration -p tsconfig.esm.json", "prepare": "npm run build && npm run build:esm", "bench": "npm run build && tsc bench.ts && node bench.js", "test": "npm run build && tsc test.ts && jest test.js", "test:coverage": "npm run build && jest --coverage", "test:coveralls": "npm run build && jest --coverage --coverageReporters=text-lcov | coveralls" }, "devDependencies": { "@types/benchmark": "^1.0.33", "@types/jest": "^26.0.15", "@typescript-eslint/eslint-plugin": "^4.7.0", "@typescript-eslint/parser": "^4.7.0", "benchmark": "^2.1.4", "coveralls": "^3.1.0", "eslint": "^7.13.0", "eslint-config-node": "^4.1.0", "eslint-config-prettier": "^6.15.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^3.1.4", "fast-levenshtein": "^2.0.6", "jest": "^26.6.3", "js-levenshtein": "^1.1.6", "leven": "^3.1.0", "levenshtein-edit-distance": "^2.0.5", "natural": "^2.1.5", "prettier": "^2.1.2", "talisman": "^1.1.3", "typescript": "^4.0.5" }, "engines": { "node": ">= 4.9.1" } } var _a = require("./mod.js"), closest = _a.closest, distance = _a.distance; var levenshtein = function (a, b) { if (a.length === 0) { return b.length; } if (b.length === 0) { return a.length; } if (a.length > b.length) { var tmp = a; a = b; b = tmp; } var row = []; for (var i = 0; i <= a.length; i++) { row[i] = i; } for (var i = 1; i <= b.length; i++) { var prev = i; for (var j = 1; j <= a.length; j++) { var val = 0; if (b.charAt(i - 1) === a.charAt(j - 1)) { val = row[j - 1]; } else { val = Math.min(row[j - 1] + 1, prev + 1, row[j] + 1); } row[j - 1] = prev; prev = val; } row[a.length] = prev; } return row[a.length]; }; var makeid = function (length) { var result = ""; var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }; for (var i = 0; i < 10000; i++) { var rnd_num1 = (Math.random() * 1000) | 0; var rnd_num2 = (Math.random() * 1000) | 0; var rnd_string1 = makeid(rnd_num1); var rnd_string2 = makeid(rnd_num2); var actual = distance(rnd_string1, rnd_string2); var expected = levenshtein(rnd_string1, rnd_string2); console.log(i); if (actual !== expected) { console.log("fail"); } } The ISC License Copyright (c) 2015-2023 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.allSignals = void 0; const node_constants_1 = __importDefault(require("node:constants")); exports.allSignals = // this is the full list of signals that Node will let us do anything with Object.keys(node_constants_1.default).filter(k => k.startsWith('SIG') && // https://github.com/tapjs/signal-exit/issues/21 k !== 'SIGPROF' && // no sense trying to listen for SIGKILL, it's impossible k !== 'SIGKILL'); // These are some obscure signals that are reported by kill -l // on macOS, Linux, or Windows, but which don't have any mapping // in Node.js. No sense trying if they're just going to throw // every time on every platform. // // 'SIGEMT', // 'SIGLOST', // 'SIGPOLL', // 'SIGRTMAX', // 'SIGRTMAX-1', // 'SIGRTMAX-10', // 'SIGRTMAX-11', // 'SIGRTMAX-12', // 'SIGRTMAX-13', // 'SIGRTMAX-14', // 'SIGRTMAX-15', // 'SIGRTMAX-2', // 'SIGRTMAX-3', // 'SIGRTMAX-4', // 'SIGRTMAX-5', // 'SIGRTMAX-6', // 'SIGRTMAX-7', // 'SIGRTMAX-8', // 'SIGRTMAX-9', // 'SIGRTMIN', // 'SIGRTMIN+1', // 'SIGRTMIN+10', // 'SIGRTMIN+11', // 'SIGRTMIN+12', // 'SIGRTMIN+13', // 'SIGRTMIN+14', // 'SIGRTMIN+15', // 'SIGRTMIN+16', // 'SIGRTMIN+2', // 'SIGRTMIN+3', // 'SIGRTMIN+4', // 'SIGRTMIN+5', // 'SIGRTMIN+6', // 'SIGRTMIN+7', // 'SIGRTMIN+8', // 'SIGRTMIN+9', // 'SIGSTKFLT', // 'SIGUNUSED', //# sourceMappingURL=all-signals.js.map"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.foregroundChild = exports.normalizeFgArgs = void 0; const child_process_1 = require("child_process"); const cross_spawn_1 = __importDefault(require("cross-spawn")); const signal_exit_1 = require("signal-exit"); const proxy_signals_js_1 = require("./proxy-signals.js"); const watchdog_js_1 = require("./watchdog.js"); /* c8 ignore start */ const spawn = process?.platform === 'win32' ? cross_spawn_1.default : child_process_1.spawn; /** * Normalizes the arguments passed to `foregroundChild`. * * Exposed for testing. * * @internal */ const normalizeFgArgs = (fgArgs) => { let [program, args = [], spawnOpts = {}, cleanup = () => { }] = fgArgs; if (typeof args === 'function') { cleanup = args; spawnOpts = {}; args = []; } else if (!!args && typeof args === 'object' && !Array.isArray(args)) { if (typeof spawnOpts === 'function') cleanup = spawnOpts; spawnOpts = args; args = []; } else if (typeof spawnOpts === 'function') { cleanup = spawnOpts; spawnOpts = {}; } if (Array.isArray(program)) { const [pp, ...pa] = program; program = pp; args = pa; } return [program, args, { ...spawnOpts }, cleanup]; }; exports.normalizeFgArgs = normalizeFgArgs; function foregroundChild(...fgArgs) { const [program, args, spawnOpts, cleanup] = (0, exports.normalizeFgArgs)(fgArgs); spawnOpts.stdio = [0, 1, 2]; if (process.send) { spawnOpts.stdio.push('ipc'); } const child = spawn(program, args, spawnOpts); const childHangup = () => { try { child.kill('SIGHUP'); /* c8 ignore start */ } catch (_) { // SIGHUP is weird on windows child.kill('SIGTERM'); } /* c8 ignore stop */ }; const removeOnExit = (0, signal_exit_1.onExit)(childHangup); (0, proxy_signals_js_1.proxySignals)(child); const dog = (0, watchdog_js_1.watchdog)(child); let done = false; child.on('close', async (code, signal) => { /* c8 ignore start */ if (done) return; /* c8 ignore stop */ done = true; const result = cleanup(code, signal, { watchdogPid: dog.pid, }); const res = isPromise(result) ? await result : result; removeOnExit(); if (res === false) return; else if (typeof res === 'string') { signal = res; code = null; } else if (typeof res === 'number') { code = res; signal = null; } if (signal) { // If there is nothing else keeping the event loop alive, // then there's a race between a graceful exit and getting // the signal to this process. Put this timeout here to // make sure we're still alive to get the signal, and thus // exit with the intended signal code. /* istanbul ignore next */ setTimeout(() => { }, 2000); try { process.kill(process.pid, signal); /* c8 ignore start */ } catch (_) { process.kill(process.pid, 'SIGTERM'); } /* c8 ignore stop */ } else { process.exit(code || 0); } }); if (process.send) { process.removeAllListeners('message'); child.on('message', (message, sendHandle) => { process.send?.(message, sendHandle); }); process.on('message', (message, sendHandle) => { child.send(message, sendHandle); }); } return child; } exports.foregroundChild = foregroundChild; const isPromise = (o) => !!o && typeof o === 'object' && typeof o.then === 'function'; //# sourceMappingURL=index.js.map{ "type": "commonjs" } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.proxySignals = void 0; const all_signals_js_1 = require("./all-signals.js"); /** * Starts forwarding signals to `child` through `parent`. */ const proxySignals = (child) => { const listeners = new Map(); for (const sig of all_signals_js_1.allSignals) { const listener = () => { // some signals can only be received, not sent try { child.kill(sig); /* c8 ignore start */ } catch (_) { } /* c8 ignore stop */ }; try { // if it's a signal this system doesn't recognize, skip it process.on(sig, listener); listeners.set(sig, listener); /* c8 ignore start */ } catch (_) { } /* c8 ignore stop */ } const unproxy = () => { for (const [sig, listener] of listeners) { process.removeListener(sig, listener); } }; child.on('exit', unproxy); return unproxy; }; exports.proxySignals = proxySignals; //# sourceMappingURL=proxy-signals.js.map"use strict"; // this spawns a child process that listens for SIGHUP when the // parent process exits, and after 200ms, sends a SIGKILL to the // child, in case it did not terminate. Object.defineProperty(exports, "__esModule", { value: true }); exports.watchdog = void 0; const child_process_1 = require("child_process"); const watchdogCode = String.raw ` const pid = parseInt(process.argv[1], 10) process.title = 'node (foreground-child watchdog pid=' + pid + ')' if (!isNaN(pid)) { let barked = false // keepalive const interval = setInterval(() => {}, 60000) const bark = () => { clearInterval(interval) if (barked) return barked = true process.removeListener('SIGHUP', bark) setTimeout(() => { try { process.kill(pid, 'SIGKILL') setTimeout(() => process.exit(), 200) } catch (_) {} }, 500) }) process.on('SIGHUP', bark) } `; /** * Pass in a ChildProcess, and this will spawn a watchdog process that * will make sure it exits if the parent does, thus preventing any * dangling detached zombie processes. * * If the child ends before the parent, then the watchdog will terminate. */ const watchdog = (child) => { let dogExited = false; const dog = (0, child_process_1.spawn)(process.execPath, ['-e', watchdogCode, String(child.pid)], { stdio: 'ignore', }); dog.on('exit', () => (dogExited = true)); child.on('exit', () => { if (!dogExited) dog.kill('SIGKILL'); }); return dog; }; exports.watchdog = watchdog; //# sourceMappingURL=watchdog.js.mapimport constants from 'node:constants'; export const allSignals = // this is the full list of signals that Node will let us do anything with Object.keys(constants).filter(k => k.startsWith('SIG') && // https://github.com/tapjs/signal-exit/issues/21 k !== 'SIGPROF' && // no sense trying to listen for SIGKILL, it's impossible k !== 'SIGKILL'); // These are some obscure signals that are reported by kill -l // on macOS, Linux, or Windows, but which don't have any mapping // in Node.js. No sense trying if they're just going to throw // every time on every platform. // // 'SIGEMT', // 'SIGLOST', // 'SIGPOLL', // 'SIGRTMAX', // 'SIGRTMAX-1', // 'SIGRTMAX-10', // 'SIGRTMAX-11', // 'SIGRTMAX-12', // 'SIGRTMAX-13', // 'SIGRTMAX-14', // 'SIGRTMAX-15', // 'SIGRTMAX-2', // 'SIGRTMAX-3', // 'SIGRTMAX-4', // 'SIGRTMAX-5', // 'SIGRTMAX-6', // 'SIGRTMAX-7', // 'SIGRTMAX-8', // 'SIGRTMAX-9', // 'SIGRTMIN', // 'SIGRTMIN+1', // 'SIGRTMIN+10', // 'SIGRTMIN+11', // 'SIGRTMIN+12', // 'SIGRTMIN+13', // 'SIGRTMIN+14', // 'SIGRTMIN+15', // 'SIGRTMIN+16', // 'SIGRTMIN+2', // 'SIGRTMIN+3', // 'SIGRTMIN+4', // 'SIGRTMIN+5', // 'SIGRTMIN+6', // 'SIGRTMIN+7', // 'SIGRTMIN+8', // 'SIGRTMIN+9', // 'SIGSTKFLT', // 'SIGUNUSED', //# sourceMappingURL=all-signals.js.mapimport { spawn as nodeSpawn, } from 'child_process'; import crossSpawn from 'cross-spawn'; import { onExit } from 'signal-exit'; import { proxySignals } from './proxy-signals.js'; import { watchdog } from './watchdog.js'; /* c8 ignore start */ const spawn = process?.platform === 'win32' ? crossSpawn : nodeSpawn; /** * Normalizes the arguments passed to `foregroundChild`. * * Exposed for testing. * * @internal */ export const normalizeFgArgs = (fgArgs) => { let [program, args = [], spawnOpts = {}, cleanup = () => { }] = fgArgs; if (typeof args === 'function') { cleanup = args; spawnOpts = {}; args = []; } else if (!!args && typeof args === 'object' && !Array.isArray(args)) { if (typeof spawnOpts === 'function') cleanup = spawnOpts; spawnOpts = args; args = []; } else if (typeof spawnOpts === 'function') { cleanup = spawnOpts; spawnOpts = {}; } if (Array.isArray(program)) { const [pp, ...pa] = program; program = pp; args = pa; } return [program, args, { ...spawnOpts }, cleanup]; }; export function foregroundChild(...fgArgs) { const [program, args, spawnOpts, cleanup] = normalizeFgArgs(fgArgs); spawnOpts.stdio = [0, 1, 2]; if (process.send) { spawnOpts.stdio.push('ipc'); } const child = spawn(program, args, spawnOpts); const childHangup = () => { try { child.kill('SIGHUP'); /* c8 ignore start */ } catch (_) { // SIGHUP is weird on windows child.kill('SIGTERM'); } /* c8 ignore stop */ }; const removeOnExit = onExit(childHangup); proxySignals(child); const dog = watchdog(child); let done = false; child.on('close', async (code, signal) => { /* c8 ignore start */ if (done) return; /* c8 ignore stop */ done = true; const result = cleanup(code, signal, { watchdogPid: dog.pid, }); const res = isPromise(result) ? await result : result; removeOnExit(); if (res === false) return; else if (typeof res === 'string') { signal = res; code = null; } else if (typeof res === 'number') { code = res; signal = null; } if (signal) { // If there is nothing else keeping the event loop alive, // then there's a race between a graceful exit and getting // the signal to this process. Put this timeout here to // make sure we're still alive to get the signal, and thus // exit with the intended signal code. /* istanbul ignore next */ setTimeout(() => { }, 2000); try { process.kill(process.pid, signal); /* c8 ignore start */ } catch (_) { process.kill(process.pid, 'SIGTERM'); } /* c8 ignore stop */ } else { process.exit(code || 0); } }); if (process.send) { process.removeAllListeners('message'); child.on('message', (message, sendHandle) => { process.send?.(message, sendHandle); }); process.on('message', (message, sendHandle) => { child.send(message, sendHandle); }); } return child; } const isPromise = (o) => !!o && typeof o === 'object' && typeof o.then === 'function'; //# sourceMappingURL=index.js.map{ "type": "module" } import { allSignals } from './all-signals.js'; /** * Starts forwarding signals to `child` through `parent`. */ export const proxySignals = (child) => { const listeners = new Map(); for (const sig of allSignals) { const listener = () => { // some signals can only be received, not sent try { child.kill(sig); /* c8 ignore start */ } catch (_) { } /* c8 ignore stop */ }; try { // if it's a signal this system doesn't recognize, skip it process.on(sig, listener); listeners.set(sig, listener); /* c8 ignore start */ } catch (_) { } /* c8 ignore stop */ } const unproxy = () => { for (const [sig, listener] of listeners) { process.removeListener(sig, listener); } }; child.on('exit', unproxy); return unproxy; }; //# sourceMappingURL=proxy-signals.js.map// this spawns a child process that listens for SIGHUP when the // parent process exits, and after 200ms, sends a SIGKILL to the // child, in case it did not terminate. import { spawn } from 'child_process'; const watchdogCode = String.raw ` const pid = parseInt(process.argv[1], 10) process.title = 'node (foreground-child watchdog pid=' + pid + ')' if (!isNaN(pid)) { let barked = false // keepalive const interval = setInterval(() => {}, 60000) const bark = () => { clearInterval(interval) if (barked) return barked = true process.removeListener('SIGHUP', bark) setTimeout(() => { try { process.kill(pid, 'SIGKILL') setTimeout(() => process.exit(), 200) } catch (_) {} }, 500) }) process.on('SIGHUP', bark) } `; /** * Pass in a ChildProcess, and this will spawn a watchdog process that * will make sure it exits if the parent does, thus preventing any * dangling detached zombie processes. * * If the child ends before the parent, then the watchdog will terminate. */ export const watchdog = (child) => { let dogExited = false; const dog = spawn(process.execPath, ['-e', watchdogCode, String(child.pid)], { stdio: 'ignore', }); dog.on('exit', () => (dogExited = true)); child.on('exit', () => { if (!dogExited) dog.kill('SIGKILL'); }); return dog; }; //# sourceMappingURL=watchdog.js.map{ "name": "foreground-child", "version": "3.3.0", "description": "Run a child as if it's the foreground process. Give it stdio. Exit when it exits.", "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", "exports": { "./watchdog": { "import": { "source": "./src/watchdog.ts", "types": "./dist/esm/watchdog.d.ts", "default": "./dist/esm/watchdog.js" }, "require": { "source": "./src/watchdog.ts", "types": "./dist/commonjs/watchdog.d.ts", "default": "./dist/commonjs/watchdog.js" } }, "./proxy-signals": { "import": { "source": "./src/proxy-signals.ts", "types": "./dist/esm/proxy-signals.d.ts", "default": "./dist/esm/proxy-signals.js" }, "require": { "source": "./src/proxy-signals.ts", "types": "./dist/commonjs/proxy-signals.d.ts", "default": "./dist/commonjs/proxy-signals.js" } }, "./package.json": "./package.json", ".": { "import": { "source": "./src/index.ts", "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "source": "./src/index.ts", "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "files": [ "dist" ], "engines": { "node": ">=14" }, "dependencies": { "cross-spawn": "^7.0.0", "signal-exit": "^4.0.1" }, "scripts": { "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "prepare": "tshy", "pretest": "npm run prepare", "presnap": "npm run prepare", "test": "tap", "snap": "tap", "format": "prettier --write . --log-level warn", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "prettier": { "experimentalTernaries": true, "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "tap": { "typecheck": true }, "repository": { "type": "git", "url": "git+https://github.com/tapjs/foreground-child.git" }, "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "license": "ISC", "devDependencies": { "@types/cross-spawn": "^6.0.2", "@types/node": "^18.15.11", "@types/tap": "^15.0.8", "prettier": "^3.3.2", "tap": "^19.2.5", "tshy": "^1.15.1", "typedoc": "^0.24.2", "typescript": "^5.0.2" }, "funding": { "url": "https://github.com/sponsors/isaacs" }, "tshy": { "exports": { "./watchdog": "./src/watchdog.ts", "./proxy-signals": "./src/proxy-signals.ts", "./package.json": "./package.json", ".": "./src/index.ts" } }, "type": "module" } The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' const { Minipass } = require('minipass') const EE = require('events').EventEmitter const fs = require('fs') const writev = fs.writev const _autoClose = Symbol('_autoClose') const _close = Symbol('_close') const _ended = Symbol('_ended') const _fd = Symbol('_fd') const _finished = Symbol('_finished') const _flags = Symbol('_flags') const _flush = Symbol('_flush') const _handleChunk = Symbol('_handleChunk') const _makeBuf = Symbol('_makeBuf') const _mode = Symbol('_mode') const _needDrain = Symbol('_needDrain') const _onerror = Symbol('_onerror') const _onopen = Symbol('_onopen') const _onread = Symbol('_onread') const _onwrite = Symbol('_onwrite') const _open = Symbol('_open') const _path = Symbol('_path') const _pos = Symbol('_pos') const _queue = Symbol('_queue') const _read = Symbol('_read') const _readSize = Symbol('_readSize') const _reading = Symbol('_reading') const _remain = Symbol('_remain') const _size = Symbol('_size') const _write = Symbol('_write') const _writing = Symbol('_writing') const _defaultFlag = Symbol('_defaultFlag') const _errored = Symbol('_errored') class ReadStream extends Minipass { constructor (path, opt) { opt = opt || {} super(opt) this.readable = true this.writable = false if (typeof path !== 'string') { throw new TypeError('path must be a string') } this[_errored] = false this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_path] = path this[_readSize] = opt.readSize || 16 * 1024 * 1024 this[_reading] = false this[_size] = typeof opt.size === 'number' ? opt.size : Infinity this[_remain] = this[_size] this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true if (typeof this[_fd] === 'number') { this[_read]() } else { this[_open]() } } get fd () { return this[_fd] } get path () { return this[_path] } write () { throw new TypeError('this is a readable stream') } end () { throw new TypeError('this is a readable stream') } [_open] () { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (er) { this[_onerror](er) } else { this[_fd] = fd this.emit('open', fd) this[_read]() } } [_makeBuf] () { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) } [_read] () { if (!this[_reading]) { this[_reading] = true const buf = this[_makeBuf]() /* istanbul ignore if */ if (buf.length === 0) { return process.nextTick(() => this[_onread](null, 0, buf)) } fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => this[_onread](er, br, b)) } } [_onread] (er, br, buf) { this[_reading] = false if (er) { this[_onerror](er) } else if (this[_handleChunk](br, buf)) { this[_read]() } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } [_onerror] (er) { this[_reading] = true this[_close]() this.emit('error', er) } [_handleChunk] (br, buf) { let ret = false // no effect if infinite this[_remain] -= br if (br > 0) { ret = super.write(br < buf.length ? buf.slice(0, br) : buf) } if (br === 0 || this[_remain] <= 0) { ret = false this[_close]() super.end() } return ret } emit (ev, data) { switch (ev) { case 'prefinish': case 'finish': break case 'drain': if (typeof this[_fd] === 'number') { this[_read]() } break case 'error': if (this[_errored]) { return } this[_errored] = true return super.emit(ev, data) default: return super.emit(ev, data) } } } class ReadStreamSync extends ReadStream { [_open] () { let threw = true try { this[_onopen](null, fs.openSync(this[_path], 'r')) threw = false } finally { if (threw) { this[_close]() } } } [_read] () { let threw = true try { if (!this[_reading]) { this[_reading] = true do { const buf = this[_makeBuf]() /* istanbul ignore next */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null) if (!this[_handleChunk](br, buf)) { break } } while (true) this[_reading] = false } threw = false } finally { if (threw) { this[_close]() } } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } } class WriteStream extends EE { constructor (path, opt) { opt = opt || {} super(opt) this.readable = false this.writable = true this[_errored] = false this[_writing] = false this[_ended] = false this[_needDrain] = false this[_queue] = [] this[_path] = path this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_mode] = opt.mode === undefined ? 0o666 : opt.mode this[_pos] = typeof opt.start === 'number' ? opt.start : null this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== null ? 'r+' : 'w' this[_defaultFlag] = opt.flags === undefined this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags if (this[_fd] === null) { this[_open]() } } emit (ev, data) { if (ev === 'error') { if (this[_errored]) { return } this[_errored] = true } return super.emit(ev, data) } get fd () { return this[_fd] } get path () { return this[_path] } [_onerror] (er) { this[_close]() this[_writing] = true this.emit('error', er) } [_open] () { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' this[_open]() } else if (er) { this[_onerror](er) } else { this[_fd] = fd this.emit('open', fd) if (!this[_writing]) { this[_flush]() } } } end (buf, enc) { if (buf) { this.write(buf, enc) } this[_ended] = true // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') { this[_onwrite](null, 0) } return this } write (buf, enc) { if (typeof buf === 'string') { buf = Buffer.from(buf, enc) } if (this[_ended]) { this.emit('error', new Error('write() after end()')) return false } if (this[_fd] === null || this[_writing] || this[_queue].length) { this[_queue].push(buf) this[_needDrain] = true return false } this[_writing] = true this[_write](buf) return true } [_write] (buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)) } [_onwrite] (er, bw) { if (er) { this[_onerror](er) } else { if (this[_pos] !== null) { this[_pos] += bw } if (this[_queue].length) { this[_flush]() } else { this[_writing] = false if (this[_ended] && !this[_finished]) { this[_finished] = true this[_close]() this.emit('finish') } else if (this[_needDrain]) { this[_needDrain] = false this.emit('drain') } } } } [_flush] () { if (this[_queue].length === 0) { if (this[_ended]) { this[_onwrite](null, 0) } } else if (this[_queue].length === 1) { this[_write](this[_queue].pop()) } else { const iovec = this[_queue] this[_queue] = [] writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)) } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } } class WriteStreamSync extends WriteStream { [_open] () { let fd // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } catch (er) { if (er.code === 'ENOENT') { this[_flags] = 'w' return this[_open]() } else { throw er } } } else { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } this[_onopen](null, fd) } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } [_write] (buf) { // throw the original, but try to close if it fails let threw = true try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) threw = false } finally { if (threw) { try { this[_close]() } catch { // ok error } } } } } exports.ReadStream = ReadStream exports.ReadStreamSync = ReadStreamSync exports.WriteStream = WriteStream exports.WriteStreamSync = WriteStreamSync { "name": "fs-minipass", "version": "3.0.3", "main": "lib/index.js", "scripts": { "test": "tap", "lint": "eslint \"**/*.js\"", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run lint -- --fix", "snap": "tap", "posttest": "npm run lint" }, "keywords": [], "author": "GitHub Inc.", "license": "ISC", "repository": { "type": "git", "url": "https://github.com/npm/fs-minipass.git" }, "bugs": { "url": "https://github.com/npm/fs-minipass/issues" }, "homepage": "https://github.com/npm/fs-minipass#readme", "description": "fs read and write streams based on minipass", "dependencies": { "minipass": "^7.0.3" }, "devDependencies": { "@npmcli/eslint-config": "^4.0.1", "@npmcli/template-oss": "4.18.0", "mutate-fs": "^2.1.1", "tap": "^16.3.2" }, "files": [ "bin/", "lib/" ], "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.18.0", "publish": "true" } } The ISC License Copyright (c) 2009-2023 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Glob Match files using the patterns the shell uses. The most correct and second fastest glob implementation in JavaScript. (See **Comparison to Other JavaScript Glob Implementations** at the bottom of this readme.) ![a fun cartoon logo made of glob characters](https://github.com/isaacs/node-glob/raw/main/logo/glob.png) ## Usage Install with npm ``` npm i glob ``` **Note** the npm package name is _not_ `node-glob` that's a different thing that was abandoned years ago. Just `glob`. ```js // load using import import { glob, globSync, globStream, globStreamSync, Glob } from 'glob' // or using commonjs, that's fine, too const { glob, globSync, globStream, globStreamSync, Glob, } = require('glob') // the main glob() and globSync() resolve/return array of filenames // all js files, but don't look in node_modules const jsfiles = await glob('**/*.js', { ignore: 'node_modules/**' }) // pass in a signal to cancel the glob walk const stopAfter100ms = await glob('**/*.css', { signal: AbortSignal.timeout(100), }) // multiple patterns supported as well const images = await glob(['css/*.{png,jpeg}', 'public/*.{png,jpeg}']) // but of course you can do that with the glob pattern also // the sync function is the same, just returns a string[] instead // of Promise const imagesAlt = globSync('{css,public}/*.{png,jpeg}') // you can also stream them, this is a Minipass stream const filesStream = globStream(['**/*.dat', 'logs/**/*.log']) // construct a Glob object if you wanna do it that way, which // allows for much faster walks if you have to look in the same // folder multiple times. const g = new Glob('**/foo', {}) // glob objects are async iterators, can also do globIterate() or // g.iterate(), same deal for await (const file of g) { console.log('found a foo file:', file) } // pass a glob as the glob options to reuse its settings and caches const g2 = new Glob('**/bar', g) // sync iteration works as well for (const file of g2) { console.log('found a bar file:', file) } // you can also pass withFileTypes: true to get Path objects // these are like a Dirent, but with some more added powers // check out http://npm.im/path-scurry for more info on their API const g3 = new Glob('**/baz/**', { withFileTypes: true }) g3.stream().on('data', path => { console.log( 'got a path object', path.fullpath(), path.isDirectory(), path.readdirSync().map(e => e.name), ) }) // if you use stat:true and withFileTypes, you can sort results // by things like modified time, filter by permission mode, etc. // All Stats fields will be available in that case. Slightly // slower, though. // For example: const results = await glob('**', { stat: true, withFileTypes: true }) const timeSortedFiles = results .sort((a, b) => a.mtimeMs - b.mtimeMs) .map(path => path.fullpath()) const groupReadableFiles = results .filter(path => path.mode & 0o040) .map(path => path.fullpath()) // custom ignores can be done like this, for example by saying // you'll ignore all markdown files, and all folders named 'docs' const customIgnoreResults = await glob('**', { ignore: { ignored: p => /\.md$/.test(p.name), childrenIgnored: p => p.isNamed('docs'), }, }) // another fun use case, only return files with the same name as // their parent folder, plus either `.ts` or `.js` const folderNamedModules = await glob('**/*.{ts,js}', { ignore: { ignored: p => { const pp = p.parent return !(p.isNamed(pp.name + '.ts') || p.isNamed(pp.name + '.js')) }, }, }) // find all files edited in the last hour, to do this, we ignore // all of them that are more than an hour old const newFiles = await glob('**', { // need stat so we have mtime stat: true, // only want the files, not the dirs nodir: true, ignore: { ignored: p => { return new Date() - p.mtime > 60 * 60 * 1000 }, // could add similar childrenIgnored here as well, but // directory mtime is inconsistent across platforms, so // probably better not to, unless you know the system // tracks this reliably. }, }) ``` **Note** Glob patterns should always use `/` as a path separator, even on Windows systems, as `\` is used to escape glob characters. If you wish to use `\` as a path separator _instead of_ using it as an escape character on Windows platforms, you may set `windowsPathsNoEscape:true` in the options. In this mode, special glob characters cannot be escaped, making it impossible to match a literal `*` `?` and so on in filenames. ## Command Line Interface ``` $ glob -h Usage: glob [options] [ [ ...]] Expand the positional glob expression arguments into any matching file system paths found. -c --cmd= Run the command provided, passing the glob expression matches as arguments. -A --all By default, the glob cli command will not expand any arguments that are an exact match to a file on disk. This prevents double-expanding, in case the shell expands an argument whose filename is a glob expression. For example, if 'app/*.ts' would match 'app/[id].ts', then on Windows powershell or cmd.exe, 'glob app/*.ts' will expand to 'app/[id].ts', as expected. However, in posix shells such as bash or zsh, the shell will first expand 'app/*.ts' to a list of filenames. Then glob will look for a file matching 'app/[id].ts' (ie, 'app/i.ts' or 'app/d.ts'), which is unexpected. Setting '--all' prevents this behavior, causing glob to treat ALL patterns as glob expressions to be expanded, even if they are an exact match to a file on disk. When setting this option, be sure to enquote arguments so that the shell will not expand them prior to passing them to the glob command process. -a --absolute Expand to absolute paths -d --dot-relative Prepend './' on relative matches -m --mark Append a / on any directories matched -x --posix Always resolve to posix style paths, using '/' as the directory separator, even on Windows. Drive letter absolute matches on Windows will be expanded to their full resolved UNC maths, eg instead of 'C:\foo\bar', it will expand to '//?/C:/foo/bar'. -f --follow Follow symlinked directories when expanding '**' -R --realpath Call 'fs.realpath' on all of the results. In the case of an entry that cannot be resolved, the entry is omitted. This incurs a slight performance penalty, of course, because of the added system calls. -s --stat Call 'fs.lstat' on all entries, whether required or not to determine if it's a valid match. -b --match-base Perform a basename-only match if the pattern does not contain any slash characters. That is, '*.js' would be treated as equivalent to '**/*.js', matching js files in all directories. --dot Allow patterns to match files/directories that start with '.', even if the pattern does not start with '.' --nobrace Do not expand {...} patterns --nocase Perform a case-insensitive match. This defaults to 'true' on macOS and Windows platforms, and false on all others. Note: 'nocase' should only be explicitly set when it is known that the filesystem's case sensitivity differs from the platform default. If set 'true' on case-insensitive file systems, then the walk may return more or less results than expected. --nodir Do not match directories, only files. Note: to *only* match directories, append a '/' at the end of the pattern. --noext Do not expand extglob patterns, such as '+(a|b)' --noglobstar Do not expand '**' against multiple path portions. Ie, treat it as a normal '*' instead. --windows-path-no-escape Use '\' as a path separator *only*, and *never* as an escape character. If set, all '\' characters are replaced with '/' in the pattern. -D --max-depth= Maximum depth to traverse from the current working directory -C --cwd= Current working directory to execute/match in -r --root= A string path resolved against the 'cwd', which is used as the starting point for absolute patterns that start with '/' (but not drive letters or UNC paths on Windows). Note that this *doesn't* necessarily limit the walk to the 'root' directory, and doesn't affect the cwd starting point for non-absolute patterns. A pattern containing '..' will still be able to traverse out of the root directory, if it is not an actual root directory on the filesystem, and any non-absolute patterns will still be matched in the 'cwd'. To start absolute and non-absolute patterns in the same path, you can use '--root=' to set it to the empty string. However, be aware that on Windows systems, a pattern like 'x:/*' or '//host/share/*' will *always* start in the 'x:/' or '//host/share/' directory, regardless of the --root setting. --platform= Defaults to the value of 'process.platform' if available, or 'linux' if not. Setting --platform=win32 on non-Windows systems may cause strange behavior! -i --ignore= Glob patterns to ignore Can be set multiple times -v --debug Output a huge amount of noisy debug information about patterns as they are parsed and used to match files. -h --help Show this usage information ``` ## `glob(pattern: string | string[], options?: GlobOptions) => Promise` Perform an asynchronous glob search for the pattern(s) specified. Returns [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the `withFileTypes` option is set to `true`. See below for full options field desciptions. ## `globSync(pattern: string | string[], options?: GlobOptions) => string[] | Path[]` Synchronous form of `glob()`. Alias: `glob.sync()` ## `globIterate(pattern: string | string[], options?: GlobOptions) => AsyncGenerator` Return an async iterator for walking glob pattern matches. Alias: `glob.iterate()` ## `globIterateSync(pattern: string | string[], options?: GlobOptions) => Generator` Return a sync iterator for walking glob pattern matches. Alias: `glob.iterate.sync()`, `glob.sync.iterate()` ## `globStream(pattern: string | string[], options?: GlobOptions) => Minipass` Return a stream that emits all the strings or `Path` objects and then emits `end` when completed. Alias: `glob.stream()` ## `globStreamSync(pattern: string | string[], options?: GlobOptions) => Minipass` Syncronous form of `globStream()`. Will read all the matches as fast as you consume them, even all in a single tick if you consume them immediately, but will still respond to backpressure if they're not consumed immediately. Alias: `glob.stream.sync()`, `glob.sync.stream()` ## `hasMagic(pattern: string | string[], options?: GlobOptions) => boolean` Returns `true` if the provided pattern contains any "magic" glob characters, given the options provided. Brace expansion is not considered "magic" unless the `magicalBraces` option is set, as brace expansion just turns one string into an array of strings. So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and `'xby'` both do not contain any magic glob characters, and it's treated the same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` is in the options, brace expansion _is_ treated as a pattern having magic. ## `escape(pattern: string, options?: GlobOptions) => string` Escape all magic characters in a glob pattern, so that it will only ever match literal strings If the `windowsPathsNoEscape` option is used, then characters are escaped by wrapping in `[]`, because a magic character wrapped in a character class can only be satisfied by that exact character. Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped or unescaped. ## `unescape(pattern: string, options?: GlobOptions) => string` Un-escape a glob string that may contain some escaped characters. If the `windowsPathsNoEscape` option is used, then square-brace escapes are removed, but not backslash escapes. For example, it will turn the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`, because `\` is a path separator in `windowsPathsNoEscape` mode. When `windowsPathsNoEscape` is not set, then both brace escapes and backslash escapes are removed. Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped or unescaped. ## Class `Glob` An object that can perform glob pattern traversals. ### `const g = new Glob(pattern: string | string[], options: GlobOptions)` Options object is required. See full options descriptions below. Note that a previous `Glob` object can be passed as the `GlobOptions` to another `Glob` instantiation to re-use settings and caches with a new pattern. Traversal functions can be called multiple times to run the walk again. ### `g.stream()` Stream results asynchronously, ### `g.streamSync()` Stream results synchronously. ### `g.iterate()` Default async iteration function. Returns an AsyncGenerator that iterates over the results. ### `g.iterateSync()` Default sync iteration function. Returns a Generator that iterates over the results. ### `g.walk()` Returns a Promise that resolves to the results array. ### `g.walkSync()` Returns a results array. ### Properties All options are stored as properties on the `Glob` object. - `opts` The options provided to the constructor. - `patterns` An array of parsed immutable `Pattern` objects. ## Options Exported as `GlobOptions` TypeScript interface. A `GlobOptions` object may be provided to any of the exported methods, and must be provided to the `Glob` constructor. All options are optional, boolean, and false by default, unless otherwise noted. All resolved options are added to the Glob object as properties. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to share the previously loaded cache. - `cwd` String path or `file://` string or URL object. The current working directory in which to search. Defaults to `process.cwd()`. See also: "Windows, CWDs, Drive Letters, and UNC Paths", below. This option may be either a string path or a `file://` URL object or string. - `root` A string path resolved against the `cwd` option, which is used as the starting point for absolute patterns that start with `/`, (but not drive letters or UNC paths on Windows). Note that this _doesn't_ necessarily limit the walk to the `root` directory, and doesn't affect the cwd starting point for non-absolute patterns. A pattern containing `..` will still be able to traverse out of the root directory, if it is not an actual root directory on the filesystem, and any non-absolute patterns will be matched in the `cwd`. For example, the pattern `/../*` with `{root:'/some/path'}` will return all files in `/some`, not all files in `/some/path`. The pattern `*` with `{root:'/some/path'}` will return all the entries in the cwd, not the entries in `/some/path`. To start absolute and non-absolute patterns in the same path, you can use `{root:''}`. However, be aware that on Windows systems, a pattern like `x:/*` or `//host/share/*` will _always_ start in the `x:/` or `//host/share` directory, regardless of the `root` setting. - `windowsPathsNoEscape` Use `\\` as a path separator _only_, and _never_ as an escape character. If set, all `\\` characters are replaced with `/` in the pattern. Note that this makes it **impossible** to match against paths containing literal glob pattern characters, but allows matching with patterns constructed using `path.join()` and `path.resolve()` on Windows platforms, mimicking the (buggy!) behavior of Glob v7 and before on Windows. Please use with caution, and be mindful of [the caveat below about Windows paths](#windows). (For legacy reasons, this is also set if `allowWindowsEscape` is set to the exact value `false`.) - `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. - `magicalBraces` Treat brace expansion like `{a,b}` as a "magic" pattern. Has no effect if {@link nobrace} is set. Only has effect on the {@link hasMagic} function, no effect on glob pattern matching itself. - `dotRelative` Prepend all relative path strings with `./` (or `.\` on Windows). Without this option, returned relative paths are "bare", so instead of returning `'./foo/bar'`, they are returned as `'foo/bar'`. Relative patterns starting with `'../'` are not prepended with `./`, even if this option is set. - `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. - `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. - `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) - `noext` Do not match "extglob" patterns such as `+(a|b)`. - `nocase` Perform a case-insensitive match. This defaults to `true` on macOS and Windows systems, and `false` on all others. **Note** `nocase` should only be explicitly set when it is known that the filesystem's case sensitivity differs from the platform default. If set `true` on case-sensitive file systems, or `false` on case-insensitive file systems, then the walk may return more or less results than expected. - `maxDepth` Specify a number to limit the depth of the directory traversal to this many levels below the `cwd`. - `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. - `nodir` Do not match directories, only files. (Note: to match _only_ directories, put a `/` at the end of the pattern.) Note: when `follow` and `nodir` are both set, then symbolic links to directories are also omitted. - `stat` Call `lstat()` on all entries, whether required or not to determine whether it's a valid match. When used with `withFileTypes`, this means that matches will include data such as modified time, permissions, and so on. Note that this will incur a performance cost due to the added system calls. - `ignore` string or string[], or an object with `ignore` and `ignoreChildren` methods. If a string or string[] is provided, then this is treated as a glob pattern or array of glob patterns to exclude from matches. To ignore all children within a directory, as well as the entry itself, append `'/**'` to the ignore pattern. **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of any other settings. If an object is provided that has `ignored(path)` and/or `childrenIgnored(path)` methods, then these methods will be called to determine whether any Path is a match or if its children should be traversed, respectively. - `follow` Follow symlinked directories when expanding `**` patterns. This can result in a lot of duplicate references in the presence of cyclic links, and make performance quite bad. By default, a `**` in a pattern will follow 1 symbolic link if it is not the first item in the pattern, or none if it is the first item in the pattern, following the same behavior as Bash. Note: when `follow` and `nodir` are both set, then symbolic links to directories are also omitted. - `realpath` Set to true to call `fs.realpath` on all of the results. In the case of an entry that cannot be resolved, the entry is omitted. This incurs a slight performance penalty, of course, because of the added system calls. - `absolute` Set to true to always receive absolute paths for matched files. Set to `false` to always receive relative paths for matched files. By default, when this option is not set, absolute paths are returned for patterns that are absolute, and otherwise paths are returned that are relative to the `cwd` setting. This does _not_ make an extra system call to get the realpath, it only does string path resolution. `absolute` may not be used along with `withFileTypes`. - `posix` Set to true to use `/` as the path separator in returned results. On posix systems, this has no effect. On Windows systems, this will return `/` delimited path results, and absolute paths will be returned in their full resolved UNC path form, eg insted of `'C:\\foo\\bar'`, it will return `//?/C:/foo/bar`. - `platform` Defaults to value of `process.platform` if available, or `'linux'` if not. Setting `platform:'win32'` on non-Windows systems may cause strange behavior. - `withFileTypes` Return [PathScurry](http://npm.im/path-scurry) `Path` objects instead of strings. These are similar to a NodeJS `Dirent` object, but with additional methods and properties. `withFileTypes` may not be used along with `absolute`. - `signal` An AbortSignal which will cancel the Glob walk when triggered. - `fs` An override object to pass in custom filesystem methods. See [PathScurry docs](http://npm.im/path-scurry) for what can be overridden. - `scurry` A [PathScurry](http://npm.im/path-scurry) object used to traverse the file system. If the `nocase` option is set explicitly, then any provided `scurry` object must match this setting. - `includeChildMatches` boolean, default `true`. Do not match any children of any matches. For example, the pattern `**\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode. This is especially useful for cases like "find all `node_modules` folders, but not the ones in `node_modules`". In order to support this, the `Ignore` implementation must support an `add(pattern: string)` method. If using the default `Ignore` class, then this is fine, but if this is set to `false`, and a custom `Ignore` is provided that does not have an `add()` method, then it will throw an error. **Caveat** It _only_ ignores matches that would be a descendant of a previous match, and only if that descendant is matched _after_ the ancestor is encountered. Since the file system walk happens in indeterminate order, it's possible that a match will already be added before its ancestor, if multiple or braced patterns are used. For example: ```js const results = await glob( [ // likely to match first, since it's just a stat 'a/b/c/d/e/f', // this pattern is more complicated! It must to various readdir() // calls and test the results against a regular expression, and that // is certainly going to take a little bit longer. // // So, later on, it encounters a match at 'a/b/c/d/e', but it's too // late to ignore a/b/c/d/e/f, because it's already been emitted. 'a/[bdf]/?/[a-z]/*', ], { includeChildMatches: false }, ) ``` It's best to only set this to `false` if you can be reasonably sure that no components of the pattern will potentially match one another's file system descendants, or if the occasional included child entry will not cause problems. ## Glob Primer Much more information about glob pattern expansion can be found by running `man bash` and searching for `Pattern Matching`. "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with 2 or more comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion. With the exception of `**`, none of these match path separators (ie, `/` on all platforms, and `\` on Windows). - `*` Matches 0 or more characters in a single path portion. When alone in a path portion, it must match at least 1 character. If `dot:true` is not specified, then `*` will not match against a `.` character at the start of a path portion. - `?` Matches 1 character. If `dot:true` is not specified, then `?` will not match against a `.` character at the start of a path portion. - `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. If the first character is `]`, then it will be considered the same as `\]`, rather than the end of the character class. - `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. May _not_ contain `/` characters. Similar to `*`, if alone in a path portion, then the path portion must have at least one character. - `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. May _not_ contain `/` characters. - `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. May _not_ contain `/` characters. - `*(a|b|c)` Matches zero or more occurrences of the patterns provided. May _not_ contain `/` characters. - `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided. May _not_ contain `/` characters. - `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories, unless `{follow:true}` is passed in the options object. A pattern like `a/b/**` will only match `a/b` if it is a directory. Follows 1 symbolic link if not the first item in the pattern, or 0 if it is the first item, unless `follow:true` is set, in which case it follows all symbolic links. `[:class:]` patterns are supported by this implementation, but `[=c=]` and `[.symbol.]` style class patterns are not. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: ```sh $ echo a*s*d*f a*s*d*f ``` ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 5, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not traversed as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. You can force glob to traverse symlinks with `**` by setting `{follow:true}` in the options. There is no equivalent of the `nonull` option. A pattern that does not find any matches simply resolves to nothing. (An empty array, immediately ended stream, etc.) If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. The character class patterns `[:class:]` (posix standard named classes) style class patterns are supported and unicode-aware, but `[=c=]` (locale-specific character collation weight), and `[.symbol.]` (collating symbol), are not. ### Repeated Slashes Unlike Bash and zsh, repeated `/` are always coalesced into a single path separator. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. To automatically coerce all `\` characters to `/` in pattern strings, **thus making it impossible to escape literal glob characters**, you may set the `windowsPathsNoEscape` option to `true`. ### Windows, CWDs, Drive Letters, and UNC Paths On posix systems, when a pattern starts with `/`, any `cwd` option is ignored, and the traversal starts at `/`, plus any non-magic path portions specified in the pattern. On Windows systems, the behavior is similar, but the concept of an "absolute path" is somewhat more involved. #### UNC Paths A UNC path may be used as the start of a pattern on Windows platforms. For example, a pattern like: `//?/x:/*` will return all file entries in the root of the `x:` drive. A pattern like `//ComputerName/Share/*` will return all files in the associated share. UNC path roots are always compared case insensitively. #### Drive Letters A pattern starting with a drive letter, like `c:/*`, will search in that drive, regardless of any `cwd` option provided. If the pattern starts with `/`, and is not a UNC path, and there is an explicit `cwd` option set with a drive letter, then the drive letter in the `cwd` is used as the root of the directory traversal. For example, `glob('/tmp', { cwd: 'c:/any/thing' })` will return `['c:/tmp']` as the result. If an explicit `cwd` option is not provided, and the pattern starts with `/`, then the traversal will run on the root of the drive provided as the `cwd` option. (That is, it is the result of `path.resolve('/')`.) ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. By design, this implementation caches all readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache object is reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ### See Also: - `man sh` - `man bash` [Pattern Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) - `man 3 fnmatch` - `man 5 gitignore` - [minimatch documentation](https://github.com/isaacs/minimatch) ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ```sh # to run tests npm test # to re-generate test fixtures npm run test-regen # run the benchmarks npm run bench # to profile javascript npm run prof ``` ## Comparison to Other JavaScript Glob Implementations **tl;dr** - If you want glob matching that is as faithful as possible to Bash pattern expansion semantics, and as fast as possible within that constraint, _use this module_. - If you are reasonably sure that the patterns you will encounter are relatively simple, and want the absolutely fastest glob matcher out there, _use [fast-glob](http://npm.im/fast-glob)_. - If you are reasonably sure that the patterns you will encounter are relatively simple, and want the convenience of automatically respecting `.gitignore` files, _use [globby](http://npm.im/globby)_. There are some other glob matcher libraries on npm, but these three are (in my opinion, as of 2023) the best. --- **full explanation** Every library reflects a set of opinions and priorities in the trade-offs it makes. Other than this library, I can personally recommend both [globby](http://npm.im/globby) and [fast-glob](http://npm.im/fast-glob), though they differ in their benefits and drawbacks. Both have very nice APIs and are reasonably fast. `fast-glob` is, as far as I am aware, the fastest glob implementation in JavaScript today. However, there are many cases where the choices that `fast-glob` makes in pursuit of speed mean that its results differ from the results returned by Bash and other sh-like shells, which may be surprising. In my testing, `fast-glob` is around 10-20% faster than this module when walking over 200k files nested 4 directories deep[1](#fn-webscale). However, there are some inconsistencies with Bash matching behavior that this module does not suffer from: - `**` only matches files, not directories - `..` path portions are not handled unless they appear at the start of the pattern - `./!()` will not match any files that _start_ with ``, even if they do not match ``. For example, `!(9).txt` will not match `9999.txt`. - Some brace patterns in the middle of a pattern will result in failing to find certain matches. - Extglob patterns are allowed to contain `/` characters. Globby exhibits all of the same pattern semantics as fast-glob, (as it is a wrapper around fast-glob) and is slightly slower than node-glob (by about 10-20% in the benchmark test set, or in other words, anywhere from 20-50% slower than fast-glob). However, it adds some API conveniences that may be worth the costs. - Support for `.gitignore` and other ignore files. - Support for negated globs (ie, patterns starting with `!` rather than using a separate `ignore` option). The priority of this module is "correctness" in the sense of performing a glob pattern expansion as faithfully as possible to the behavior of Bash and other sh-like shells, with as much speed as possible. Note that prior versions of `node-glob` are _not_ on this list. Former versions of this module are far too slow for any cases where performance matters at all, and were designed with APIs that are extremely dated by current JavaScript standards. --- [1]: In the cases where this module returns results and `fast-glob` doesn't, it's even faster, of course. ![lumpy space princess saying 'oh my GLOB'](https://github.com/isaacs/node-glob/raw/main/oh-my-glob.gif) ### Benchmark Results First number is time, smaller is better. Second number is the count of results returned. ``` --- pattern: '**' --- ~~ sync ~~ node fast-glob sync 0m0.598s 200364 node globby sync 0m0.765s 200364 node current globSync mjs 0m0.683s 222656 node current glob syncStream 0m0.649s 222656 ~~ async ~~ node fast-glob async 0m0.350s 200364 node globby async 0m0.509s 200364 node current glob async mjs 0m0.463s 222656 node current glob stream 0m0.411s 222656 --- pattern: '**/..' --- ~~ sync ~~ node fast-glob sync 0m0.486s 0 node globby sync 0m0.769s 200364 node current globSync mjs 0m0.564s 2242 node current glob syncStream 0m0.583s 2242 ~~ async ~~ node fast-glob async 0m0.283s 0 node globby async 0m0.512s 200364 node current glob async mjs 0m0.299s 2242 node current glob stream 0m0.312s 2242 --- pattern: './**/0/**/0/**/0/**/0/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.490s 10 node globby sync 0m0.517s 10 node current globSync mjs 0m0.540s 10 node current glob syncStream 0m0.550s 10 ~~ async ~~ node fast-glob async 0m0.290s 10 node globby async 0m0.296s 10 node current glob async mjs 0m0.278s 10 node current glob stream 0m0.302s 10 --- pattern: './**/[01]/**/[12]/**/[23]/**/[45]/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.500s 160 node globby sync 0m0.528s 160 node current globSync mjs 0m0.556s 160 node current glob syncStream 0m0.573s 160 ~~ async ~~ node fast-glob async 0m0.283s 160 node globby async 0m0.301s 160 node current glob async mjs 0m0.306s 160 node current glob stream 0m0.322s 160 --- pattern: './**/0/**/0/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.502s 5230 node globby sync 0m0.527s 5230 node current globSync mjs 0m0.544s 5230 node current glob syncStream 0m0.557s 5230 ~~ async ~~ node fast-glob async 0m0.285s 5230 node globby async 0m0.305s 5230 node current glob async mjs 0m0.304s 5230 node current glob stream 0m0.310s 5230 --- pattern: '**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.580s 200023 node globby sync 0m0.771s 200023 node current globSync mjs 0m0.685s 200023 node current glob syncStream 0m0.649s 200023 ~~ async ~~ node fast-glob async 0m0.349s 200023 node globby async 0m0.509s 200023 node current glob async mjs 0m0.427s 200023 node current glob stream 0m0.388s 200023 --- pattern: '{**/*.txt,**/?/**/*.txt,**/?/**/?/**/*.txt,**/?/**/?/**/?/**/*.txt,**/?/**/?/**/?/**/?/**/*.txt}' --- ~~ sync ~~ node fast-glob sync 0m0.589s 200023 node globby sync 0m0.771s 200023 node current globSync mjs 0m0.716s 200023 node current glob syncStream 0m0.684s 200023 ~~ async ~~ node fast-glob async 0m0.351s 200023 node globby async 0m0.518s 200023 node current glob async mjs 0m0.462s 200023 node current glob stream 0m0.468s 200023 --- pattern: '**/5555/0000/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.496s 1000 node globby sync 0m0.519s 1000 node current globSync mjs 0m0.539s 1000 node current glob syncStream 0m0.567s 1000 ~~ async ~~ node fast-glob async 0m0.285s 1000 node globby async 0m0.299s 1000 node current glob async mjs 0m0.305s 1000 node current glob stream 0m0.301s 1000 --- pattern: './**/0/**/../[01]/**/0/../**/0/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.484s 0 node globby sync 0m0.507s 0 node current globSync mjs 0m0.577s 4880 node current glob syncStream 0m0.586s 4880 ~~ async ~~ node fast-glob async 0m0.280s 0 node globby async 0m0.298s 0 node current glob async mjs 0m0.327s 4880 node current glob stream 0m0.324s 4880 --- pattern: '**/????/????/????/????/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.547s 100000 node globby sync 0m0.673s 100000 node current globSync mjs 0m0.626s 100000 node current glob syncStream 0m0.618s 100000 ~~ async ~~ node fast-glob async 0m0.315s 100000 node globby async 0m0.414s 100000 node current glob async mjs 0m0.366s 100000 node current glob stream 0m0.345s 100000 --- pattern: './{**/?{/**/?{/**/?{/**/?,,,,},,,,},,,,},,,}/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.588s 100000 node globby sync 0m0.670s 100000 node current globSync mjs 0m0.717s 200023 node current glob syncStream 0m0.687s 200023 ~~ async ~~ node fast-glob async 0m0.343s 100000 node globby async 0m0.418s 100000 node current glob async mjs 0m0.519s 200023 node current glob stream 0m0.451s 200023 --- pattern: '**/!(0|9).txt' --- ~~ sync ~~ node fast-glob sync 0m0.573s 160023 node globby sync 0m0.731s 160023 node current globSync mjs 0m0.680s 180023 node current glob syncStream 0m0.659s 180023 ~~ async ~~ node fast-glob async 0m0.345s 160023 node globby async 0m0.476s 160023 node current glob async mjs 0m0.427s 180023 node current glob stream 0m0.388s 180023 --- pattern: './{*/**/../{*/**/../{*/**/../{*/**/../{*/**,,,,},,,,},,,,},,,,},,,,}/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.483s 0 node globby sync 0m0.512s 0 node current globSync mjs 0m0.811s 200023 node current glob syncStream 0m0.773s 200023 ~~ async ~~ node fast-glob async 0m0.280s 0 node globby async 0m0.299s 0 node current glob async mjs 0m0.617s 200023 node current glob stream 0m0.568s 200023 --- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.485s 0 node globby sync 0m0.507s 0 node current globSync mjs 0m0.759s 200023 node current glob syncStream 0m0.740s 200023 ~~ async ~~ node fast-glob async 0m0.281s 0 node globby async 0m0.297s 0 node current glob async mjs 0m0.544s 200023 node current glob stream 0m0.464s 200023 --- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.486s 0 node globby sync 0m0.513s 0 node current globSync mjs 0m0.734s 200023 node current glob syncStream 0m0.696s 200023 ~~ async ~~ node fast-glob async 0m0.286s 0 node globby async 0m0.296s 0 node current glob async mjs 0m0.506s 200023 node current glob stream 0m0.483s 200023 --- pattern: './0/**/../1/**/../2/**/../3/**/../4/**/../5/**/../6/**/../7/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.060s 0 node globby sync 0m0.074s 0 node current globSync mjs 0m0.067s 0 node current glob syncStream 0m0.066s 0 ~~ async ~~ node fast-glob async 0m0.060s 0 node globby async 0m0.075s 0 node current glob async mjs 0m0.066s 0 node current glob stream 0m0.067s 0 --- pattern: './**/?/**/?/**/?/**/?/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.568s 100000 node globby sync 0m0.651s 100000 node current globSync mjs 0m0.619s 100000 node current glob syncStream 0m0.617s 100000 ~~ async ~~ node fast-glob async 0m0.332s 100000 node globby async 0m0.409s 100000 node current glob async mjs 0m0.372s 100000 node current glob stream 0m0.351s 100000 --- pattern: '**/*/**/*/**/*/**/*/**' --- ~~ sync ~~ node fast-glob sync 0m0.603s 200113 node globby sync 0m0.798s 200113 node current globSync mjs 0m0.730s 222137 node current glob syncStream 0m0.693s 222137 ~~ async ~~ node fast-glob async 0m0.356s 200113 node globby async 0m0.525s 200113 node current glob async mjs 0m0.508s 222137 node current glob stream 0m0.455s 222137 --- pattern: './**/*/**/*/**/*/**/*/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.622s 200000 node globby sync 0m0.792s 200000 node current globSync mjs 0m0.722s 200000 node current glob syncStream 0m0.695s 200000 ~~ async ~~ node fast-glob async 0m0.369s 200000 node globby async 0m0.527s 200000 node current glob async mjs 0m0.502s 200000 node current glob stream 0m0.481s 200000 --- pattern: '**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.588s 200023 node globby sync 0m0.771s 200023 node current globSync mjs 0m0.684s 200023 node current glob syncStream 0m0.658s 200023 ~~ async ~~ node fast-glob async 0m0.352s 200023 node globby async 0m0.516s 200023 node current glob async mjs 0m0.432s 200023 node current glob stream 0m0.384s 200023 --- pattern: './**/**/**/**/**/**/**/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.589s 200023 node globby sync 0m0.766s 200023 node current globSync mjs 0m0.682s 200023 node current glob syncStream 0m0.652s 200023 ~~ async ~~ node fast-glob async 0m0.352s 200023 node globby async 0m0.523s 200023 node current glob async mjs 0m0.436s 200023 node current glob stream 0m0.380s 200023 --- pattern: '**/*/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.592s 200023 node globby sync 0m0.776s 200023 node current globSync mjs 0m0.691s 200023 node current glob syncStream 0m0.659s 200023 ~~ async ~~ node fast-glob async 0m0.357s 200023 node globby async 0m0.513s 200023 node current glob async mjs 0m0.471s 200023 node current glob stream 0m0.424s 200023 --- pattern: '**/*/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.585s 200023 node globby sync 0m0.766s 200023 node current globSync mjs 0m0.694s 200023 node current glob syncStream 0m0.664s 200023 ~~ async ~~ node fast-glob async 0m0.350s 200023 node globby async 0m0.514s 200023 node current glob async mjs 0m0.472s 200023 node current glob stream 0m0.424s 200023 --- pattern: '**/[0-9]/**/*.txt' --- ~~ sync ~~ node fast-glob sync 0m0.544s 100000 node globby sync 0m0.636s 100000 node current globSync mjs 0m0.626s 100000 node current glob syncStream 0m0.621s 100000 ~~ async ~~ node fast-glob async 0m0.322s 100000 node globby async 0m0.404s 100000 node current glob async mjs 0m0.360s 100000 node current glob stream 0m0.352s 100000 ``` import { Minimatch } from 'minimatch'; import { Minipass } from 'minipass'; import { FSOption, Path, PathScurry } from 'path-scurry'; import { IgnoreLike } from './ignore.js'; import { Pattern } from './pattern.js'; export type MatchSet = Minimatch['set']; export type GlobParts = Exclude; /** * A `GlobOptions` object may be provided to any of the exported methods, and * must be provided to the `Glob` constructor. * * All options are optional, boolean, and false by default, unless otherwise * noted. * * All resolved options are added to the Glob object as properties. * * If you are running many `glob` operations, you can pass a Glob object as the * `options` argument to a subsequent operation to share the previously loaded * cache. */ export interface GlobOptions { /** * Set to `true` to always receive absolute paths for * matched files. Set to `false` to always return relative paths. * * When this option is not set, absolute paths are returned for patterns * that are absolute, and otherwise paths are returned that are relative * to the `cwd` setting. * * This does _not_ make an extra system call to get * the realpath, it only does string path resolution. * * Conflicts with {@link withFileTypes} */ absolute?: boolean; /** * Set to false to enable {@link windowsPathsNoEscape} * * @deprecated */ allowWindowsEscape?: boolean; /** * The current working directory in which to search. Defaults to * `process.cwd()`. * * May be eiher a string path or a `file://` URL object or string. */ cwd?: string | URL; /** * Include `.dot` files in normal matches and `globstar` * matches. Note that an explicit dot in a portion of the pattern * will always match dot files. */ dot?: boolean; /** * Prepend all relative path strings with `./` (or `.\` on Windows). * * Without this option, returned relative paths are "bare", so instead of * returning `'./foo/bar'`, they are returned as `'foo/bar'`. * * Relative patterns starting with `'../'` are not prepended with `./`, even * if this option is set. */ dotRelative?: boolean; /** * Follow symlinked directories when expanding `**` * patterns. This can result in a lot of duplicate references in * the presence of cyclic links, and make performance quite bad. * * By default, a `**` in a pattern will follow 1 symbolic link if * it is not the first item in the pattern, or none if it is the * first item in the pattern, following the same behavior as Bash. */ follow?: boolean; /** * string or string[], or an object with `ignore` and `ignoreChildren` * methods. * * If a string or string[] is provided, then this is treated as a glob * pattern or array of glob patterns to exclude from matches. To ignore all * children within a directory, as well as the entry itself, append `'/**'` * to the ignore pattern. * * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of * any other settings. * * If an object is provided that has `ignored(path)` and/or * `childrenIgnored(path)` methods, then these methods will be called to * determine whether any Path is a match or if its children should be * traversed, respectively. */ ignore?: string | string[] | IgnoreLike; /** * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no * effect if {@link nobrace} is set. * * Only has effect on the {@link hasMagic} function. */ magicalBraces?: boolean; /** * Add a `/` character to directory matches. Note that this requires * additional stat calls in some cases. */ mark?: boolean; /** * Perform a basename-only match if the pattern does not contain any slash * characters. That is, `*.js` would be treated as equivalent to * `**\/*.js`, matching all js files in all directories. */ matchBase?: boolean; /** * Limit the directory traversal to a given depth below the cwd. * Note that this does NOT prevent traversal to sibling folders, * root patterns, and so on. It only limits the maximum folder depth * that the walk will descend, relative to the cwd. */ maxDepth?: number; /** * Do not expand `{a,b}` and `{1..3}` brace sets. */ nobrace?: boolean; /** * Perform a case-insensitive match. This defaults to `true` on macOS and * Windows systems, and `false` on all others. * * **Note** `nocase` should only be explicitly set when it is * known that the filesystem's case sensitivity differs from the * platform default. If set `true` on case-sensitive file * systems, or `false` on case-insensitive file systems, then the * walk may return more or less results than expected. */ nocase?: boolean; /** * Do not match directories, only files. (Note: to match * _only_ directories, put a `/` at the end of the pattern.) */ nodir?: boolean; /** * Do not match "extglob" patterns such as `+(a|b)`. */ noext?: boolean; /** * Do not match `**` against multiple filenames. (Ie, treat it as a normal * `*` instead.) * * Conflicts with {@link matchBase} */ noglobstar?: boolean; /** * Defaults to value of `process.platform` if available, or `'linux'` if * not. Setting `platform:'win32'` on non-Windows systems may cause strange * behavior. */ platform?: NodeJS.Platform; /** * Set to true to call `fs.realpath` on all of the * results. In the case of an entry that cannot be resolved, the * entry is omitted. This incurs a slight performance penalty, of * course, because of the added system calls. */ realpath?: boolean; /** * * A string path resolved against the `cwd` option, which * is used as the starting point for absolute patterns that start * with `/`, (but not drive letters or UNC paths on Windows). * * Note that this _doesn't_ necessarily limit the walk to the * `root` directory, and doesn't affect the cwd starting point for * non-absolute patterns. A pattern containing `..` will still be * able to traverse out of the root directory, if it is not an * actual root directory on the filesystem, and any non-absolute * patterns will be matched in the `cwd`. For example, the * pattern `/../*` with `{root:'/some/path'}` will return all * files in `/some`, not all files in `/some/path`. The pattern * `*` with `{root:'/some/path'}` will return all the entries in * the cwd, not the entries in `/some/path`. * * To start absolute and non-absolute patterns in the same * path, you can use `{root:''}`. However, be aware that on * Windows systems, a pattern like `x:/*` or `//host/share/*` will * _always_ start in the `x:/` or `//host/share` directory, * regardless of the `root` setting. */ root?: string; /** * A [PathScurry](http://npm.im/path-scurry) object used * to traverse the file system. If the `nocase` option is set * explicitly, then any provided `scurry` object must match this * setting. */ scurry?: PathScurry; /** * Call `lstat()` on all entries, whether required or not to determine * if it's a valid match. When used with {@link withFileTypes}, this means * that matches will include data such as modified time, permissions, and * so on. Note that this will incur a performance cost due to the added * system calls. */ stat?: boolean; /** * An AbortSignal which will cancel the Glob walk when * triggered. */ signal?: AbortSignal; /** * Use `\\` as a path separator _only_, and * _never_ as an escape character. If set, all `\\` characters are * replaced with `/` in the pattern. * * Note that this makes it **impossible** to match against paths * containing literal glob pattern characters, but allows matching * with patterns constructed using `path.join()` and * `path.resolve()` on Windows platforms, mimicking the (buggy!) * behavior of Glob v7 and before on Windows. Please use with * caution, and be mindful of [the caveat below about Windows * paths](#windows). (For legacy reasons, this is also set if * `allowWindowsEscape` is set to the exact value `false`.) */ windowsPathsNoEscape?: boolean; /** * Return [PathScurry](http://npm.im/path-scurry) * `Path` objects instead of strings. These are similar to a * NodeJS `Dirent` object, but with additional methods and * properties. * * Conflicts with {@link absolute} */ withFileTypes?: boolean; /** * An fs implementation to override some or all of the defaults. See * http://npm.im/path-scurry for details about what can be overridden. */ fs?: FSOption; /** * Just passed along to Minimatch. Note that this makes all pattern * matching operations slower and *extremely* noisy. */ debug?: boolean; /** * Return `/` delimited paths, even on Windows. * * On posix systems, this has no effect. But, on Windows, it means that * paths will be `/` delimited, and absolute paths will be their full * resolved UNC forms, eg instead of `'C:\\foo\\bar'`, it would return * `'//?/C:/foo/bar'` */ posix?: boolean; /** * Do not match any children of any matches. For example, the pattern * `**\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode. * * This is especially useful for cases like "find all `node_modules` * folders, but not the ones in `node_modules`". * * In order to support this, the `Ignore` implementation must support an * `add(pattern: string)` method. If using the default `Ignore` class, then * this is fine, but if this is set to `false`, and a custom `Ignore` is * provided that does not have an `add()` method, then it will throw an * error. * * **Caveat** It *only* ignores matches that would be a descendant of a * previous match, and only if that descendant is matched *after* the * ancestor is encountered. Since the file system walk happens in * indeterminate order, it's possible that a match will already be added * before its ancestor, if multiple or braced patterns are used. * * For example: * * ```ts * const results = await glob([ * // likely to match first, since it's just a stat * 'a/b/c/d/e/f', * * // this pattern is more complicated! It must to various readdir() * // calls and test the results against a regular expression, and that * // is certainly going to take a little bit longer. * // * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too * // late to ignore a/b/c/d/e/f, because it's already been emitted. * 'a/[bdf]/?/[a-z]/*', * ], { includeChildMatches: false }) * ``` * * It's best to only set this to `false` if you can be reasonably sure that * no components of the pattern will potentially match one another's file * system descendants, or if the occasional included child entry will not * cause problems. * * @default true */ includeChildMatches?: boolean; } export type GlobOptionsWithFileTypesTrue = GlobOptions & { withFileTypes: true; absolute?: undefined; mark?: undefined; posix?: undefined; }; export type GlobOptionsWithFileTypesFalse = GlobOptions & { withFileTypes?: false; }; export type GlobOptionsWithFileTypesUnset = GlobOptions & { withFileTypes?: undefined; }; export type Result = Opts extends GlobOptionsWithFileTypesTrue ? Path : Opts extends GlobOptionsWithFileTypesFalse ? string : Opts extends GlobOptionsWithFileTypesUnset ? string : string | Path; export type Results = Result[]; export type FileTypes = Opts extends GlobOptionsWithFileTypesTrue ? true : Opts extends GlobOptionsWithFileTypesFalse ? false : Opts extends GlobOptionsWithFileTypesUnset ? false : boolean; /** * An object that can perform glob pattern traversals. */ export declare class Glob implements GlobOptions { absolute?: boolean; cwd: string; root?: string; dot: boolean; dotRelative: boolean; follow: boolean; ignore?: string | string[] | IgnoreLike; magicalBraces: boolean; mark?: boolean; matchBase: boolean; maxDepth: number; nobrace: boolean; nocase: boolean; nodir: boolean; noext: boolean; noglobstar: boolean; pattern: string[]; platform: NodeJS.Platform; realpath: boolean; scurry: PathScurry; stat: boolean; signal?: AbortSignal; windowsPathsNoEscape: boolean; withFileTypes: FileTypes; includeChildMatches: boolean; /** * The options provided to the constructor. */ opts: Opts; /** * An array of parsed immutable {@link Pattern} objects. */ patterns: Pattern[]; /** * All options are stored as properties on the `Glob` object. * * See {@link GlobOptions} for full options descriptions. * * Note that a previous `Glob` object can be passed as the * `GlobOptions` to another `Glob` instantiation to re-use settings * and caches with a new pattern. * * Traversal functions can be called multiple times to run the walk * again. */ constructor(pattern: string | string[], opts: Opts); /** * Returns a Promise that resolves to the results array. */ walk(): Promise>; /** * synchronous {@link Glob.walk} */ walkSync(): Results; /** * Stream results asynchronously. */ stream(): Minipass, Result>; /** * Stream results synchronously. */ streamSync(): Minipass, Result>; /** * Default sync iteration function. Returns a Generator that * iterates over the results. */ iterateSync(): Generator, void, void>; [Symbol.iterator](): Generator, void, void>; /** * Default async iteration function. Returns an AsyncGenerator that * iterates over the results. */ iterate(): AsyncGenerator, void, void>; [Symbol.asyncIterator](): AsyncGenerator, void, void>; } //# sourceMappingURL=glob.d.ts.map{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAEnC,OAAO,EACL,QAAQ,EACR,IAAI,EACJ,UAAU,EAIX,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAGtC,MAAM,MAAM,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAC,CAAA;AACvC,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,SAAS,CAAC,CAAA;AAalE;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;;;;;;;OAYG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAE5B;;;;;OAKG;IACH,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;IAElB;;;;OAIG;IACH,GAAG,CAAC,EAAE,OAAO,CAAA;IAEb;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,OAAO,CAAA;IAErB;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAEhB;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IAEvC;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;OAGG;IACH,IAAI,CAAC,EAAE,OAAO,CAAA;IAEd;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAA;IAEnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IAEjB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IAEjB;;;;;;;;;OASG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAEhB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;IAEpB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;IAE1B;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,IAAI,CAAC,EAAE,MAAM,CAAA;IAEb;;;;;OAKG;IACH,MAAM,CAAC,EAAE,UAAU,CAAA;IAEnB;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,OAAO,CAAA;IAEd;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAA;IAEpB;;;;;;;;;;;;;OAaG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAE9B;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;OAGG;IACH,EAAE,CAAC,EAAE,QAAQ,CAAA;IAEb;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA0CG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B;AAED,MAAM,MAAM,4BAA4B,GAAG,WAAW,GAAG;IACvD,aAAa,EAAE,IAAI,CAAA;IAEnB,QAAQ,CAAC,EAAE,SAAS,CAAA;IACpB,IAAI,CAAC,EAAE,SAAS,CAAA;IAChB,KAAK,CAAC,EAAE,SAAS,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,6BAA6B,GAAG,WAAW,GAAG;IACxD,aAAa,CAAC,EAAE,KAAK,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,6BAA6B,GAAG,WAAW,GAAG;IACxD,aAAa,CAAC,EAAE,SAAS,CAAA;CAC1B,CAAA;AAED,MAAM,MAAM,MAAM,CAAC,IAAI,IACrB,IAAI,SAAS,4BAA4B,GAAG,IAAI,GAC9C,IAAI,SAAS,6BAA6B,GAAG,MAAM,GACnD,IAAI,SAAS,6BAA6B,GAAG,MAAM,GACnD,MAAM,GAAG,IAAI,CAAA;AACjB,MAAM,MAAM,OAAO,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,EAAE,CAAA;AAE1C,MAAM,MAAM,SAAS,CAAC,IAAI,IACxB,IAAI,SAAS,4BAA4B,GAAG,IAAI,GAC9C,IAAI,SAAS,6BAA6B,GAAG,KAAK,GAClD,IAAI,SAAS,6BAA6B,GAAG,KAAK,GAClD,OAAO,CAAA;AAEX;;GAEG;AACH,qBAAa,IAAI,CAAC,IAAI,SAAS,WAAW,CAAE,YAAW,WAAW;IAChE,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,GAAG,EAAE,OAAO,CAAA;IACZ,WAAW,EAAE,OAAO,CAAA;IACpB,MAAM,EAAE,OAAO,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IACvC,aAAa,EAAE,OAAO,CAAA;IACtB,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,SAAS,EAAE,OAAO,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,OAAO,CAAA;IACf,KAAK,EAAE,OAAO,CAAA;IACd,KAAK,EAAE,OAAO,CAAA;IACd,UAAU,EAAE,OAAO,CAAA;IACnB,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,QAAQ,EAAE,OAAO,CAAA;IACjB,MAAM,EAAE,UAAU,CAAA;IAClB,IAAI,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,oBAAoB,EAAE,OAAO,CAAA;IAC7B,aAAa,EAAE,SAAS,CAAC,IAAI,CAAC,CAAA;IAC9B,mBAAmB,EAAE,OAAO,CAAA;IAE5B;;OAEG;IACH,IAAI,EAAE,IAAI,CAAA;IAEV;;OAEG;IACH,QAAQ,EAAE,OAAO,EAAE,CAAA;IAEnB;;;;;;;;;;;OAWG;gBACS,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI;IA2HlD;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAoBpC;;OAEG;IACH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBzB;;OAEG;IACH,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAc9C;;OAEG;IACH,UAAU,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAclD;;;OAGG;IACH,WAAW,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGlD,CAAC,MAAM,CAAC,QAAQ,CAAC;IAIjB;;;OAGG;IACH,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGnD,CAAC,MAAM,CAAC,aAAa,CAAC;CAGvB"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Glob = void 0; const minimatch_1 = require("minimatch"); const node_url_1 = require("node:url"); const path_scurry_1 = require("path-scurry"); const pattern_js_1 = require("./pattern.js"); const walker_js_1 = require("./walker.js"); // if no process global, just call it linux. // so we default to case-sensitive, / separators const defaultPlatform = (typeof process === 'object' && process && typeof process.platform === 'string') ? process.platform : 'linux'; /** * An object that can perform glob pattern traversals. */ class Glob { absolute; cwd; root; dot; dotRelative; follow; ignore; magicalBraces; mark; matchBase; maxDepth; nobrace; nocase; nodir; noext; noglobstar; pattern; platform; realpath; scurry; stat; signal; windowsPathsNoEscape; withFileTypes; includeChildMatches; /** * The options provided to the constructor. */ opts; /** * An array of parsed immutable {@link Pattern} objects. */ patterns; /** * All options are stored as properties on the `Glob` object. * * See {@link GlobOptions} for full options descriptions. * * Note that a previous `Glob` object can be passed as the * `GlobOptions` to another `Glob` instantiation to re-use settings * and caches with a new pattern. * * Traversal functions can be called multiple times to run the walk * again. */ constructor(pattern, opts) { /* c8 ignore start */ if (!opts) throw new TypeError('glob options required'); /* c8 ignore stop */ this.withFileTypes = !!opts.withFileTypes; this.signal = opts.signal; this.follow = !!opts.follow; this.dot = !!opts.dot; this.dotRelative = !!opts.dotRelative; this.nodir = !!opts.nodir; this.mark = !!opts.mark; if (!opts.cwd) { this.cwd = ''; } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) { opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd); } this.cwd = opts.cwd || ''; this.root = opts.root; this.magicalBraces = !!opts.magicalBraces; this.nobrace = !!opts.nobrace; this.noext = !!opts.noext; this.realpath = !!opts.realpath; this.absolute = opts.absolute; this.includeChildMatches = opts.includeChildMatches !== false; this.noglobstar = !!opts.noglobstar; this.matchBase = !!opts.matchBase; this.maxDepth = typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity; this.stat = !!opts.stat; this.ignore = opts.ignore; if (this.withFileTypes && this.absolute !== undefined) { throw new Error('cannot set absolute and withFileTypes:true'); } if (typeof pattern === 'string') { pattern = [pattern]; } this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false; if (this.windowsPathsNoEscape) { pattern = pattern.map(p => p.replace(/\\/g, '/')); } if (this.matchBase) { if (opts.noglobstar) { throw new TypeError('base matching requires globstar'); } pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`)); } this.pattern = pattern; this.platform = opts.platform || defaultPlatform; this.opts = { ...opts, platform: this.platform }; if (opts.scurry) { this.scurry = opts.scurry; if (opts.nocase !== undefined && opts.nocase !== opts.scurry.nocase) { throw new Error('nocase option contradicts provided scurry option'); } } else { const Scurry = opts.platform === 'win32' ? path_scurry_1.PathScurryWin32 : opts.platform === 'darwin' ? path_scurry_1.PathScurryDarwin : opts.platform ? path_scurry_1.PathScurryPosix : path_scurry_1.PathScurry; this.scurry = new Scurry(this.cwd, { nocase: opts.nocase, fs: opts.fs, }); } this.nocase = this.scurry.nocase; // If you do nocase:true on a case-sensitive file system, then // we need to use regexps instead of strings for non-magic // path portions, because statting `aBc` won't return results // for the file `AbC` for example. const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; const mmo = { // default nocase based on platform ...opts, dot: this.dot, matchBase: this.matchBase, nobrace: this.nobrace, nocase: this.nocase, nocaseMagicOnly, nocomment: true, noext: this.noext, nonegate: true, optimizationLevel: 2, platform: this.platform, windowsPathsNoEscape: this.windowsPathsNoEscape, debug: !!this.opts.debug, }; const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo)); const [matchSet, globParts] = mms.reduce((set, m) => { set[0].push(...m.set); set[1].push(...m.globParts); return set; }, [[], []]); this.patterns = matchSet.map((set, i) => { const g = globParts[i]; /* c8 ignore start */ if (!g) throw new Error('invalid pattern object'); /* c8 ignore stop */ return new pattern_js_1.Pattern(set, g, 0, this.platform); }); } async walk() { // Walkers always return array of Path objects, so we just have to // coerce them into the right shape. It will have already called // realpath() if the option was set to do so, so we know that's cached. // start out knowing the cwd, at least return [ ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches, }).walk()), ]; } walkSync() { return [ ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches, }).walkSync(), ]; } stream() { return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches, }).stream(); } streamSync() { return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches, }).streamSync(); } /** * Default sync iteration function. Returns a Generator that * iterates over the results. */ iterateSync() { return this.streamSync()[Symbol.iterator](); } [Symbol.iterator]() { return this.iterateSync(); } /** * Default async iteration function. Returns an AsyncGenerator that * iterates over the results. */ iterate() { return this.stream()[Symbol.asyncIterator](); } [Symbol.asyncIterator]() { return this.iterate(); } } exports.Glob = Glob; //# sourceMappingURL=glob.js.map{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":";;;AAAA,yCAAuD;AAEvD,uCAAwC;AACxC,6CAOoB;AAEpB,6CAAsC;AACtC,2CAAoD;AAKpD,4CAA4C;AAC5C,gDAAgD;AAChD,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAyVX;;GAEG;AACH,MAAa,IAAI;IACf,QAAQ,CAAU;IAClB,GAAG,CAAQ;IACX,IAAI,CAAS;IACb,GAAG,CAAS;IACZ,WAAW,CAAS;IACpB,MAAM,CAAS;IACf,MAAM,CAAiC;IACvC,aAAa,CAAS;IACtB,IAAI,CAAU;IACd,SAAS,CAAS;IAClB,QAAQ,CAAQ;IAChB,OAAO,CAAS;IAChB,MAAM,CAAS;IACf,KAAK,CAAS;IACd,KAAK,CAAS;IACd,UAAU,CAAS;IACnB,OAAO,CAAU;IACjB,QAAQ,CAAiB;IACzB,QAAQ,CAAS;IACjB,MAAM,CAAY;IAClB,IAAI,CAAS;IACb,MAAM,CAAc;IACpB,oBAAoB,CAAS;IAC7B,aAAa,CAAiB;IAC9B,mBAAmB,CAAS;IAE5B;;OAEG;IACH,IAAI,CAAM;IAEV;;OAEG;IACH,QAAQ,CAAW;IAEnB;;;;;;;;;;;OAWG;IACH,YAAY,OAA0B,EAAE,IAAU;QAChD,qBAAqB;QACrB,IAAI,CAAC,IAAI;YAAE,MAAM,IAAI,SAAS,CAAC,uBAAuB,CAAC,CAAA;QACvD,oBAAoB;QACpB,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC,IAAI,CAAC,aAAgC,CAAA;QAC5D,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QACzB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;QAC3B,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAA;QACrB,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAA;QACrC,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAA;QACzB,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAA;QACvB,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;YACd,IAAI,CAAC,GAAG,GAAG,EAAE,CAAA;QACf,CAAC;aAAM,IAAI,IAAI,CAAC,GAAG,YAAY,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;YACrE,IAAI,CAAC,GAAG,GAAG,IAAA,wBAAa,EAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACpC,CAAC;QACD,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,EAAE,CAAA;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAA;QACrB,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC,IAAI,CAAC,aAAa,CAAA;QACzC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAA;QAC7B,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAA;QACzB,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAA;QAC/B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAA;QAC7B,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,mBAAmB,KAAK,KAAK,CAAA;QAE7D,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,CAAA;QACnC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,CAAA;QACjC,IAAI,CAAC,QAAQ;YACX,OAAO,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAA;QAC9D,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAA;QACvB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QAEzB,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACtD,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAA;QAC/D,CAAC;QAED,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAChC,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;QACrB,CAAC;QAED,IAAI,CAAC,oBAAoB;YACvB,CAAC,CAAC,IAAI,CAAC,oBAAoB;gBAC1B,IAAyC,CAAC,kBAAkB;oBAC3D,KAAK,CAAA;QAET,IAAI,IAAI,CAAC,oBAAoB,EAAE,CAAC;YAC9B,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAA;QACnD,CAAC;QAED,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;gBACpB,MAAM,IAAI,SAAS,CAAC,iCAAiC,CAAC,CAAA;YACxD,CAAC;YACD,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAA;QACjE,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QAEtB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,eAAe,CAAA;QAChD,IAAI,CAAC,IAAI,GAAG,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAA;QAChD,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;YACzB,IACE,IAAI,CAAC,MAAM,KAAK,SAAS;gBACzB,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAAC,MAAM,EAClC,CAAC;gBACD,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;YACrE,CAAC;QACH,CAAC;aAAM,CAAC;YACN,MAAM,MAAM,GACV,IAAI,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,6BAAe;gBAC3C,CAAC,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,8BAAgB;oBAC/C,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,6BAAe;wBACjC,CAAC,CAAC,wBAAU,CAAA;YACd,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE;gBACjC,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,EAAE,EAAE,IAAI,CAAC,EAAE;aACZ,CAAC,CAAA;QACJ,CAAC;QACD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA;QAEhC,8DAA8D;QAC9D,0DAA0D;QAC1D,6DAA6D;QAC7D,kCAAkC;QAClC,MAAM,eAAe,GACnB,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,IAAI,CAAC,QAAQ,KAAK,OAAO,CAAA;QAEzD,MAAM,GAAG,GAAqB;YAC5B,mCAAmC;YACnC,GAAG,IAAI;YACP,GAAG,EAAE,IAAI,CAAC,GAAG;YACb,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,eAAe;YACf,SAAS,EAAE,IAAI;YACf,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,QAAQ,EAAE,IAAI;YACd,iBAAiB,EAAE,CAAC;YACpB,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK;SACzB,CAAA;QAED,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,qBAAS,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAA;QACxD,MAAM,CAAC,QAAQ,EAAE,SAAS,CAAC,GAAG,GAAG,CAAC,MAAM,CACtC,CAAC,GAA0B,EAAE,CAAC,EAAE,EAAE;YAChC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAA;YACrB,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,CAAA;YAC3B,OAAO,GAAG,CAAA;QACZ,CAAC,EACD,CAAC,EAAE,EAAE,EAAE,CAAC,CACT,CAAA;QACD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;YACtC,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAA;YACtB,qBAAqB;YACrB,IAAI,CAAC,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;YACjD,oBAAoB;YACpB,OAAO,IAAI,oBAAO,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;QAC9C,CAAC,CAAC,CAAA;IACJ,CAAC;IAMD,KAAK,CAAC,IAAI;QACR,kEAAkE;QAClE,iEAAiE;QACjE,uEAAuE;QACvE,sCAAsC;QACtC,OAAO;YACL,GAAG,CAAC,MAAM,IAAI,sBAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;gBACvD,GAAG,IAAI,CAAC,IAAI;gBACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;oBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;oBACzC,CAAC,CAAC,QAAQ;gBACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;aAC9C,CAAC,CAAC,IAAI,EAAE,CAAC;SACX,CAAA;IACH,CAAC;IAMD,QAAQ;QACN,OAAO;YACL,GAAG,IAAI,sBAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;gBAChD,GAAG,IAAI,CAAC,IAAI;gBACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;oBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;oBACzC,CAAC,CAAC,QAAQ;gBACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;aAC9C,CAAC,CAAC,QAAQ,EAAE;SACd,CAAA;IACH,CAAC;IAMD,MAAM;QACJ,OAAO,IAAI,sBAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACpD,GAAG,IAAI,CAAC,IAAI;YACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,MAAM,EAAE,CAAA;IACb,CAAC;IAMD,UAAU;QACR,OAAO,IAAI,sBAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACpD,GAAG,IAAI,CAAC,IAAI;YACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,UAAU,EAAE,CAAA;IACjB,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF;AA7QD,oBA6QC","sourcesContent":["import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n /**\n * Set to `true` to always receive absolute paths for\n * matched files. Set to `false` to always return relative paths.\n *\n * When this option is not set, absolute paths are returned for patterns\n * that are absolute, and otherwise paths are returned that are relative\n * to the `cwd` setting.\n *\n * This does _not_ make an extra system call to get\n * the realpath, it only does string path resolution.\n *\n * Conflicts with {@link withFileTypes}\n */\n absolute?: boolean\n\n /**\n * Set to false to enable {@link windowsPathsNoEscape}\n *\n * @deprecated\n */\n allowWindowsEscape?: boolean\n\n /**\n * The current working directory in which to search. Defaults to\n * `process.cwd()`.\n *\n * May be eiher a string path or a `file://` URL object or string.\n */\n cwd?: string | URL\n\n /**\n * Include `.dot` files in normal matches and `globstar`\n * matches. Note that an explicit dot in a portion of the pattern\n * will always match dot files.\n */\n dot?: boolean\n\n /**\n * Prepend all relative path strings with `./` (or `.\\` on Windows).\n *\n * Without this option, returned relative paths are \"bare\", so instead of\n * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n *\n * Relative patterns starting with `'../'` are not prepended with `./`, even\n * if this option is set.\n */\n dotRelative?: boolean\n\n /**\n * Follow symlinked directories when expanding `**`\n * patterns. This can result in a lot of duplicate references in\n * the presence of cyclic links, and make performance quite bad.\n *\n * By default, a `**` in a pattern will follow 1 symbolic link if\n * it is not the first item in the pattern, or none if it is the\n * first item in the pattern, following the same behavior as Bash.\n */\n follow?: boolean\n\n /**\n * string or string[], or an object with `ignore` and `ignoreChildren`\n * methods.\n *\n * If a string or string[] is provided, then this is treated as a glob\n * pattern or array of glob patterns to exclude from matches. To ignore all\n * children within a directory, as well as the entry itself, append `'/**'`\n * to the ignore pattern.\n *\n * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n * any other settings.\n *\n * If an object is provided that has `ignored(path)` and/or\n * `childrenIgnored(path)` methods, then these methods will be called to\n * determine whether any Path is a match or if its children should be\n * traversed, respectively.\n */\n ignore?: string | string[] | IgnoreLike\n\n /**\n * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n * effect if {@link nobrace} is set.\n *\n * Only has effect on the {@link hasMagic} function.\n */\n magicalBraces?: boolean\n\n /**\n * Add a `/` character to directory matches. Note that this requires\n * additional stat calls in some cases.\n */\n mark?: boolean\n\n /**\n * Perform a basename-only match if the pattern does not contain any slash\n * characters. That is, `*.js` would be treated as equivalent to\n * `**\\/*.js`, matching all js files in all directories.\n */\n matchBase?: boolean\n\n /**\n * Limit the directory traversal to a given depth below the cwd.\n * Note that this does NOT prevent traversal to sibling folders,\n * root patterns, and so on. It only limits the maximum folder depth\n * that the walk will descend, relative to the cwd.\n */\n maxDepth?: number\n\n /**\n * Do not expand `{a,b}` and `{1..3}` brace sets.\n */\n nobrace?: boolean\n\n /**\n * Perform a case-insensitive match. This defaults to `true` on macOS and\n * Windows systems, and `false` on all others.\n *\n * **Note** `nocase` should only be explicitly set when it is\n * known that the filesystem's case sensitivity differs from the\n * platform default. If set `true` on case-sensitive file\n * systems, or `false` on case-insensitive file systems, then the\n * walk may return more or less results than expected.\n */\n nocase?: boolean\n\n /**\n * Do not match directories, only files. (Note: to match\n * _only_ directories, put a `/` at the end of the pattern.)\n */\n nodir?: boolean\n\n /**\n * Do not match \"extglob\" patterns such as `+(a|b)`.\n */\n noext?: boolean\n\n /**\n * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n * `*` instead.)\n *\n * Conflicts with {@link matchBase}\n */\n noglobstar?: boolean\n\n /**\n * Defaults to value of `process.platform` if available, or `'linux'` if\n * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n * behavior.\n */\n platform?: NodeJS.Platform\n\n /**\n * Set to true to call `fs.realpath` on all of the\n * results. In the case of an entry that cannot be resolved, the\n * entry is omitted. This incurs a slight performance penalty, of\n * course, because of the added system calls.\n */\n realpath?: boolean\n\n /**\n *\n * A string path resolved against the `cwd` option, which\n * is used as the starting point for absolute patterns that start\n * with `/`, (but not drive letters or UNC paths on Windows).\n *\n * Note that this _doesn't_ necessarily limit the walk to the\n * `root` directory, and doesn't affect the cwd starting point for\n * non-absolute patterns. A pattern containing `..` will still be\n * able to traverse out of the root directory, if it is not an\n * actual root directory on the filesystem, and any non-absolute\n * patterns will be matched in the `cwd`. For example, the\n * pattern `/../*` with `{root:'/some/path'}` will return all\n * files in `/some`, not all files in `/some/path`. The pattern\n * `*` with `{root:'/some/path'}` will return all the entries in\n * the cwd, not the entries in `/some/path`.\n *\n * To start absolute and non-absolute patterns in the same\n * path, you can use `{root:''}`. However, be aware that on\n * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n * _always_ start in the `x:/` or `//host/share` directory,\n * regardless of the `root` setting.\n */\n root?: string\n\n /**\n * A [PathScurry](http://npm.im/path-scurry) object used\n * to traverse the file system. If the `nocase` option is set\n * explicitly, then any provided `scurry` object must match this\n * setting.\n */\n scurry?: PathScurry\n\n /**\n * Call `lstat()` on all entries, whether required or not to determine\n * if it's a valid match. When used with {@link withFileTypes}, this means\n * that matches will include data such as modified time, permissions, and\n * so on. Note that this will incur a performance cost due to the added\n * system calls.\n */\n stat?: boolean\n\n /**\n * An AbortSignal which will cancel the Glob walk when\n * triggered.\n */\n signal?: AbortSignal\n\n /**\n * Use `\\\\` as a path separator _only_, and\n * _never_ as an escape character. If set, all `\\\\` characters are\n * replaced with `/` in the pattern.\n *\n * Note that this makes it **impossible** to match against paths\n * containing literal glob pattern characters, but allows matching\n * with patterns constructed using `path.join()` and\n * `path.resolve()` on Windows platforms, mimicking the (buggy!)\n * behavior of Glob v7 and before on Windows. Please use with\n * caution, and be mindful of [the caveat below about Windows\n * paths](#windows). (For legacy reasons, this is also set if\n * `allowWindowsEscape` is set to the exact value `false`.)\n */\n windowsPathsNoEscape?: boolean\n\n /**\n * Return [PathScurry](http://npm.im/path-scurry)\n * `Path` objects instead of strings. These are similar to a\n * NodeJS `Dirent` object, but with additional methods and\n * properties.\n *\n * Conflicts with {@link absolute}\n */\n withFileTypes?: boolean\n\n /**\n * An fs implementation to override some or all of the defaults. See\n * http://npm.im/path-scurry for details about what can be overridden.\n */\n fs?: FSOption\n\n /**\n * Just passed along to Minimatch. Note that this makes all pattern\n * matching operations slower and *extremely* noisy.\n */\n debug?: boolean\n\n /**\n * Return `/` delimited paths, even on Windows.\n *\n * On posix systems, this has no effect. But, on Windows, it means that\n * paths will be `/` delimited, and absolute paths will be their full\n * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n * `'//?/C:/foo/bar'`\n */\n posix?: boolean\n\n /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n withFileTypes: true\n // string options not relevant if returning Path objects.\n absolute?: undefined\n mark?: undefined\n posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n withFileTypes?: undefined\n}\n\nexport type Result =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? false\n : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n absolute?: boolean\n cwd: string\n root?: string\n dot: boolean\n dotRelative: boolean\n follow: boolean\n ignore?: string | string[] | IgnoreLike\n magicalBraces: boolean\n mark?: boolean\n matchBase: boolean\n maxDepth: number\n nobrace: boolean\n nocase: boolean\n nodir: boolean\n noext: boolean\n noglobstar: boolean\n pattern: string[]\n platform: NodeJS.Platform\n realpath: boolean\n scurry: PathScurry\n stat: boolean\n signal?: AbortSignal\n windowsPathsNoEscape: boolean\n withFileTypes: FileTypes\n includeChildMatches: boolean\n\n /**\n * The options provided to the constructor.\n */\n opts: Opts\n\n /**\n * An array of parsed immutable {@link Pattern} objects.\n */\n patterns: Pattern[]\n\n /**\n * All options are stored as properties on the `Glob` object.\n *\n * See {@link GlobOptions} for full options descriptions.\n *\n * Note that a previous `Glob` object can be passed as the\n * `GlobOptions` to another `Glob` instantiation to re-use settings\n * and caches with a new pattern.\n *\n * Traversal functions can be called multiple times to run the walk\n * again.\n */\n constructor(pattern: string | string[], opts: Opts) {\n /* c8 ignore start */\n if (!opts) throw new TypeError('glob options required')\n /* c8 ignore stop */\n this.withFileTypes = !!opts.withFileTypes as FileTypes\n this.signal = opts.signal\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.dotRelative = !!opts.dotRelative\n this.nodir = !!opts.nodir\n this.mark = !!opts.mark\n if (!opts.cwd) {\n this.cwd = ''\n } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n opts.cwd = fileURLToPath(opts.cwd)\n }\n this.cwd = opts.cwd || ''\n this.root = opts.root\n this.magicalBraces = !!opts.magicalBraces\n this.nobrace = !!opts.nobrace\n this.noext = !!opts.noext\n this.realpath = !!opts.realpath\n this.absolute = opts.absolute\n this.includeChildMatches = opts.includeChildMatches !== false\n\n this.noglobstar = !!opts.noglobstar\n this.matchBase = !!opts.matchBase\n this.maxDepth =\n typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n this.stat = !!opts.stat\n this.ignore = opts.ignore\n\n if (this.withFileTypes && this.absolute !== undefined) {\n throw new Error('cannot set absolute and withFileTypes:true')\n }\n\n if (typeof pattern === 'string') {\n pattern = [pattern]\n }\n\n this.windowsPathsNoEscape =\n !!opts.windowsPathsNoEscape ||\n (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n false\n\n if (this.windowsPathsNoEscape) {\n pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n }\n\n if (this.matchBase) {\n if (opts.noglobstar) {\n throw new TypeError('base matching requires globstar')\n }\n pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n }\n\n this.pattern = pattern\n\n this.platform = opts.platform || defaultPlatform\n this.opts = { ...opts, platform: this.platform }\n if (opts.scurry) {\n this.scurry = opts.scurry\n if (\n opts.nocase !== undefined &&\n opts.nocase !== opts.scurry.nocase\n ) {\n throw new Error('nocase option contradicts provided scurry option')\n }\n } else {\n const Scurry =\n opts.platform === 'win32' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? PathScurryPosix\n : PathScurry\n this.scurry = new Scurry(this.cwd, {\n nocase: opts.nocase,\n fs: opts.fs,\n })\n }\n this.nocase = this.scurry.nocase\n\n // If you do nocase:true on a case-sensitive file system, then\n // we need to use regexps instead of strings for non-magic\n // path portions, because statting `aBc` won't return results\n // for the file `AbC` for example.\n const nocaseMagicOnly =\n this.platform === 'darwin' || this.platform === 'win32'\n\n const mmo: MinimatchOptions = {\n // default nocase based on platform\n ...opts,\n dot: this.dot,\n matchBase: this.matchBase,\n nobrace: this.nobrace,\n nocase: this.nocase,\n nocaseMagicOnly,\n nocomment: true,\n noext: this.noext,\n nonegate: true,\n optimizationLevel: 2,\n platform: this.platform,\n windowsPathsNoEscape: this.windowsPathsNoEscape,\n debug: !!this.opts.debug,\n }\n\n const mms = this.pattern.map(p => new Minimatch(p, mmo))\n const [matchSet, globParts] = mms.reduce(\n (set: [MatchSet, GlobParts], m) => {\n set[0].push(...m.set)\n set[1].push(...m.globParts)\n return set\n },\n [[], []],\n )\n this.patterns = matchSet.map((set, i) => {\n const g = globParts[i]\n /* c8 ignore start */\n if (!g) throw new Error('invalid pattern object')\n /* c8 ignore stop */\n return new Pattern(set, g, 0, this.platform)\n })\n }\n\n /**\n * Returns a Promise that resolves to the results array.\n */\n async walk(): Promise>\n async walk(): Promise<(string | Path)[]> {\n // Walkers always return array of Path objects, so we just have to\n // coerce them into the right shape. It will have already called\n // realpath() if the option was set to do so, so we know that's cached.\n // start out knowing the cwd, at least\n return [\n ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walk()),\n ]\n }\n\n /**\n * synchronous {@link Glob.walk}\n */\n walkSync(): Results\n walkSync(): (string | Path)[] {\n return [\n ...new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walkSync(),\n ]\n }\n\n /**\n * Stream results asynchronously.\n */\n stream(): Minipass, Result>\n stream(): Minipass {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).stream()\n }\n\n /**\n * Stream results synchronously.\n */\n streamSync(): Minipass, Result>\n streamSync(): Minipass {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).streamSync()\n }\n\n /**\n * Default sync iteration function. Returns a Generator that\n * iterates over the results.\n */\n iterateSync(): Generator, void, void> {\n return this.streamSync()[Symbol.iterator]()\n }\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n /**\n * Default async iteration function. Returns an AsyncGenerator that\n * iterates over the results.\n */\n iterate(): AsyncGenerator, void, void> {\n return this.stream()[Symbol.asyncIterator]()\n }\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n}\n"]}import { GlobOptions } from './glob.js'; /** * Return true if the patterns provided contain any magic glob characters, * given the options provided. * * Brace expansion is not considered "magic" unless the `magicalBraces` option * is set, as brace expansion just turns one string into an array of strings. * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and * `'xby'` both do not contain any magic glob characters, and it's treated the * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` * is in the options, brace expansion _is_ treated as a pattern having magic. */ export declare const hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean; //# sourceMappingURL=has-magic.d.ts.map{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,YACV,MAAM,GAAG,MAAM,EAAE,YACjB,WAAW,KACnB,OAQF,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hasMagic = void 0; const minimatch_1 = require("minimatch"); /** * Return true if the patterns provided contain any magic glob characters, * given the options provided. * * Brace expansion is not considered "magic" unless the `magicalBraces` option * is set, as brace expansion just turns one string into an array of strings. * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and * `'xby'` both do not contain any magic glob characters, and it's treated the * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` * is in the options, brace expansion _is_ treated as a pattern having magic. */ const hasMagic = (pattern, options = {}) => { if (!Array.isArray(pattern)) { pattern = [pattern]; } for (const p of pattern) { if (new minimatch_1.Minimatch(p, options).hasMagic()) return true; } return false; }; exports.hasMagic = hasMagic; //# sourceMappingURL=has-magic.js.map{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":";;;AAAA,yCAAqC;AAGrC;;;;;;;;;;GAUG;AACI,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,IAAI,qBAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AAXY,QAAA,QAAQ,YAWpB","sourcesContent":["import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n pattern: string | string[],\n options: GlobOptions = {},\n): boolean => {\n if (!Array.isArray(pattern)) {\n pattern = [pattern]\n }\n for (const p of pattern) {\n if (new Minimatch(p, options).hasMagic()) return true\n }\n return false\n}\n"]}import { Minimatch, MinimatchOptions } from 'minimatch'; import { Path } from 'path-scurry'; import { GlobWalkerOpts } from './walker.js'; export interface IgnoreLike { ignored?: (p: Path) => boolean; childrenIgnored?: (p: Path) => boolean; add?: (ignore: string) => void; } /** * Class used to process ignored patterns */ export declare class Ignore implements IgnoreLike { relative: Minimatch[]; relativeChildren: Minimatch[]; absolute: Minimatch[]; absoluteChildren: Minimatch[]; platform: NodeJS.Platform; mmopts: MinimatchOptions; constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, platform, }: GlobWalkerOpts); add(ign: string): void; ignored(p: Path): boolean; childrenIgnored(p: Path): boolean; } //# sourceMappingURL=ignore.d.ts.map{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;AACH,qBAAa,MAAO,YAAW,UAAU;IACvC,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;gBAGtB,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAA0B,GAC3B,EAAE,cAAc;IAqBnB,GAAG,CAAC,GAAG,EAAE,MAAM;IAyCf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"}"use strict"; // give it a pattern, and it'll be able to tell you if // a given path should be ignored. // Ignoring a path ignores its children if the pattern ends in /** // Ignores are always parsed in dot:true mode Object.defineProperty(exports, "__esModule", { value: true }); exports.Ignore = void 0; const minimatch_1 = require("minimatch"); const pattern_js_1 = require("./pattern.js"); const defaultPlatform = (typeof process === 'object' && process && typeof process.platform === 'string') ? process.platform : 'linux'; /** * Class used to process ignored patterns */ class Ignore { relative; relativeChildren; absolute; absoluteChildren; platform; mmopts; constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) { this.relative = []; this.absolute = []; this.relativeChildren = []; this.absoluteChildren = []; this.platform = platform; this.mmopts = { dot: true, nobrace, nocase, noext, noglobstar, optimizationLevel: 2, platform, nocomment: true, nonegate: true, }; for (const ign of ignored) this.add(ign); } add(ign) { // this is a little weird, but it gives us a clean set of optimized // minimatch matchers, without getting tripped up if one of them // ends in /** inside a brace section, and it's only inefficient at // the start of the walk, not along it. // It'd be nice if the Pattern class just had a .test() method, but // handling globstars is a bit of a pita, and that code already lives // in minimatch anyway. // Another way would be if maybe Minimatch could take its set/globParts // as an option, and then we could at least just use Pattern to test // for absolute-ness. // Yet another way, Minimatch could take an array of glob strings, and // a cwd option, and do the right thing. const mm = new minimatch_1.Minimatch(ign, this.mmopts); for (let i = 0; i < mm.set.length; i++) { const parsed = mm.set[i]; const globParts = mm.globParts[i]; /* c8 ignore start */ if (!parsed || !globParts) { throw new Error('invalid pattern object'); } // strip off leading ./ portions // https://github.com/isaacs/node-glob/issues/570 while (parsed[0] === '.' && globParts[0] === '.') { parsed.shift(); globParts.shift(); } /* c8 ignore stop */ const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform); const m = new minimatch_1.Minimatch(p.globString(), this.mmopts); const children = globParts[globParts.length - 1] === '**'; const absolute = p.isAbsolute(); if (absolute) this.absolute.push(m); else this.relative.push(m); if (children) { if (absolute) this.absoluteChildren.push(m); else this.relativeChildren.push(m); } } } ignored(p) { const fullpath = p.fullpath(); const fullpaths = `${fullpath}/`; const relative = p.relative() || '.'; const relatives = `${relative}/`; for (const m of this.relative) { if (m.match(relative) || m.match(relatives)) return true; } for (const m of this.absolute) { if (m.match(fullpath) || m.match(fullpaths)) return true; } return false; } childrenIgnored(p) { const fullpath = p.fullpath() + '/'; const relative = (p.relative() || '.') + '/'; for (const m of this.relativeChildren) { if (m.match(relative)) return true; } for (const m of this.absoluteChildren) { if (m.match(fullpath)) return true; } return false; } } exports.Ignore = Ignore; //# sourceMappingURL=ignore.js.map{"version":3,"file":"ignore.js","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,kCAAkC;AAClC,kEAAkE;AAClE,6CAA6C;;;AAE7C,yCAAuD;AAEvD,6CAAsC;AAStC,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAEX;;GAEG;AACH,MAAa,MAAM;IACjB,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAiB;IACzB,MAAM,CAAkB;IAExB,YACE,OAAiB,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAAQ,GAAG,eAAe,GACX;QAEjB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,MAAM,GAAG;YACZ,GAAG,EAAE,IAAI;YACT,OAAO;YACP,MAAM;YACN,KAAK;YACL,UAAU;YACV,iBAAiB,EAAE,CAAC;YACpB,QAAQ;YACR,SAAS,EAAE,IAAI;YACf,QAAQ,EAAE,IAAI;SACf,CAAA;QACD,KAAK,MAAM,GAAG,IAAI,OAAO;YAAE,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IAC1C,CAAC;IAED,GAAG,CAAC,GAAW;QACb,mEAAmE;QACnE,gEAAgE;QAChE,mEAAmE;QACnE,uCAAuC;QACvC,mEAAmE;QACnE,qEAAqE;QACrE,uBAAuB;QACvB,uEAAuE;QACvE,oEAAoE;QACpE,qBAAqB;QACrB,sEAAsE;QACtE,wCAAwC;QACxC,MAAM,EAAE,GAAG,IAAI,qBAAS,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QAC1C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACvC,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;YACxB,MAAM,SAAS,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;YACjC,qBAAqB;YACrB,IAAI,CAAC,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;gBAC1B,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;YAC3C,CAAC;YACD,gCAAgC;YAChC,iDAAiD;YACjD,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,SAAS,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;gBACjD,MAAM,CAAC,KAAK,EAAE,CAAA;gBACd,SAAS,CAAC,KAAK,EAAE,CAAA;YACnB,CAAC;YACD,oBAAoB;YACpB,MAAM,CAAC,GAAG,IAAI,oBAAO,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;YAC1D,MAAM,CAAC,GAAG,IAAI,qBAAS,CAAC,CAAC,CAAC,UAAU,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;YACpD,MAAM,QAAQ,GAAG,SAAS,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,IAAI,CAAA;YACzD,MAAM,QAAQ,GAAG,CAAC,CAAC,UAAU,EAAE,CAAA;YAC/B,IAAI,QAAQ;gBAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;;gBAC9B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;YAC1B,IAAI,QAAQ,EAAE,CAAC;gBACb,IAAI,QAAQ;oBAAE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;;oBACtC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;YACpC,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,CAAC,CAAO;QACb,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAA;QAC7B,MAAM,SAAS,GAAG,GAAG,QAAQ,GAAG,CAAA;QAChC,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAA;QACpC,MAAM,SAAS,GAAG,GAAG,QAAQ,GAAG,CAAA;QAChC,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,eAAe,CAAC,CAAO;QACrB,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,GAAG,CAAA;QACnC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,GAAG,GAAG,CAAA;QAC5C,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAvGD,wBAuGC","sourcesContent":["// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n ignored?: (p: Path) => boolean\n childrenIgnored?: (p: Path) => boolean\n add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n relative: Minimatch[]\n relativeChildren: Minimatch[]\n absolute: Minimatch[]\n absoluteChildren: Minimatch[]\n platform: NodeJS.Platform\n mmopts: MinimatchOptions\n\n constructor(\n ignored: string[],\n {\n nobrace,\n nocase,\n noext,\n noglobstar,\n platform = defaultPlatform,\n }: GlobWalkerOpts,\n ) {\n this.relative = []\n this.absolute = []\n this.relativeChildren = []\n this.absoluteChildren = []\n this.platform = platform\n this.mmopts = {\n dot: true,\n nobrace,\n nocase,\n noext,\n noglobstar,\n optimizationLevel: 2,\n platform,\n nocomment: true,\n nonegate: true,\n }\n for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\n // this is a little weird, but it gives us a clean set of optimized\n // minimatch matchers, without getting tripped up if one of them\n // ends in /** inside a brace section, and it's only inefficient at\n // the start of the walk, not along it.\n // It'd be nice if the Pattern class just had a .test() method, but\n // handling globstars is a bit of a pita, and that code already lives\n // in minimatch anyway.\n // Another way would be if maybe Minimatch could take its set/globParts\n // as an option, and then we could at least just use Pattern to test\n // for absolute-ness.\n // Yet another way, Minimatch could take an array of glob strings, and\n // a cwd option, and do the right thing.\n const mm = new Minimatch(ign, this.mmopts)\n for (let i = 0; i < mm.set.length; i++) {\n const parsed = mm.set[i]\n const globParts = mm.globParts[i]\n /* c8 ignore start */\n if (!parsed || !globParts) {\n throw new Error('invalid pattern object')\n }\n // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.mmopts)\n const children = globParts[globParts.length - 1] === '**'\n const absolute = p.isAbsolute()\n if (absolute) this.absolute.push(m)\n else this.relative.push(m)\n if (children) {\n if (absolute) this.absoluteChildren.push(m)\n else this.relativeChildren.push(m)\n }\n }\n }\n\n ignored(p: Path): boolean {\n const fullpath = p.fullpath()\n const fullpaths = `${fullpath}/`\n const relative = p.relative() || '.'\n const relatives = `${relative}/`\n for (const m of this.relative) {\n if (m.match(relative) || m.match(relatives)) return true\n }\n for (const m of this.absolute) {\n if (m.match(fullpath) || m.match(fullpaths)) return true\n }\n return false\n }\n\n childrenIgnored(p: Path): boolean {\n const fullpath = p.fullpath() + '/'\n const relative = (p.relative() || '.') + '/'\n for (const m of this.relativeChildren) {\n if (m.match(relative)) return true\n }\n for (const m of this.absoluteChildren) {\n if (m.match(fullpath)) return true\n }\n return false\n }\n}\n"]}import { Minipass } from 'minipass'; import { Path } from 'path-scurry'; import type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset } from './glob.js'; import { Glob } from './glob.js'; export { escape, unescape } from 'minimatch'; export type { FSOption, Path, WalkOptions, WalkOptionsWithFileTypesTrue, WalkOptionsWithFileTypesUnset, } from 'path-scurry'; export { Glob } from './glob.js'; export type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset, } from './glob.js'; export { hasMagic } from './has-magic.js'; export { Ignore } from './ignore.js'; export type { IgnoreLike } from './ignore.js'; export type { MatchStream } from './walker.js'; /** * Syncronous form of {@link globStream}. Will read all the matches as fast as * you consume them, even all in a single tick if you consume them immediately, * but will still respond to backpressure if they're not consumed immediately. */ export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass; export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass; export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesUnset): Minipass; export declare function globStreamSync(pattern: string | string[], options: GlobOptions): Minipass | Minipass; /** * Return a stream that emits all the strings or `Path` objects and * then emits `end` when completed. */ export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass; export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass; export declare function globStream(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Minipass; export declare function globStream(pattern: string | string[], options: GlobOptions): Minipass | Minipass; /** * Synchronous form of {@link glob} */ export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): string[]; export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Path[]; export declare function globSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): string[]; export declare function globSync(pattern: string | string[], options: GlobOptions): Path[] | string[]; /** * Perform an asynchronous glob search for the pattern(s) specified. Returns * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for * full option descriptions. */ declare function glob_(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Promise; declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Promise; declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Promise; declare function glob_(pattern: string | string[], options: GlobOptions): Promise; /** * Return a sync iterator for walking glob pattern matches. */ export declare function globIterateSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Generator; export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Generator; export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Generator; export declare function globIterateSync(pattern: string | string[], options: GlobOptions): Generator | Generator; /** * Return an async iterator for walking glob pattern matches. */ export declare function globIterate(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): AsyncGenerator; export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): AsyncGenerator; export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): AsyncGenerator; export declare function globIterate(pattern: string | string[], options: GlobOptions): AsyncGenerator | AsyncGenerator; export declare const streamSync: typeof globStreamSync; export declare const stream: typeof globStream & { sync: typeof globStreamSync; }; export declare const iterateSync: typeof globIterateSync; export declare const iterate: typeof globIterate & { sync: typeof globIterateSync; }; export declare const sync: typeof globSync & { stream: typeof globStreamSync; iterate: typeof globIterateSync; }; export declare const glob: typeof glob_ & { glob: typeof glob_; globSync: typeof globSync; sync: typeof globSync & { stream: typeof globStreamSync; iterate: typeof globIterateSync; }; globStream: typeof globStream; stream: typeof globStream & { sync: typeof globStreamSync; }; globStreamSync: typeof globStreamSync; streamSync: typeof globStreamSync; globIterate: typeof globIterate; iterate: typeof globIterate & { sync: typeof globIterateSync; }; globIterateSync: typeof globIterateSync; iterateSync: typeof globIterateSync; Glob: typeof Glob; hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean; escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; }; //# sourceMappingURL=index.d.ts.map{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,KAAK,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,EAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAGhC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC5C,YAAY,EACV,QAAQ,EACR,IAAI,EACJ,WAAW,EACX,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,YAAY,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAC7C,YAAY,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;AACvB,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC3B,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC3B,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAQlD;;;GAGG;AACH,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC3B,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;AACvB,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC3B,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAQlD;;GAEG;AACH,wBAAgB,QAAQ,CACtB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,MAAM,EAAE,CAAA;AACX,wBAAgB,QAAQ,CACtB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,IAAI,EAAE,CAAA;AACT,wBAAgB,QAAQ,CACtB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,MAAM,EAAE,CAAA;AACX,wBAAgB,QAAQ,CACtB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,IAAI,EAAE,GAAG,MAAM,EAAE,CAAA;AAQpB;;;;;GAKG;AACH,iBAAe,KAAK,CAClB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;AACpB,iBAAe,KAAK,CAClB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;AAClB,iBAAe,KAAK,CAClB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;AACpB,iBAAe,KAAK,CAClB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,OAAO,CAAC,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,CAAA;AAQ7B;;GAEG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AAChC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AAC9B,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AAChC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AAQ9D;;GAEG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACrC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACnC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACrC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AASxE,eAAO,MAAM,UAAU,uBAAiB,CAAA;AACxC,eAAO,MAAM,MAAM;;CAAsD,CAAA;AACzE,eAAO,MAAM,WAAW,wBAAkB,CAAA;AAC1C,eAAO,MAAM,OAAO;;CAElB,CAAA;AACF,eAAO,MAAM,IAAI;;;CAGf,CAAA;AAEF,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;CAgBf,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = void 0; exports.globStreamSync = globStreamSync; exports.globStream = globStream; exports.globSync = globSync; exports.globIterateSync = globIterateSync; exports.globIterate = globIterate; const minimatch_1 = require("minimatch"); const glob_js_1 = require("./glob.js"); const has_magic_js_1 = require("./has-magic.js"); var minimatch_2 = require("minimatch"); Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return minimatch_2.escape; } }); Object.defineProperty(exports, "unescape", { enumerable: true, get: function () { return minimatch_2.unescape; } }); var glob_js_2 = require("./glob.js"); Object.defineProperty(exports, "Glob", { enumerable: true, get: function () { return glob_js_2.Glob; } }); var has_magic_js_2 = require("./has-magic.js"); Object.defineProperty(exports, "hasMagic", { enumerable: true, get: function () { return has_magic_js_2.hasMagic; } }); var ignore_js_1 = require("./ignore.js"); Object.defineProperty(exports, "Ignore", { enumerable: true, get: function () { return ignore_js_1.Ignore; } }); function globStreamSync(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).streamSync(); } function globStream(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).stream(); } function globSync(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).walkSync(); } async function glob_(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).walk(); } function globIterateSync(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).iterateSync(); } function globIterate(pattern, options = {}) { return new glob_js_1.Glob(pattern, options).iterate(); } // aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc exports.streamSync = globStreamSync; exports.stream = Object.assign(globStream, { sync: globStreamSync }); exports.iterateSync = globIterateSync; exports.iterate = Object.assign(globIterate, { sync: globIterateSync, }); exports.sync = Object.assign(globSync, { stream: globStreamSync, iterate: globIterateSync, }); exports.glob = Object.assign(glob_, { glob: glob_, globSync, sync: exports.sync, globStream, stream: exports.stream, globStreamSync, streamSync: exports.streamSync, globIterate, iterate: exports.iterate, globIterateSync, iterateSync: exports.iterateSync, Glob: glob_js_1.Glob, hasMagic: has_magic_js_1.hasMagic, escape: minimatch_1.escape, unescape: minimatch_1.unescape, }); exports.glob.glob = exports.glob; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAqDA,wCAKC;AAsBD,gCAKC;AAqBD,4BAKC;AAkDD,0CAKC;AAqBD,kCAKC;AAhMD,yCAA4C;AAS5C,uCAAgC;AAChC,iDAAyC;AAEzC,uCAA4C;AAAnC,mGAAA,MAAM,OAAA;AAAE,qGAAA,QAAQ,OAAA;AAQzB,qCAAgC;AAAvB,+FAAA,IAAI,OAAA;AAOb,+CAAyC;AAAhC,wGAAA,QAAQ,OAAA;AACjB,yCAAoC;AAA3B,mGAAA,MAAM,OAAA;AAyBf,SAAgB,cAAc,CAC5B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAA;AAChD,CAAC;AAsBD,SAAgB,UAAU,CACxB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,EAAE,CAAA;AAC5C,CAAC;AAqBD,SAAgB,QAAQ,CACtB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAA;AAC9C,CAAC;AAwBD,KAAK,UAAU,KAAK,CAClB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAA;AAC1C,CAAC;AAqBD,SAAgB,eAAe,CAC7B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAA;AACjD,CAAC;AAqBD,SAAgB,WAAW,CACzB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,OAAO,EAAE,CAAA;AAC7C,CAAC;AAED,iEAAiE;AACpD,QAAA,UAAU,GAAG,cAAc,CAAA;AAC3B,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAA;AAC5D,QAAA,WAAW,GAAG,eAAe,CAAA;AAC7B,QAAA,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;IAChD,IAAI,EAAE,eAAe;CACtB,CAAC,CAAA;AACW,QAAA,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC1C,MAAM,EAAE,cAAc;IACtB,OAAO,EAAE,eAAe;CACzB,CAAC,CAAA;AAEW,QAAA,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,KAAK;IACX,QAAQ;IACR,IAAI,EAAJ,YAAI;IACJ,UAAU;IACV,MAAM,EAAN,cAAM;IACN,cAAc;IACd,UAAU,EAAV,kBAAU;IACV,WAAW;IACX,OAAO,EAAP,eAAO;IACP,eAAe;IACf,WAAW,EAAX,mBAAW;IACX,IAAI,EAAJ,cAAI;IACJ,QAAQ,EAAR,uBAAQ;IACR,MAAM,EAAN,kBAAM;IACN,QAAQ,EAAR,oBAAQ;CACT,CAAC,CAAA;AACF,YAAI,CAAC,IAAI,GAAG,YAAI,CAAA","sourcesContent":["import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n stream: globStreamSync,\n iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n glob: glob_,\n globSync,\n sync,\n globStream,\n stream,\n globStreamSync,\n streamSync,\n globIterate,\n iterate,\n globIterateSync,\n iterateSync,\n Glob,\n hasMagic,\n escape,\n unescape,\n})\nglob.glob = glob\n"]}{ "type": "commonjs" } import { GLOBSTAR } from 'minimatch'; export type MMPattern = string | RegExp | typeof GLOBSTAR; export type PatternList = [p: MMPattern, ...rest: MMPattern[]]; export type UNCPatternList = [ p0: '', p1: '', p2: string, p3: string, ...rest: MMPattern[] ]; export type DrivePatternList = [p0: string, ...rest: MMPattern[]]; export type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]; export type GlobList = [p: string, ...rest: string[]]; /** * An immutable-ish view on an array of glob parts and their parsed * results */ export declare class Pattern { #private; readonly length: number; constructor(patternList: MMPattern[], globList: string[], index: number, platform: NodeJS.Platform); /** * The first entry in the parsed list of patterns */ pattern(): MMPattern; /** * true of if pattern() returns a string */ isString(): boolean; /** * true of if pattern() returns GLOBSTAR */ isGlobstar(): boolean; /** * true if pattern() returns a regexp */ isRegExp(): boolean; /** * The /-joined set of glob parts that make up this pattern */ globString(): string; /** * true if there are more pattern parts after this one */ hasMore(): boolean; /** * The rest of the pattern after this part, or null if this is the end */ rest(): Pattern | null; /** * true if the pattern represents a //unc/path/ on windows */ isUNC(): boolean; /** * True if the pattern starts with a drive letter on Windows */ isDrive(): boolean; /** * True if the pattern is rooted on an absolute path */ isAbsolute(): boolean; /** * consume the root of the pattern, and return it */ root(): string; /** * Check to see if the current globstar pattern is allowed to follow * a symbolic link. */ checkFollowGlobstar(): boolean; /** * Mark that the current globstar pattern is following a symbolic link */ markFollowGlobstar(): boolean; } //# sourceMappingURL=pattern.d.ts.map{"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,QAAQ,CAAA;AAGzD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAC9D,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,MAAM;IACV,EAAE,EAAE,MAAM;IACV,GAAG,IAAI,EAAE,SAAS,EAAE;CACrB,CAAA;AACD,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AACjE,MAAM,MAAM,mBAAmB,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAChE,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;AAMrD;;;GAGG;AACH,qBAAa,OAAO;;IAIlB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;gBAUrB,WAAW,EAAE,SAAS,EAAE,EACxB,QAAQ,EAAE,MAAM,EAAE,EAClB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,CAAC,QAAQ;IA6D3B;;OAEG;IACH,OAAO,IAAI,SAAS;IAIpB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAGnB;;OAEG;IACH,UAAU,IAAI,OAAO;IAGrB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAInB;;OAEG;IACH,UAAU,IAAI,MAAM;IAUpB;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACH,IAAI,IAAI,OAAO,GAAG,IAAI;IAetB;;OAEG;IACH,KAAK,IAAI,OAAO;IAoBhB;;OAEG;IACH,OAAO,IAAI,OAAO;IAelB;;OAEG;IACH,UAAU,IAAI,OAAO;IAUrB;;OAEG;IACH,IAAI,IAAI,MAAM;IASd;;;OAGG;IACH,mBAAmB,IAAI,OAAO;IAQ9B;;OAEG;IACH,kBAAkB,IAAI,OAAO;CAM9B"}"use strict"; // this is just a very light wrapper around 2 arrays with an offset index Object.defineProperty(exports, "__esModule", { value: true }); exports.Pattern = void 0; const minimatch_1 = require("minimatch"); const isPatternList = (pl) => pl.length >= 1; const isGlobList = (gl) => gl.length >= 1; /** * An immutable-ish view on an array of glob parts and their parsed * results */ class Pattern { #patternList; #globList; #index; length; #platform; #rest; #globString; #isDrive; #isUNC; #isAbsolute; #followGlobstar = true; constructor(patternList, globList, index, platform) { if (!isPatternList(patternList)) { throw new TypeError('empty pattern list'); } if (!isGlobList(globList)) { throw new TypeError('empty glob list'); } if (globList.length !== patternList.length) { throw new TypeError('mismatched pattern list and glob list lengths'); } this.length = patternList.length; if (index < 0 || index >= this.length) { throw new TypeError('index out of range'); } this.#patternList = patternList; this.#globList = globList; this.#index = index; this.#platform = platform; // normalize root entries of absolute patterns on initial creation. if (this.#index === 0) { // c: => ['c:/'] // C:/ => ['C:/'] // C:/x => ['C:/', 'x'] // //host/share => ['//host/share/'] // //host/share/ => ['//host/share/'] // //host/share/x => ['//host/share/', 'x'] // /etc => ['/', 'etc'] // / => ['/'] if (this.isUNC()) { // '' / '' / 'host' / 'share' const [p0, p1, p2, p3, ...prest] = this.#patternList; const [g0, g1, g2, g3, ...grest] = this.#globList; if (prest[0] === '') { // ends in / prest.shift(); grest.shift(); } const p = [p0, p1, p2, p3, ''].join('/'); const g = [g0, g1, g2, g3, ''].join('/'); this.#patternList = [p, ...prest]; this.#globList = [g, ...grest]; this.length = this.#patternList.length; } else if (this.isDrive() || this.isAbsolute()) { const [p1, ...prest] = this.#patternList; const [g1, ...grest] = this.#globList; if (prest[0] === '') { // ends in / prest.shift(); grest.shift(); } const p = p1 + '/'; const g = g1 + '/'; this.#patternList = [p, ...prest]; this.#globList = [g, ...grest]; this.length = this.#patternList.length; } } } /** * The first entry in the parsed list of patterns */ pattern() { return this.#patternList[this.#index]; } /** * true of if pattern() returns a string */ isString() { return typeof this.#patternList[this.#index] === 'string'; } /** * true of if pattern() returns GLOBSTAR */ isGlobstar() { return this.#patternList[this.#index] === minimatch_1.GLOBSTAR; } /** * true if pattern() returns a regexp */ isRegExp() { return this.#patternList[this.#index] instanceof RegExp; } /** * The /-joined set of glob parts that make up this pattern */ globString() { return (this.#globString = this.#globString || (this.#index === 0 ? this.isAbsolute() ? this.#globList[0] + this.#globList.slice(1).join('/') : this.#globList.join('/') : this.#globList.slice(this.#index).join('/'))); } /** * true if there are more pattern parts after this one */ hasMore() { return this.length > this.#index + 1; } /** * The rest of the pattern after this part, or null if this is the end */ rest() { if (this.#rest !== undefined) return this.#rest; if (!this.hasMore()) return (this.#rest = null); this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform); this.#rest.#isAbsolute = this.#isAbsolute; this.#rest.#isUNC = this.#isUNC; this.#rest.#isDrive = this.#isDrive; return this.#rest; } /** * true if the pattern represents a //unc/path/ on windows */ isUNC() { const pl = this.#patternList; return this.#isUNC !== undefined ? this.#isUNC : (this.#isUNC = this.#platform === 'win32' && this.#index === 0 && pl[0] === '' && pl[1] === '' && typeof pl[2] === 'string' && !!pl[2] && typeof pl[3] === 'string' && !!pl[3]); } // pattern like C:/... // split = ['C:', ...] // XXX: would be nice to handle patterns like `c:*` to test the cwd // in c: for *, but I don't know of a way to even figure out what that // cwd is without actually chdir'ing into it? /** * True if the pattern starts with a drive letter on Windows */ isDrive() { const pl = this.#patternList; return this.#isDrive !== undefined ? this.#isDrive : (this.#isDrive = this.#platform === 'win32' && this.#index === 0 && this.length > 1 && typeof pl[0] === 'string' && /^[a-z]:$/i.test(pl[0])); } // pattern = '/' or '/...' or '/x/...' // split = ['', ''] or ['', ...] or ['', 'x', ...] // Drive and UNC both considered absolute on windows /** * True if the pattern is rooted on an absolute path */ isAbsolute() { const pl = this.#patternList; return this.#isAbsolute !== undefined ? this.#isAbsolute : (this.#isAbsolute = (pl[0] === '' && pl.length > 1) || this.isDrive() || this.isUNC()); } /** * consume the root of the pattern, and return it */ root() { const p = this.#patternList[0]; return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ? p : ''; } /** * Check to see if the current globstar pattern is allowed to follow * a symbolic link. */ checkFollowGlobstar() { return !(this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar); } /** * Mark that the current globstar pattern is following a symbolic link */ markFollowGlobstar() { if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar) return false; this.#followGlobstar = false; return true; } } exports.Pattern = Pattern; //# sourceMappingURL=pattern.js.map{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":";AAAA,yEAAyE;;;AAEzE,yCAAoC;AAgBpC,MAAM,aAAa,GAAG,CAAC,EAAe,EAAqB,EAAE,CAC3D,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAChB,MAAM,UAAU,GAAG,CAAC,EAAY,EAAkB,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAEnE;;;GAGG;AACH,MAAa,OAAO;IACT,YAAY,CAAa;IACzB,SAAS,CAAU;IACnB,MAAM,CAAQ;IACd,MAAM,CAAQ;IACd,SAAS,CAAiB;IACnC,KAAK,CAAiB;IACtB,WAAW,CAAS;IACpB,QAAQ,CAAU;IAClB,MAAM,CAAU;IAChB,WAAW,CAAU;IACrB,eAAe,GAAY,IAAI,CAAA;IAE/B,YACE,WAAwB,EACxB,QAAkB,EAClB,KAAa,EACb,QAAyB;QAEzB,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,SAAS,CAAC,oBAAoB,CAAC,CAAA;QAC3C,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;QACxC,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,CAAC,MAAM,EAAE,CAAC;YAC3C,MAAM,IAAI,SAAS,CAAC,+CAA+C,CAAC,CAAA;QACtE,CAAC;QACD,IAAI,CAAC,MAAM,GAAG,WAAW,CAAC,MAAM,CAAA;QAChC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YACtC,MAAM,IAAI,SAAS,CAAC,oBAAoB,CAAC,CAAA;QAC3C,CAAC;QACD,IAAI,CAAC,YAAY,GAAG,WAAW,CAAA;QAC/B,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QACzB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;QACnB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QAEzB,mEAAmE;QACnE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,gBAAgB;YAChB,iBAAiB;YACjB,uBAAuB;YACvB,oCAAoC;YACpC,qCAAqC;YACrC,2CAA2C;YAC3C,uBAAuB;YACvB,aAAa;YACb,IAAI,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;gBACjB,6BAA6B;gBAC7B,MAAM,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,YAAY,CAAA;gBACpD,MAAM,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAA;gBACjD,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;oBACpB,YAAY;oBACZ,KAAK,CAAC,KAAK,EAAE,CAAA;oBACb,KAAK,CAAC,KAAK,EAAE,CAAA;gBACf,CAAC;gBACD,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACxC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACxC,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAA;gBACjC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAA;gBAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAA;YACxC,CAAC;iBAAM,IAAI,IAAI,CAAC,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,EAAE,EAAE,CAAC;gBAC/C,MAAM,CAAC,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,YAAY,CAAA;gBACxC,MAAM,CAAC,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAA;gBACrC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;oBACpB,YAAY;oBACZ,KAAK,CAAC,KAAK,EAAE,CAAA;oBACb,KAAK,CAAC,KAAK,EAAE,CAAA;gBACf,CAAC;gBACD,MAAM,CAAC,GAAI,EAAa,GAAG,GAAG,CAAA;gBAC9B,MAAM,CAAC,GAAG,EAAE,GAAG,GAAG,CAAA;gBAClB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAA;gBACjC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAA;gBAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAA;YACxC,CAAC;QACH,CAAC;IACH,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAc,CAAA;IACpD,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,OAAO,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,QAAQ,CAAA;IAC3D,CAAC;IACD;;OAEG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,oBAAQ,CAAA;IACpD,CAAC;IACD;;OAEG;IACH,QAAQ;QACN,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,MAAM,CAAA;IACzD,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,CAAC,IAAI,CAAC,WAAW;YACtB,IAAI,CAAC,WAAW;gBAChB,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;oBAClB,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;wBACjB,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;wBACvD,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC;oBAC5B,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;IACnD,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAA;IACtC,CAAC;IAED;;OAEG;IACH,IAAI;QACF,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO,IAAI,CAAC,KAAK,CAAA;QAC/C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YAAE,OAAO,CAAC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,CAAA;QAC/C,IAAI,CAAC,KAAK,GAAG,IAAI,OAAO,CACtB,IAAI,CAAC,YAAY,EACjB,IAAI,CAAC,SAAS,EACd,IAAI,CAAC,MAAM,GAAG,CAAC,EACf,IAAI,CAAC,SAAS,CACf,CAAA;QACD,IAAI,CAAC,KAAK,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAA;QACzC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QAC/B,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAA;QACnC,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAA;QAC5B,OAAO,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC;YAC9B,IAAI,CAAC,MAAM;YACb,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM;gBACV,IAAI,CAAC,SAAS,KAAK,OAAO;oBAC1B,IAAI,CAAC,MAAM,KAAK,CAAC;oBACjB,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE;oBACZ,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE;oBACZ,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,QAAQ;oBACzB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;oBACP,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,QAAQ;oBACzB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IAChB,CAAC;IAED,sBAAsB;IACtB,sBAAsB;IACtB,mEAAmE;IACnE,sEAAsE;IACtE,6CAA6C;IAC7C;;OAEG;IACH,OAAO;QACL,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAA;QAC5B,OAAO,IAAI,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC;YAChC,IAAI,CAAC,QAAQ;YACf,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ;gBACZ,IAAI,CAAC,SAAS,KAAK,OAAO;oBAC1B,IAAI,CAAC,MAAM,KAAK,CAAC;oBACjB,IAAI,CAAC,MAAM,GAAG,CAAC;oBACf,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,QAAQ;oBACzB,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAChC,CAAC;IAED,sCAAsC;IACtC,kDAAkD;IAClD,oDAAoD;IACpD;;OAEG;IACH,UAAU;QACR,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAA;QAC5B,OAAO,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC;YACnC,IAAI,CAAC,WAAW;YAClB,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW;gBACf,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;oBAC/B,IAAI,CAAC,OAAO,EAAE;oBACd,IAAI,CAAC,KAAK,EAAE,CAAC,CAAA;IACrB,CAAC;IAED;;OAEG;IACH,IAAI;QACF,MAAM,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;QAC9B,OAAO,CACH,OAAO,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,CAChE,CAAC,CAAC;YACD,CAAC;YACH,CAAC,CAAC,EAAE,CAAA;IACR,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,CAAC,CACN,IAAI,CAAC,MAAM,KAAK,CAAC;YACjB,CAAC,IAAI,CAAC,UAAU,EAAE;YAClB,CAAC,IAAI,CAAC,eAAe,CACtB,CAAA;IACH,CAAC;IAED;;OAEG;IACH,kBAAkB;QAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;YAClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AArOD,0BAqOC","sourcesContent":["// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n p0: '',\n p1: '',\n p2: string,\n p3: string,\n ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n readonly #patternList: PatternList\n readonly #globList: GlobList\n readonly #index: number\n readonly length: number\n readonly #platform: NodeJS.Platform\n #rest?: Pattern | null\n #globString?: string\n #isDrive?: boolean\n #isUNC?: boolean\n #isAbsolute?: boolean\n #followGlobstar: boolean = true\n\n constructor(\n patternList: MMPattern[],\n globList: string[],\n index: number,\n platform: NodeJS.Platform,\n ) {\n if (!isPatternList(patternList)) {\n throw new TypeError('empty pattern list')\n }\n if (!isGlobList(globList)) {\n throw new TypeError('empty glob list')\n }\n if (globList.length !== patternList.length) {\n throw new TypeError('mismatched pattern list and glob list lengths')\n }\n this.length = patternList.length\n if (index < 0 || index >= this.length) {\n throw new TypeError('index out of range')\n }\n this.#patternList = patternList\n this.#globList = globList\n this.#index = index\n this.#platform = platform\n\n // normalize root entries of absolute patterns on initial creation.\n if (this.#index === 0) {\n // c: => ['c:/']\n // C:/ => ['C:/']\n // C:/x => ['C:/', 'x']\n // //host/share => ['//host/share/']\n // //host/share/ => ['//host/share/']\n // //host/share/x => ['//host/share/', 'x']\n // /etc => ['/', 'etc']\n // / => ['/']\n if (this.isUNC()) {\n // '' / '' / 'host' / 'share'\n const [p0, p1, p2, p3, ...prest] = this.#patternList\n const [g0, g1, g2, g3, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = [p0, p1, p2, p3, ''].join('/')\n const g = [g0, g1, g2, g3, ''].join('/')\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n } else if (this.isDrive() || this.isAbsolute()) {\n const [p1, ...prest] = this.#patternList\n const [g1, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = (p1 as string) + '/'\n const g = g1 + '/'\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n }\n }\n }\n\n /**\n * The first entry in the parsed list of patterns\n */\n pattern(): MMPattern {\n return this.#patternList[this.#index] as MMPattern\n }\n\n /**\n * true of if pattern() returns a string\n */\n isString(): boolean {\n return typeof this.#patternList[this.#index] === 'string'\n }\n /**\n * true of if pattern() returns GLOBSTAR\n */\n isGlobstar(): boolean {\n return this.#patternList[this.#index] === GLOBSTAR\n }\n /**\n * true if pattern() returns a regexp\n */\n isRegExp(): boolean {\n return this.#patternList[this.#index] instanceof RegExp\n }\n\n /**\n * The /-joined set of glob parts that make up this pattern\n */\n globString(): string {\n return (this.#globString =\n this.#globString ||\n (this.#index === 0 ?\n this.isAbsolute() ?\n this.#globList[0] + this.#globList.slice(1).join('/')\n : this.#globList.join('/')\n : this.#globList.slice(this.#index).join('/')))\n }\n\n /**\n * true if there are more pattern parts after this one\n */\n hasMore(): boolean {\n return this.length > this.#index + 1\n }\n\n /**\n * The rest of the pattern after this part, or null if this is the end\n */\n rest(): Pattern | null {\n if (this.#rest !== undefined) return this.#rest\n if (!this.hasMore()) return (this.#rest = null)\n this.#rest = new Pattern(\n this.#patternList,\n this.#globList,\n this.#index + 1,\n this.#platform,\n )\n this.#rest.#isAbsolute = this.#isAbsolute\n this.#rest.#isUNC = this.#isUNC\n this.#rest.#isDrive = this.#isDrive\n return this.#rest\n }\n\n /**\n * true if the pattern represents a //unc/path/ on windows\n */\n isUNC(): boolean {\n const pl = this.#patternList\n return this.#isUNC !== undefined ?\n this.#isUNC\n : (this.#isUNC =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n pl[0] === '' &&\n pl[1] === '' &&\n typeof pl[2] === 'string' &&\n !!pl[2] &&\n typeof pl[3] === 'string' &&\n !!pl[3])\n }\n\n // pattern like C:/...\n // split = ['C:', ...]\n // XXX: would be nice to handle patterns like `c:*` to test the cwd\n // in c: for *, but I don't know of a way to even figure out what that\n // cwd is without actually chdir'ing into it?\n /**\n * True if the pattern starts with a drive letter on Windows\n */\n isDrive(): boolean {\n const pl = this.#patternList\n return this.#isDrive !== undefined ?\n this.#isDrive\n : (this.#isDrive =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n this.length > 1 &&\n typeof pl[0] === 'string' &&\n /^[a-z]:$/i.test(pl[0]))\n }\n\n // pattern = '/' or '/...' or '/x/...'\n // split = ['', ''] or ['', ...] or ['', 'x', ...]\n // Drive and UNC both considered absolute on windows\n /**\n * True if the pattern is rooted on an absolute path\n */\n isAbsolute(): boolean {\n const pl = this.#patternList\n return this.#isAbsolute !== undefined ?\n this.#isAbsolute\n : (this.#isAbsolute =\n (pl[0] === '' && pl.length > 1) ||\n this.isDrive() ||\n this.isUNC())\n }\n\n /**\n * consume the root of the pattern, and return it\n */\n root(): string {\n const p = this.#patternList[0]\n return (\n typeof p === 'string' && this.isAbsolute() && this.#index === 0\n ) ?\n p\n : ''\n }\n\n /**\n * Check to see if the current globstar pattern is allowed to follow\n * a symbolic link.\n */\n checkFollowGlobstar(): boolean {\n return !(\n this.#index === 0 ||\n !this.isGlobstar() ||\n !this.#followGlobstar\n )\n }\n\n /**\n * Mark that the current globstar pattern is following a symbolic link\n */\n markFollowGlobstar(): boolean {\n if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n return false\n this.#followGlobstar = false\n return true\n }\n}\n"]}import { MMRegExp } from 'minimatch'; import { Path } from 'path-scurry'; import { Pattern } from './pattern.js'; import { GlobWalkerOpts } from './walker.js'; /** * A cache of which patterns have been processed for a given Path */ export declare class HasWalkedCache { store: Map>; constructor(store?: Map>); copy(): HasWalkedCache; hasWalked(target: Path, pattern: Pattern): boolean | undefined; storeWalked(target: Path, pattern: Pattern): void; } /** * A record of which paths have been matched in a given walk step, * and whether they only are considered a match if they are a directory, * and whether their absolute or relative path should be returned. */ export declare class MatchRecord { store: Map; add(target: Path, absolute: boolean, ifDir: boolean): void; entries(): [Path, boolean, boolean][]; } /** * A collection of patterns that must be processed in a subsequent step * for a given path. */ export declare class SubWalks { store: Map; add(target: Path, pattern: Pattern): void; get(target: Path): Pattern[]; entries(): [Path, Pattern[]][]; keys(): Path[]; } /** * The class that processes patterns for a given path. * * Handles child entry filtering, and determining whether a path's * directory contents must be read. */ export declare class Processor { hasWalkedCache: HasWalkedCache; matches: MatchRecord; subwalks: SubWalks; patterns?: Pattern[]; follow: boolean; dot: boolean; opts: GlobWalkerOpts; constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache); processPatterns(target: Path, patterns: Pattern[]): this; subwalkTargets(): Path[]; child(): Processor; filterEntries(parent: Path, entries: Path[]): Processor; testGlobstar(e: Path, pattern: Pattern, rest: Pattern | null, absolute: boolean): void; testRegExp(e: Path, p: MMRegExp, rest: Pattern | null, absolute: boolean): void; testString(e: Path, p: string, rest: Pattern | null, absolute: boolean): void; } //# sourceMappingURL=processor.d.ts.map{"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAa,OAAO,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C;;GAEG;AACH,qBAAa,cAAc;IACzB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;gBACnB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAa;IAGvD,IAAI;IAGJ,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAGxC,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;CAM3C;AAED;;;;GAIG;AACH,qBAAa,WAAW;IACtB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAY;IACpC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;IAMnD,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;CAOtC;AAED;;;GAGG;AACH,qBAAa,QAAQ;IACnB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAY;IACvC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAWlC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE;IAS5B,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE;IAG9B,IAAI,IAAI,IAAI,EAAE;CAGf;AAED;;;;;GAKG;AACH,qBAAa,SAAS;IACpB,cAAc,EAAE,cAAc,CAAA;IAC9B,OAAO,cAAoB;IAC3B,QAAQ,WAAiB;IACzB,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IACpB,MAAM,EAAE,OAAO,CAAA;IACf,GAAG,EAAE,OAAO,CAAA;IACZ,IAAI,EAAE,cAAc,CAAA;gBAER,IAAI,EAAE,cAAc,EAAE,cAAc,CAAC,EAAE,cAAc;IAQjE,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE;IAmGjD,cAAc,IAAI,IAAI,EAAE;IAIxB,KAAK;IAQL,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS;IAqBvD,YAAY,CACV,CAAC,EAAE,IAAI,EACP,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IA8CnB,UAAU,CACR,CAAC,EAAE,IAAI,EACP,CAAC,EAAE,QAAQ,EACX,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IAUnB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,EAAE,QAAQ,EAAE,OAAO;CASvE"}"use strict"; // synchronous utility for filtering entries and calculating subwalks Object.defineProperty(exports, "__esModule", { value: true }); exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0; const minimatch_1 = require("minimatch"); /** * A cache of which patterns have been processed for a given Path */ class HasWalkedCache { store; constructor(store = new Map()) { this.store = store; } copy() { return new HasWalkedCache(new Map(this.store)); } hasWalked(target, pattern) { return this.store.get(target.fullpath())?.has(pattern.globString()); } storeWalked(target, pattern) { const fullpath = target.fullpath(); const cached = this.store.get(fullpath); if (cached) cached.add(pattern.globString()); else this.store.set(fullpath, new Set([pattern.globString()])); } } exports.HasWalkedCache = HasWalkedCache; /** * A record of which paths have been matched in a given walk step, * and whether they only are considered a match if they are a directory, * and whether their absolute or relative path should be returned. */ class MatchRecord { store = new Map(); add(target, absolute, ifDir) { const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0); const current = this.store.get(target); this.store.set(target, current === undefined ? n : n & current); } // match, absolute, ifdir entries() { return [...this.store.entries()].map(([path, n]) => [ path, !!(n & 2), !!(n & 1), ]); } } exports.MatchRecord = MatchRecord; /** * A collection of patterns that must be processed in a subsequent step * for a given path. */ class SubWalks { store = new Map(); add(target, pattern) { if (!target.canReaddir()) { return; } const subs = this.store.get(target); if (subs) { if (!subs.find(p => p.globString() === pattern.globString())) { subs.push(pattern); } } else this.store.set(target, [pattern]); } get(target) { const subs = this.store.get(target); /* c8 ignore start */ if (!subs) { throw new Error('attempting to walk unknown path'); } /* c8 ignore stop */ return subs; } entries() { return this.keys().map(k => [k, this.store.get(k)]); } keys() { return [...this.store.keys()].filter(t => t.canReaddir()); } } exports.SubWalks = SubWalks; /** * The class that processes patterns for a given path. * * Handles child entry filtering, and determining whether a path's * directory contents must be read. */ class Processor { hasWalkedCache; matches = new MatchRecord(); subwalks = new SubWalks(); patterns; follow; dot; opts; constructor(opts, hasWalkedCache) { this.opts = opts; this.follow = !!opts.follow; this.dot = !!opts.dot; this.hasWalkedCache = hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache(); } processPatterns(target, patterns) { this.patterns = patterns; const processingSet = patterns.map(p => [target, p]); // map of paths to the magic-starting subwalks they need to walk // first item in patterns is the filter for (let [t, pattern] of processingSet) { this.hasWalkedCache.storeWalked(t, pattern); const root = pattern.root(); const absolute = pattern.isAbsolute() && this.opts.absolute !== false; // start absolute patterns at root if (root) { t = t.resolve(root === '/' && this.opts.root !== undefined ? this.opts.root : root); const rest = pattern.rest(); if (!rest) { this.matches.add(t, true, false); continue; } else { pattern = rest; } } if (t.isENOENT()) continue; let p; let rest; let changed = false; while (typeof (p = pattern.pattern()) === 'string' && (rest = pattern.rest())) { const c = t.resolve(p); t = c; pattern = rest; changed = true; } p = pattern.pattern(); rest = pattern.rest(); if (changed) { if (this.hasWalkedCache.hasWalked(t, pattern)) continue; this.hasWalkedCache.storeWalked(t, pattern); } // now we have either a final string for a known entry, // more strings for an unknown entry, // or a pattern starting with magic, mounted on t. if (typeof p === 'string') { // must not be final entry, otherwise we would have // concatenated it earlier. const ifDir = p === '..' || p === '' || p === '.'; this.matches.add(t.resolve(p), absolute, ifDir); continue; } else if (p === minimatch_1.GLOBSTAR) { // if no rest, match and subwalk pattern // if rest, process rest and subwalk pattern // if it's a symlink, but we didn't get here by way of a // globstar match (meaning it's the first time THIS globstar // has traversed a symlink), then we follow it. Otherwise, stop. if (!t.isSymbolicLink() || this.follow || pattern.checkFollowGlobstar()) { this.subwalks.add(t, pattern); } const rp = rest?.pattern(); const rrest = rest?.rest(); if (!rest || ((rp === '' || rp === '.') && !rrest)) { // only HAS to be a dir if it ends in **/ or **/. // but ending in ** will match files as well. this.matches.add(t, absolute, rp === '' || rp === '.'); } else { if (rp === '..') { // this would mean you're matching **/.. at the fs root, // and no thanks, I'm not gonna test that specific case. /* c8 ignore start */ const tp = t.parent || t; /* c8 ignore stop */ if (!rrest) this.matches.add(tp, absolute, true); else if (!this.hasWalkedCache.hasWalked(tp, rrest)) { this.subwalks.add(tp, rrest); } } } } else if (p instanceof RegExp) { this.subwalks.add(t, pattern); } } return this; } subwalkTargets() { return this.subwalks.keys(); } child() { return new Processor(this.opts, this.hasWalkedCache); } // return a new Processor containing the subwalks for each // child entry, and a set of matches, and // a hasWalkedCache that's a copy of this one // then we're going to call filterEntries(parent, entries) { const patterns = this.subwalks.get(parent); // put matches and entry walks into the results processor const results = this.child(); for (const e of entries) { for (const pattern of patterns) { const absolute = pattern.isAbsolute(); const p = pattern.pattern(); const rest = pattern.rest(); if (p === minimatch_1.GLOBSTAR) { results.testGlobstar(e, pattern, rest, absolute); } else if (p instanceof RegExp) { results.testRegExp(e, p, rest, absolute); } else { results.testString(e, p, rest, absolute); } } } return results; } testGlobstar(e, pattern, rest, absolute) { if (this.dot || !e.name.startsWith('.')) { if (!pattern.hasMore()) { this.matches.add(e, absolute, false); } if (e.canReaddir()) { // if we're in follow mode or it's not a symlink, just keep // testing the same pattern. If there's more after the globstar, // then this symlink consumes the globstar. If not, then we can // follow at most ONE symlink along the way, so we mark it, which // also checks to ensure that it wasn't already marked. if (this.follow || !e.isSymbolicLink()) { this.subwalks.add(e, pattern); } else if (e.isSymbolicLink()) { if (rest && pattern.checkFollowGlobstar()) { this.subwalks.add(e, rest); } else if (pattern.markFollowGlobstar()) { this.subwalks.add(e, pattern); } } } } // if the NEXT thing matches this entry, then also add // the rest. if (rest) { const rp = rest.pattern(); if (typeof rp === 'string' && // dots and empty were handled already rp !== '..' && rp !== '' && rp !== '.') { this.testString(e, rp, rest.rest(), absolute); } else if (rp === '..') { /* c8 ignore start */ const ep = e.parent || e; /* c8 ignore stop */ this.subwalks.add(ep, rest); } else if (rp instanceof RegExp) { this.testRegExp(e, rp, rest.rest(), absolute); } } } testRegExp(e, p, rest, absolute) { if (!p.test(e.name)) return; if (!rest) { this.matches.add(e, absolute, false); } else { this.subwalks.add(e, rest); } } testString(e, p, rest, absolute) { // should never happen? if (!e.isNamed(p)) return; if (!rest) { this.matches.add(e, absolute, false); } else { this.subwalks.add(e, rest); } } } exports.Processor = Processor; //# sourceMappingURL=processor.js.map{"version":3,"file":"processor.js","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":";AAAA,qEAAqE;;;AAErE,yCAA8C;AAK9C;;GAEG;AACH,MAAa,cAAc;IACzB,KAAK,CAA0B;IAC/B,YAAY,QAAkC,IAAI,GAAG,EAAE;QACrD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IACD,IAAI;QACF,OAAO,IAAI,cAAc,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,CAAC;IACD,SAAS,CAAC,MAAY,EAAE,OAAgB;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;IACrE,CAAC;IACD,WAAW,CAAC,MAAY,EAAE,OAAgB;QACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAA;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;QACvC,IAAI,MAAM;YAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;;YACvC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,CAAA;IAChE,CAAC;CACF;AAjBD,wCAiBC;AAED;;;;GAIG;AACH,MAAa,WAAW;IACtB,KAAK,GAAsB,IAAI,GAAG,EAAE,CAAA;IACpC,GAAG,CAAC,MAAY,EAAE,QAAiB,EAAE,KAAc;QACjD,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QAC9C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACtC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAA;IACjE,CAAC;IACD,yBAAyB;IACzB,OAAO;QACL,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC;YAClD,IAAI;YACJ,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YACT,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SACV,CAAC,CAAA;IACJ,CAAC;CACF;AAfD,kCAeC;AAED;;;GAGG;AACH,MAAa,QAAQ;IACnB,KAAK,GAAyB,IAAI,GAAG,EAAE,CAAA;IACvC,GAAG,CAAC,MAAY,EAAE,OAAgB;QAChC,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC;YACzB,OAAM;QACR,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACnC,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,EAAE,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC,EAAE,CAAC;gBAC7D,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YACpB,CAAC;QACH,CAAC;;YAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC,CAAA;IAC1C,CAAC;IACD,GAAG,CAAC,MAAY;QACd,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACnC,qBAAqB;QACrB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;QACpD,CAAC;QACD,oBAAoB;QACpB,OAAO,IAAI,CAAA;IACb,CAAC;IACD,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAc,CAAC,CAAC,CAAA;IAClE,CAAC;IACD,IAAI;QACF,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAA;IAC3D,CAAC;CACF;AA5BD,4BA4BC;AAED;;;;;GAKG;AACH,MAAa,SAAS;IACpB,cAAc,CAAgB;IAC9B,OAAO,GAAG,IAAI,WAAW,EAAE,CAAA;IAC3B,QAAQ,GAAG,IAAI,QAAQ,EAAE,CAAA;IACzB,QAAQ,CAAY;IACpB,MAAM,CAAS;IACf,GAAG,CAAS;IACZ,IAAI,CAAgB;IAEpB,YAAY,IAAoB,EAAE,cAA+B;QAC/D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;QAC3B,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAA;QACrB,IAAI,CAAC,cAAc;YACjB,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,cAAc,EAAE,CAAA;IACjE,CAAC;IAED,eAAe,CAAC,MAAY,EAAE,QAAmB;QAC/C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,MAAM,aAAa,GAAsB,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAA;QAEvE,gEAAgE;QAChE,uCAAuC;QAEvC,KAAK,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,IAAI,aAAa,EAAE,CAAC;YACvC,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;YAE3C,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;YAC3B,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,KAAK,KAAK,CAAA;YAErE,kCAAkC;YAClC,IAAI,IAAI,EAAE,CAAC;gBACT,CAAC,GAAG,CAAC,CAAC,OAAO,CACX,IAAI,KAAK,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;oBAC5C,IAAI,CAAC,IAAI,CAAC,IAAI;oBAChB,CAAC,CAAC,IAAI,CACP,CAAA;gBACD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;gBAC3B,IAAI,CAAC,IAAI,EAAE,CAAC;oBACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;oBAChC,SAAQ;gBACV,CAAC;qBAAM,CAAC;oBACN,OAAO,GAAG,IAAI,CAAA;gBAChB,CAAC;YACH,CAAC;YAED,IAAI,CAAC,CAAC,QAAQ,EAAE;gBAAE,SAAQ;YAE1B,IAAI,CAAY,CAAA;YAChB,IAAI,IAAoB,CAAA;YACxB,IAAI,OAAO,GAAG,KAAK,CAAA;YACnB,OACE,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,QAAQ;gBAC3C,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,EACvB,CAAC;gBACD,MAAM,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;gBACtB,CAAC,GAAG,CAAC,CAAA;gBACL,OAAO,GAAG,IAAI,CAAA;gBACd,OAAO,GAAG,IAAI,CAAA;YAChB,CAAC;YACD,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,CAAA;YACrB,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;YACrB,IAAI,OAAO,EAAE,CAAC;gBACZ,IAAI,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC;oBAAE,SAAQ;gBACvD,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;YAC7C,CAAC;YAED,uDAAuD;YACvD,qCAAqC;YACrC,kDAAkD;YAClD,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE,CAAC;gBAC1B,mDAAmD;gBACnD,2BAA2B;gBAC3B,MAAM,KAAK,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,GAAG,CAAA;gBACjD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;gBAC/C,SAAQ;YACV,CAAC;iBAAM,IAAI,CAAC,KAAK,oBAAQ,EAAE,CAAC;gBAC1B,wCAAwC;gBACxC,4CAA4C;gBAC5C,wDAAwD;gBACxD,4DAA4D;gBAC5D,gEAAgE;gBAChE,IACE,CAAC,CAAC,CAAC,cAAc,EAAE;oBACnB,IAAI,CAAC,MAAM;oBACX,OAAO,CAAC,mBAAmB,EAAE,EAC7B,CAAC;oBACD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;gBAC/B,CAAC;gBACD,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAA;gBAC1B,MAAM,KAAK,GAAG,IAAI,EAAE,IAAI,EAAE,CAAA;gBAC1B,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;oBACnD,iDAAiD;oBACjD,6CAA6C;oBAC7C,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC,CAAA;gBACxD,CAAC;qBAAM,CAAC;oBACN,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;wBAChB,wDAAwD;wBACxD,wDAAwD;wBACxD,qBAAqB;wBACrB,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAA;wBACxB,oBAAoB;wBACpB,IAAI,CAAC,KAAK;4BAAE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAA;6BAC3C,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC;4BACnD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;wBAC9B,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;iBAAM,IAAI,CAAC,YAAY,MAAM,EAAE,CAAC;gBAC/B,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;YAC/B,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAA;IACb,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAA;IAC7B,CAAC;IAED,KAAK;QACH,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,CAAA;IACtD,CAAC;IAED,0DAA0D;IAC1D,yCAAyC;IACzC,6CAA6C;IAC7C,2BAA2B;IAC3B,aAAa,CAAC,MAAY,EAAE,OAAe;QACzC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QAC1C,yDAAyD;QACzD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,EAAE,CAAA;QAC5B,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;YACxB,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;gBAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,EAAE,CAAA;gBACrC,MAAM,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,CAAA;gBAC3B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;gBAC3B,IAAI,CAAC,KAAK,oBAAQ,EAAE,CAAC;oBACnB,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;gBAClD,CAAC;qBAAM,IAAI,CAAC,YAAY,MAAM,EAAE,CAAC;oBAC/B,OAAO,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;gBAC1C,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;gBAC1C,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,OAAO,CAAA;IAChB,CAAC;IAED,YAAY,CACV,CAAO,EACP,OAAgB,EAChB,IAAoB,EACpB,QAAiB;QAEjB,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACxC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;gBACvB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;YACtC,CAAC;YACD,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC;gBACnB,2DAA2D;gBAC3D,gEAAgE;gBAChE,+DAA+D;gBAC/D,iEAAiE;gBACjE,uDAAuD;gBACvD,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,cAAc,EAAE,EAAE,CAAC;oBACvC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;gBAC/B,CAAC;qBAAM,IAAI,CAAC,CAAC,cAAc,EAAE,EAAE,CAAC;oBAC9B,IAAI,IAAI,IAAI,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC;wBAC1C,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;oBAC5B,CAAC;yBAAM,IAAI,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC;wBACxC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;oBAC/B,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QACD,sDAAsD;QACtD,YAAY;QACZ,IAAI,IAAI,EAAE,CAAC;YACT,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,CAAA;YACzB,IACE,OAAO,EAAE,KAAK,QAAQ;gBACtB,sCAAsC;gBACtC,EAAE,KAAK,IAAI;gBACX,EAAE,KAAK,EAAE;gBACT,EAAE,KAAK,GAAG,EACV,CAAC;gBACD,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/C,CAAC;iBAAM,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;gBACvB,qBAAqB;gBACrB,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAA;gBACxB,oBAAoB;gBACpB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;YAC7B,CAAC;iBAAM,IAAI,EAAE,YAAY,MAAM,EAAE,CAAC;gBAChC,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/C,CAAC;QACH,CAAC;IACH,CAAC;IAED,UAAU,CACR,CAAO,EACP,CAAW,EACX,IAAoB,EACpB,QAAiB;QAEjB,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;YAAE,OAAM;QAC3B,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;IAED,UAAU,CAAC,CAAO,EAAE,CAAS,EAAE,IAAoB,EAAE,QAAiB;QACpE,uBAAuB;QACvB,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;YAAE,OAAM;QACzB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF;AA9ND,8BA8NC","sourcesContent":["// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n store: Map>\n constructor(store: Map> = new Map()) {\n this.store = store\n }\n copy() {\n return new HasWalkedCache(new Map(this.store))\n }\n hasWalked(target: Path, pattern: Pattern) {\n return this.store.get(target.fullpath())?.has(pattern.globString())\n }\n storeWalked(target: Path, pattern: Pattern) {\n const fullpath = target.fullpath()\n const cached = this.store.get(fullpath)\n if (cached) cached.add(pattern.globString())\n else this.store.set(fullpath, new Set([pattern.globString()]))\n }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n store: Map = new Map()\n add(target: Path, absolute: boolean, ifDir: boolean) {\n const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n const current = this.store.get(target)\n this.store.set(target, current === undefined ? n : n & current)\n }\n // match, absolute, ifdir\n entries(): [Path, boolean, boolean][] {\n return [...this.store.entries()].map(([path, n]) => [\n path,\n !!(n & 2),\n !!(n & 1),\n ])\n }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n store: Map = new Map()\n add(target: Path, pattern: Pattern) {\n if (!target.canReaddir()) {\n return\n }\n const subs = this.store.get(target)\n if (subs) {\n if (!subs.find(p => p.globString() === pattern.globString())) {\n subs.push(pattern)\n }\n } else this.store.set(target, [pattern])\n }\n get(target: Path): Pattern[] {\n const subs = this.store.get(target)\n /* c8 ignore start */\n if (!subs) {\n throw new Error('attempting to walk unknown path')\n }\n /* c8 ignore stop */\n return subs\n }\n entries(): [Path, Pattern[]][] {\n return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n }\n keys(): Path[] {\n return [...this.store.keys()].filter(t => t.canReaddir())\n }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n hasWalkedCache: HasWalkedCache\n matches = new MatchRecord()\n subwalks = new SubWalks()\n patterns?: Pattern[]\n follow: boolean\n dot: boolean\n opts: GlobWalkerOpts\n\n constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n this.opts = opts\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.hasWalkedCache =\n hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n }\n\n processPatterns(target: Path, patterns: Pattern[]) {\n this.patterns = patterns\n const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n // map of paths to the magic-starting subwalks they need to walk\n // first item in patterns is the filter\n\n for (let [t, pattern] of processingSet) {\n this.hasWalkedCache.storeWalked(t, pattern)\n\n const root = pattern.root()\n const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n // start absolute patterns at root\n if (root) {\n t = t.resolve(\n root === '/' && this.opts.root !== undefined ?\n this.opts.root\n : root,\n )\n const rest = pattern.rest()\n if (!rest) {\n this.matches.add(t, true, false)\n continue\n } else {\n pattern = rest\n }\n }\n\n if (t.isENOENT()) continue\n\n let p: MMPattern\n let rest: Pattern | null\n let changed = false\n while (\n typeof (p = pattern.pattern()) === 'string' &&\n (rest = pattern.rest())\n ) {\n const c = t.resolve(p)\n t = c\n pattern = rest\n changed = true\n }\n p = pattern.pattern()\n rest = pattern.rest()\n if (changed) {\n if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n this.hasWalkedCache.storeWalked(t, pattern)\n }\n\n // now we have either a final string for a known entry,\n // more strings for an unknown entry,\n // or a pattern starting with magic, mounted on t.\n if (typeof p === 'string') {\n // must not be final entry, otherwise we would have\n // concatenated it earlier.\n const ifDir = p === '..' || p === '' || p === '.'\n this.matches.add(t.resolve(p), absolute, ifDir)\n continue\n } else if (p === GLOBSTAR) {\n // if no rest, match and subwalk pattern\n // if rest, process rest and subwalk pattern\n // if it's a symlink, but we didn't get here by way of a\n // globstar match (meaning it's the first time THIS globstar\n // has traversed a symlink), then we follow it. Otherwise, stop.\n if (\n !t.isSymbolicLink() ||\n this.follow ||\n pattern.checkFollowGlobstar()\n ) {\n this.subwalks.add(t, pattern)\n }\n const rp = rest?.pattern()\n const rrest = rest?.rest()\n if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n // only HAS to be a dir if it ends in **/ or **/.\n // but ending in ** will match files as well.\n this.matches.add(t, absolute, rp === '' || rp === '.')\n } else {\n if (rp === '..') {\n // this would mean you're matching **/.. at the fs root,\n // and no thanks, I'm not gonna test that specific case.\n /* c8 ignore start */\n const tp = t.parent || t\n /* c8 ignore stop */\n if (!rrest) this.matches.add(tp, absolute, true)\n else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n this.subwalks.add(tp, rrest)\n }\n }\n }\n } else if (p instanceof RegExp) {\n this.subwalks.add(t, pattern)\n }\n }\n\n return this\n }\n\n subwalkTargets(): Path[] {\n return this.subwalks.keys()\n }\n\n child() {\n return new Processor(this.opts, this.hasWalkedCache)\n }\n\n // return a new Processor containing the subwalks for each\n // child entry, and a set of matches, and\n // a hasWalkedCache that's a copy of this one\n // then we're going to call\n filterEntries(parent: Path, entries: Path[]): Processor {\n const patterns = this.subwalks.get(parent)\n // put matches and entry walks into the results processor\n const results = this.child()\n for (const e of entries) {\n for (const pattern of patterns) {\n const absolute = pattern.isAbsolute()\n const p = pattern.pattern()\n const rest = pattern.rest()\n if (p === GLOBSTAR) {\n results.testGlobstar(e, pattern, rest, absolute)\n } else if (p instanceof RegExp) {\n results.testRegExp(e, p, rest, absolute)\n } else {\n results.testString(e, p, rest, absolute)\n }\n }\n }\n return results\n }\n\n testGlobstar(\n e: Path,\n pattern: Pattern,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (this.dot || !e.name.startsWith('.')) {\n if (!pattern.hasMore()) {\n this.matches.add(e, absolute, false)\n }\n if (e.canReaddir()) {\n // if we're in follow mode or it's not a symlink, just keep\n // testing the same pattern. If there's more after the globstar,\n // then this symlink consumes the globstar. If not, then we can\n // follow at most ONE symlink along the way, so we mark it, which\n // also checks to ensure that it wasn't already marked.\n if (this.follow || !e.isSymbolicLink()) {\n this.subwalks.add(e, pattern)\n } else if (e.isSymbolicLink()) {\n if (rest && pattern.checkFollowGlobstar()) {\n this.subwalks.add(e, rest)\n } else if (pattern.markFollowGlobstar()) {\n this.subwalks.add(e, pattern)\n }\n }\n }\n }\n // if the NEXT thing matches this entry, then also add\n // the rest.\n if (rest) {\n const rp = rest.pattern()\n if (\n typeof rp === 'string' &&\n // dots and empty were handled already\n rp !== '..' &&\n rp !== '' &&\n rp !== '.'\n ) {\n this.testString(e, rp, rest.rest(), absolute)\n } else if (rp === '..') {\n /* c8 ignore start */\n const ep = e.parent || e\n /* c8 ignore stop */\n this.subwalks.add(ep, rest)\n } else if (rp instanceof RegExp) {\n this.testRegExp(e, rp, rest.rest(), absolute)\n }\n }\n }\n\n testRegExp(\n e: Path,\n p: MMRegExp,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (!p.test(e.name)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n\n testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n // should never happen?\n if (!e.isNamed(p)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n}\n"]}/** * Single-use utility classes to provide functionality to the {@link Glob} * methods. * * @module */ import { Minipass } from 'minipass'; import { Path } from 'path-scurry'; import { IgnoreLike } from './ignore.js'; import { Pattern } from './pattern.js'; import { Processor } from './processor.js'; export interface GlobWalkerOpts { absolute?: boolean; allowWindowsEscape?: boolean; cwd?: string | URL; dot?: boolean; dotRelative?: boolean; follow?: boolean; ignore?: string | string[] | IgnoreLike; mark?: boolean; matchBase?: boolean; maxDepth?: number; nobrace?: boolean; nocase?: boolean; nodir?: boolean; noext?: boolean; noglobstar?: boolean; platform?: NodeJS.Platform; posix?: boolean; realpath?: boolean; root?: string; stat?: boolean; signal?: AbortSignal; windowsPathsNoEscape?: boolean; withFileTypes?: boolean; includeChildMatches?: boolean; } export type GWOFileTypesTrue = GlobWalkerOpts & { withFileTypes: true; }; export type GWOFileTypesFalse = GlobWalkerOpts & { withFileTypes: false; }; export type GWOFileTypesUnset = GlobWalkerOpts & { withFileTypes?: undefined; }; export type Result = O extends GWOFileTypesTrue ? Path : O extends GWOFileTypesFalse ? string : O extends GWOFileTypesUnset ? string : Path | string; export type Matches = O extends GWOFileTypesTrue ? Set : O extends GWOFileTypesFalse ? Set : O extends GWOFileTypesUnset ? Set : Set; export type MatchStream = Minipass, Result>; /** * basic walking utilities that all the glob walker types use */ export declare abstract class GlobUtil { #private; path: Path; patterns: Pattern[]; opts: O; seen: Set; paused: boolean; aborted: boolean; signal?: AbortSignal; maxDepth: number; includeChildMatches: boolean; constructor(patterns: Pattern[], path: Path, opts: O); pause(): void; resume(): void; onResume(fn: () => any): void; matchCheck(e: Path, ifDir: boolean): Promise; matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined; matchCheckSync(e: Path, ifDir: boolean): Path | undefined; abstract matchEmit(p: Result): void; abstract matchEmit(p: string | Path): void; matchFinish(e: Path, absolute: boolean): void; match(e: Path, absolute: boolean, ifDir: boolean): Promise; matchSync(e: Path, absolute: boolean, ifDir: boolean): void; walkCB(target: Path, patterns: Pattern[], cb: () => any): void; walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any; walkCB3(target: Path, entries: Path[], processor: Processor, cb: () => any): void; walkCBSync(target: Path, patterns: Pattern[], cb: () => any): void; walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any; walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => any): void; } export declare class GlobWalker extends GlobUtil { matches: Set>; constructor(patterns: Pattern[], path: Path, opts: O); matchEmit(e: Result): void; walk(): Promise>>; walkSync(): Set>; } export declare class GlobStream extends GlobUtil { results: Minipass, Result>; constructor(patterns: Pattern[], path: Path, opts: O); matchEmit(e: Result): void; stream(): MatchStream; streamSync(): MatchStream; } //# sourceMappingURL=walker.d.ts.map{"version":3,"file":"walker.d.ts","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAU,UAAU,EAAE,MAAM,aAAa,CAAA;AAOhD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE1C,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;IAClB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IACvC,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,CAAA;IAGnB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;IAC1B,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B;AAED,MAAM,MAAM,gBAAgB,GAAG,cAAc,GAAG;IAC9C,aAAa,EAAE,IAAI,CAAA;CACpB,CAAA;AACD,MAAM,MAAM,iBAAiB,GAAG,cAAc,GAAG;IAC/C,aAAa,EAAE,KAAK,CAAA;CACrB,CAAA;AACD,MAAM,MAAM,iBAAiB,GAAG,cAAc,GAAG;IAC/C,aAAa,CAAC,EAAE,SAAS,CAAA;CAC1B,CAAA;AAED,MAAM,MAAM,MAAM,CAAC,CAAC,SAAS,cAAc,IACzC,CAAC,SAAS,gBAAgB,GAAG,IAAI,GAC/B,CAAC,SAAS,iBAAiB,GAAG,MAAM,GACpC,CAAC,SAAS,iBAAiB,GAAG,MAAM,GACpC,IAAI,GAAG,MAAM,CAAA;AAEjB,MAAM,MAAM,OAAO,CAAC,CAAC,SAAS,cAAc,IAC1C,CAAC,SAAS,gBAAgB,GAAG,GAAG,CAAC,IAAI,CAAC,GACpC,CAAC,SAAS,iBAAiB,GAAG,GAAG,CAAC,MAAM,CAAC,GACzC,CAAC,SAAS,iBAAiB,GAAG,GAAG,CAAC,MAAM,CAAC,GACzC,GAAG,CAAC,IAAI,GAAG,MAAM,CAAC,CAAA;AAEtB,MAAM,MAAM,WAAW,CAAC,CAAC,SAAS,cAAc,IAAI,QAAQ,CAC1D,MAAM,CAAC,CAAC,CAAC,EACT,MAAM,CAAC,CAAC,CAAC,CACV,CAAA;AAUD;;GAEG;AACH,8BAAsB,QAAQ,CAAC,CAAC,SAAS,cAAc,GAAG,cAAc;;IACtE,IAAI,EAAE,IAAI,CAAA;IACV,QAAQ,EAAE,OAAO,EAAE,CAAA;IACnB,IAAI,EAAE,CAAC,CAAA;IACP,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAkB;IACjC,MAAM,EAAE,OAAO,CAAQ;IACvB,OAAO,EAAE,OAAO,CAAQ;IAIxB,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,QAAQ,EAAE,MAAM,CAAA;IAChB,mBAAmB,EAAE,OAAO,CAAA;gBAEhB,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAsCpD,KAAK;IAGL,MAAM;IAUN,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG;IAahB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAqBpE,cAAc,CAAC,CAAC,EAAE,IAAI,GAAG,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS;IAgBrE,cAAc,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS;IAmBzD,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IACtC,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAE1C,WAAW,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO;IA2BhC,KAAK,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAKtE,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAK3D,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,MAAM,GAAG;IAOvD,OAAO,CACL,MAAM,EAAE,IAAI,EACZ,QAAQ,EAAE,OAAO,EAAE,EACnB,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;IA2Cf,OAAO,CACL,MAAM,EAAE,IAAI,EACZ,OAAO,EAAE,IAAI,EAAE,EACf,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;IAsBf,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,MAAM,GAAG;IAO3D,WAAW,CACT,MAAM,EAAE,IAAI,EACZ,QAAQ,EAAE,OAAO,EAAE,EACnB,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;IAqCf,WAAW,CACT,MAAM,EAAE,IAAI,EACZ,OAAO,EAAE,IAAI,EAAE,EACf,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;CAoBhB;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,iBAAuB;gBAElB,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAIpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAIvB,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAiBrC,QAAQ,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;CAW3B;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;gBAE3B,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAUpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAK7B,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC;IAYxB,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC;CAO7B"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0; /** * Single-use utility classes to provide functionality to the {@link Glob} * methods. * * @module */ const minipass_1 = require("minipass"); const ignore_js_1 = require("./ignore.js"); const processor_js_1 = require("./processor.js"); const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts) : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts) : ignore; /** * basic walking utilities that all the glob walker types use */ class GlobUtil { path; patterns; opts; seen = new Set(); paused = false; aborted = false; #onResume = []; #ignore; #sep; signal; maxDepth; includeChildMatches; constructor(patterns, path, opts) { this.patterns = patterns; this.path = path; this.opts = opts; this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/'; this.includeChildMatches = opts.includeChildMatches !== false; if (opts.ignore || !this.includeChildMatches) { this.#ignore = makeIgnore(opts.ignore ?? [], opts); if (!this.includeChildMatches && typeof this.#ignore.add !== 'function') { const m = 'cannot ignore child matches, ignore lacks add() method.'; throw new Error(m); } } // ignore, always set with maxDepth, but it's optional on the // GlobOptions type /* c8 ignore start */ this.maxDepth = opts.maxDepth || Infinity; /* c8 ignore stop */ if (opts.signal) { this.signal = opts.signal; this.signal.addEventListener('abort', () => { this.#onResume.length = 0; }); } } #ignored(path) { return this.seen.has(path) || !!this.#ignore?.ignored?.(path); } #childrenIgnored(path) { return !!this.#ignore?.childrenIgnored?.(path); } // backpressure mechanism pause() { this.paused = true; } resume() { /* c8 ignore start */ if (this.signal?.aborted) return; /* c8 ignore stop */ this.paused = false; let fn = undefined; while (!this.paused && (fn = this.#onResume.shift())) { fn(); } } onResume(fn) { if (this.signal?.aborted) return; /* c8 ignore start */ if (!this.paused) { fn(); } else { /* c8 ignore stop */ this.#onResume.push(fn); } } // do the requisite realpath/stat checking, and return the path // to add or undefined to filter it out. async matchCheck(e, ifDir) { if (ifDir && this.opts.nodir) return undefined; let rpc; if (this.opts.realpath) { rpc = e.realpathCached() || (await e.realpath()); if (!rpc) return undefined; e = rpc; } const needStat = e.isUnknown() || this.opts.stat; const s = needStat ? await e.lstat() : e; if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { const target = await s.realpath(); /* c8 ignore start */ if (target && (target.isUnknown() || this.opts.stat)) { await target.lstat(); } /* c8 ignore stop */ } return this.matchCheckTest(s, ifDir); } matchCheckTest(e, ifDir) { return (e && (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && (!ifDir || e.canReaddir()) && (!this.opts.nodir || !e.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e.isSymbolicLink() || !e.realpathCached()?.isDirectory()) && !this.#ignored(e)) ? e : undefined; } matchCheckSync(e, ifDir) { if (ifDir && this.opts.nodir) return undefined; let rpc; if (this.opts.realpath) { rpc = e.realpathCached() || e.realpathSync(); if (!rpc) return undefined; e = rpc; } const needStat = e.isUnknown() || this.opts.stat; const s = needStat ? e.lstatSync() : e; if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { const target = s.realpathSync(); if (target && (target?.isUnknown() || this.opts.stat)) { target.lstatSync(); } } return this.matchCheckTest(s, ifDir); } matchFinish(e, absolute) { if (this.#ignored(e)) return; // we know we have an ignore if this is false, but TS doesn't if (!this.includeChildMatches && this.#ignore?.add) { const ign = `${e.relativePosix()}/**`; this.#ignore.add(ign); } const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute; this.seen.add(e); const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''; // ok, we have what we need! if (this.opts.withFileTypes) { this.matchEmit(e); } else if (abs) { const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath(); this.matchEmit(abs + mark); } else { const rel = this.opts.posix ? e.relativePosix() : e.relative(); const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ? '.' + this.#sep : ''; this.matchEmit(!rel ? '.' + mark : pre + rel + mark); } } async match(e, absolute, ifDir) { const p = await this.matchCheck(e, ifDir); if (p) this.matchFinish(p, absolute); } matchSync(e, absolute, ifDir) { const p = this.matchCheckSync(e, ifDir); if (p) this.matchFinish(p, absolute); } walkCB(target, patterns, cb) { /* c8 ignore start */ if (this.signal?.aborted) cb(); /* c8 ignore stop */ this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb); } walkCB2(target, patterns, processor, cb) { if (this.#childrenIgnored(target)) return cb(); if (this.signal?.aborted) cb(); if (this.paused) { this.onResume(() => this.walkCB2(target, patterns, processor, cb)); return; } processor.processPatterns(target, patterns); // done processing. all of the above is sync, can be abstracted out. // subwalks is a map of paths to the entry filters they need // matches is a map of paths to [absolute, ifDir] tuples. let tasks = 1; const next = () => { if (--tasks === 0) cb(); }; for (const [m, absolute, ifDir] of processor.matches.entries()) { if (this.#ignored(m)) continue; tasks++; this.match(m, absolute, ifDir).then(() => next()); } for (const t of processor.subwalkTargets()) { if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { continue; } tasks++; const childrenCached = t.readdirCached(); if (t.calledReaddir()) this.walkCB3(t, childrenCached, processor, next); else { t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true); } } next(); } walkCB3(target, entries, processor, cb) { processor = processor.filterEntries(target, entries); let tasks = 1; const next = () => { if (--tasks === 0) cb(); }; for (const [m, absolute, ifDir] of processor.matches.entries()) { if (this.#ignored(m)) continue; tasks++; this.match(m, absolute, ifDir).then(() => next()); } for (const [target, patterns] of processor.subwalks.entries()) { tasks++; this.walkCB2(target, patterns, processor.child(), next); } next(); } walkCBSync(target, patterns, cb) { /* c8 ignore start */ if (this.signal?.aborted) cb(); /* c8 ignore stop */ this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb); } walkCB2Sync(target, patterns, processor, cb) { if (this.#childrenIgnored(target)) return cb(); if (this.signal?.aborted) cb(); if (this.paused) { this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb)); return; } processor.processPatterns(target, patterns); // done processing. all of the above is sync, can be abstracted out. // subwalks is a map of paths to the entry filters they need // matches is a map of paths to [absolute, ifDir] tuples. let tasks = 1; const next = () => { if (--tasks === 0) cb(); }; for (const [m, absolute, ifDir] of processor.matches.entries()) { if (this.#ignored(m)) continue; this.matchSync(m, absolute, ifDir); } for (const t of processor.subwalkTargets()) { if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { continue; } tasks++; const children = t.readdirSync(); this.walkCB3Sync(t, children, processor, next); } next(); } walkCB3Sync(target, entries, processor, cb) { processor = processor.filterEntries(target, entries); let tasks = 1; const next = () => { if (--tasks === 0) cb(); }; for (const [m, absolute, ifDir] of processor.matches.entries()) { if (this.#ignored(m)) continue; this.matchSync(m, absolute, ifDir); } for (const [target, patterns] of processor.subwalks.entries()) { tasks++; this.walkCB2Sync(target, patterns, processor.child(), next); } next(); } } exports.GlobUtil = GlobUtil; class GlobWalker extends GlobUtil { matches = new Set(); constructor(patterns, path, opts) { super(patterns, path, opts); } matchEmit(e) { this.matches.add(e); } async walk() { if (this.signal?.aborted) throw this.signal.reason; if (this.path.isUnknown()) { await this.path.lstat(); } await new Promise((res, rej) => { this.walkCB(this.path, this.patterns, () => { if (this.signal?.aborted) { rej(this.signal.reason); } else { res(this.matches); } }); }); return this.matches; } walkSync() { if (this.signal?.aborted) throw this.signal.reason; if (this.path.isUnknown()) { this.path.lstatSync(); } // nothing for the callback to do, because this never pauses this.walkCBSync(this.path, this.patterns, () => { if (this.signal?.aborted) throw this.signal.reason; }); return this.matches; } } exports.GlobWalker = GlobWalker; class GlobStream extends GlobUtil { results; constructor(patterns, path, opts) { super(patterns, path, opts); this.results = new minipass_1.Minipass({ signal: this.signal, objectMode: true, }); this.results.on('drain', () => this.resume()); this.results.on('resume', () => this.resume()); } matchEmit(e) { this.results.write(e); if (!this.results.flowing) this.pause(); } stream() { const target = this.path; if (target.isUnknown()) { target.lstat().then(() => { this.walkCB(target, this.patterns, () => this.results.end()); }); } else { this.walkCB(target, this.patterns, () => this.results.end()); } return this.results; } streamSync() { if (this.path.isUnknown()) { this.path.lstatSync(); } this.walkCBSync(this.path, this.patterns, () => this.results.end()); return this.results; } } exports.GlobStream = GlobStream; //# sourceMappingURL=walker.js.map{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,uCAAmC;AAEnC,2CAAgD;AAQhD,iDAA0C;AA0D1C,MAAM,UAAU,GAAG,CACjB,MAAsC,EACtC,IAAoB,EACR,EAAE,CACd,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,kBAAM,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC;IACvD,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,kBAAM,CAAC,MAAM,EAAE,IAAI,CAAC;QAClD,CAAC,CAAC,MAAM,CAAA;AAEV;;GAEG;AACH,MAAsB,QAAQ;IAC5B,IAAI,CAAM;IACV,QAAQ,CAAW;IACnB,IAAI,CAAG;IACP,IAAI,GAAc,IAAI,GAAG,EAAQ,CAAA;IACjC,MAAM,GAAY,KAAK,CAAA;IACvB,OAAO,GAAY,KAAK,CAAA;IACxB,SAAS,GAAkB,EAAE,CAAA;IAC7B,OAAO,CAAa;IACpB,IAAI,CAAY;IAChB,MAAM,CAAc;IACpB,QAAQ,CAAQ;IAChB,mBAAmB,CAAS;IAG5B,YAAY,QAAmB,EAAE,IAAU,EAAE,IAAO;QAClD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAA;QACjE,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,mBAAmB,KAAK,KAAK,CAAA;QAC7D,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC;YAC7C,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,EAAE,IAAI,CAAC,CAAA;YAClD,IACE,CAAC,IAAI,CAAC,mBAAmB;gBACzB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,UAAU,EACtC,CAAC;gBACD,MAAM,CAAC,GAAG,yDAAyD,CAAA;gBACnE,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,CAAA;YACpB,CAAC;QACH,CAAC;QACD,6DAA6D;QAC7D,mBAAmB;QACnB,qBAAqB;QACrB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAA;QACzC,oBAAoB;QACpB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;YACzB,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;gBACzC,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAA;YAC3B,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;IAED,QAAQ,CAAC,IAAU;QACjB,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;IAC/D,CAAC;IACD,gBAAgB,CAAC,IAAU;QACzB,OAAO,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,eAAe,EAAE,CAAC,IAAI,CAAC,CAAA;IAChD,CAAC;IAED,yBAAyB;IACzB,KAAK;QACH,IAAI,CAAC,MAAM,GAAG,IAAI,CAAA;IACpB,CAAC;IACD,MAAM;QACJ,qBAAqB;QACrB,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,OAAM;QAChC,oBAAoB;QACpB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;QACnB,IAAI,EAAE,GAA4B,SAAS,CAAA;QAC3C,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC;YACrD,EAAE,EAAE,CAAA;QACN,CAAC;IACH,CAAC;IACD,QAAQ,CAAC,EAAa;QACpB,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,OAAM;QAChC,qBAAqB;QACrB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,EAAE,EAAE,CAAA;QACN,CAAC;aAAM,CAAC;YACN,oBAAoB;YACpB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACzB,CAAC;IACH,CAAC;IAED,+DAA+D;IAC/D,wCAAwC;IACxC,KAAK,CAAC,UAAU,CAAC,CAAO,EAAE,KAAc;QACtC,IAAI,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAA;QAC9C,IAAI,GAAqB,CAAA;QACzB,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvB,GAAG,GAAG,CAAC,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAA;YAChD,IAAI,CAAC,GAAG;gBAAE,OAAO,SAAS,CAAA;YAC1B,CAAC,GAAG,GAAG,CAAA;QACT,CAAC;QACD,MAAM,QAAQ,GAAG,CAAC,CAAC,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;QAChD,MAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;QACxC,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,EAAE,cAAc,EAAE,EAAE,CAAC;YAC/D,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAA;YACjC,qBAAqB;YACrB,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrD,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;YACtB,CAAC;YACD,oBAAoB;QACtB,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;IACtC,CAAC;IAED,cAAc,CAAC,CAAmB,EAAE,KAAc;QAChD,OAAO,CACH,CAAC;YACC,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,CAAC;YAC1D,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;YAC1B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;YACtC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK;gBACf,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM;gBACjB,CAAC,CAAC,CAAC,cAAc,EAAE;gBACnB,CAAC,CAAC,CAAC,cAAc,EAAE,EAAE,WAAW,EAAE,CAAC;YACrC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CACpB,CAAC,CAAC;YACD,CAAC;YACH,CAAC,CAAC,SAAS,CAAA;IACf,CAAC;IAED,cAAc,CAAC,CAAO,EAAE,KAAc;QACpC,IAAI,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAA;QAC9C,IAAI,GAAqB,CAAA;QACzB,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvB,GAAG,GAAG,CAAC,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC,YAAY,EAAE,CAAA;YAC5C,IAAI,CAAC,GAAG;gBAAE,OAAO,SAAS,CAAA;YAC1B,CAAC,GAAG,GAAG,CAAA;QACT,CAAC;QACD,MAAM,QAAQ,GAAG,CAAC,CAAC,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;QAChD,MAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;QACtC,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,EAAE,cAAc,EAAE,EAAE,CAAC;YAC/D,MAAM,MAAM,GAAG,CAAC,CAAC,YAAY,EAAE,CAAA;YAC/B,IAAI,MAAM,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBACtD,MAAM,CAAC,SAAS,EAAE,CAAA;YACpB,CAAC;QACH,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;IACtC,CAAC;IAKD,WAAW,CAAC,CAAO,EAAE,QAAiB;QACpC,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;YAAE,OAAM;QAC5B,6DAA6D;QAC7D,IAAI,CAAC,IAAI,CAAC,mBAAmB,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC;YACnD,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,aAAa,EAAE,KAAK,CAAA;YACrC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QACvB,CAAC;QACD,MAAM,GAAG,GACP,IAAI,CAAC,IAAI,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAA;QAClE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;QAChB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;QAC/D,4BAA4B;QAC5B,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YAC5B,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;QACnB,CAAC;aAAM,IAAI,GAAG,EAAE,CAAC;YACf,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAA;YAC9D,IAAI,CAAC,SAAS,CAAC,GAAG,GAAG,IAAI,CAAC,CAAA;QAC5B,CAAC;aAAM,CAAC;YACN,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAA;YAC9D,MAAM,GAAG,GACP,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;gBAC1D,GAAG,GAAG,IAAI,CAAC,IAAI;gBACjB,CAAC,CAAC,EAAE,CAAA;YACN,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,IAAI,CAAC,CAAA;QACtD,CAAC;IACH,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,CAAO,EAAE,QAAiB,EAAE,KAAc;QACpD,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;QACzC,IAAI,CAAC;YAAE,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAA;IACtC,CAAC;IAED,SAAS,CAAC,CAAO,EAAE,QAAiB,EAAE,KAAc;QAClD,MAAM,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;QACvC,IAAI,CAAC;YAAE,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAA;IACtC,CAAC;IAED,MAAM,CAAC,MAAY,EAAE,QAAmB,EAAE,EAAa;QACrD,qBAAqB;QACrB,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,EAAE,EAAE,CAAA;QAC9B,oBAAoB;QACpB,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,wBAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAA;IAC9D,CAAC;IAED,OAAO,CACL,MAAY,EACZ,QAAmB,EACnB,SAAoB,EACpB,EAAa;QAEb,IAAI,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC;YAAE,OAAO,EAAE,EAAE,CAAA;QAC9C,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,EAAE,EAAE,CAAA;QAC9B,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC,CAAA;YAClE,OAAM;QACR,CAAC;QACD,SAAS,CAAC,eAAe,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QAE3C,qEAAqE;QACrE,4DAA4D;QAC5D,yDAAyD;QACzD,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,IAAI,EAAE,KAAK,KAAK,CAAC;gBAAE,EAAE,EAAE,CAAA;QACzB,CAAC,CAAA;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,SAAQ;YAC9B,KAAK,EAAE,CAAA;YACP,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAA;QACnD,CAAC;QAED,KAAK,MAAM,CAAC,IAAI,SAAS,CAAC,cAAc,EAAE,EAAE,CAAC;YAC3C,IAAI,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAC7D,SAAQ;YACV,CAAC;YACD,KAAK,EAAE,CAAA;YACP,MAAM,cAAc,GAAG,CAAC,CAAC,aAAa,EAAE,CAAA;YACxC,IAAI,CAAC,CAAC,aAAa,EAAE;gBACnB,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,cAAc,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;iBAC7C,CAAC;gBACJ,CAAC,CAAC,SAAS,CACT,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,EACzD,IAAI,CACL,CAAA;YACH,CAAC;QACH,CAAC;QAED,IAAI,EAAE,CAAA;IACR,CAAC;IAED,OAAO,CACL,MAAY,EACZ,OAAe,EACf,SAAoB,EACpB,EAAa;QAEb,SAAS,GAAG,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;QAEpD,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,IAAI,EAAE,KAAK,KAAK,CAAC;gBAAE,EAAE,EAAE,CAAA;QACzB,CAAC,CAAA;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,SAAQ;YAC9B,KAAK,EAAE,CAAA;YACP,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAA;QACnD,CAAC;QACD,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YAC9D,KAAK,EAAE,CAAA;YACP,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,CAAA;QACzD,CAAC;QAED,IAAI,EAAE,CAAA;IACR,CAAC;IAED,UAAU,CAAC,MAAY,EAAE,QAAmB,EAAE,EAAa;QACzD,qBAAqB;QACrB,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,EAAE,EAAE,CAAA;QAC9B,oBAAoB;QACpB,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,wBAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAA;IAClE,CAAC;IAED,WAAW,CACT,MAAY,EACZ,QAAmB,EACnB,SAAoB,EACpB,EAAa;QAEb,IAAI,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC;YAAE,OAAO,EAAE,EAAE,CAAA;QAC9C,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,EAAE,EAAE,CAAA;QAC9B,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CACjB,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,EAAE,CAAC,CAClD,CAAA;YACD,OAAM;QACR,CAAC;QACD,SAAS,CAAC,eAAe,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QAE3C,qEAAqE;QACrE,4DAA4D;QAC5D,yDAAyD;QACzD,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,IAAI,EAAE,KAAK,KAAK,CAAC;gBAAE,EAAE,EAAE,CAAA;QACzB,CAAC,CAAA;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,SAAQ;YAC9B,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACpC,CAAC;QAED,KAAK,MAAM,CAAC,IAAI,SAAS,CAAC,cAAc,EAAE,EAAE,CAAC;YAC3C,IAAI,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAC7D,SAAQ;YACV,CAAC;YACD,KAAK,EAAE,CAAA;YACP,MAAM,QAAQ,GAAG,CAAC,CAAC,WAAW,EAAE,CAAA;YAChC,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;QAChD,CAAC;QAED,IAAI,EAAE,CAAA;IACR,CAAC;IAED,WAAW,CACT,MAAY,EACZ,OAAe,EACf,SAAoB,EACpB,EAAa;QAEb,SAAS,GAAG,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;QAEpD,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,IAAI,EAAE,KAAK,KAAK,CAAC;gBAAE,EAAE,EAAE,CAAA;QACzB,CAAC,CAAA;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,SAAQ;YAC9B,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YAC9D,KAAK,EAAE,CAAA;YACP,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,CAAA;QAC7D,CAAC;QAED,IAAI,EAAE,CAAA;IACR,CAAC;CACF;AAtUD,4BAsUC;AAED,MAAa,UAEX,SAAQ,QAAW;IACnB,OAAO,GAAG,IAAI,GAAG,EAAa,CAAA;IAE9B,YAAY,QAAmB,EAAE,IAAU,EAAE,IAAO;QAClD,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;IAC7B,CAAC;IAED,SAAS,CAAC,CAAY;QACpB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;IACrB,CAAC;IAED,KAAK,CAAC,IAAI;QACR,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA;QAClD,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAA;QACzB,CAAC;QACD,MAAM,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC7B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE;gBACzC,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;oBACzB,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;gBACzB,CAAC;qBAAM,CAAC;oBACN,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;gBACnB,CAAC;YACH,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,QAAQ;QACN,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA;QAClD,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,4DAA4D;QAC5D,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE;YAC7C,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;gBAAE,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA;QACpD,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF;AAzCD,gCAyCC;AAED,MAAa,UAEX,SAAQ,QAAW;IACnB,OAAO,CAAgC;IAEvC,YAAY,QAAmB,EAAE,IAAU,EAAE,IAAO;QAClD,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,mBAAQ,CAAuB;YAChD,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,UAAU,EAAE,IAAI;SACjB,CAAC,CAAA;QACF,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAA;QAC7C,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAA;IAChD,CAAC;IAED,SAAS,CAAC,CAAY;QACpB,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QACrB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO;YAAE,IAAI,CAAC,KAAK,EAAE,CAAA;IACzC,CAAC;IAED,MAAM;QACJ,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAA;QACxB,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,MAAM,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;gBACvB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;YAC9D,CAAC,CAAC,CAAA;QACJ,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QAC9D,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,UAAU;QACR,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF;AAvCD,gCAuCC","sourcesContent":["/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed? that'd speed\n// things up a lot. Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n absolute?: boolean\n allowWindowsEscape?: boolean\n cwd?: string | URL\n dot?: boolean\n dotRelative?: boolean\n follow?: boolean\n ignore?: string | string[] | IgnoreLike\n mark?: boolean\n matchBase?: boolean\n // Note: maxDepth here means \"maximum actual Path.depth()\",\n // not \"maximum depth beyond cwd\"\n maxDepth?: number\n nobrace?: boolean\n nocase?: boolean\n nodir?: boolean\n noext?: boolean\n noglobstar?: boolean\n platform?: NodeJS.Platform\n posix?: boolean\n realpath?: boolean\n root?: string\n stat?: boolean\n signal?: AbortSignal\n windowsPathsNoEscape?: boolean\n withFileTypes?: boolean\n includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n withFileTypes?: undefined\n}\n\nexport type Result =\n O extends GWOFileTypesTrue ? Path\n : O extends GWOFileTypesFalse ? string\n : O extends GWOFileTypesUnset ? string\n : Path | string\n\nexport type Matches =\n O extends GWOFileTypesTrue ? Set\n : O extends GWOFileTypesFalse ? Set\n : O extends GWOFileTypesUnset ? Set\n : Set\n\nexport type MatchStream = Minipass<\n Result,\n Result\n>\n\nconst makeIgnore = (\n ignore: string | string[] | IgnoreLike,\n opts: GlobWalkerOpts,\n): IgnoreLike =>\n typeof ignore === 'string' ? new Ignore([ignore], opts)\n : Array.isArray(ignore) ? new Ignore(ignore, opts)\n : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n path: Path\n patterns: Pattern[]\n opts: O\n seen: Set = new Set()\n paused: boolean = false\n aborted: boolean = false\n #onResume: (() => any)[] = []\n #ignore?: IgnoreLike\n #sep: '\\\\' | '/'\n signal?: AbortSignal\n maxDepth: number\n includeChildMatches: boolean\n\n constructor(patterns: Pattern[], path: Path, opts: O)\n constructor(patterns: Pattern[], path: Path, opts: O) {\n this.patterns = patterns\n this.path = path\n this.opts = opts\n this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n this.includeChildMatches = opts.includeChildMatches !== false\n if (opts.ignore || !this.includeChildMatches) {\n this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n if (\n !this.includeChildMatches &&\n typeof this.#ignore.add !== 'function'\n ) {\n const m = 'cannot ignore child matches, ignore lacks add() method.'\n throw new Error(m)\n }\n }\n // ignore, always set with maxDepth, but it's optional on the\n // GlobOptions type\n /* c8 ignore start */\n this.maxDepth = opts.maxDepth || Infinity\n /* c8 ignore stop */\n if (opts.signal) {\n this.signal = opts.signal\n this.signal.addEventListener('abort', () => {\n this.#onResume.length = 0\n })\n }\n }\n\n #ignored(path: Path): boolean {\n return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n }\n #childrenIgnored(path: Path): boolean {\n return !!this.#ignore?.childrenIgnored?.(path)\n }\n\n // backpressure mechanism\n pause() {\n this.paused = true\n }\n resume() {\n /* c8 ignore start */\n if (this.signal?.aborted) return\n /* c8 ignore stop */\n this.paused = false\n let fn: (() => any) | undefined = undefined\n while (!this.paused && (fn = this.#onResume.shift())) {\n fn()\n }\n }\n onResume(fn: () => any) {\n if (this.signal?.aborted) return\n /* c8 ignore start */\n if (!this.paused) {\n fn()\n } else {\n /* c8 ignore stop */\n this.#onResume.push(fn)\n }\n }\n\n // do the requisite realpath/stat checking, and return the path\n // to add or undefined to filter it out.\n async matchCheck(e: Path, ifDir: boolean): Promise {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || (await e.realpath())\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? await e.lstat() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = await s.realpath()\n /* c8 ignore start */\n if (target && (target.isUnknown() || this.opts.stat)) {\n await target.lstat()\n }\n /* c8 ignore stop */\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n return (\n e &&\n (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n (!ifDir || e.canReaddir()) &&\n (!this.opts.nodir || !e.isDirectory()) &&\n (!this.opts.nodir ||\n !this.opts.follow ||\n !e.isSymbolicLink() ||\n !e.realpathCached()?.isDirectory()) &&\n !this.#ignored(e)\n ) ?\n e\n : undefined\n }\n\n matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || e.realpathSync()\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? e.lstatSync() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = s.realpathSync()\n if (target && (target?.isUnknown() || this.opts.stat)) {\n target.lstatSync()\n }\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n abstract matchEmit(p: Result): void\n abstract matchEmit(p: string | Path): void\n\n matchFinish(e: Path, absolute: boolean) {\n if (this.#ignored(e)) return\n // we know we have an ignore if this is false, but TS doesn't\n if (!this.includeChildMatches && this.#ignore?.add) {\n const ign = `${e.relativePosix()}/**`\n this.#ignore.add(ign)\n }\n const abs =\n this.opts.absolute === undefined ? absolute : this.opts.absolute\n this.seen.add(e)\n const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n // ok, we have what we need!\n if (this.opts.withFileTypes) {\n this.matchEmit(e)\n } else if (abs) {\n const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n this.matchEmit(abs + mark)\n } else {\n const rel = this.opts.posix ? e.relativePosix() : e.relative()\n const pre =\n this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n '.' + this.#sep\n : ''\n this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n }\n }\n\n async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n const p = await this.matchCheck(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n const p = this.matchCheckSync(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const childrenCached = t.readdirCached()\n if (t.calledReaddir())\n this.walkCB3(t, childrenCached, processor, next)\n else {\n t.readdirCB(\n (_, entries) => this.walkCB3(t, entries, processor, next),\n true,\n )\n }\n }\n\n next()\n }\n\n walkCB3(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2(target, patterns, processor.child(), next)\n }\n\n next()\n }\n\n walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2Sync(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() =>\n this.walkCB2Sync(target, patterns, processor, cb),\n )\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const children = t.readdirSync()\n this.walkCB3Sync(t, children, processor, next)\n }\n\n next()\n }\n\n walkCB3Sync(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2Sync(target, patterns, processor.child(), next)\n }\n\n next()\n }\n}\n\nexport class GlobWalker<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n matches = new Set>()\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n }\n\n matchEmit(e: Result): void {\n this.matches.add(e)\n }\n\n async walk(): Promise>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n await this.path.lstat()\n }\n await new Promise((res, rej) => {\n this.walkCB(this.path, this.patterns, () => {\n if (this.signal?.aborted) {\n rej(this.signal.reason)\n } else {\n res(this.matches)\n }\n })\n })\n return this.matches\n }\n\n walkSync(): Set> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n // nothing for the callback to do, because this never pauses\n this.walkCBSync(this.path, this.patterns, () => {\n if (this.signal?.aborted) throw this.signal.reason\n })\n return this.matches\n }\n}\n\nexport class GlobStream<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n results: Minipass, Result>\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n this.results = new Minipass, Result>({\n signal: this.signal,\n objectMode: true,\n })\n this.results.on('drain', () => this.resume())\n this.results.on('resume', () => this.resume())\n }\n\n matchEmit(e: Result): void {\n this.results.write(e)\n if (!this.results.flowing) this.pause()\n }\n\n stream(): MatchStream {\n const target = this.path\n if (target.isUnknown()) {\n target.lstat().then(() => {\n this.walkCB(target, this.patterns, () => this.results.end())\n })\n } else {\n this.walkCB(target, this.patterns, () => this.results.end())\n }\n return this.results\n }\n\n streamSync(): MatchStream {\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n this.walkCBSync(this.path, this.patterns, () => this.results.end())\n return this.results\n }\n}\n"]}#!/usr/bin/env node export {}; //# sourceMappingURL=bin.d.mts.map{"version":3,"file":"bin.d.mts","sourceRoot":"","sources":["../../src/bin.mts"],"names":[],"mappings":""}#!/usr/bin/env node import { foregroundChild } from 'foreground-child'; import { existsSync } from 'fs'; import { jack } from 'jackspeak'; import { loadPackageJson } from 'package-json-from-dist'; import { join } from 'path'; import { globStream } from './index.js'; const { version } = loadPackageJson(import.meta.url, '../package.json'); const j = jack({ usage: 'glob [options] [ [ ...]]', }) .description(` Glob v${version} Expand the positional glob expression arguments into any matching file system paths found. `) .opt({ cmd: { short: 'c', hint: 'command', description: `Run the command provided, passing the glob expression matches as arguments.`, }, }) .opt({ default: { short: 'p', hint: 'pattern', description: `If no positional arguments are provided, glob will use this pattern`, }, }) .flag({ all: { short: 'A', description: `By default, the glob cli command will not expand any arguments that are an exact match to a file on disk. This prevents double-expanding, in case the shell expands an argument whose filename is a glob expression. For example, if 'app/*.ts' would match 'app/[id].ts', then on Windows powershell or cmd.exe, 'glob app/*.ts' will expand to 'app/[id].ts', as expected. However, in posix shells such as bash or zsh, the shell will first expand 'app/*.ts' to a list of filenames. Then glob will look for a file matching 'app/[id].ts' (ie, 'app/i.ts' or 'app/d.ts'), which is unexpected. Setting '--all' prevents this behavior, causing glob to treat ALL patterns as glob expressions to be expanded, even if they are an exact match to a file on disk. When setting this option, be sure to enquote arguments so that the shell will not expand them prior to passing them to the glob command process. `, }, absolute: { short: 'a', description: 'Expand to absolute paths', }, 'dot-relative': { short: 'd', description: `Prepend './' on relative matches`, }, mark: { short: 'm', description: `Append a / on any directories matched`, }, posix: { short: 'x', description: `Always resolve to posix style paths, using '/' as the directory separator, even on Windows. Drive letter absolute matches on Windows will be expanded to their full resolved UNC maths, eg instead of 'C:\\foo\\bar', it will expand to '//?/C:/foo/bar'. `, }, follow: { short: 'f', description: `Follow symlinked directories when expanding '**'`, }, realpath: { short: 'R', description: `Call 'fs.realpath' on all of the results. In the case of an entry that cannot be resolved, the entry is omitted. This incurs a slight performance penalty, of course, because of the added system calls.`, }, stat: { short: 's', description: `Call 'fs.lstat' on all entries, whether required or not to determine if it's a valid match.`, }, 'match-base': { short: 'b', description: `Perform a basename-only match if the pattern does not contain any slash characters. That is, '*.js' would be treated as equivalent to '**/*.js', matching js files in all directories. `, }, dot: { description: `Allow patterns to match files/directories that start with '.', even if the pattern does not start with '.' `, }, nobrace: { description: 'Do not expand {...} patterns', }, nocase: { description: `Perform a case-insensitive match. This defaults to 'true' on macOS and Windows platforms, and false on all others. Note: 'nocase' should only be explicitly set when it is known that the filesystem's case sensitivity differs from the platform default. If set 'true' on case-insensitive file systems, then the walk may return more or less results than expected. `, }, nodir: { description: `Do not match directories, only files. Note: to *only* match directories, append a '/' at the end of the pattern. `, }, noext: { description: `Do not expand extglob patterns, such as '+(a|b)'`, }, noglobstar: { description: `Do not expand '**' against multiple path portions. Ie, treat it as a normal '*' instead.`, }, 'windows-path-no-escape': { description: `Use '\\' as a path separator *only*, and *never* as an escape character. If set, all '\\' characters are replaced with '/' in the pattern.`, }, }) .num({ 'max-depth': { short: 'D', description: `Maximum depth to traverse from the current working directory`, }, }) .opt({ cwd: { short: 'C', description: 'Current working directory to execute/match in', default: process.cwd(), }, root: { short: 'r', description: `A string path resolved against the 'cwd', which is used as the starting point for absolute patterns that start with '/' (but not drive letters or UNC paths on Windows). Note that this *doesn't* necessarily limit the walk to the 'root' directory, and doesn't affect the cwd starting point for non-absolute patterns. A pattern containing '..' will still be able to traverse out of the root directory, if it is not an actual root directory on the filesystem, and any non-absolute patterns will still be matched in the 'cwd'. To start absolute and non-absolute patterns in the same path, you can use '--root=' to set it to the empty string. However, be aware that on Windows systems, a pattern like 'x:/*' or '//host/share/*' will *always* start in the 'x:/' or '//host/share/' directory, regardless of the --root setting. `, }, platform: { description: `Defaults to the value of 'process.platform' if available, or 'linux' if not. Setting --platform=win32 on non-Windows systems may cause strange behavior!`, validOptions: [ 'aix', 'android', 'darwin', 'freebsd', 'haiku', 'linux', 'openbsd', 'sunos', 'win32', 'cygwin', 'netbsd', ], }, }) .optList({ ignore: { short: 'i', description: `Glob patterns to ignore`, }, }) .flag({ debug: { short: 'v', description: `Output a huge amount of noisy debug information about patterns as they are parsed and used to match files.`, }, }) .flag({ help: { short: 'h', description: 'Show this usage information', }, }); try { const { positionals, values } = j.parse(); if (values.help) { console.log(j.usage()); process.exit(0); } if (positionals.length === 0 && !values.default) throw 'No patterns provided'; if (positionals.length === 0 && values.default) positionals.push(values.default); const patterns = values.all ? positionals : positionals.filter(p => !existsSync(p)); const matches = values.all ? [] : positionals.filter(p => existsSync(p)).map(p => join(p)); const stream = globStream(patterns, { absolute: values.absolute, cwd: values.cwd, dot: values.dot, dotRelative: values['dot-relative'], follow: values.follow, ignore: values.ignore, mark: values.mark, matchBase: values['match-base'], maxDepth: values['max-depth'], nobrace: values.nobrace, nocase: values.nocase, nodir: values.nodir, noext: values.noext, noglobstar: values.noglobstar, platform: values.platform, realpath: values.realpath, root: values.root, stat: values.stat, debug: values.debug, posix: values.posix, }); const cmd = values.cmd; if (!cmd) { matches.forEach(m => console.log(m)); stream.on('data', f => console.log(f)); } else { stream.on('data', f => matches.push(f)); stream.on('end', () => foregroundChild(cmd, matches, { shell: true })); } } catch (e) { console.error(j.usage()); console.error(e instanceof Error ? e.message : String(e)); process.exit(1); } //# sourceMappingURL=bin.mjs.map{"version":3,"file":"bin.mjs","sourceRoot":"","sources":["../../src/bin.mts"],"names":[],"mappings":";AACA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAA;AAC/B,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACxD,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAEvC,MAAM,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAA;AAEvE,MAAM,CAAC,GAAG,IAAI,CAAC;IACb,KAAK,EAAE,4CAA4C;CACpD,CAAC;KACC,WAAW,CACV;YACQ,OAAO;;;;GAIhB,CACA;KACA,GAAG,CAAC;IACH,GAAG,EAAE;QACH,KAAK,EAAE,GAAG;QACV,IAAI,EAAE,SAAS;QACf,WAAW,EAAE;0CACuB;KACrC;CACF,CAAC;KACD,GAAG,CAAC;IACH,OAAO,EAAE;QACP,KAAK,EAAE,GAAG;QACV,IAAI,EAAE,SAAS;QACf,WAAW,EAAE;iCACc;KAC5B;CACF,CAAC;KACD,IAAI,CAAC;IACJ,GAAG,EAAE;QACH,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;;;;;;;;;;;;;;;;;;;;;OAqBZ;KACF;IACD,QAAQ,EAAE;QACR,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,0BAA0B;KACxC;IACD,cAAc,EAAE;QACd,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,kCAAkC;KAChD;IACD,IAAI,EAAE;QACJ,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,uCAAuC;KACrD;IACD,KAAK,EAAE;QACL,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;;;;;OAKZ;KACF;IAED,MAAM,EAAE;QACN,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,kDAAkD;KAChE;IACD,QAAQ,EAAE;QACR,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;;;+DAG4C;KAC1D;IACD,IAAI,EAAE;QACJ,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;wDACqC;KACnD;IACD,YAAY,EAAE;QACZ,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;;;;OAIZ;KACF;IAED,GAAG,EAAE;QACH,WAAW,EAAE;;OAEZ;KACF;IACD,OAAO,EAAE;QACP,WAAW,EAAE,8BAA8B;KAC5C;IACD,MAAM,EAAE;QACN,WAAW,EAAE;;;;;;;;;OASZ;KACF;IACD,KAAK,EAAE;QACL,WAAW,EAAE;;;;OAIZ;KACF;IACD,KAAK,EAAE;QACL,WAAW,EAAE,kDAAkD;KAChE;IACD,UAAU,EAAE;QACV,WAAW,EAAE;0DACuC;KACrD;IACD,wBAAwB,EAAE;QACxB,WAAW,EAAE;;sDAEmC;KACjD;CACF,CAAC;KACD,GAAG,CAAC;IACH,WAAW,EAAE;QACX,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;sCACmB;KACjC;CACF,CAAC;KACD,GAAG,CAAC;IACH,GAAG,EAAE;QACH,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,+CAA+C;QAC5D,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE;KACvB;IACD,IAAI,EAAE;QACJ,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;;;;;;;;;;;;;;;;;;;OAmBZ;KACF;IACD,QAAQ,EAAE;QACR,WAAW,EAAE;;uEAEoD;QACjE,YAAY,EAAE;YACZ,KAAK;YACL,SAAS;YACT,QAAQ;YACR,SAAS;YACT,OAAO;YACP,OAAO;YACP,SAAS;YACT,OAAO;YACP,OAAO;YACP,QAAQ;YACR,QAAQ;SACT;KACF;CACF,CAAC;KACD,OAAO,CAAC;IACP,MAAM,EAAE;QACN,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,yBAAyB;KACvC;CACF,CAAC;KACD,IAAI,CAAC;IACJ,KAAK,EAAE;QACL,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;yEACsD;KACpE;CACF,CAAC;KACD,IAAI,CAAC;IACJ,IAAI,EAAE;QACJ,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,6BAA6B;KAC3C;CACF,CAAC,CAAA;AAEJ,IAAI,CAAC;IACH,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,KAAK,EAAE,CAAA;IACzC,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;QACtB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IACjB,CAAC;IACD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO;QAC7C,MAAM,sBAAsB,CAAA;IAC9B,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO;QAC5C,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IAClC,MAAM,QAAQ,GACZ,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;IACpE,MAAM,OAAO,GACX,MAAM,CAAC,GAAG,CAAC,CAAC;QACV,EAAE;QACJ,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;IAC5D,MAAM,MAAM,GAAG,UAAU,CAAC,QAAQ,EAAE;QAClC,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,WAAW,EAAE,MAAM,CAAC,cAAc,CAAC;QACnC,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,SAAS,EAAE,MAAM,CAAC,YAAY,CAAC;QAC/B,QAAQ,EAAE,MAAM,CAAC,WAAW,CAAC;QAC7B,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,QAAQ,EAAE,MAAM,CAAC,QAAuC;QACxD,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,KAAK,EAAE,MAAM,CAAC,KAAK;KACpB,CAAC,CAAA;IAEF,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAA;IACtB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;QACpC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;IACxC,CAAC;SAAM,CAAC;QACN,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;QACvC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;IACxE,CAAC;AACH,CAAC;AAAC,OAAO,CAAC,EAAE,CAAC;IACX,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;IACxB,OAAO,CAAC,KAAK,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;IACzD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { foregroundChild } from 'foreground-child'\nimport { existsSync } from 'fs'\nimport { jack } from 'jackspeak'\nimport { loadPackageJson } from 'package-json-from-dist'\nimport { join } from 'path'\nimport { globStream } from './index.js'\n\nconst { version } = loadPackageJson(import.meta.url, '../package.json')\n\nconst j = jack({\n usage: 'glob [options] [ [ ...]]',\n})\n .description(\n `\n Glob v${version}\n\n Expand the positional glob expression arguments into any matching file\n system paths found.\n `,\n )\n .opt({\n cmd: {\n short: 'c',\n hint: 'command',\n description: `Run the command provided, passing the glob expression\n matches as arguments.`,\n },\n })\n .opt({\n default: {\n short: 'p',\n hint: 'pattern',\n description: `If no positional arguments are provided, glob will use\n this pattern`,\n },\n })\n .flag({\n all: {\n short: 'A',\n description: `By default, the glob cli command will not expand any\n arguments that are an exact match to a file on disk.\n\n This prevents double-expanding, in case the shell expands\n an argument whose filename is a glob expression.\n\n For example, if 'app/*.ts' would match 'app/[id].ts', then\n on Windows powershell or cmd.exe, 'glob app/*.ts' will\n expand to 'app/[id].ts', as expected. However, in posix\n shells such as bash or zsh, the shell will first expand\n 'app/*.ts' to a list of filenames. Then glob will look\n for a file matching 'app/[id].ts' (ie, 'app/i.ts' or\n 'app/d.ts'), which is unexpected.\n\n Setting '--all' prevents this behavior, causing glob\n to treat ALL patterns as glob expressions to be expanded,\n even if they are an exact match to a file on disk.\n\n When setting this option, be sure to enquote arguments\n so that the shell will not expand them prior to passing\n them to the glob command process.\n `,\n },\n absolute: {\n short: 'a',\n description: 'Expand to absolute paths',\n },\n 'dot-relative': {\n short: 'd',\n description: `Prepend './' on relative matches`,\n },\n mark: {\n short: 'm',\n description: `Append a / on any directories matched`,\n },\n posix: {\n short: 'x',\n description: `Always resolve to posix style paths, using '/' as the\n directory separator, even on Windows. Drive letter\n absolute matches on Windows will be expanded to their\n full resolved UNC maths, eg instead of 'C:\\\\foo\\\\bar',\n it will expand to '//?/C:/foo/bar'.\n `,\n },\n\n follow: {\n short: 'f',\n description: `Follow symlinked directories when expanding '**'`,\n },\n realpath: {\n short: 'R',\n description: `Call 'fs.realpath' on all of the results. In the case\n of an entry that cannot be resolved, the entry is\n omitted. This incurs a slight performance penalty, of\n course, because of the added system calls.`,\n },\n stat: {\n short: 's',\n description: `Call 'fs.lstat' on all entries, whether required or not\n to determine if it's a valid match.`,\n },\n 'match-base': {\n short: 'b',\n description: `Perform a basename-only match if the pattern does not\n contain any slash characters. That is, '*.js' would be\n treated as equivalent to '**/*.js', matching js files\n in all directories.\n `,\n },\n\n dot: {\n description: `Allow patterns to match files/directories that start\n with '.', even if the pattern does not start with '.'\n `,\n },\n nobrace: {\n description: 'Do not expand {...} patterns',\n },\n nocase: {\n description: `Perform a case-insensitive match. This defaults to\n 'true' on macOS and Windows platforms, and false on\n all others.\n\n Note: 'nocase' should only be explicitly set when it is\n known that the filesystem's case sensitivity differs\n from the platform default. If set 'true' on\n case-insensitive file systems, then the walk may return\n more or less results than expected.\n `,\n },\n nodir: {\n description: `Do not match directories, only files.\n\n Note: to *only* match directories, append a '/' at the\n end of the pattern.\n `,\n },\n noext: {\n description: `Do not expand extglob patterns, such as '+(a|b)'`,\n },\n noglobstar: {\n description: `Do not expand '**' against multiple path portions.\n Ie, treat it as a normal '*' instead.`,\n },\n 'windows-path-no-escape': {\n description: `Use '\\\\' as a path separator *only*, and *never* as an\n escape character. If set, all '\\\\' characters are\n replaced with '/' in the pattern.`,\n },\n })\n .num({\n 'max-depth': {\n short: 'D',\n description: `Maximum depth to traverse from the current\n working directory`,\n },\n })\n .opt({\n cwd: {\n short: 'C',\n description: 'Current working directory to execute/match in',\n default: process.cwd(),\n },\n root: {\n short: 'r',\n description: `A string path resolved against the 'cwd', which is\n used as the starting point for absolute patterns that\n start with '/' (but not drive letters or UNC paths\n on Windows).\n\n Note that this *doesn't* necessarily limit the walk to\n the 'root' directory, and doesn't affect the cwd\n starting point for non-absolute patterns. A pattern\n containing '..' will still be able to traverse out of\n the root directory, if it is not an actual root directory\n on the filesystem, and any non-absolute patterns will\n still be matched in the 'cwd'.\n\n To start absolute and non-absolute patterns in the same\n path, you can use '--root=' to set it to the empty\n string. However, be aware that on Windows systems, a\n pattern like 'x:/*' or '//host/share/*' will *always*\n start in the 'x:/' or '//host/share/' directory,\n regardless of the --root setting.\n `,\n },\n platform: {\n description: `Defaults to the value of 'process.platform' if\n available, or 'linux' if not. Setting --platform=win32\n on non-Windows systems may cause strange behavior!`,\n validOptions: [\n 'aix',\n 'android',\n 'darwin',\n 'freebsd',\n 'haiku',\n 'linux',\n 'openbsd',\n 'sunos',\n 'win32',\n 'cygwin',\n 'netbsd',\n ],\n },\n })\n .optList({\n ignore: {\n short: 'i',\n description: `Glob patterns to ignore`,\n },\n })\n .flag({\n debug: {\n short: 'v',\n description: `Output a huge amount of noisy debug information about\n patterns as they are parsed and used to match files.`,\n },\n })\n .flag({\n help: {\n short: 'h',\n description: 'Show this usage information',\n },\n })\n\ntry {\n const { positionals, values } = j.parse()\n if (values.help) {\n console.log(j.usage())\n process.exit(0)\n }\n if (positionals.length === 0 && !values.default)\n throw 'No patterns provided'\n if (positionals.length === 0 && values.default)\n positionals.push(values.default)\n const patterns =\n values.all ? positionals : positionals.filter(p => !existsSync(p))\n const matches =\n values.all ?\n []\n : positionals.filter(p => existsSync(p)).map(p => join(p))\n const stream = globStream(patterns, {\n absolute: values.absolute,\n cwd: values.cwd,\n dot: values.dot,\n dotRelative: values['dot-relative'],\n follow: values.follow,\n ignore: values.ignore,\n mark: values.mark,\n matchBase: values['match-base'],\n maxDepth: values['max-depth'],\n nobrace: values.nobrace,\n nocase: values.nocase,\n nodir: values.nodir,\n noext: values.noext,\n noglobstar: values.noglobstar,\n platform: values.platform as undefined | NodeJS.Platform,\n realpath: values.realpath,\n root: values.root,\n stat: values.stat,\n debug: values.debug,\n posix: values.posix,\n })\n\n const cmd = values.cmd\n if (!cmd) {\n matches.forEach(m => console.log(m))\n stream.on('data', f => console.log(f))\n } else {\n stream.on('data', f => matches.push(f))\n stream.on('end', () => foregroundChild(cmd, matches, { shell: true }))\n }\n} catch (e) {\n console.error(j.usage())\n console.error(e instanceof Error ? e.message : String(e))\n process.exit(1)\n}\n"]}import { Minimatch } from 'minimatch'; import { Minipass } from 'minipass'; import { FSOption, Path, PathScurry } from 'path-scurry'; import { IgnoreLike } from './ignore.js'; import { Pattern } from './pattern.js'; export type MatchSet = Minimatch['set']; export type GlobParts = Exclude; /** * A `GlobOptions` object may be provided to any of the exported methods, and * must be provided to the `Glob` constructor. * * All options are optional, boolean, and false by default, unless otherwise * noted. * * All resolved options are added to the Glob object as properties. * * If you are running many `glob` operations, you can pass a Glob object as the * `options` argument to a subsequent operation to share the previously loaded * cache. */ export interface GlobOptions { /** * Set to `true` to always receive absolute paths for * matched files. Set to `false` to always return relative paths. * * When this option is not set, absolute paths are returned for patterns * that are absolute, and otherwise paths are returned that are relative * to the `cwd` setting. * * This does _not_ make an extra system call to get * the realpath, it only does string path resolution. * * Conflicts with {@link withFileTypes} */ absolute?: boolean; /** * Set to false to enable {@link windowsPathsNoEscape} * * @deprecated */ allowWindowsEscape?: boolean; /** * The current working directory in which to search. Defaults to * `process.cwd()`. * * May be eiher a string path or a `file://` URL object or string. */ cwd?: string | URL; /** * Include `.dot` files in normal matches and `globstar` * matches. Note that an explicit dot in a portion of the pattern * will always match dot files. */ dot?: boolean; /** * Prepend all relative path strings with `./` (or `.\` on Windows). * * Without this option, returned relative paths are "bare", so instead of * returning `'./foo/bar'`, they are returned as `'foo/bar'`. * * Relative patterns starting with `'../'` are not prepended with `./`, even * if this option is set. */ dotRelative?: boolean; /** * Follow symlinked directories when expanding `**` * patterns. This can result in a lot of duplicate references in * the presence of cyclic links, and make performance quite bad. * * By default, a `**` in a pattern will follow 1 symbolic link if * it is not the first item in the pattern, or none if it is the * first item in the pattern, following the same behavior as Bash. */ follow?: boolean; /** * string or string[], or an object with `ignore` and `ignoreChildren` * methods. * * If a string or string[] is provided, then this is treated as a glob * pattern or array of glob patterns to exclude from matches. To ignore all * children within a directory, as well as the entry itself, append `'/**'` * to the ignore pattern. * * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of * any other settings. * * If an object is provided that has `ignored(path)` and/or * `childrenIgnored(path)` methods, then these methods will be called to * determine whether any Path is a match or if its children should be * traversed, respectively. */ ignore?: string | string[] | IgnoreLike; /** * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no * effect if {@link nobrace} is set. * * Only has effect on the {@link hasMagic} function. */ magicalBraces?: boolean; /** * Add a `/` character to directory matches. Note that this requires * additional stat calls in some cases. */ mark?: boolean; /** * Perform a basename-only match if the pattern does not contain any slash * characters. That is, `*.js` would be treated as equivalent to * `**\/*.js`, matching all js files in all directories. */ matchBase?: boolean; /** * Limit the directory traversal to a given depth below the cwd. * Note that this does NOT prevent traversal to sibling folders, * root patterns, and so on. It only limits the maximum folder depth * that the walk will descend, relative to the cwd. */ maxDepth?: number; /** * Do not expand `{a,b}` and `{1..3}` brace sets. */ nobrace?: boolean; /** * Perform a case-insensitive match. This defaults to `true` on macOS and * Windows systems, and `false` on all others. * * **Note** `nocase` should only be explicitly set when it is * known that the filesystem's case sensitivity differs from the * platform default. If set `true` on case-sensitive file * systems, or `false` on case-insensitive file systems, then the * walk may return more or less results than expected. */ nocase?: boolean; /** * Do not match directories, only files. (Note: to match * _only_ directories, put a `/` at the end of the pattern.) */ nodir?: boolean; /** * Do not match "extglob" patterns such as `+(a|b)`. */ noext?: boolean; /** * Do not match `**` against multiple filenames. (Ie, treat it as a normal * `*` instead.) * * Conflicts with {@link matchBase} */ noglobstar?: boolean; /** * Defaults to value of `process.platform` if available, or `'linux'` if * not. Setting `platform:'win32'` on non-Windows systems may cause strange * behavior. */ platform?: NodeJS.Platform; /** * Set to true to call `fs.realpath` on all of the * results. In the case of an entry that cannot be resolved, the * entry is omitted. This incurs a slight performance penalty, of * course, because of the added system calls. */ realpath?: boolean; /** * * A string path resolved against the `cwd` option, which * is used as the starting point for absolute patterns that start * with `/`, (but not drive letters or UNC paths on Windows). * * Note that this _doesn't_ necessarily limit the walk to the * `root` directory, and doesn't affect the cwd starting point for * non-absolute patterns. A pattern containing `..` will still be * able to traverse out of the root directory, if it is not an * actual root directory on the filesystem, and any non-absolute * patterns will be matched in the `cwd`. For example, the * pattern `/../*` with `{root:'/some/path'}` will return all * files in `/some`, not all files in `/some/path`. The pattern * `*` with `{root:'/some/path'}` will return all the entries in * the cwd, not the entries in `/some/path`. * * To start absolute and non-absolute patterns in the same * path, you can use `{root:''}`. However, be aware that on * Windows systems, a pattern like `x:/*` or `//host/share/*` will * _always_ start in the `x:/` or `//host/share` directory, * regardless of the `root` setting. */ root?: string; /** * A [PathScurry](http://npm.im/path-scurry) object used * to traverse the file system. If the `nocase` option is set * explicitly, then any provided `scurry` object must match this * setting. */ scurry?: PathScurry; /** * Call `lstat()` on all entries, whether required or not to determine * if it's a valid match. When used with {@link withFileTypes}, this means * that matches will include data such as modified time, permissions, and * so on. Note that this will incur a performance cost due to the added * system calls. */ stat?: boolean; /** * An AbortSignal which will cancel the Glob walk when * triggered. */ signal?: AbortSignal; /** * Use `\\` as a path separator _only_, and * _never_ as an escape character. If set, all `\\` characters are * replaced with `/` in the pattern. * * Note that this makes it **impossible** to match against paths * containing literal glob pattern characters, but allows matching * with patterns constructed using `path.join()` and * `path.resolve()` on Windows platforms, mimicking the (buggy!) * behavior of Glob v7 and before on Windows. Please use with * caution, and be mindful of [the caveat below about Windows * paths](#windows). (For legacy reasons, this is also set if * `allowWindowsEscape` is set to the exact value `false`.) */ windowsPathsNoEscape?: boolean; /** * Return [PathScurry](http://npm.im/path-scurry) * `Path` objects instead of strings. These are similar to a * NodeJS `Dirent` object, but with additional methods and * properties. * * Conflicts with {@link absolute} */ withFileTypes?: boolean; /** * An fs implementation to override some or all of the defaults. See * http://npm.im/path-scurry for details about what can be overridden. */ fs?: FSOption; /** * Just passed along to Minimatch. Note that this makes all pattern * matching operations slower and *extremely* noisy. */ debug?: boolean; /** * Return `/` delimited paths, even on Windows. * * On posix systems, this has no effect. But, on Windows, it means that * paths will be `/` delimited, and absolute paths will be their full * resolved UNC forms, eg instead of `'C:\\foo\\bar'`, it would return * `'//?/C:/foo/bar'` */ posix?: boolean; /** * Do not match any children of any matches. For example, the pattern * `**\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode. * * This is especially useful for cases like "find all `node_modules` * folders, but not the ones in `node_modules`". * * In order to support this, the `Ignore` implementation must support an * `add(pattern: string)` method. If using the default `Ignore` class, then * this is fine, but if this is set to `false`, and a custom `Ignore` is * provided that does not have an `add()` method, then it will throw an * error. * * **Caveat** It *only* ignores matches that would be a descendant of a * previous match, and only if that descendant is matched *after* the * ancestor is encountered. Since the file system walk happens in * indeterminate order, it's possible that a match will already be added * before its ancestor, if multiple or braced patterns are used. * * For example: * * ```ts * const results = await glob([ * // likely to match first, since it's just a stat * 'a/b/c/d/e/f', * * // this pattern is more complicated! It must to various readdir() * // calls and test the results against a regular expression, and that * // is certainly going to take a little bit longer. * // * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too * // late to ignore a/b/c/d/e/f, because it's already been emitted. * 'a/[bdf]/?/[a-z]/*', * ], { includeChildMatches: false }) * ``` * * It's best to only set this to `false` if you can be reasonably sure that * no components of the pattern will potentially match one another's file * system descendants, or if the occasional included child entry will not * cause problems. * * @default true */ includeChildMatches?: boolean; } export type GlobOptionsWithFileTypesTrue = GlobOptions & { withFileTypes: true; absolute?: undefined; mark?: undefined; posix?: undefined; }; export type GlobOptionsWithFileTypesFalse = GlobOptions & { withFileTypes?: false; }; export type GlobOptionsWithFileTypesUnset = GlobOptions & { withFileTypes?: undefined; }; export type Result = Opts extends GlobOptionsWithFileTypesTrue ? Path : Opts extends GlobOptionsWithFileTypesFalse ? string : Opts extends GlobOptionsWithFileTypesUnset ? string : string | Path; export type Results = Result[]; export type FileTypes = Opts extends GlobOptionsWithFileTypesTrue ? true : Opts extends GlobOptionsWithFileTypesFalse ? false : Opts extends GlobOptionsWithFileTypesUnset ? false : boolean; /** * An object that can perform glob pattern traversals. */ export declare class Glob implements GlobOptions { absolute?: boolean; cwd: string; root?: string; dot: boolean; dotRelative: boolean; follow: boolean; ignore?: string | string[] | IgnoreLike; magicalBraces: boolean; mark?: boolean; matchBase: boolean; maxDepth: number; nobrace: boolean; nocase: boolean; nodir: boolean; noext: boolean; noglobstar: boolean; pattern: string[]; platform: NodeJS.Platform; realpath: boolean; scurry: PathScurry; stat: boolean; signal?: AbortSignal; windowsPathsNoEscape: boolean; withFileTypes: FileTypes; includeChildMatches: boolean; /** * The options provided to the constructor. */ opts: Opts; /** * An array of parsed immutable {@link Pattern} objects. */ patterns: Pattern[]; /** * All options are stored as properties on the `Glob` object. * * See {@link GlobOptions} for full options descriptions. * * Note that a previous `Glob` object can be passed as the * `GlobOptions` to another `Glob` instantiation to re-use settings * and caches with a new pattern. * * Traversal functions can be called multiple times to run the walk * again. */ constructor(pattern: string | string[], opts: Opts); /** * Returns a Promise that resolves to the results array. */ walk(): Promise>; /** * synchronous {@link Glob.walk} */ walkSync(): Results; /** * Stream results asynchronously. */ stream(): Minipass, Result>; /** * Stream results synchronously. */ streamSync(): Minipass, Result>; /** * Default sync iteration function. Returns a Generator that * iterates over the results. */ iterateSync(): Generator, void, void>; [Symbol.iterator](): Generator, void, void>; /** * Default async iteration function. Returns an AsyncGenerator that * iterates over the results. */ iterate(): AsyncGenerator, void, void>; [Symbol.asyncIterator](): AsyncGenerator, void, void>; } //# sourceMappingURL=glob.d.ts.map{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAEnC,OAAO,EACL,QAAQ,EACR,IAAI,EACJ,UAAU,EAIX,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAGtC,MAAM,MAAM,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAC,CAAA;AACvC,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,SAAS,CAAC,CAAA;AAalE;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;;;;;;;OAYG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAE5B;;;;;OAKG;IACH,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;IAElB;;;;OAIG;IACH,GAAG,CAAC,EAAE,OAAO,CAAA;IAEb;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,OAAO,CAAA;IAErB;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAEhB;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IAEvC;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;OAGG;IACH,IAAI,CAAC,EAAE,OAAO,CAAA;IAEd;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAA;IAEnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IAEjB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IAEjB;;;;;;;;;OASG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAEhB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;IAEpB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;IAE1B;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,IAAI,CAAC,EAAE,MAAM,CAAA;IAEb;;;;;OAKG;IACH,MAAM,CAAC,EAAE,UAAU,CAAA;IAEnB;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,OAAO,CAAA;IAEd;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAA;IAEpB;;;;;;;;;;;;;OAaG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAE9B;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;OAGG;IACH,EAAE,CAAC,EAAE,QAAQ,CAAA;IAEb;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA0CG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B;AAED,MAAM,MAAM,4BAA4B,GAAG,WAAW,GAAG;IACvD,aAAa,EAAE,IAAI,CAAA;IAEnB,QAAQ,CAAC,EAAE,SAAS,CAAA;IACpB,IAAI,CAAC,EAAE,SAAS,CAAA;IAChB,KAAK,CAAC,EAAE,SAAS,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,6BAA6B,GAAG,WAAW,GAAG;IACxD,aAAa,CAAC,EAAE,KAAK,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,6BAA6B,GAAG,WAAW,GAAG;IACxD,aAAa,CAAC,EAAE,SAAS,CAAA;CAC1B,CAAA;AAED,MAAM,MAAM,MAAM,CAAC,IAAI,IACrB,IAAI,SAAS,4BAA4B,GAAG,IAAI,GAC9C,IAAI,SAAS,6BAA6B,GAAG,MAAM,GACnD,IAAI,SAAS,6BAA6B,GAAG,MAAM,GACnD,MAAM,GAAG,IAAI,CAAA;AACjB,MAAM,MAAM,OAAO,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,EAAE,CAAA;AAE1C,MAAM,MAAM,SAAS,CAAC,IAAI,IACxB,IAAI,SAAS,4BAA4B,GAAG,IAAI,GAC9C,IAAI,SAAS,6BAA6B,GAAG,KAAK,GAClD,IAAI,SAAS,6BAA6B,GAAG,KAAK,GAClD,OAAO,CAAA;AAEX;;GAEG;AACH,qBAAa,IAAI,CAAC,IAAI,SAAS,WAAW,CAAE,YAAW,WAAW;IAChE,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,GAAG,EAAE,OAAO,CAAA;IACZ,WAAW,EAAE,OAAO,CAAA;IACpB,MAAM,EAAE,OAAO,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IACvC,aAAa,EAAE,OAAO,CAAA;IACtB,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,SAAS,EAAE,OAAO,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,OAAO,CAAA;IACf,KAAK,EAAE,OAAO,CAAA;IACd,KAAK,EAAE,OAAO,CAAA;IACd,UAAU,EAAE,OAAO,CAAA;IACnB,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,QAAQ,EAAE,OAAO,CAAA;IACjB,MAAM,EAAE,UAAU,CAAA;IAClB,IAAI,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,oBAAoB,EAAE,OAAO,CAAA;IAC7B,aAAa,EAAE,SAAS,CAAC,IAAI,CAAC,CAAA;IAC9B,mBAAmB,EAAE,OAAO,CAAA;IAE5B;;OAEG;IACH,IAAI,EAAE,IAAI,CAAA;IAEV;;OAEG;IACH,QAAQ,EAAE,OAAO,EAAE,CAAA;IAEnB;;;;;;;;;;;OAWG;gBACS,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI;IA2HlD;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAoBpC;;OAEG;IACH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBzB;;OAEG;IACH,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAc9C;;OAEG;IACH,UAAU,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAclD;;;OAGG;IACH,WAAW,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGlD,CAAC,MAAM,CAAC,QAAQ,CAAC;IAIjB;;;OAGG;IACH,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGnD,CAAC,MAAM,CAAC,aAAa,CAAC;CAGvB"}import { Minimatch } from 'minimatch'; import { fileURLToPath } from 'node:url'; import { PathScurry, PathScurryDarwin, PathScurryPosix, PathScurryWin32, } from 'path-scurry'; import { Pattern } from './pattern.js'; import { GlobStream, GlobWalker } from './walker.js'; // if no process global, just call it linux. // so we default to case-sensitive, / separators const defaultPlatform = (typeof process === 'object' && process && typeof process.platform === 'string') ? process.platform : 'linux'; /** * An object that can perform glob pattern traversals. */ export class Glob { absolute; cwd; root; dot; dotRelative; follow; ignore; magicalBraces; mark; matchBase; maxDepth; nobrace; nocase; nodir; noext; noglobstar; pattern; platform; realpath; scurry; stat; signal; windowsPathsNoEscape; withFileTypes; includeChildMatches; /** * The options provided to the constructor. */ opts; /** * An array of parsed immutable {@link Pattern} objects. */ patterns; /** * All options are stored as properties on the `Glob` object. * * See {@link GlobOptions} for full options descriptions. * * Note that a previous `Glob` object can be passed as the * `GlobOptions` to another `Glob` instantiation to re-use settings * and caches with a new pattern. * * Traversal functions can be called multiple times to run the walk * again. */ constructor(pattern, opts) { /* c8 ignore start */ if (!opts) throw new TypeError('glob options required'); /* c8 ignore stop */ this.withFileTypes = !!opts.withFileTypes; this.signal = opts.signal; this.follow = !!opts.follow; this.dot = !!opts.dot; this.dotRelative = !!opts.dotRelative; this.nodir = !!opts.nodir; this.mark = !!opts.mark; if (!opts.cwd) { this.cwd = ''; } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) { opts.cwd = fileURLToPath(opts.cwd); } this.cwd = opts.cwd || ''; this.root = opts.root; this.magicalBraces = !!opts.magicalBraces; this.nobrace = !!opts.nobrace; this.noext = !!opts.noext; this.realpath = !!opts.realpath; this.absolute = opts.absolute; this.includeChildMatches = opts.includeChildMatches !== false; this.noglobstar = !!opts.noglobstar; this.matchBase = !!opts.matchBase; this.maxDepth = typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity; this.stat = !!opts.stat; this.ignore = opts.ignore; if (this.withFileTypes && this.absolute !== undefined) { throw new Error('cannot set absolute and withFileTypes:true'); } if (typeof pattern === 'string') { pattern = [pattern]; } this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false; if (this.windowsPathsNoEscape) { pattern = pattern.map(p => p.replace(/\\/g, '/')); } if (this.matchBase) { if (opts.noglobstar) { throw new TypeError('base matching requires globstar'); } pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`)); } this.pattern = pattern; this.platform = opts.platform || defaultPlatform; this.opts = { ...opts, platform: this.platform }; if (opts.scurry) { this.scurry = opts.scurry; if (opts.nocase !== undefined && opts.nocase !== opts.scurry.nocase) { throw new Error('nocase option contradicts provided scurry option'); } } else { const Scurry = opts.platform === 'win32' ? PathScurryWin32 : opts.platform === 'darwin' ? PathScurryDarwin : opts.platform ? PathScurryPosix : PathScurry; this.scurry = new Scurry(this.cwd, { nocase: opts.nocase, fs: opts.fs, }); } this.nocase = this.scurry.nocase; // If you do nocase:true on a case-sensitive file system, then // we need to use regexps instead of strings for non-magic // path portions, because statting `aBc` won't return results // for the file `AbC` for example. const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; const mmo = { // default nocase based on platform ...opts, dot: this.dot, matchBase: this.matchBase, nobrace: this.nobrace, nocase: this.nocase, nocaseMagicOnly, nocomment: true, noext: this.noext, nonegate: true, optimizationLevel: 2, platform: this.platform, windowsPathsNoEscape: this.windowsPathsNoEscape, debug: !!this.opts.debug, }; const mms = this.pattern.map(p => new Minimatch(p, mmo)); const [matchSet, globParts] = mms.reduce((set, m) => { set[0].push(...m.set); set[1].push(...m.globParts); return set; }, [[], []]); this.patterns = matchSet.map((set, i) => { const g = globParts[i]; /* c8 ignore start */ if (!g) throw new Error('invalid pattern object'); /* c8 ignore stop */ return new Pattern(set, g, 0, this.platform); }); } async walk() { // Walkers always return array of Path objects, so we just have to // coerce them into the right shape. It will have already called // realpath() if the option was set to do so, so we know that's cached. // start out knowing the cwd, at least return [ ...(await new GlobWalker(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches, }).walk()), ]; } walkSync() { return [ ...new GlobWalker(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches, }).walkSync(), ]; } stream() { return new GlobStream(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches, }).stream(); } streamSync() { return new GlobStream(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches, }).streamSync(); } /** * Default sync iteration function. Returns a Generator that * iterates over the results. */ iterateSync() { return this.streamSync()[Symbol.iterator](); } [Symbol.iterator]() { return this.iterateSync(); } /** * Default async iteration function. Returns an AsyncGenerator that * iterates over the results. */ iterate() { return this.stream()[Symbol.asyncIterator](); } [Symbol.asyncIterator]() { return this.iterate(); } } //# sourceMappingURL=glob.js.map{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AAEvD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAGL,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,aAAa,CAAA;AAEpB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAKpD,4CAA4C;AAC5C,gDAAgD;AAChD,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAyVX;;GAEG;AACH,MAAM,OAAO,IAAI;IACf,QAAQ,CAAU;IAClB,GAAG,CAAQ;IACX,IAAI,CAAS;IACb,GAAG,CAAS;IACZ,WAAW,CAAS;IACpB,MAAM,CAAS;IACf,MAAM,CAAiC;IACvC,aAAa,CAAS;IACtB,IAAI,CAAU;IACd,SAAS,CAAS;IAClB,QAAQ,CAAQ;IAChB,OAAO,CAAS;IAChB,MAAM,CAAS;IACf,KAAK,CAAS;IACd,KAAK,CAAS;IACd,UAAU,CAAS;IACnB,OAAO,CAAU;IACjB,QAAQ,CAAiB;IACzB,QAAQ,CAAS;IACjB,MAAM,CAAY;IAClB,IAAI,CAAS;IACb,MAAM,CAAc;IACpB,oBAAoB,CAAS;IAC7B,aAAa,CAAiB;IAC9B,mBAAmB,CAAS;IAE5B;;OAEG;IACH,IAAI,CAAM;IAEV;;OAEG;IACH,QAAQ,CAAW;IAEnB;;;;;;;;;;;OAWG;IACH,YAAY,OAA0B,EAAE,IAAU;QAChD,qBAAqB;QACrB,IAAI,CAAC,IAAI;YAAE,MAAM,IAAI,SAAS,CAAC,uBAAuB,CAAC,CAAA;QACvD,oBAAoB;QACpB,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC,IAAI,CAAC,aAAgC,CAAA;QAC5D,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QACzB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;QAC3B,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAA;QACrB,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAA;QACrC,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAA;QACzB,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAA;QACvB,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;YACd,IAAI,CAAC,GAAG,GAAG,EAAE,CAAA;QACf,CAAC;aAAM,IAAI,IAAI,CAAC,GAAG,YAAY,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;YACrE,IAAI,CAAC,GAAG,GAAG,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACpC,CAAC;QACD,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,EAAE,CAAA;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAA;QACrB,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC,IAAI,CAAC,aAAa,CAAA;QACzC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAA;QAC7B,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAA;QACzB,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAA;QAC/B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAA;QAC7B,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,mBAAmB,KAAK,KAAK,CAAA;QAE7D,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,CAAA;QACnC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,CAAA;QACjC,IAAI,CAAC,QAAQ;YACX,OAAO,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAA;QAC9D,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAA;QACvB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QAEzB,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACtD,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAA;QAC/D,CAAC;QAED,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAChC,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;QACrB,CAAC;QAED,IAAI,CAAC,oBAAoB;YACvB,CAAC,CAAC,IAAI,CAAC,oBAAoB;gBAC1B,IAAyC,CAAC,kBAAkB;oBAC3D,KAAK,CAAA;QAET,IAAI,IAAI,CAAC,oBAAoB,EAAE,CAAC;YAC9B,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAA;QACnD,CAAC;QAED,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;gBACpB,MAAM,IAAI,SAAS,CAAC,iCAAiC,CAAC,CAAA;YACxD,CAAC;YACD,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAA;QACjE,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QAEtB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,eAAe,CAAA;QAChD,IAAI,CAAC,IAAI,GAAG,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAA;QAChD,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;YACzB,IACE,IAAI,CAAC,MAAM,KAAK,SAAS;gBACzB,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAAC,MAAM,EAClC,CAAC;gBACD,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;YACrE,CAAC;QACH,CAAC;aAAM,CAAC;YACN,MAAM,MAAM,GACV,IAAI,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,eAAe;gBAC3C,CAAC,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB;oBAC/C,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,eAAe;wBACjC,CAAC,CAAC,UAAU,CAAA;YACd,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE;gBACjC,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,EAAE,EAAE,IAAI,CAAC,EAAE;aACZ,CAAC,CAAA;QACJ,CAAC;QACD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA;QAEhC,8DAA8D;QAC9D,0DAA0D;QAC1D,6DAA6D;QAC7D,kCAAkC;QAClC,MAAM,eAAe,GACnB,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,IAAI,CAAC,QAAQ,KAAK,OAAO,CAAA;QAEzD,MAAM,GAAG,GAAqB;YAC5B,mCAAmC;YACnC,GAAG,IAAI;YACP,GAAG,EAAE,IAAI,CAAC,GAAG;YACb,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,eAAe;YACf,SAAS,EAAE,IAAI;YACf,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,QAAQ,EAAE,IAAI;YACd,iBAAiB,EAAE,CAAC;YACpB,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK;SACzB,CAAA;QAED,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAA;QACxD,MAAM,CAAC,QAAQ,EAAE,SAAS,CAAC,GAAG,GAAG,CAAC,MAAM,CACtC,CAAC,GAA0B,EAAE,CAAC,EAAE,EAAE;YAChC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAA;YACrB,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,CAAA;YAC3B,OAAO,GAAG,CAAA;QACZ,CAAC,EACD,CAAC,EAAE,EAAE,EAAE,CAAC,CACT,CAAA;QACD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;YACtC,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAA;YACtB,qBAAqB;YACrB,IAAI,CAAC,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;YACjD,oBAAoB;YACpB,OAAO,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;QAC9C,CAAC,CAAC,CAAA;IACJ,CAAC;IAMD,KAAK,CAAC,IAAI;QACR,kEAAkE;QAClE,iEAAiE;QACjE,uEAAuE;QACvE,sCAAsC;QACtC,OAAO;YACL,GAAG,CAAC,MAAM,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;gBACvD,GAAG,IAAI,CAAC,IAAI;gBACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;oBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;oBACzC,CAAC,CAAC,QAAQ;gBACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;aAC9C,CAAC,CAAC,IAAI,EAAE,CAAC;SACX,CAAA;IACH,CAAC;IAMD,QAAQ;QACN,OAAO;YACL,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;gBAChD,GAAG,IAAI,CAAC,IAAI;gBACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;oBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;oBACzC,CAAC,CAAC,QAAQ;gBACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;aAC9C,CAAC,CAAC,QAAQ,EAAE;SACd,CAAA;IACH,CAAC;IAMD,MAAM;QACJ,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACpD,GAAG,IAAI,CAAC,IAAI;YACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,MAAM,EAAE,CAAA;IACb,CAAC;IAMD,UAAU;QACR,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACpD,GAAG,IAAI,CAAC,IAAI;YACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,UAAU,EAAE,CAAA;IACjB,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF","sourcesContent":["import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n /**\n * Set to `true` to always receive absolute paths for\n * matched files. Set to `false` to always return relative paths.\n *\n * When this option is not set, absolute paths are returned for patterns\n * that are absolute, and otherwise paths are returned that are relative\n * to the `cwd` setting.\n *\n * This does _not_ make an extra system call to get\n * the realpath, it only does string path resolution.\n *\n * Conflicts with {@link withFileTypes}\n */\n absolute?: boolean\n\n /**\n * Set to false to enable {@link windowsPathsNoEscape}\n *\n * @deprecated\n */\n allowWindowsEscape?: boolean\n\n /**\n * The current working directory in which to search. Defaults to\n * `process.cwd()`.\n *\n * May be eiher a string path or a `file://` URL object or string.\n */\n cwd?: string | URL\n\n /**\n * Include `.dot` files in normal matches and `globstar`\n * matches. Note that an explicit dot in a portion of the pattern\n * will always match dot files.\n */\n dot?: boolean\n\n /**\n * Prepend all relative path strings with `./` (or `.\\` on Windows).\n *\n * Without this option, returned relative paths are \"bare\", so instead of\n * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n *\n * Relative patterns starting with `'../'` are not prepended with `./`, even\n * if this option is set.\n */\n dotRelative?: boolean\n\n /**\n * Follow symlinked directories when expanding `**`\n * patterns. This can result in a lot of duplicate references in\n * the presence of cyclic links, and make performance quite bad.\n *\n * By default, a `**` in a pattern will follow 1 symbolic link if\n * it is not the first item in the pattern, or none if it is the\n * first item in the pattern, following the same behavior as Bash.\n */\n follow?: boolean\n\n /**\n * string or string[], or an object with `ignore` and `ignoreChildren`\n * methods.\n *\n * If a string or string[] is provided, then this is treated as a glob\n * pattern or array of glob patterns to exclude from matches. To ignore all\n * children within a directory, as well as the entry itself, append `'/**'`\n * to the ignore pattern.\n *\n * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n * any other settings.\n *\n * If an object is provided that has `ignored(path)` and/or\n * `childrenIgnored(path)` methods, then these methods will be called to\n * determine whether any Path is a match or if its children should be\n * traversed, respectively.\n */\n ignore?: string | string[] | IgnoreLike\n\n /**\n * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n * effect if {@link nobrace} is set.\n *\n * Only has effect on the {@link hasMagic} function.\n */\n magicalBraces?: boolean\n\n /**\n * Add a `/` character to directory matches. Note that this requires\n * additional stat calls in some cases.\n */\n mark?: boolean\n\n /**\n * Perform a basename-only match if the pattern does not contain any slash\n * characters. That is, `*.js` would be treated as equivalent to\n * `**\\/*.js`, matching all js files in all directories.\n */\n matchBase?: boolean\n\n /**\n * Limit the directory traversal to a given depth below the cwd.\n * Note that this does NOT prevent traversal to sibling folders,\n * root patterns, and so on. It only limits the maximum folder depth\n * that the walk will descend, relative to the cwd.\n */\n maxDepth?: number\n\n /**\n * Do not expand `{a,b}` and `{1..3}` brace sets.\n */\n nobrace?: boolean\n\n /**\n * Perform a case-insensitive match. This defaults to `true` on macOS and\n * Windows systems, and `false` on all others.\n *\n * **Note** `nocase` should only be explicitly set when it is\n * known that the filesystem's case sensitivity differs from the\n * platform default. If set `true` on case-sensitive file\n * systems, or `false` on case-insensitive file systems, then the\n * walk may return more or less results than expected.\n */\n nocase?: boolean\n\n /**\n * Do not match directories, only files. (Note: to match\n * _only_ directories, put a `/` at the end of the pattern.)\n */\n nodir?: boolean\n\n /**\n * Do not match \"extglob\" patterns such as `+(a|b)`.\n */\n noext?: boolean\n\n /**\n * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n * `*` instead.)\n *\n * Conflicts with {@link matchBase}\n */\n noglobstar?: boolean\n\n /**\n * Defaults to value of `process.platform` if available, or `'linux'` if\n * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n * behavior.\n */\n platform?: NodeJS.Platform\n\n /**\n * Set to true to call `fs.realpath` on all of the\n * results. In the case of an entry that cannot be resolved, the\n * entry is omitted. This incurs a slight performance penalty, of\n * course, because of the added system calls.\n */\n realpath?: boolean\n\n /**\n *\n * A string path resolved against the `cwd` option, which\n * is used as the starting point for absolute patterns that start\n * with `/`, (but not drive letters or UNC paths on Windows).\n *\n * Note that this _doesn't_ necessarily limit the walk to the\n * `root` directory, and doesn't affect the cwd starting point for\n * non-absolute patterns. A pattern containing `..` will still be\n * able to traverse out of the root directory, if it is not an\n * actual root directory on the filesystem, and any non-absolute\n * patterns will be matched in the `cwd`. For example, the\n * pattern `/../*` with `{root:'/some/path'}` will return all\n * files in `/some`, not all files in `/some/path`. The pattern\n * `*` with `{root:'/some/path'}` will return all the entries in\n * the cwd, not the entries in `/some/path`.\n *\n * To start absolute and non-absolute patterns in the same\n * path, you can use `{root:''}`. However, be aware that on\n * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n * _always_ start in the `x:/` or `//host/share` directory,\n * regardless of the `root` setting.\n */\n root?: string\n\n /**\n * A [PathScurry](http://npm.im/path-scurry) object used\n * to traverse the file system. If the `nocase` option is set\n * explicitly, then any provided `scurry` object must match this\n * setting.\n */\n scurry?: PathScurry\n\n /**\n * Call `lstat()` on all entries, whether required or not to determine\n * if it's a valid match. When used with {@link withFileTypes}, this means\n * that matches will include data such as modified time, permissions, and\n * so on. Note that this will incur a performance cost due to the added\n * system calls.\n */\n stat?: boolean\n\n /**\n * An AbortSignal which will cancel the Glob walk when\n * triggered.\n */\n signal?: AbortSignal\n\n /**\n * Use `\\\\` as a path separator _only_, and\n * _never_ as an escape character. If set, all `\\\\` characters are\n * replaced with `/` in the pattern.\n *\n * Note that this makes it **impossible** to match against paths\n * containing literal glob pattern characters, but allows matching\n * with patterns constructed using `path.join()` and\n * `path.resolve()` on Windows platforms, mimicking the (buggy!)\n * behavior of Glob v7 and before on Windows. Please use with\n * caution, and be mindful of [the caveat below about Windows\n * paths](#windows). (For legacy reasons, this is also set if\n * `allowWindowsEscape` is set to the exact value `false`.)\n */\n windowsPathsNoEscape?: boolean\n\n /**\n * Return [PathScurry](http://npm.im/path-scurry)\n * `Path` objects instead of strings. These are similar to a\n * NodeJS `Dirent` object, but with additional methods and\n * properties.\n *\n * Conflicts with {@link absolute}\n */\n withFileTypes?: boolean\n\n /**\n * An fs implementation to override some or all of the defaults. See\n * http://npm.im/path-scurry for details about what can be overridden.\n */\n fs?: FSOption\n\n /**\n * Just passed along to Minimatch. Note that this makes all pattern\n * matching operations slower and *extremely* noisy.\n */\n debug?: boolean\n\n /**\n * Return `/` delimited paths, even on Windows.\n *\n * On posix systems, this has no effect. But, on Windows, it means that\n * paths will be `/` delimited, and absolute paths will be their full\n * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n * `'//?/C:/foo/bar'`\n */\n posix?: boolean\n\n /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n withFileTypes: true\n // string options not relevant if returning Path objects.\n absolute?: undefined\n mark?: undefined\n posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n withFileTypes?: undefined\n}\n\nexport type Result =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? false\n : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n absolute?: boolean\n cwd: string\n root?: string\n dot: boolean\n dotRelative: boolean\n follow: boolean\n ignore?: string | string[] | IgnoreLike\n magicalBraces: boolean\n mark?: boolean\n matchBase: boolean\n maxDepth: number\n nobrace: boolean\n nocase: boolean\n nodir: boolean\n noext: boolean\n noglobstar: boolean\n pattern: string[]\n platform: NodeJS.Platform\n realpath: boolean\n scurry: PathScurry\n stat: boolean\n signal?: AbortSignal\n windowsPathsNoEscape: boolean\n withFileTypes: FileTypes\n includeChildMatches: boolean\n\n /**\n * The options provided to the constructor.\n */\n opts: Opts\n\n /**\n * An array of parsed immutable {@link Pattern} objects.\n */\n patterns: Pattern[]\n\n /**\n * All options are stored as properties on the `Glob` object.\n *\n * See {@link GlobOptions} for full options descriptions.\n *\n * Note that a previous `Glob` object can be passed as the\n * `GlobOptions` to another `Glob` instantiation to re-use settings\n * and caches with a new pattern.\n *\n * Traversal functions can be called multiple times to run the walk\n * again.\n */\n constructor(pattern: string | string[], opts: Opts) {\n /* c8 ignore start */\n if (!opts) throw new TypeError('glob options required')\n /* c8 ignore stop */\n this.withFileTypes = !!opts.withFileTypes as FileTypes\n this.signal = opts.signal\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.dotRelative = !!opts.dotRelative\n this.nodir = !!opts.nodir\n this.mark = !!opts.mark\n if (!opts.cwd) {\n this.cwd = ''\n } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n opts.cwd = fileURLToPath(opts.cwd)\n }\n this.cwd = opts.cwd || ''\n this.root = opts.root\n this.magicalBraces = !!opts.magicalBraces\n this.nobrace = !!opts.nobrace\n this.noext = !!opts.noext\n this.realpath = !!opts.realpath\n this.absolute = opts.absolute\n this.includeChildMatches = opts.includeChildMatches !== false\n\n this.noglobstar = !!opts.noglobstar\n this.matchBase = !!opts.matchBase\n this.maxDepth =\n typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n this.stat = !!opts.stat\n this.ignore = opts.ignore\n\n if (this.withFileTypes && this.absolute !== undefined) {\n throw new Error('cannot set absolute and withFileTypes:true')\n }\n\n if (typeof pattern === 'string') {\n pattern = [pattern]\n }\n\n this.windowsPathsNoEscape =\n !!opts.windowsPathsNoEscape ||\n (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n false\n\n if (this.windowsPathsNoEscape) {\n pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n }\n\n if (this.matchBase) {\n if (opts.noglobstar) {\n throw new TypeError('base matching requires globstar')\n }\n pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n }\n\n this.pattern = pattern\n\n this.platform = opts.platform || defaultPlatform\n this.opts = { ...opts, platform: this.platform }\n if (opts.scurry) {\n this.scurry = opts.scurry\n if (\n opts.nocase !== undefined &&\n opts.nocase !== opts.scurry.nocase\n ) {\n throw new Error('nocase option contradicts provided scurry option')\n }\n } else {\n const Scurry =\n opts.platform === 'win32' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? PathScurryPosix\n : PathScurry\n this.scurry = new Scurry(this.cwd, {\n nocase: opts.nocase,\n fs: opts.fs,\n })\n }\n this.nocase = this.scurry.nocase\n\n // If you do nocase:true on a case-sensitive file system, then\n // we need to use regexps instead of strings for non-magic\n // path portions, because statting `aBc` won't return results\n // for the file `AbC` for example.\n const nocaseMagicOnly =\n this.platform === 'darwin' || this.platform === 'win32'\n\n const mmo: MinimatchOptions = {\n // default nocase based on platform\n ...opts,\n dot: this.dot,\n matchBase: this.matchBase,\n nobrace: this.nobrace,\n nocase: this.nocase,\n nocaseMagicOnly,\n nocomment: true,\n noext: this.noext,\n nonegate: true,\n optimizationLevel: 2,\n platform: this.platform,\n windowsPathsNoEscape: this.windowsPathsNoEscape,\n debug: !!this.opts.debug,\n }\n\n const mms = this.pattern.map(p => new Minimatch(p, mmo))\n const [matchSet, globParts] = mms.reduce(\n (set: [MatchSet, GlobParts], m) => {\n set[0].push(...m.set)\n set[1].push(...m.globParts)\n return set\n },\n [[], []],\n )\n this.patterns = matchSet.map((set, i) => {\n const g = globParts[i]\n /* c8 ignore start */\n if (!g) throw new Error('invalid pattern object')\n /* c8 ignore stop */\n return new Pattern(set, g, 0, this.platform)\n })\n }\n\n /**\n * Returns a Promise that resolves to the results array.\n */\n async walk(): Promise>\n async walk(): Promise<(string | Path)[]> {\n // Walkers always return array of Path objects, so we just have to\n // coerce them into the right shape. It will have already called\n // realpath() if the option was set to do so, so we know that's cached.\n // start out knowing the cwd, at least\n return [\n ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walk()),\n ]\n }\n\n /**\n * synchronous {@link Glob.walk}\n */\n walkSync(): Results\n walkSync(): (string | Path)[] {\n return [\n ...new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walkSync(),\n ]\n }\n\n /**\n * Stream results asynchronously.\n */\n stream(): Minipass, Result>\n stream(): Minipass {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).stream()\n }\n\n /**\n * Stream results synchronously.\n */\n streamSync(): Minipass, Result>\n streamSync(): Minipass {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).streamSync()\n }\n\n /**\n * Default sync iteration function. Returns a Generator that\n * iterates over the results.\n */\n iterateSync(): Generator, void, void> {\n return this.streamSync()[Symbol.iterator]()\n }\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n /**\n * Default async iteration function. Returns an AsyncGenerator that\n * iterates over the results.\n */\n iterate(): AsyncGenerator, void, void> {\n return this.stream()[Symbol.asyncIterator]()\n }\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n}\n"]}import { GlobOptions } from './glob.js'; /** * Return true if the patterns provided contain any magic glob characters, * given the options provided. * * Brace expansion is not considered "magic" unless the `magicalBraces` option * is set, as brace expansion just turns one string into an array of strings. * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and * `'xby'` both do not contain any magic glob characters, and it's treated the * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` * is in the options, brace expansion _is_ treated as a pattern having magic. */ export declare const hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean; //# sourceMappingURL=has-magic.d.ts.map{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,YACV,MAAM,GAAG,MAAM,EAAE,YACjB,WAAW,KACnB,OAQF,CAAA"}import { Minimatch } from 'minimatch'; /** * Return true if the patterns provided contain any magic glob characters, * given the options provided. * * Brace expansion is not considered "magic" unless the `magicalBraces` option * is set, as brace expansion just turns one string into an array of strings. * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and * `'xby'` both do not contain any magic glob characters, and it's treated the * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` * is in the options, brace expansion _is_ treated as a pattern having magic. */ export const hasMagic = (pattern, options = {}) => { if (!Array.isArray(pattern)) { pattern = [pattern]; } for (const p of pattern) { if (new Minimatch(p, options).hasMagic()) return true; } return false; }; //# sourceMappingURL=has-magic.js.map{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAGrC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,IAAI,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n pattern: string | string[],\n options: GlobOptions = {},\n): boolean => {\n if (!Array.isArray(pattern)) {\n pattern = [pattern]\n }\n for (const p of pattern) {\n if (new Minimatch(p, options).hasMagic()) return true\n }\n return false\n}\n"]}import { Minimatch, MinimatchOptions } from 'minimatch'; import { Path } from 'path-scurry'; import { GlobWalkerOpts } from './walker.js'; export interface IgnoreLike { ignored?: (p: Path) => boolean; childrenIgnored?: (p: Path) => boolean; add?: (ignore: string) => void; } /** * Class used to process ignored patterns */ export declare class Ignore implements IgnoreLike { relative: Minimatch[]; relativeChildren: Minimatch[]; absolute: Minimatch[]; absoluteChildren: Minimatch[]; platform: NodeJS.Platform; mmopts: MinimatchOptions; constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, platform, }: GlobWalkerOpts); add(ign: string): void; ignored(p: Path): boolean; childrenIgnored(p: Path): boolean; } //# sourceMappingURL=ignore.d.ts.map{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;AACH,qBAAa,MAAO,YAAW,UAAU;IACvC,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;gBAGtB,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAA0B,GAC3B,EAAE,cAAc;IAqBnB,GAAG,CAAC,GAAG,EAAE,MAAM;IAyCf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"}// give it a pattern, and it'll be able to tell you if // a given path should be ignored. // Ignoring a path ignores its children if the pattern ends in /** // Ignores are always parsed in dot:true mode import { Minimatch } from 'minimatch'; import { Pattern } from './pattern.js'; const defaultPlatform = (typeof process === 'object' && process && typeof process.platform === 'string') ? process.platform : 'linux'; /** * Class used to process ignored patterns */ export class Ignore { relative; relativeChildren; absolute; absoluteChildren; platform; mmopts; constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) { this.relative = []; this.absolute = []; this.relativeChildren = []; this.absoluteChildren = []; this.platform = platform; this.mmopts = { dot: true, nobrace, nocase, noext, noglobstar, optimizationLevel: 2, platform, nocomment: true, nonegate: true, }; for (const ign of ignored) this.add(ign); } add(ign) { // this is a little weird, but it gives us a clean set of optimized // minimatch matchers, without getting tripped up if one of them // ends in /** inside a brace section, and it's only inefficient at // the start of the walk, not along it. // It'd be nice if the Pattern class just had a .test() method, but // handling globstars is a bit of a pita, and that code already lives // in minimatch anyway. // Another way would be if maybe Minimatch could take its set/globParts // as an option, and then we could at least just use Pattern to test // for absolute-ness. // Yet another way, Minimatch could take an array of glob strings, and // a cwd option, and do the right thing. const mm = new Minimatch(ign, this.mmopts); for (let i = 0; i < mm.set.length; i++) { const parsed = mm.set[i]; const globParts = mm.globParts[i]; /* c8 ignore start */ if (!parsed || !globParts) { throw new Error('invalid pattern object'); } // strip off leading ./ portions // https://github.com/isaacs/node-glob/issues/570 while (parsed[0] === '.' && globParts[0] === '.') { parsed.shift(); globParts.shift(); } /* c8 ignore stop */ const p = new Pattern(parsed, globParts, 0, this.platform); const m = new Minimatch(p.globString(), this.mmopts); const children = globParts[globParts.length - 1] === '**'; const absolute = p.isAbsolute(); if (absolute) this.absolute.push(m); else this.relative.push(m); if (children) { if (absolute) this.absoluteChildren.push(m); else this.relativeChildren.push(m); } } } ignored(p) { const fullpath = p.fullpath(); const fullpaths = `${fullpath}/`; const relative = p.relative() || '.'; const relatives = `${relative}/`; for (const m of this.relative) { if (m.match(relative) || m.match(relatives)) return true; } for (const m of this.absolute) { if (m.match(fullpath) || m.match(fullpaths)) return true; } return false; } childrenIgnored(p) { const fullpath = p.fullpath() + '/'; const relative = (p.relative() || '.') + '/'; for (const m of this.relativeChildren) { if (m.match(relative)) return true; } for (const m of this.absoluteChildren) { if (m.match(fullpath)) return true; } return false; } } //# sourceMappingURL=ignore.js.map{"version":3,"file":"ignore.js","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,kCAAkC;AAClC,kEAAkE;AAClE,6CAA6C;AAE7C,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AAEvD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAStC,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAEX;;GAEG;AACH,MAAM,OAAO,MAAM;IACjB,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAiB;IACzB,MAAM,CAAkB;IAExB,YACE,OAAiB,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAAQ,GAAG,eAAe,GACX;QAEjB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,MAAM,GAAG;YACZ,GAAG,EAAE,IAAI;YACT,OAAO;YACP,MAAM;YACN,KAAK;YACL,UAAU;YACV,iBAAiB,EAAE,CAAC;YACpB,QAAQ;YACR,SAAS,EAAE,IAAI;YACf,QAAQ,EAAE,IAAI;SACf,CAAA;QACD,KAAK,MAAM,GAAG,IAAI,OAAO;YAAE,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IAC1C,CAAC;IAED,GAAG,CAAC,GAAW;QACb,mEAAmE;QACnE,gEAAgE;QAChE,mEAAmE;QACnE,uCAAuC;QACvC,mEAAmE;QACnE,qEAAqE;QACrE,uBAAuB;QACvB,uEAAuE;QACvE,oEAAoE;QACpE,qBAAqB;QACrB,sEAAsE;QACtE,wCAAwC;QACxC,MAAM,EAAE,GAAG,IAAI,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QAC1C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACvC,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;YACxB,MAAM,SAAS,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;YACjC,qBAAqB;YACrB,IAAI,CAAC,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;gBAC1B,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;YAC3C,CAAC;YACD,gCAAgC;YAChC,iDAAiD;YACjD,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,SAAS,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;gBACjD,MAAM,CAAC,KAAK,EAAE,CAAA;gBACd,SAAS,CAAC,KAAK,EAAE,CAAA;YACnB,CAAC;YACD,oBAAoB;YACpB,MAAM,CAAC,GAAG,IAAI,OAAO,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;YAC1D,MAAM,CAAC,GAAG,IAAI,SAAS,CAAC,CAAC,CAAC,UAAU,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;YACpD,MAAM,QAAQ,GAAG,SAAS,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,IAAI,CAAA;YACzD,MAAM,QAAQ,GAAG,CAAC,CAAC,UAAU,EAAE,CAAA;YAC/B,IAAI,QAAQ;gBAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;;gBAC9B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;YAC1B,IAAI,QAAQ,EAAE,CAAC;gBACb,IAAI,QAAQ;oBAAE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;;oBACtC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;YACpC,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,CAAC,CAAO;QACb,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAA;QAC7B,MAAM,SAAS,GAAG,GAAG,QAAQ,GAAG,CAAA;QAChC,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAA;QACpC,MAAM,SAAS,GAAG,GAAG,QAAQ,GAAG,CAAA;QAChC,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,eAAe,CAAC,CAAO;QACrB,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,GAAG,CAAA;QACnC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,GAAG,GAAG,CAAA;QAC5C,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF","sourcesContent":["// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n ignored?: (p: Path) => boolean\n childrenIgnored?: (p: Path) => boolean\n add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n relative: Minimatch[]\n relativeChildren: Minimatch[]\n absolute: Minimatch[]\n absoluteChildren: Minimatch[]\n platform: NodeJS.Platform\n mmopts: MinimatchOptions\n\n constructor(\n ignored: string[],\n {\n nobrace,\n nocase,\n noext,\n noglobstar,\n platform = defaultPlatform,\n }: GlobWalkerOpts,\n ) {\n this.relative = []\n this.absolute = []\n this.relativeChildren = []\n this.absoluteChildren = []\n this.platform = platform\n this.mmopts = {\n dot: true,\n nobrace,\n nocase,\n noext,\n noglobstar,\n optimizationLevel: 2,\n platform,\n nocomment: true,\n nonegate: true,\n }\n for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\n // this is a little weird, but it gives us a clean set of optimized\n // minimatch matchers, without getting tripped up if one of them\n // ends in /** inside a brace section, and it's only inefficient at\n // the start of the walk, not along it.\n // It'd be nice if the Pattern class just had a .test() method, but\n // handling globstars is a bit of a pita, and that code already lives\n // in minimatch anyway.\n // Another way would be if maybe Minimatch could take its set/globParts\n // as an option, and then we could at least just use Pattern to test\n // for absolute-ness.\n // Yet another way, Minimatch could take an array of glob strings, and\n // a cwd option, and do the right thing.\n const mm = new Minimatch(ign, this.mmopts)\n for (let i = 0; i < mm.set.length; i++) {\n const parsed = mm.set[i]\n const globParts = mm.globParts[i]\n /* c8 ignore start */\n if (!parsed || !globParts) {\n throw new Error('invalid pattern object')\n }\n // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.mmopts)\n const children = globParts[globParts.length - 1] === '**'\n const absolute = p.isAbsolute()\n if (absolute) this.absolute.push(m)\n else this.relative.push(m)\n if (children) {\n if (absolute) this.absoluteChildren.push(m)\n else this.relativeChildren.push(m)\n }\n }\n }\n\n ignored(p: Path): boolean {\n const fullpath = p.fullpath()\n const fullpaths = `${fullpath}/`\n const relative = p.relative() || '.'\n const relatives = `${relative}/`\n for (const m of this.relative) {\n if (m.match(relative) || m.match(relatives)) return true\n }\n for (const m of this.absolute) {\n if (m.match(fullpath) || m.match(fullpaths)) return true\n }\n return false\n }\n\n childrenIgnored(p: Path): boolean {\n const fullpath = p.fullpath() + '/'\n const relative = (p.relative() || '.') + '/'\n for (const m of this.relativeChildren) {\n if (m.match(relative)) return true\n }\n for (const m of this.absoluteChildren) {\n if (m.match(fullpath)) return true\n }\n return false\n }\n}\n"]}import { Minipass } from 'minipass'; import { Path } from 'path-scurry'; import type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset } from './glob.js'; import { Glob } from './glob.js'; export { escape, unescape } from 'minimatch'; export type { FSOption, Path, WalkOptions, WalkOptionsWithFileTypesTrue, WalkOptionsWithFileTypesUnset, } from 'path-scurry'; export { Glob } from './glob.js'; export type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset, } from './glob.js'; export { hasMagic } from './has-magic.js'; export { Ignore } from './ignore.js'; export type { IgnoreLike } from './ignore.js'; export type { MatchStream } from './walker.js'; /** * Syncronous form of {@link globStream}. Will read all the matches as fast as * you consume them, even all in a single tick if you consume them immediately, * but will still respond to backpressure if they're not consumed immediately. */ export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass; export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass; export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesUnset): Minipass; export declare function globStreamSync(pattern: string | string[], options: GlobOptions): Minipass | Minipass; /** * Return a stream that emits all the strings or `Path` objects and * then emits `end` when completed. */ export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass; export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass; export declare function globStream(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Minipass; export declare function globStream(pattern: string | string[], options: GlobOptions): Minipass | Minipass; /** * Synchronous form of {@link glob} */ export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): string[]; export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Path[]; export declare function globSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): string[]; export declare function globSync(pattern: string | string[], options: GlobOptions): Path[] | string[]; /** * Perform an asynchronous glob search for the pattern(s) specified. Returns * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for * full option descriptions. */ declare function glob_(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Promise; declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Promise; declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Promise; declare function glob_(pattern: string | string[], options: GlobOptions): Promise; /** * Return a sync iterator for walking glob pattern matches. */ export declare function globIterateSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Generator; export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Generator; export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Generator; export declare function globIterateSync(pattern: string | string[], options: GlobOptions): Generator | Generator; /** * Return an async iterator for walking glob pattern matches. */ export declare function globIterate(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): AsyncGenerator; export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): AsyncGenerator; export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): AsyncGenerator; export declare function globIterate(pattern: string | string[], options: GlobOptions): AsyncGenerator | AsyncGenerator; export declare const streamSync: typeof globStreamSync; export declare const stream: typeof globStream & { sync: typeof globStreamSync; }; export declare const iterateSync: typeof globIterateSync; export declare const iterate: typeof globIterate & { sync: typeof globIterateSync; }; export declare const sync: typeof globSync & { stream: typeof globStreamSync; iterate: typeof globIterateSync; }; export declare const glob: typeof glob_ & { glob: typeof glob_; globSync: typeof globSync; sync: typeof globSync & { stream: typeof globStreamSync; iterate: typeof globIterateSync; }; globStream: typeof globStream; stream: typeof globStream & { sync: typeof globStreamSync; }; globStreamSync: typeof globStreamSync; streamSync: typeof globStreamSync; globIterate: typeof globIterate; iterate: typeof globIterate & { sync: typeof globIterateSync; }; globIterateSync: typeof globIterateSync; iterateSync: typeof globIterateSync; Glob: typeof Glob; hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean; escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; }; //# sourceMappingURL=index.d.ts.map{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,KAAK,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,EAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAGhC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC5C,YAAY,EACV,QAAQ,EACR,IAAI,EACJ,WAAW,EACX,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,YAAY,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAC7C,YAAY,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;AACvB,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC3B,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC3B,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAQlD;;;GAGG;AACH,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC3B,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;AACvB,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC3B,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAQlD;;GAEG;AACH,wBAAgB,QAAQ,CACtB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,MAAM,EAAE,CAAA;AACX,wBAAgB,QAAQ,CACtB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,IAAI,EAAE,CAAA;AACT,wBAAgB,QAAQ,CACtB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,MAAM,EAAE,CAAA;AACX,wBAAgB,QAAQ,CACtB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,IAAI,EAAE,GAAG,MAAM,EAAE,CAAA;AAQpB;;;;;GAKG;AACH,iBAAe,KAAK,CAClB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;AACpB,iBAAe,KAAK,CAClB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;AAClB,iBAAe,KAAK,CAClB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;AACpB,iBAAe,KAAK,CAClB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,OAAO,CAAC,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,CAAA;AAQ7B;;GAEG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AAChC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AAC9B,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AAChC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AAQ9D;;GAEG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,6BAA6B,GAAG,SAAS,GAClD,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACrC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACnC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACrC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AASxE,eAAO,MAAM,UAAU,uBAAiB,CAAA;AACxC,eAAO,MAAM,MAAM;;CAAsD,CAAA;AACzE,eAAO,MAAM,WAAW,wBAAkB,CAAA;AAC1C,eAAO,MAAM,OAAO;;CAElB,CAAA;AACF,eAAO,MAAM,IAAI;;;CAGf,CAAA;AAEF,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;CAgBf,CAAA"}import { escape, unescape } from 'minimatch'; import { Glob } from './glob.js'; import { hasMagic } from './has-magic.js'; export { escape, unescape } from 'minimatch'; export { Glob } from './glob.js'; export { hasMagic } from './has-magic.js'; export { Ignore } from './ignore.js'; export function globStreamSync(pattern, options = {}) { return new Glob(pattern, options).streamSync(); } export function globStream(pattern, options = {}) { return new Glob(pattern, options).stream(); } export function globSync(pattern, options = {}) { return new Glob(pattern, options).walkSync(); } async function glob_(pattern, options = {}) { return new Glob(pattern, options).walk(); } export function globIterateSync(pattern, options = {}) { return new Glob(pattern, options).iterateSync(); } export function globIterate(pattern, options = {}) { return new Glob(pattern, options).iterate(); } // aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc export const streamSync = globStreamSync; export const stream = Object.assign(globStream, { sync: globStreamSync }); export const iterateSync = globIterateSync; export const iterate = Object.assign(globIterate, { sync: globIterateSync, }); export const sync = Object.assign(globSync, { stream: globStreamSync, iterate: globIterateSync, }); export const glob = Object.assign(glob_, { glob: glob_, globSync, sync, globStream, stream, globStreamSync, streamSync, globIterate, iterate, globIterateSync, iterateSync, Glob, hasMagic, escape, unescape, }); glob.glob = glob; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAS5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEzC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAQ5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAOhC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAyBpC,MAAM,UAAU,cAAc,CAC5B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAA;AAChD,CAAC;AAsBD,MAAM,UAAU,UAAU,CACxB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,EAAE,CAAA;AAC5C,CAAC;AAqBD,MAAM,UAAU,QAAQ,CACtB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAA;AAC9C,CAAC;AAwBD,KAAK,UAAU,KAAK,CAClB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAA;AAC1C,CAAC;AAqBD,MAAM,UAAU,eAAe,CAC7B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAA;AACjD,CAAC;AAqBD,MAAM,UAAU,WAAW,CACzB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,OAAO,EAAE,CAAA;AAC7C,CAAC;AAED,iEAAiE;AACjE,MAAM,CAAC,MAAM,UAAU,GAAG,cAAc,CAAA;AACxC,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAA;AACzE,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAA;AAC1C,MAAM,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;IAChD,IAAI,EAAE,eAAe;CACtB,CAAC,CAAA;AACF,MAAM,CAAC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC1C,MAAM,EAAE,cAAc;IACtB,OAAO,EAAE,eAAe;CACzB,CAAC,CAAA;AAEF,MAAM,CAAC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,KAAK;IACX,QAAQ;IACR,IAAI;IACJ,UAAU;IACV,MAAM;IACN,cAAc;IACd,UAAU;IACV,WAAW;IACX,OAAO;IACP,eAAe;IACf,WAAW;IACX,IAAI;IACJ,QAAQ;IACR,MAAM;IACN,QAAQ;CACT,CAAC,CAAA;AACF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA","sourcesContent":["import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n stream: globStreamSync,\n iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n glob: glob_,\n globSync,\n sync,\n globStream,\n stream,\n globStreamSync,\n streamSync,\n globIterate,\n iterate,\n globIterateSync,\n iterateSync,\n Glob,\n hasMagic,\n escape,\n unescape,\n})\nglob.glob = glob\n"]}{ "type": "module" } import { GLOBSTAR } from 'minimatch'; export type MMPattern = string | RegExp | typeof GLOBSTAR; export type PatternList = [p: MMPattern, ...rest: MMPattern[]]; export type UNCPatternList = [ p0: '', p1: '', p2: string, p3: string, ...rest: MMPattern[] ]; export type DrivePatternList = [p0: string, ...rest: MMPattern[]]; export type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]; export type GlobList = [p: string, ...rest: string[]]; /** * An immutable-ish view on an array of glob parts and their parsed * results */ export declare class Pattern { #private; readonly length: number; constructor(patternList: MMPattern[], globList: string[], index: number, platform: NodeJS.Platform); /** * The first entry in the parsed list of patterns */ pattern(): MMPattern; /** * true of if pattern() returns a string */ isString(): boolean; /** * true of if pattern() returns GLOBSTAR */ isGlobstar(): boolean; /** * true if pattern() returns a regexp */ isRegExp(): boolean; /** * The /-joined set of glob parts that make up this pattern */ globString(): string; /** * true if there are more pattern parts after this one */ hasMore(): boolean; /** * The rest of the pattern after this part, or null if this is the end */ rest(): Pattern | null; /** * true if the pattern represents a //unc/path/ on windows */ isUNC(): boolean; /** * True if the pattern starts with a drive letter on Windows */ isDrive(): boolean; /** * True if the pattern is rooted on an absolute path */ isAbsolute(): boolean; /** * consume the root of the pattern, and return it */ root(): string; /** * Check to see if the current globstar pattern is allowed to follow * a symbolic link. */ checkFollowGlobstar(): boolean; /** * Mark that the current globstar pattern is following a symbolic link */ markFollowGlobstar(): boolean; } //# sourceMappingURL=pattern.d.ts.map{"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,QAAQ,CAAA;AAGzD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAC9D,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,MAAM;IACV,EAAE,EAAE,MAAM;IACV,GAAG,IAAI,EAAE,SAAS,EAAE;CACrB,CAAA;AACD,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AACjE,MAAM,MAAM,mBAAmB,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAChE,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;AAMrD;;;GAGG;AACH,qBAAa,OAAO;;IAIlB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;gBAUrB,WAAW,EAAE,SAAS,EAAE,EACxB,QAAQ,EAAE,MAAM,EAAE,EAClB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,CAAC,QAAQ;IA6D3B;;OAEG;IACH,OAAO,IAAI,SAAS;IAIpB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAGnB;;OAEG;IACH,UAAU,IAAI,OAAO;IAGrB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAInB;;OAEG;IACH,UAAU,IAAI,MAAM;IAUpB;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACH,IAAI,IAAI,OAAO,GAAG,IAAI;IAetB;;OAEG;IACH,KAAK,IAAI,OAAO;IAoBhB;;OAEG;IACH,OAAO,IAAI,OAAO;IAelB;;OAEG;IACH,UAAU,IAAI,OAAO;IAUrB;;OAEG;IACH,IAAI,IAAI,MAAM;IASd;;;OAGG;IACH,mBAAmB,IAAI,OAAO;IAQ9B;;OAEG;IACH,kBAAkB,IAAI,OAAO;CAM9B"}// this is just a very light wrapper around 2 arrays with an offset index import { GLOBSTAR } from 'minimatch'; const isPatternList = (pl) => pl.length >= 1; const isGlobList = (gl) => gl.length >= 1; /** * An immutable-ish view on an array of glob parts and their parsed * results */ export class Pattern { #patternList; #globList; #index; length; #platform; #rest; #globString; #isDrive; #isUNC; #isAbsolute; #followGlobstar = true; constructor(patternList, globList, index, platform) { if (!isPatternList(patternList)) { throw new TypeError('empty pattern list'); } if (!isGlobList(globList)) { throw new TypeError('empty glob list'); } if (globList.length !== patternList.length) { throw new TypeError('mismatched pattern list and glob list lengths'); } this.length = patternList.length; if (index < 0 || index >= this.length) { throw new TypeError('index out of range'); } this.#patternList = patternList; this.#globList = globList; this.#index = index; this.#platform = platform; // normalize root entries of absolute patterns on initial creation. if (this.#index === 0) { // c: => ['c:/'] // C:/ => ['C:/'] // C:/x => ['C:/', 'x'] // //host/share => ['//host/share/'] // //host/share/ => ['//host/share/'] // //host/share/x => ['//host/share/', 'x'] // /etc => ['/', 'etc'] // / => ['/'] if (this.isUNC()) { // '' / '' / 'host' / 'share' const [p0, p1, p2, p3, ...prest] = this.#patternList; const [g0, g1, g2, g3, ...grest] = this.#globList; if (prest[0] === '') { // ends in / prest.shift(); grest.shift(); } const p = [p0, p1, p2, p3, ''].join('/'); const g = [g0, g1, g2, g3, ''].join('/'); this.#patternList = [p, ...prest]; this.#globList = [g, ...grest]; this.length = this.#patternList.length; } else if (this.isDrive() || this.isAbsolute()) { const [p1, ...prest] = this.#patternList; const [g1, ...grest] = this.#globList; if (prest[0] === '') { // ends in / prest.shift(); grest.shift(); } const p = p1 + '/'; const g = g1 + '/'; this.#patternList = [p, ...prest]; this.#globList = [g, ...grest]; this.length = this.#patternList.length; } } } /** * The first entry in the parsed list of patterns */ pattern() { return this.#patternList[this.#index]; } /** * true of if pattern() returns a string */ isString() { return typeof this.#patternList[this.#index] === 'string'; } /** * true of if pattern() returns GLOBSTAR */ isGlobstar() { return this.#patternList[this.#index] === GLOBSTAR; } /** * true if pattern() returns a regexp */ isRegExp() { return this.#patternList[this.#index] instanceof RegExp; } /** * The /-joined set of glob parts that make up this pattern */ globString() { return (this.#globString = this.#globString || (this.#index === 0 ? this.isAbsolute() ? this.#globList[0] + this.#globList.slice(1).join('/') : this.#globList.join('/') : this.#globList.slice(this.#index).join('/'))); } /** * true if there are more pattern parts after this one */ hasMore() { return this.length > this.#index + 1; } /** * The rest of the pattern after this part, or null if this is the end */ rest() { if (this.#rest !== undefined) return this.#rest; if (!this.hasMore()) return (this.#rest = null); this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform); this.#rest.#isAbsolute = this.#isAbsolute; this.#rest.#isUNC = this.#isUNC; this.#rest.#isDrive = this.#isDrive; return this.#rest; } /** * true if the pattern represents a //unc/path/ on windows */ isUNC() { const pl = this.#patternList; return this.#isUNC !== undefined ? this.#isUNC : (this.#isUNC = this.#platform === 'win32' && this.#index === 0 && pl[0] === '' && pl[1] === '' && typeof pl[2] === 'string' && !!pl[2] && typeof pl[3] === 'string' && !!pl[3]); } // pattern like C:/... // split = ['C:', ...] // XXX: would be nice to handle patterns like `c:*` to test the cwd // in c: for *, but I don't know of a way to even figure out what that // cwd is without actually chdir'ing into it? /** * True if the pattern starts with a drive letter on Windows */ isDrive() { const pl = this.#patternList; return this.#isDrive !== undefined ? this.#isDrive : (this.#isDrive = this.#platform === 'win32' && this.#index === 0 && this.length > 1 && typeof pl[0] === 'string' && /^[a-z]:$/i.test(pl[0])); } // pattern = '/' or '/...' or '/x/...' // split = ['', ''] or ['', ...] or ['', 'x', ...] // Drive and UNC both considered absolute on windows /** * True if the pattern is rooted on an absolute path */ isAbsolute() { const pl = this.#patternList; return this.#isAbsolute !== undefined ? this.#isAbsolute : (this.#isAbsolute = (pl[0] === '' && pl.length > 1) || this.isDrive() || this.isUNC()); } /** * consume the root of the pattern, and return it */ root() { const p = this.#patternList[0]; return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ? p : ''; } /** * Check to see if the current globstar pattern is allowed to follow * a symbolic link. */ checkFollowGlobstar() { return !(this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar); } /** * Mark that the current globstar pattern is following a symbolic link */ markFollowGlobstar() { if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar) return false; this.#followGlobstar = false; return true; } } //# sourceMappingURL=pattern.js.map{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAgBpC,MAAM,aAAa,GAAG,CAAC,EAAe,EAAqB,EAAE,CAC3D,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAChB,MAAM,UAAU,GAAG,CAAC,EAAY,EAAkB,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAEnE;;;GAGG;AACH,MAAM,OAAO,OAAO;IACT,YAAY,CAAa;IACzB,SAAS,CAAU;IACnB,MAAM,CAAQ;IACd,MAAM,CAAQ;IACd,SAAS,CAAiB;IACnC,KAAK,CAAiB;IACtB,WAAW,CAAS;IACpB,QAAQ,CAAU;IAClB,MAAM,CAAU;IAChB,WAAW,CAAU;IACrB,eAAe,GAAY,IAAI,CAAA;IAE/B,YACE,WAAwB,EACxB,QAAkB,EAClB,KAAa,EACb,QAAyB;QAEzB,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,SAAS,CAAC,oBAAoB,CAAC,CAAA;QAC3C,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;QACxC,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,CAAC,MAAM,EAAE,CAAC;YAC3C,MAAM,IAAI,SAAS,CAAC,+CAA+C,CAAC,CAAA;QACtE,CAAC;QACD,IAAI,CAAC,MAAM,GAAG,WAAW,CAAC,MAAM,CAAA;QAChC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YACtC,MAAM,IAAI,SAAS,CAAC,oBAAoB,CAAC,CAAA;QAC3C,CAAC;QACD,IAAI,CAAC,YAAY,GAAG,WAAW,CAAA;QAC/B,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QACzB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;QACnB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QAEzB,mEAAmE;QACnE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,gBAAgB;YAChB,iBAAiB;YACjB,uBAAuB;YACvB,oCAAoC;YACpC,qCAAqC;YACrC,2CAA2C;YAC3C,uBAAuB;YACvB,aAAa;YACb,IAAI,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;gBACjB,6BAA6B;gBAC7B,MAAM,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,YAAY,CAAA;gBACpD,MAAM,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAA;gBACjD,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;oBACpB,YAAY;oBACZ,KAAK,CAAC,KAAK,EAAE,CAAA;oBACb,KAAK,CAAC,KAAK,EAAE,CAAA;gBACf,CAAC;gBACD,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACxC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACxC,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAA;gBACjC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAA;gBAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAA;YACxC,CAAC;iBAAM,IAAI,IAAI,CAAC,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,EAAE,EAAE,CAAC;gBAC/C,MAAM,CAAC,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,YAAY,CAAA;gBACxC,MAAM,CAAC,EAAE,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAA;gBACrC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;oBACpB,YAAY;oBACZ,KAAK,CAAC,KAAK,EAAE,CAAA;oBACb,KAAK,CAAC,KAAK,EAAE,CAAA;gBACf,CAAC;gBACD,MAAM,CAAC,GAAI,EAAa,GAAG,GAAG,CAAA;gBAC9B,MAAM,CAAC,GAAG,EAAE,GAAG,GAAG,CAAA;gBAClB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAA;gBACjC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAA;gBAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAA;YACxC,CAAC;QACH,CAAC;IACH,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAc,CAAA;IACpD,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,OAAO,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,QAAQ,CAAA;IAC3D,CAAC;IACD;;OAEG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,QAAQ,CAAA;IACpD,CAAC;IACD;;OAEG;IACH,QAAQ;QACN,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,MAAM,CAAA;IACzD,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,CAAC,IAAI,CAAC,WAAW;YACtB,IAAI,CAAC,WAAW;gBAChB,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;oBAClB,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;wBACjB,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;wBACvD,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC;oBAC5B,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;IACnD,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAA;IACtC,CAAC;IAED;;OAEG;IACH,IAAI;QACF,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO,IAAI,CAAC,KAAK,CAAA;QAC/C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YAAE,OAAO,CAAC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,CAAA;QAC/C,IAAI,CAAC,KAAK,GAAG,IAAI,OAAO,CACtB,IAAI,CAAC,YAAY,EACjB,IAAI,CAAC,SAAS,EACd,IAAI,CAAC,MAAM,GAAG,CAAC,EACf,IAAI,CAAC,SAAS,CACf,CAAA;QACD,IAAI,CAAC,KAAK,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAA;QACzC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QAC/B,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAA;QACnC,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAA;QAC5B,OAAO,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC;YAC9B,IAAI,CAAC,MAAM;YACb,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM;gBACV,IAAI,CAAC,SAAS,KAAK,OAAO;oBAC1B,IAAI,CAAC,MAAM,KAAK,CAAC;oBACjB,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE;oBACZ,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE;oBACZ,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,QAAQ;oBACzB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;oBACP,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,QAAQ;oBACzB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IAChB,CAAC;IAED,sBAAsB;IACtB,sBAAsB;IACtB,mEAAmE;IACnE,sEAAsE;IACtE,6CAA6C;IAC7C;;OAEG;IACH,OAAO;QACL,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAA;QAC5B,OAAO,IAAI,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC;YAChC,IAAI,CAAC,QAAQ;YACf,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ;gBACZ,IAAI,CAAC,SAAS,KAAK,OAAO;oBAC1B,IAAI,CAAC,MAAM,KAAK,CAAC;oBACjB,IAAI,CAAC,MAAM,GAAG,CAAC;oBACf,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,QAAQ;oBACzB,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAChC,CAAC;IAED,sCAAsC;IACtC,kDAAkD;IAClD,oDAAoD;IACpD;;OAEG;IACH,UAAU;QACR,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAA;QAC5B,OAAO,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC;YACnC,IAAI,CAAC,WAAW;YAClB,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW;gBACf,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;oBAC/B,IAAI,CAAC,OAAO,EAAE;oBACd,IAAI,CAAC,KAAK,EAAE,CAAC,CAAA;IACrB,CAAC;IAED;;OAEG;IACH,IAAI;QACF,MAAM,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;QAC9B,OAAO,CACH,OAAO,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,CAChE,CAAC,CAAC;YACD,CAAC;YACH,CAAC,CAAC,EAAE,CAAA;IACR,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,CAAC,CACN,IAAI,CAAC,MAAM,KAAK,CAAC;YACjB,CAAC,IAAI,CAAC,UAAU,EAAE;YAClB,CAAC,IAAI,CAAC,eAAe,CACtB,CAAA;IACH,CAAC;IAED;;OAEG;IACH,kBAAkB;QAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;YAClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF","sourcesContent":["// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n p0: '',\n p1: '',\n p2: string,\n p3: string,\n ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n readonly #patternList: PatternList\n readonly #globList: GlobList\n readonly #index: number\n readonly length: number\n readonly #platform: NodeJS.Platform\n #rest?: Pattern | null\n #globString?: string\n #isDrive?: boolean\n #isUNC?: boolean\n #isAbsolute?: boolean\n #followGlobstar: boolean = true\n\n constructor(\n patternList: MMPattern[],\n globList: string[],\n index: number,\n platform: NodeJS.Platform,\n ) {\n if (!isPatternList(patternList)) {\n throw new TypeError('empty pattern list')\n }\n if (!isGlobList(globList)) {\n throw new TypeError('empty glob list')\n }\n if (globList.length !== patternList.length) {\n throw new TypeError('mismatched pattern list and glob list lengths')\n }\n this.length = patternList.length\n if (index < 0 || index >= this.length) {\n throw new TypeError('index out of range')\n }\n this.#patternList = patternList\n this.#globList = globList\n this.#index = index\n this.#platform = platform\n\n // normalize root entries of absolute patterns on initial creation.\n if (this.#index === 0) {\n // c: => ['c:/']\n // C:/ => ['C:/']\n // C:/x => ['C:/', 'x']\n // //host/share => ['//host/share/']\n // //host/share/ => ['//host/share/']\n // //host/share/x => ['//host/share/', 'x']\n // /etc => ['/', 'etc']\n // / => ['/']\n if (this.isUNC()) {\n // '' / '' / 'host' / 'share'\n const [p0, p1, p2, p3, ...prest] = this.#patternList\n const [g0, g1, g2, g3, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = [p0, p1, p2, p3, ''].join('/')\n const g = [g0, g1, g2, g3, ''].join('/')\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n } else if (this.isDrive() || this.isAbsolute()) {\n const [p1, ...prest] = this.#patternList\n const [g1, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = (p1 as string) + '/'\n const g = g1 + '/'\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n }\n }\n }\n\n /**\n * The first entry in the parsed list of patterns\n */\n pattern(): MMPattern {\n return this.#patternList[this.#index] as MMPattern\n }\n\n /**\n * true of if pattern() returns a string\n */\n isString(): boolean {\n return typeof this.#patternList[this.#index] === 'string'\n }\n /**\n * true of if pattern() returns GLOBSTAR\n */\n isGlobstar(): boolean {\n return this.#patternList[this.#index] === GLOBSTAR\n }\n /**\n * true if pattern() returns a regexp\n */\n isRegExp(): boolean {\n return this.#patternList[this.#index] instanceof RegExp\n }\n\n /**\n * The /-joined set of glob parts that make up this pattern\n */\n globString(): string {\n return (this.#globString =\n this.#globString ||\n (this.#index === 0 ?\n this.isAbsolute() ?\n this.#globList[0] + this.#globList.slice(1).join('/')\n : this.#globList.join('/')\n : this.#globList.slice(this.#index).join('/')))\n }\n\n /**\n * true if there are more pattern parts after this one\n */\n hasMore(): boolean {\n return this.length > this.#index + 1\n }\n\n /**\n * The rest of the pattern after this part, or null if this is the end\n */\n rest(): Pattern | null {\n if (this.#rest !== undefined) return this.#rest\n if (!this.hasMore()) return (this.#rest = null)\n this.#rest = new Pattern(\n this.#patternList,\n this.#globList,\n this.#index + 1,\n this.#platform,\n )\n this.#rest.#isAbsolute = this.#isAbsolute\n this.#rest.#isUNC = this.#isUNC\n this.#rest.#isDrive = this.#isDrive\n return this.#rest\n }\n\n /**\n * true if the pattern represents a //unc/path/ on windows\n */\n isUNC(): boolean {\n const pl = this.#patternList\n return this.#isUNC !== undefined ?\n this.#isUNC\n : (this.#isUNC =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n pl[0] === '' &&\n pl[1] === '' &&\n typeof pl[2] === 'string' &&\n !!pl[2] &&\n typeof pl[3] === 'string' &&\n !!pl[3])\n }\n\n // pattern like C:/...\n // split = ['C:', ...]\n // XXX: would be nice to handle patterns like `c:*` to test the cwd\n // in c: for *, but I don't know of a way to even figure out what that\n // cwd is without actually chdir'ing into it?\n /**\n * True if the pattern starts with a drive letter on Windows\n */\n isDrive(): boolean {\n const pl = this.#patternList\n return this.#isDrive !== undefined ?\n this.#isDrive\n : (this.#isDrive =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n this.length > 1 &&\n typeof pl[0] === 'string' &&\n /^[a-z]:$/i.test(pl[0]))\n }\n\n // pattern = '/' or '/...' or '/x/...'\n // split = ['', ''] or ['', ...] or ['', 'x', ...]\n // Drive and UNC both considered absolute on windows\n /**\n * True if the pattern is rooted on an absolute path\n */\n isAbsolute(): boolean {\n const pl = this.#patternList\n return this.#isAbsolute !== undefined ?\n this.#isAbsolute\n : (this.#isAbsolute =\n (pl[0] === '' && pl.length > 1) ||\n this.isDrive() ||\n this.isUNC())\n }\n\n /**\n * consume the root of the pattern, and return it\n */\n root(): string {\n const p = this.#patternList[0]\n return (\n typeof p === 'string' && this.isAbsolute() && this.#index === 0\n ) ?\n p\n : ''\n }\n\n /**\n * Check to see if the current globstar pattern is allowed to follow\n * a symbolic link.\n */\n checkFollowGlobstar(): boolean {\n return !(\n this.#index === 0 ||\n !this.isGlobstar() ||\n !this.#followGlobstar\n )\n }\n\n /**\n * Mark that the current globstar pattern is following a symbolic link\n */\n markFollowGlobstar(): boolean {\n if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n return false\n this.#followGlobstar = false\n return true\n }\n}\n"]}import { MMRegExp } from 'minimatch'; import { Path } from 'path-scurry'; import { Pattern } from './pattern.js'; import { GlobWalkerOpts } from './walker.js'; /** * A cache of which patterns have been processed for a given Path */ export declare class HasWalkedCache { store: Map>; constructor(store?: Map>); copy(): HasWalkedCache; hasWalked(target: Path, pattern: Pattern): boolean | undefined; storeWalked(target: Path, pattern: Pattern): void; } /** * A record of which paths have been matched in a given walk step, * and whether they only are considered a match if they are a directory, * and whether their absolute or relative path should be returned. */ export declare class MatchRecord { store: Map; add(target: Path, absolute: boolean, ifDir: boolean): void; entries(): [Path, boolean, boolean][]; } /** * A collection of patterns that must be processed in a subsequent step * for a given path. */ export declare class SubWalks { store: Map; add(target: Path, pattern: Pattern): void; get(target: Path): Pattern[]; entries(): [Path, Pattern[]][]; keys(): Path[]; } /** * The class that processes patterns for a given path. * * Handles child entry filtering, and determining whether a path's * directory contents must be read. */ export declare class Processor { hasWalkedCache: HasWalkedCache; matches: MatchRecord; subwalks: SubWalks; patterns?: Pattern[]; follow: boolean; dot: boolean; opts: GlobWalkerOpts; constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache); processPatterns(target: Path, patterns: Pattern[]): this; subwalkTargets(): Path[]; child(): Processor; filterEntries(parent: Path, entries: Path[]): Processor; testGlobstar(e: Path, pattern: Pattern, rest: Pattern | null, absolute: boolean): void; testRegExp(e: Path, p: MMRegExp, rest: Pattern | null, absolute: boolean): void; testString(e: Path, p: string, rest: Pattern | null, absolute: boolean): void; } //# sourceMappingURL=processor.d.ts.map{"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAa,OAAO,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C;;GAEG;AACH,qBAAa,cAAc;IACzB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;gBACnB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAa;IAGvD,IAAI;IAGJ,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAGxC,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;CAM3C;AAED;;;;GAIG;AACH,qBAAa,WAAW;IACtB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAY;IACpC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;IAMnD,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;CAOtC;AAED;;;GAGG;AACH,qBAAa,QAAQ;IACnB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAY;IACvC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAWlC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE;IAS5B,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE;IAG9B,IAAI,IAAI,IAAI,EAAE;CAGf;AAED;;;;;GAKG;AACH,qBAAa,SAAS;IACpB,cAAc,EAAE,cAAc,CAAA;IAC9B,OAAO,cAAoB;IAC3B,QAAQ,WAAiB;IACzB,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IACpB,MAAM,EAAE,OAAO,CAAA;IACf,GAAG,EAAE,OAAO,CAAA;IACZ,IAAI,EAAE,cAAc,CAAA;gBAER,IAAI,EAAE,cAAc,EAAE,cAAc,CAAC,EAAE,cAAc;IAQjE,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE;IAmGjD,cAAc,IAAI,IAAI,EAAE;IAIxB,KAAK;IAQL,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS;IAqBvD,YAAY,CACV,CAAC,EAAE,IAAI,EACP,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IA8CnB,UAAU,CACR,CAAC,EAAE,IAAI,EACP,CAAC,EAAE,QAAQ,EACX,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IAUnB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,EAAE,QAAQ,EAAE,OAAO;CASvE"}// synchronous utility for filtering entries and calculating subwalks import { GLOBSTAR } from 'minimatch'; /** * A cache of which patterns have been processed for a given Path */ export class HasWalkedCache { store; constructor(store = new Map()) { this.store = store; } copy() { return new HasWalkedCache(new Map(this.store)); } hasWalked(target, pattern) { return this.store.get(target.fullpath())?.has(pattern.globString()); } storeWalked(target, pattern) { const fullpath = target.fullpath(); const cached = this.store.get(fullpath); if (cached) cached.add(pattern.globString()); else this.store.set(fullpath, new Set([pattern.globString()])); } } /** * A record of which paths have been matched in a given walk step, * and whether they only are considered a match if they are a directory, * and whether their absolute or relative path should be returned. */ export class MatchRecord { store = new Map(); add(target, absolute, ifDir) { const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0); const current = this.store.get(target); this.store.set(target, current === undefined ? n : n & current); } // match, absolute, ifdir entries() { return [...this.store.entries()].map(([path, n]) => [ path, !!(n & 2), !!(n & 1), ]); } } /** * A collection of patterns that must be processed in a subsequent step * for a given path. */ export class SubWalks { store = new Map(); add(target, pattern) { if (!target.canReaddir()) { return; } const subs = this.store.get(target); if (subs) { if (!subs.find(p => p.globString() === pattern.globString())) { subs.push(pattern); } } else this.store.set(target, [pattern]); } get(target) { const subs = this.store.get(target); /* c8 ignore start */ if (!subs) { throw new Error('attempting to walk unknown path'); } /* c8 ignore stop */ return subs; } entries() { return this.keys().map(k => [k, this.store.get(k)]); } keys() { return [...this.store.keys()].filter(t => t.canReaddir()); } } /** * The class that processes patterns for a given path. * * Handles child entry filtering, and determining whether a path's * directory contents must be read. */ export class Processor { hasWalkedCache; matches = new MatchRecord(); subwalks = new SubWalks(); patterns; follow; dot; opts; constructor(opts, hasWalkedCache) { this.opts = opts; this.follow = !!opts.follow; this.dot = !!opts.dot; this.hasWalkedCache = hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache(); } processPatterns(target, patterns) { this.patterns = patterns; const processingSet = patterns.map(p => [target, p]); // map of paths to the magic-starting subwalks they need to walk // first item in patterns is the filter for (let [t, pattern] of processingSet) { this.hasWalkedCache.storeWalked(t, pattern); const root = pattern.root(); const absolute = pattern.isAbsolute() && this.opts.absolute !== false; // start absolute patterns at root if (root) { t = t.resolve(root === '/' && this.opts.root !== undefined ? this.opts.root : root); const rest = pattern.rest(); if (!rest) { this.matches.add(t, true, false); continue; } else { pattern = rest; } } if (t.isENOENT()) continue; let p; let rest; let changed = false; while (typeof (p = pattern.pattern()) === 'string' && (rest = pattern.rest())) { const c = t.resolve(p); t = c; pattern = rest; changed = true; } p = pattern.pattern(); rest = pattern.rest(); if (changed) { if (this.hasWalkedCache.hasWalked(t, pattern)) continue; this.hasWalkedCache.storeWalked(t, pattern); } // now we have either a final string for a known entry, // more strings for an unknown entry, // or a pattern starting with magic, mounted on t. if (typeof p === 'string') { // must not be final entry, otherwise we would have // concatenated it earlier. const ifDir = p === '..' || p === '' || p === '.'; this.matches.add(t.resolve(p), absolute, ifDir); continue; } else if (p === GLOBSTAR) { // if no rest, match and subwalk pattern // if rest, process rest and subwalk pattern // if it's a symlink, but we didn't get here by way of a // globstar match (meaning it's the first time THIS globstar // has traversed a symlink), then we follow it. Otherwise, stop. if (!t.isSymbolicLink() || this.follow || pattern.checkFollowGlobstar()) { this.subwalks.add(t, pattern); } const rp = rest?.pattern(); const rrest = rest?.rest(); if (!rest || ((rp === '' || rp === '.') && !rrest)) { // only HAS to be a dir if it ends in **/ or **/. // but ending in ** will match files as well. this.matches.add(t, absolute, rp === '' || rp === '.'); } else { if (rp === '..') { // this would mean you're matching **/.. at the fs root, // and no thanks, I'm not gonna test that specific case. /* c8 ignore start */ const tp = t.parent || t; /* c8 ignore stop */ if (!rrest) this.matches.add(tp, absolute, true); else if (!this.hasWalkedCache.hasWalked(tp, rrest)) { this.subwalks.add(tp, rrest); } } } } else if (p instanceof RegExp) { this.subwalks.add(t, pattern); } } return this; } subwalkTargets() { return this.subwalks.keys(); } child() { return new Processor(this.opts, this.hasWalkedCache); } // return a new Processor containing the subwalks for each // child entry, and a set of matches, and // a hasWalkedCache that's a copy of this one // then we're going to call filterEntries(parent, entries) { const patterns = this.subwalks.get(parent); // put matches and entry walks into the results processor const results = this.child(); for (const e of entries) { for (const pattern of patterns) { const absolute = pattern.isAbsolute(); const p = pattern.pattern(); const rest = pattern.rest(); if (p === GLOBSTAR) { results.testGlobstar(e, pattern, rest, absolute); } else if (p instanceof RegExp) { results.testRegExp(e, p, rest, absolute); } else { results.testString(e, p, rest, absolute); } } } return results; } testGlobstar(e, pattern, rest, absolute) { if (this.dot || !e.name.startsWith('.')) { if (!pattern.hasMore()) { this.matches.add(e, absolute, false); } if (e.canReaddir()) { // if we're in follow mode or it's not a symlink, just keep // testing the same pattern. If there's more after the globstar, // then this symlink consumes the globstar. If not, then we can // follow at most ONE symlink along the way, so we mark it, which // also checks to ensure that it wasn't already marked. if (this.follow || !e.isSymbolicLink()) { this.subwalks.add(e, pattern); } else if (e.isSymbolicLink()) { if (rest && pattern.checkFollowGlobstar()) { this.subwalks.add(e, rest); } else if (pattern.markFollowGlobstar()) { this.subwalks.add(e, pattern); } } } } // if the NEXT thing matches this entry, then also add // the rest. if (rest) { const rp = rest.pattern(); if (typeof rp === 'string' && // dots and empty were handled already rp !== '..' && rp !== '' && rp !== '.') { this.testString(e, rp, rest.rest(), absolute); } else if (rp === '..') { /* c8 ignore start */ const ep = e.parent || e; /* c8 ignore stop */ this.subwalks.add(ep, rest); } else if (rp instanceof RegExp) { this.testRegExp(e, rp, rest.rest(), absolute); } } } testRegExp(e, p, rest, absolute) { if (!p.test(e.name)) return; if (!rest) { this.matches.add(e, absolute, false); } else { this.subwalks.add(e, rest); } } testString(e, p, rest, absolute) { // should never happen? if (!e.isNamed(p)) return; if (!rest) { this.matches.add(e, absolute, false); } else { this.subwalks.add(e, rest); } } } //# sourceMappingURL=processor.js.map{"version":3,"file":"processor.js","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAAA,qEAAqE;AAErE,OAAO,EAAE,QAAQ,EAAY,MAAM,WAAW,CAAA;AAK9C;;GAEG;AACH,MAAM,OAAO,cAAc;IACzB,KAAK,CAA0B;IAC/B,YAAY,QAAkC,IAAI,GAAG,EAAE;QACrD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IACD,IAAI;QACF,OAAO,IAAI,cAAc,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,CAAC;IACD,SAAS,CAAC,MAAY,EAAE,OAAgB;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;IACrE,CAAC;IACD,WAAW,CAAC,MAAY,EAAE,OAAgB;QACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAA;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;QACvC,IAAI,MAAM;YAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;;YACvC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,CAAA;IAChE,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,WAAW;IACtB,KAAK,GAAsB,IAAI,GAAG,EAAE,CAAA;IACpC,GAAG,CAAC,MAAY,EAAE,QAAiB,EAAE,KAAc;QACjD,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QAC9C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACtC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAA;IACjE,CAAC;IACD,yBAAyB;IACzB,OAAO;QACL,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC;YAClD,IAAI;YACJ,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YACT,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SACV,CAAC,CAAA;IACJ,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,QAAQ;IACnB,KAAK,GAAyB,IAAI,GAAG,EAAE,CAAA;IACvC,GAAG,CAAC,MAAY,EAAE,OAAgB;QAChC,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC;YACzB,OAAM;QACR,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACnC,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,EAAE,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC,EAAE,CAAC;gBAC7D,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YACpB,CAAC;QACH,CAAC;;YAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC,CAAA;IAC1C,CAAC;IACD,GAAG,CAAC,MAAY;QACd,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACnC,qBAAqB;QACrB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;QACpD,CAAC;QACD,oBAAoB;QACpB,OAAO,IAAI,CAAA;IACb,CAAC;IACD,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAc,CAAC,CAAC,CAAA;IAClE,CAAC;IACD,IAAI;QACF,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAA;IAC3D,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,OAAO,SAAS;IACpB,cAAc,CAAgB;IAC9B,OAAO,GAAG,IAAI,WAAW,EAAE,CAAA;IAC3B,QAAQ,GAAG,IAAI,QAAQ,EAAE,CAAA;IACzB,QAAQ,CAAY;IACpB,MAAM,CAAS;IACf,GAAG,CAAS;IACZ,IAAI,CAAgB;IAEpB,YAAY,IAAoB,EAAE,cAA+B;QAC/D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;QAC3B,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAA;QACrB,IAAI,CAAC,cAAc;YACjB,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,cAAc,EAAE,CAAA;IACjE,CAAC;IAED,eAAe,CAAC,MAAY,EAAE,QAAmB;QAC/C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,MAAM,aAAa,GAAsB,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAA;QAEvE,gEAAgE;QAChE,uCAAuC;QAEvC,KAAK,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,IAAI,aAAa,EAAE,CAAC;YACvC,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;YAE3C,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;YAC3B,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,KAAK,KAAK,CAAA;YAErE,kCAAkC;YAClC,IAAI,IAAI,EAAE,CAAC;gBACT,CAAC,GAAG,CAAC,CAAC,OAAO,CACX,IAAI,KAAK,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;oBAC5C,IAAI,CAAC,IAAI,CAAC,IAAI;oBAChB,CAAC,CAAC,IAAI,CACP,CAAA;gBACD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;gBAC3B,IAAI,CAAC,IAAI,EAAE,CAAC;oBACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;oBAChC,SAAQ;gBACV,CAAC;qBAAM,CAAC;oBACN,OAAO,GAAG,IAAI,CAAA;gBAChB,CAAC;YACH,CAAC;YAED,IAAI,CAAC,CAAC,QAAQ,EAAE;gBAAE,SAAQ;YAE1B,IAAI,CAAY,CAAA;YAChB,IAAI,IAAoB,CAAA;YACxB,IAAI,OAAO,GAAG,KAAK,CAAA;YACnB,OACE,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,QAAQ;gBAC3C,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,EACvB,CAAC;gBACD,MAAM,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;gBACtB,CAAC,GAAG,CAAC,CAAA;gBACL,OAAO,GAAG,IAAI,CAAA;gBACd,OAAO,GAAG,IAAI,CAAA;YAChB,CAAC;YACD,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,CAAA;YACrB,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;YACrB,IAAI,OAAO,EAAE,CAAC;gBACZ,IAAI,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC;oBAAE,SAAQ;gBACvD,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;YAC7C,CAAC;YAED,uDAAuD;YACvD,qCAAqC;YACrC,kDAAkD;YAClD,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE,CAAC;gBAC1B,mDAAmD;gBACnD,2BAA2B;gBAC3B,MAAM,KAAK,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,GAAG,CAAA;gBACjD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;gBAC/C,SAAQ;YACV,CAAC;iBAAM,IAAI,CAAC,KAAK,QAAQ,EAAE,CAAC;gBAC1B,wCAAwC;gBACxC,4CAA4C;gBAC5C,wDAAwD;gBACxD,4DAA4D;gBAC5D,gEAAgE;gBAChE,IACE,CAAC,CAAC,CAAC,cAAc,EAAE;oBACnB,IAAI,CAAC,MAAM;oBACX,OAAO,CAAC,mBAAmB,EAAE,EAC7B,CAAC;oBACD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;gBAC/B,CAAC;gBACD,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAA;gBAC1B,MAAM,KAAK,GAAG,IAAI,EAAE,IAAI,EAAE,CAAA;gBAC1B,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;oBACnD,iDAAiD;oBACjD,6CAA6C;oBAC7C,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC,CAAA;gBACxD,CAAC;qBAAM,CAAC;oBACN,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;wBAChB,wDAAwD;wBACxD,wDAAwD;wBACxD,qBAAqB;wBACrB,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAA;wBACxB,oBAAoB;wBACpB,IAAI,CAAC,KAAK;4BAAE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAA;6BAC3C,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC;4BACnD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;wBAC9B,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;iBAAM,IAAI,CAAC,YAAY,MAAM,EAAE,CAAC;gBAC/B,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;YAC/B,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAA;IACb,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAA;IAC7B,CAAC;IAED,KAAK;QACH,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,CAAA;IACtD,CAAC;IAED,0DAA0D;IAC1D,yCAAyC;IACzC,6CAA6C;IAC7C,2BAA2B;IAC3B,aAAa,CAAC,MAAY,EAAE,OAAe;QACzC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QAC1C,yDAAyD;QACzD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,EAAE,CAAA;QAC5B,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;YACxB,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;gBAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,EAAE,CAAA;gBACrC,MAAM,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,CAAA;gBAC3B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;gBAC3B,IAAI,CAAC,KAAK,QAAQ,EAAE,CAAC;oBACnB,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;gBAClD,CAAC;qBAAM,IAAI,CAAC,YAAY,MAAM,EAAE,CAAC;oBAC/B,OAAO,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;gBAC1C,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;gBAC1C,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,OAAO,CAAA;IAChB,CAAC;IAED,YAAY,CACV,CAAO,EACP,OAAgB,EAChB,IAAoB,EACpB,QAAiB;QAEjB,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACxC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;gBACvB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;YACtC,CAAC;YACD,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC;gBACnB,2DAA2D;gBAC3D,gEAAgE;gBAChE,+DAA+D;gBAC/D,iEAAiE;gBACjE,uDAAuD;gBACvD,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,cAAc,EAAE,EAAE,CAAC;oBACvC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;gBAC/B,CAAC;qBAAM,IAAI,CAAC,CAAC,cAAc,EAAE,EAAE,CAAC;oBAC9B,IAAI,IAAI,IAAI,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC;wBAC1C,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;oBAC5B,CAAC;yBAAM,IAAI,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC;wBACxC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;oBAC/B,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QACD,sDAAsD;QACtD,YAAY;QACZ,IAAI,IAAI,EAAE,CAAC;YACT,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,CAAA;YACzB,IACE,OAAO,EAAE,KAAK,QAAQ;gBACtB,sCAAsC;gBACtC,EAAE,KAAK,IAAI;gBACX,EAAE,KAAK,EAAE;gBACT,EAAE,KAAK,GAAG,EACV,CAAC;gBACD,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/C,CAAC;iBAAM,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;gBACvB,qBAAqB;gBACrB,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAA;gBACxB,oBAAoB;gBACpB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;YAC7B,CAAC;iBAAM,IAAI,EAAE,YAAY,MAAM,EAAE,CAAC;gBAChC,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/C,CAAC;QACH,CAAC;IACH,CAAC;IAED,UAAU,CACR,CAAO,EACP,CAAW,EACX,IAAoB,EACpB,QAAiB;QAEjB,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;YAAE,OAAM;QAC3B,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;IAED,UAAU,CAAC,CAAO,EAAE,CAAS,EAAE,IAAoB,EAAE,QAAiB;QACpE,uBAAuB;QACvB,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;YAAE,OAAM;QACzB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF","sourcesContent":["// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n store: Map>\n constructor(store: Map> = new Map()) {\n this.store = store\n }\n copy() {\n return new HasWalkedCache(new Map(this.store))\n }\n hasWalked(target: Path, pattern: Pattern) {\n return this.store.get(target.fullpath())?.has(pattern.globString())\n }\n storeWalked(target: Path, pattern: Pattern) {\n const fullpath = target.fullpath()\n const cached = this.store.get(fullpath)\n if (cached) cached.add(pattern.globString())\n else this.store.set(fullpath, new Set([pattern.globString()]))\n }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n store: Map = new Map()\n add(target: Path, absolute: boolean, ifDir: boolean) {\n const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n const current = this.store.get(target)\n this.store.set(target, current === undefined ? n : n & current)\n }\n // match, absolute, ifdir\n entries(): [Path, boolean, boolean][] {\n return [...this.store.entries()].map(([path, n]) => [\n path,\n !!(n & 2),\n !!(n & 1),\n ])\n }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n store: Map = new Map()\n add(target: Path, pattern: Pattern) {\n if (!target.canReaddir()) {\n return\n }\n const subs = this.store.get(target)\n if (subs) {\n if (!subs.find(p => p.globString() === pattern.globString())) {\n subs.push(pattern)\n }\n } else this.store.set(target, [pattern])\n }\n get(target: Path): Pattern[] {\n const subs = this.store.get(target)\n /* c8 ignore start */\n if (!subs) {\n throw new Error('attempting to walk unknown path')\n }\n /* c8 ignore stop */\n return subs\n }\n entries(): [Path, Pattern[]][] {\n return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n }\n keys(): Path[] {\n return [...this.store.keys()].filter(t => t.canReaddir())\n }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n hasWalkedCache: HasWalkedCache\n matches = new MatchRecord()\n subwalks = new SubWalks()\n patterns?: Pattern[]\n follow: boolean\n dot: boolean\n opts: GlobWalkerOpts\n\n constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n this.opts = opts\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.hasWalkedCache =\n hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n }\n\n processPatterns(target: Path, patterns: Pattern[]) {\n this.patterns = patterns\n const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n // map of paths to the magic-starting subwalks they need to walk\n // first item in patterns is the filter\n\n for (let [t, pattern] of processingSet) {\n this.hasWalkedCache.storeWalked(t, pattern)\n\n const root = pattern.root()\n const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n // start absolute patterns at root\n if (root) {\n t = t.resolve(\n root === '/' && this.opts.root !== undefined ?\n this.opts.root\n : root,\n )\n const rest = pattern.rest()\n if (!rest) {\n this.matches.add(t, true, false)\n continue\n } else {\n pattern = rest\n }\n }\n\n if (t.isENOENT()) continue\n\n let p: MMPattern\n let rest: Pattern | null\n let changed = false\n while (\n typeof (p = pattern.pattern()) === 'string' &&\n (rest = pattern.rest())\n ) {\n const c = t.resolve(p)\n t = c\n pattern = rest\n changed = true\n }\n p = pattern.pattern()\n rest = pattern.rest()\n if (changed) {\n if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n this.hasWalkedCache.storeWalked(t, pattern)\n }\n\n // now we have either a final string for a known entry,\n // more strings for an unknown entry,\n // or a pattern starting with magic, mounted on t.\n if (typeof p === 'string') {\n // must not be final entry, otherwise we would have\n // concatenated it earlier.\n const ifDir = p === '..' || p === '' || p === '.'\n this.matches.add(t.resolve(p), absolute, ifDir)\n continue\n } else if (p === GLOBSTAR) {\n // if no rest, match and subwalk pattern\n // if rest, process rest and subwalk pattern\n // if it's a symlink, but we didn't get here by way of a\n // globstar match (meaning it's the first time THIS globstar\n // has traversed a symlink), then we follow it. Otherwise, stop.\n if (\n !t.isSymbolicLink() ||\n this.follow ||\n pattern.checkFollowGlobstar()\n ) {\n this.subwalks.add(t, pattern)\n }\n const rp = rest?.pattern()\n const rrest = rest?.rest()\n if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n // only HAS to be a dir if it ends in **/ or **/.\n // but ending in ** will match files as well.\n this.matches.add(t, absolute, rp === '' || rp === '.')\n } else {\n if (rp === '..') {\n // this would mean you're matching **/.. at the fs root,\n // and no thanks, I'm not gonna test that specific case.\n /* c8 ignore start */\n const tp = t.parent || t\n /* c8 ignore stop */\n if (!rrest) this.matches.add(tp, absolute, true)\n else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n this.subwalks.add(tp, rrest)\n }\n }\n }\n } else if (p instanceof RegExp) {\n this.subwalks.add(t, pattern)\n }\n }\n\n return this\n }\n\n subwalkTargets(): Path[] {\n return this.subwalks.keys()\n }\n\n child() {\n return new Processor(this.opts, this.hasWalkedCache)\n }\n\n // return a new Processor containing the subwalks for each\n // child entry, and a set of matches, and\n // a hasWalkedCache that's a copy of this one\n // then we're going to call\n filterEntries(parent: Path, entries: Path[]): Processor {\n const patterns = this.subwalks.get(parent)\n // put matches and entry walks into the results processor\n const results = this.child()\n for (const e of entries) {\n for (const pattern of patterns) {\n const absolute = pattern.isAbsolute()\n const p = pattern.pattern()\n const rest = pattern.rest()\n if (p === GLOBSTAR) {\n results.testGlobstar(e, pattern, rest, absolute)\n } else if (p instanceof RegExp) {\n results.testRegExp(e, p, rest, absolute)\n } else {\n results.testString(e, p, rest, absolute)\n }\n }\n }\n return results\n }\n\n testGlobstar(\n e: Path,\n pattern: Pattern,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (this.dot || !e.name.startsWith('.')) {\n if (!pattern.hasMore()) {\n this.matches.add(e, absolute, false)\n }\n if (e.canReaddir()) {\n // if we're in follow mode or it's not a symlink, just keep\n // testing the same pattern. If there's more after the globstar,\n // then this symlink consumes the globstar. If not, then we can\n // follow at most ONE symlink along the way, so we mark it, which\n // also checks to ensure that it wasn't already marked.\n if (this.follow || !e.isSymbolicLink()) {\n this.subwalks.add(e, pattern)\n } else if (e.isSymbolicLink()) {\n if (rest && pattern.checkFollowGlobstar()) {\n this.subwalks.add(e, rest)\n } else if (pattern.markFollowGlobstar()) {\n this.subwalks.add(e, pattern)\n }\n }\n }\n }\n // if the NEXT thing matches this entry, then also add\n // the rest.\n if (rest) {\n const rp = rest.pattern()\n if (\n typeof rp === 'string' &&\n // dots and empty were handled already\n rp !== '..' &&\n rp !== '' &&\n rp !== '.'\n ) {\n this.testString(e, rp, rest.rest(), absolute)\n } else if (rp === '..') {\n /* c8 ignore start */\n const ep = e.parent || e\n /* c8 ignore stop */\n this.subwalks.add(ep, rest)\n } else if (rp instanceof RegExp) {\n this.testRegExp(e, rp, rest.rest(), absolute)\n }\n }\n }\n\n testRegExp(\n e: Path,\n p: MMRegExp,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (!p.test(e.name)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n\n testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n // should never happen?\n if (!e.isNamed(p)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n}\n"]}/** * Single-use utility classes to provide functionality to the {@link Glob} * methods. * * @module */ import { Minipass } from 'minipass'; import { Path } from 'path-scurry'; import { IgnoreLike } from './ignore.js'; import { Pattern } from './pattern.js'; import { Processor } from './processor.js'; export interface GlobWalkerOpts { absolute?: boolean; allowWindowsEscape?: boolean; cwd?: string | URL; dot?: boolean; dotRelative?: boolean; follow?: boolean; ignore?: string | string[] | IgnoreLike; mark?: boolean; matchBase?: boolean; maxDepth?: number; nobrace?: boolean; nocase?: boolean; nodir?: boolean; noext?: boolean; noglobstar?: boolean; platform?: NodeJS.Platform; posix?: boolean; realpath?: boolean; root?: string; stat?: boolean; signal?: AbortSignal; windowsPathsNoEscape?: boolean; withFileTypes?: boolean; includeChildMatches?: boolean; } export type GWOFileTypesTrue = GlobWalkerOpts & { withFileTypes: true; }; export type GWOFileTypesFalse = GlobWalkerOpts & { withFileTypes: false; }; export type GWOFileTypesUnset = GlobWalkerOpts & { withFileTypes?: undefined; }; export type Result = O extends GWOFileTypesTrue ? Path : O extends GWOFileTypesFalse ? string : O extends GWOFileTypesUnset ? string : Path | string; export type Matches = O extends GWOFileTypesTrue ? Set : O extends GWOFileTypesFalse ? Set : O extends GWOFileTypesUnset ? Set : Set; export type MatchStream = Minipass, Result>; /** * basic walking utilities that all the glob walker types use */ export declare abstract class GlobUtil { #private; path: Path; patterns: Pattern[]; opts: O; seen: Set; paused: boolean; aborted: boolean; signal?: AbortSignal; maxDepth: number; includeChildMatches: boolean; constructor(patterns: Pattern[], path: Path, opts: O); pause(): void; resume(): void; onResume(fn: () => any): void; matchCheck(e: Path, ifDir: boolean): Promise; matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined; matchCheckSync(e: Path, ifDir: boolean): Path | undefined; abstract matchEmit(p: Result): void; abstract matchEmit(p: string | Path): void; matchFinish(e: Path, absolute: boolean): void; match(e: Path, absolute: boolean, ifDir: boolean): Promise; matchSync(e: Path, absolute: boolean, ifDir: boolean): void; walkCB(target: Path, patterns: Pattern[], cb: () => any): void; walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any; walkCB3(target: Path, entries: Path[], processor: Processor, cb: () => any): void; walkCBSync(target: Path, patterns: Pattern[], cb: () => any): void; walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any; walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => any): void; } export declare class GlobWalker extends GlobUtil { matches: Set>; constructor(patterns: Pattern[], path: Path, opts: O); matchEmit(e: Result): void; walk(): Promise>>; walkSync(): Set>; } export declare class GlobStream extends GlobUtil { results: Minipass, Result>; constructor(patterns: Pattern[], path: Path, opts: O); matchEmit(e: Result): void; stream(): MatchStream; streamSync(): MatchStream; } //# sourceMappingURL=walker.d.ts.map{"version":3,"file":"walker.d.ts","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAU,UAAU,EAAE,MAAM,aAAa,CAAA;AAOhD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE1C,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;IAClB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IACvC,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,CAAA;IAGnB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;IAC1B,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B;AAED,MAAM,MAAM,gBAAgB,GAAG,cAAc,GAAG;IAC9C,aAAa,EAAE,IAAI,CAAA;CACpB,CAAA;AACD,MAAM,MAAM,iBAAiB,GAAG,cAAc,GAAG;IAC/C,aAAa,EAAE,KAAK,CAAA;CACrB,CAAA;AACD,MAAM,MAAM,iBAAiB,GAAG,cAAc,GAAG;IAC/C,aAAa,CAAC,EAAE,SAAS,CAAA;CAC1B,CAAA;AAED,MAAM,MAAM,MAAM,CAAC,CAAC,SAAS,cAAc,IACzC,CAAC,SAAS,gBAAgB,GAAG,IAAI,GAC/B,CAAC,SAAS,iBAAiB,GAAG,MAAM,GACpC,CAAC,SAAS,iBAAiB,GAAG,MAAM,GACpC,IAAI,GAAG,MAAM,CAAA;AAEjB,MAAM,MAAM,OAAO,CAAC,CAAC,SAAS,cAAc,IAC1C,CAAC,SAAS,gBAAgB,GAAG,GAAG,CAAC,IAAI,CAAC,GACpC,CAAC,SAAS,iBAAiB,GAAG,GAAG,CAAC,MAAM,CAAC,GACzC,CAAC,SAAS,iBAAiB,GAAG,GAAG,CAAC,MAAM,CAAC,GACzC,GAAG,CAAC,IAAI,GAAG,MAAM,CAAC,CAAA;AAEtB,MAAM,MAAM,WAAW,CAAC,CAAC,SAAS,cAAc,IAAI,QAAQ,CAC1D,MAAM,CAAC,CAAC,CAAC,EACT,MAAM,CAAC,CAAC,CAAC,CACV,CAAA;AAUD;;GAEG;AACH,8BAAsB,QAAQ,CAAC,CAAC,SAAS,cAAc,GAAG,cAAc;;IACtE,IAAI,EAAE,IAAI,CAAA;IACV,QAAQ,EAAE,OAAO,EAAE,CAAA;IACnB,IAAI,EAAE,CAAC,CAAA;IACP,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAkB;IACjC,MAAM,EAAE,OAAO,CAAQ;IACvB,OAAO,EAAE,OAAO,CAAQ;IAIxB,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,QAAQ,EAAE,MAAM,CAAA;IAChB,mBAAmB,EAAE,OAAO,CAAA;gBAEhB,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAsCpD,KAAK;IAGL,MAAM;IAUN,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG;IAahB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAqBpE,cAAc,CAAC,CAAC,EAAE,IAAI,GAAG,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS;IAgBrE,cAAc,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS;IAmBzD,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IACtC,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAE1C,WAAW,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO;IA2BhC,KAAK,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAKtE,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAK3D,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,MAAM,GAAG;IAOvD,OAAO,CACL,MAAM,EAAE,IAAI,EACZ,QAAQ,EAAE,OAAO,EAAE,EACnB,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;IA2Cf,OAAO,CACL,MAAM,EAAE,IAAI,EACZ,OAAO,EAAE,IAAI,EAAE,EACf,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;IAsBf,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,MAAM,GAAG;IAO3D,WAAW,CACT,MAAM,EAAE,IAAI,EACZ,QAAQ,EAAE,OAAO,EAAE,EACnB,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;IAqCf,WAAW,CACT,MAAM,EAAE,IAAI,EACZ,OAAO,EAAE,IAAI,EAAE,EACf,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;CAoBhB;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,iBAAuB;gBAElB,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAIpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAIvB,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAiBrC,QAAQ,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;CAW3B;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;gBAE3B,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAUpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAK7B,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC;IAYxB,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC;CAO7B"}/** * Single-use utility classes to provide functionality to the {@link Glob} * methods. * * @module */ import { Minipass } from 'minipass'; import { Ignore } from './ignore.js'; import { Processor } from './processor.js'; const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore; /** * basic walking utilities that all the glob walker types use */ export class GlobUtil { path; patterns; opts; seen = new Set(); paused = false; aborted = false; #onResume = []; #ignore; #sep; signal; maxDepth; includeChildMatches; constructor(patterns, path, opts) { this.patterns = patterns; this.path = path; this.opts = opts; this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/'; this.includeChildMatches = opts.includeChildMatches !== false; if (opts.ignore || !this.includeChildMatches) { this.#ignore = makeIgnore(opts.ignore ?? [], opts); if (!this.includeChildMatches && typeof this.#ignore.add !== 'function') { const m = 'cannot ignore child matches, ignore lacks add() method.'; throw new Error(m); } } // ignore, always set with maxDepth, but it's optional on the // GlobOptions type /* c8 ignore start */ this.maxDepth = opts.maxDepth || Infinity; /* c8 ignore stop */ if (opts.signal) { this.signal = opts.signal; this.signal.addEventListener('abort', () => { this.#onResume.length = 0; }); } } #ignored(path) { return this.seen.has(path) || !!this.#ignore?.ignored?.(path); } #childrenIgnored(path) { return !!this.#ignore?.childrenIgnored?.(path); } // backpressure mechanism pause() { this.paused = true; } resume() { /* c8 ignore start */ if (this.signal?.aborted) return; /* c8 ignore stop */ this.paused = false; let fn = undefined; while (!this.paused && (fn = this.#onResume.shift())) { fn(); } } onResume(fn) { if (this.signal?.aborted) return; /* c8 ignore start */ if (!this.paused) { fn(); } else { /* c8 ignore stop */ this.#onResume.push(fn); } } // do the requisite realpath/stat checking, and return the path // to add or undefined to filter it out. async matchCheck(e, ifDir) { if (ifDir && this.opts.nodir) return undefined; let rpc; if (this.opts.realpath) { rpc = e.realpathCached() || (await e.realpath()); if (!rpc) return undefined; e = rpc; } const needStat = e.isUnknown() || this.opts.stat; const s = needStat ? await e.lstat() : e; if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { const target = await s.realpath(); /* c8 ignore start */ if (target && (target.isUnknown() || this.opts.stat)) { await target.lstat(); } /* c8 ignore stop */ } return this.matchCheckTest(s, ifDir); } matchCheckTest(e, ifDir) { return (e && (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && (!ifDir || e.canReaddir()) && (!this.opts.nodir || !e.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e.isSymbolicLink() || !e.realpathCached()?.isDirectory()) && !this.#ignored(e)) ? e : undefined; } matchCheckSync(e, ifDir) { if (ifDir && this.opts.nodir) return undefined; let rpc; if (this.opts.realpath) { rpc = e.realpathCached() || e.realpathSync(); if (!rpc) return undefined; e = rpc; } const needStat = e.isUnknown() || this.opts.stat; const s = needStat ? e.lstatSync() : e; if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { const target = s.realpathSync(); if (target && (target?.isUnknown() || this.opts.stat)) { target.lstatSync(); } } return this.matchCheckTest(s, ifDir); } matchFinish(e, absolute) { if (this.#ignored(e)) return; // we know we have an ignore if this is false, but TS doesn't if (!this.includeChildMatches && this.#ignore?.add) { const ign = `${e.relativePosix()}/**`; this.#ignore.add(ign); } const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute; this.seen.add(e); const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''; // ok, we have what we need! if (this.opts.withFileTypes) { this.matchEmit(e); } else if (abs) { const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath(); this.matchEmit(abs + mark); } else { const rel = this.opts.posix ? e.relativePosix() : e.relative(); const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ? '.' + this.#sep : ''; this.matchEmit(!rel ? '.' + mark : pre + rel + mark); } } async match(e, absolute, ifDir) { const p = await this.matchCheck(e, ifDir); if (p) this.matchFinish(p, absolute); } matchSync(e, absolute, ifDir) { const p = this.matchCheckSync(e, ifDir); if (p) this.matchFinish(p, absolute); } walkCB(target, patterns, cb) { /* c8 ignore start */ if (this.signal?.aborted) cb(); /* c8 ignore stop */ this.walkCB2(target, patterns, new Processor(this.opts), cb); } walkCB2(target, patterns, processor, cb) { if (this.#childrenIgnored(target)) return cb(); if (this.signal?.aborted) cb(); if (this.paused) { this.onResume(() => this.walkCB2(target, patterns, processor, cb)); return; } processor.processPatterns(target, patterns); // done processing. all of the above is sync, can be abstracted out. // subwalks is a map of paths to the entry filters they need // matches is a map of paths to [absolute, ifDir] tuples. let tasks = 1; const next = () => { if (--tasks === 0) cb(); }; for (const [m, absolute, ifDir] of processor.matches.entries()) { if (this.#ignored(m)) continue; tasks++; this.match(m, absolute, ifDir).then(() => next()); } for (const t of processor.subwalkTargets()) { if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { continue; } tasks++; const childrenCached = t.readdirCached(); if (t.calledReaddir()) this.walkCB3(t, childrenCached, processor, next); else { t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true); } } next(); } walkCB3(target, entries, processor, cb) { processor = processor.filterEntries(target, entries); let tasks = 1; const next = () => { if (--tasks === 0) cb(); }; for (const [m, absolute, ifDir] of processor.matches.entries()) { if (this.#ignored(m)) continue; tasks++; this.match(m, absolute, ifDir).then(() => next()); } for (const [target, patterns] of processor.subwalks.entries()) { tasks++; this.walkCB2(target, patterns, processor.child(), next); } next(); } walkCBSync(target, patterns, cb) { /* c8 ignore start */ if (this.signal?.aborted) cb(); /* c8 ignore stop */ this.walkCB2Sync(target, patterns, new Processor(this.opts), cb); } walkCB2Sync(target, patterns, processor, cb) { if (this.#childrenIgnored(target)) return cb(); if (this.signal?.aborted) cb(); if (this.paused) { this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb)); return; } processor.processPatterns(target, patterns); // done processing. all of the above is sync, can be abstracted out. // subwalks is a map of paths to the entry filters they need // matches is a map of paths to [absolute, ifDir] tuples. let tasks = 1; const next = () => { if (--tasks === 0) cb(); }; for (const [m, absolute, ifDir] of processor.matches.entries()) { if (this.#ignored(m)) continue; this.matchSync(m, absolute, ifDir); } for (const t of processor.subwalkTargets()) { if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { continue; } tasks++; const children = t.readdirSync(); this.walkCB3Sync(t, children, processor, next); } next(); } walkCB3Sync(target, entries, processor, cb) { processor = processor.filterEntries(target, entries); let tasks = 1; const next = () => { if (--tasks === 0) cb(); }; for (const [m, absolute, ifDir] of processor.matches.entries()) { if (this.#ignored(m)) continue; this.matchSync(m, absolute, ifDir); } for (const [target, patterns] of processor.subwalks.entries()) { tasks++; this.walkCB2Sync(target, patterns, processor.child(), next); } next(); } } export class GlobWalker extends GlobUtil { matches = new Set(); constructor(patterns, path, opts) { super(patterns, path, opts); } matchEmit(e) { this.matches.add(e); } async walk() { if (this.signal?.aborted) throw this.signal.reason; if (this.path.isUnknown()) { await this.path.lstat(); } await new Promise((res, rej) => { this.walkCB(this.path, this.patterns, () => { if (this.signal?.aborted) { rej(this.signal.reason); } else { res(this.matches); } }); }); return this.matches; } walkSync() { if (this.signal?.aborted) throw this.signal.reason; if (this.path.isUnknown()) { this.path.lstatSync(); } // nothing for the callback to do, because this never pauses this.walkCBSync(this.path, this.patterns, () => { if (this.signal?.aborted) throw this.signal.reason; }); return this.matches; } } export class GlobStream extends GlobUtil { results; constructor(patterns, path, opts) { super(patterns, path, opts); this.results = new Minipass({ signal: this.signal, objectMode: true, }); this.results.on('drain', () => this.resume()); this.results.on('resume', () => this.resume()); } matchEmit(e) { this.results.write(e); if (!this.results.flowing) this.pause(); } stream() { const target = this.path; if (target.isUnknown()) { target.lstat().then(() => { this.walkCB(target, this.patterns, () => this.results.end()); }); } else { this.walkCB(target, this.patterns, () => this.results.end()); } return this.results; } streamSync() { if (this.path.isUnknown()) { this.path.lstatSync(); } this.walkCBSync(this.path, this.patterns, () => this.results.end()); return this.results; } } //# sourceMappingURL=walker.js.map{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAEnC,OAAO,EAAE,MAAM,EAAc,MAAM,aAAa,CAAA;AAQhD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AA0D1C,MAAM,UAAU,GAAG,CACjB,MAAsC,EACtC,IAAoB,EACR,EAAE,CACd,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC;IACvD,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC;QAClD,CAAC,CAAC,MAAM,CAAA;AAEV;;GAEG;AACH,MAAM,OAAgB,QAAQ;IAC5B,IAAI,CAAM;IACV,QAAQ,CAAW;IACnB,IAAI,CAAG;IACP,IAAI,GAAc,IAAI,GAAG,EAAQ,CAAA;IACjC,MAAM,GAAY,KAAK,CAAA;IACvB,OAAO,GAAY,KAAK,CAAA;IACxB,SAAS,GAAkB,EAAE,CAAA;IAC7B,OAAO,CAAa;IACpB,IAAI,CAAY;IAChB,MAAM,CAAc;IACpB,QAAQ,CAAQ;IAChB,mBAAmB,CAAS;IAG5B,YAAY,QAAmB,EAAE,IAAU,EAAE,IAAO;QAClD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAA;QACjE,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,mBAAmB,KAAK,KAAK,CAAA;QAC7D,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC;YAC7C,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,EAAE,IAAI,CAAC,CAAA;YAClD,IACE,CAAC,IAAI,CAAC,mBAAmB;gBACzB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,UAAU,EACtC,CAAC;gBACD,MAAM,CAAC,GAAG,yDAAyD,CAAA;gBACnE,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,CAAA;YACpB,CAAC;QACH,CAAC;QACD,6DAA6D;QAC7D,mBAAmB;QACnB,qBAAqB;QACrB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAA;QACzC,oBAAoB;QACpB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;YACzB,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;gBACzC,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAA;YAC3B,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;IAED,QAAQ,CAAC,IAAU;QACjB,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;IAC/D,CAAC;IACD,gBAAgB,CAAC,IAAU;QACzB,OAAO,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,eAAe,EAAE,CAAC,IAAI,CAAC,CAAA;IAChD,CAAC;IAED,yBAAyB;IACzB,KAAK;QACH,IAAI,CAAC,MAAM,GAAG,IAAI,CAAA;IACpB,CAAC;IACD,MAAM;QACJ,qBAAqB;QACrB,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,OAAM;QAChC,oBAAoB;QACpB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;QACnB,IAAI,EAAE,GAA4B,SAAS,CAAA;QAC3C,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC;YACrD,EAAE,EAAE,CAAA;QACN,CAAC;IACH,CAAC;IACD,QAAQ,CAAC,EAAa;QACpB,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,OAAM;QAChC,qBAAqB;QACrB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,EAAE,EAAE,CAAA;QACN,CAAC;aAAM,CAAC;YACN,oBAAoB;YACpB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACzB,CAAC;IACH,CAAC;IAED,+DAA+D;IAC/D,wCAAwC;IACxC,KAAK,CAAC,UAAU,CAAC,CAAO,EAAE,KAAc;QACtC,IAAI,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAA;QAC9C,IAAI,GAAqB,CAAA;QACzB,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvB,GAAG,GAAG,CAAC,CAAC,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAA;YAChD,IAAI,CAAC,GAAG;gBAAE,OAAO,SAAS,CAAA;YAC1B,CAAC,GAAG,GAAG,CAAA;QACT,CAAC;QACD,MAAM,QAAQ,GAAG,CAAC,CAAC,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;QAChD,MAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;QACxC,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,EAAE,cAAc,EAAE,EAAE,CAAC;YAC/D,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAA;YACjC,qBAAqB;YACrB,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrD,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;YACtB,CAAC;YACD,oBAAoB;QACtB,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;IACtC,CAAC;IAED,cAAc,CAAC,CAAmB,EAAE,KAAc;QAChD,OAAO,CACH,CAAC;YACC,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,CAAC;YAC1D,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;YAC1B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;YACtC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK;gBACf,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM;gBACjB,CAAC,CAAC,CAAC,cAAc,EAAE;gBACnB,CAAC,CAAC,CAAC,cAAc,EAAE,EAAE,WAAW,EAAE,CAAC;YACrC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CACpB,CAAC,CAAC;YACD,CAAC;YACH,CAAC,CAAC,SAAS,CAAA;IACf,CAAC;IAED,cAAc,CAAC,CAAO,EAAE,KAAc;QACpC,IAAI,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAA;QAC9C,IAAI,GAAqB,CAAA;QACzB,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvB,GAAG,GAAG,CAAC,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC,YAAY,EAAE,CAAA;YAC5C,IAAI,CAAC,GAAG;gBAAE,OAAO,SAAS,CAAA;YAC1B,CAAC,GAAG,GAAG,CAAA;QACT,CAAC;QACD,MAAM,QAAQ,GAAG,CAAC,CAAC,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;QAChD,MAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;QACtC,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,EAAE,cAAc,EAAE,EAAE,CAAC;YAC/D,MAAM,MAAM,GAAG,CAAC,CAAC,YAAY,EAAE,CAAA;YAC/B,IAAI,MAAM,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBACtD,MAAM,CAAC,SAAS,EAAE,CAAA;YACpB,CAAC;QACH,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;IACtC,CAAC;IAKD,WAAW,CAAC,CAAO,EAAE,QAAiB;QACpC,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;YAAE,OAAM;QAC5B,6DAA6D;QAC7D,IAAI,CAAC,IAAI,CAAC,mBAAmB,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC;YACnD,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,aAAa,EAAE,KAAK,CAAA;YACrC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QACvB,CAAC;QACD,MAAM,GAAG,GACP,IAAI,CAAC,IAAI,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAA;QAClE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;QAChB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;QAC/D,4BAA4B;QAC5B,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YAC5B,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;QACnB,CAAC;aAAM,IAAI,GAAG,EAAE,CAAC;YACf,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAA;YAC9D,IAAI,CAAC,SAAS,CAAC,GAAG,GAAG,IAAI,CAAC,CAAA;QAC5B,CAAC;aAAM,CAAC;YACN,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAA;YAC9D,MAAM,GAAG,GACP,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;gBAC1D,GAAG,GAAG,IAAI,CAAC,IAAI;gBACjB,CAAC,CAAC,EAAE,CAAA;YACN,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,IAAI,CAAC,CAAA;QACtD,CAAC;IACH,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,CAAO,EAAE,QAAiB,EAAE,KAAc;QACpD,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;QACzC,IAAI,CAAC;YAAE,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAA;IACtC,CAAC;IAED,SAAS,CAAC,CAAO,EAAE,QAAiB,EAAE,KAAc;QAClD,MAAM,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;QACvC,IAAI,CAAC;YAAE,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAA;IACtC,CAAC;IAED,MAAM,CAAC,MAAY,EAAE,QAAmB,EAAE,EAAa;QACrD,qBAAqB;QACrB,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,EAAE,EAAE,CAAA;QAC9B,oBAAoB;QACpB,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAA;IAC9D,CAAC;IAED,OAAO,CACL,MAAY,EACZ,QAAmB,EACnB,SAAoB,EACpB,EAAa;QAEb,IAAI,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC;YAAE,OAAO,EAAE,EAAE,CAAA;QAC9C,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,EAAE,EAAE,CAAA;QAC9B,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC,CAAA;YAClE,OAAM;QACR,CAAC;QACD,SAAS,CAAC,eAAe,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QAE3C,qEAAqE;QACrE,4DAA4D;QAC5D,yDAAyD;QACzD,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,IAAI,EAAE,KAAK,KAAK,CAAC;gBAAE,EAAE,EAAE,CAAA;QACzB,CAAC,CAAA;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,SAAQ;YAC9B,KAAK,EAAE,CAAA;YACP,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAA;QACnD,CAAC;QAED,KAAK,MAAM,CAAC,IAAI,SAAS,CAAC,cAAc,EAAE,EAAE,CAAC;YAC3C,IAAI,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAC7D,SAAQ;YACV,CAAC;YACD,KAAK,EAAE,CAAA;YACP,MAAM,cAAc,GAAG,CAAC,CAAC,aAAa,EAAE,CAAA;YACxC,IAAI,CAAC,CAAC,aAAa,EAAE;gBACnB,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,cAAc,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;iBAC7C,CAAC;gBACJ,CAAC,CAAC,SAAS,CACT,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,EACzD,IAAI,CACL,CAAA;YACH,CAAC;QACH,CAAC;QAED,IAAI,EAAE,CAAA;IACR,CAAC;IAED,OAAO,CACL,MAAY,EACZ,OAAe,EACf,SAAoB,EACpB,EAAa;QAEb,SAAS,GAAG,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;QAEpD,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,IAAI,EAAE,KAAK,KAAK,CAAC;gBAAE,EAAE,EAAE,CAAA;QACzB,CAAC,CAAA;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,SAAQ;YAC9B,KAAK,EAAE,CAAA;YACP,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAA;QACnD,CAAC;QACD,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YAC9D,KAAK,EAAE,CAAA;YACP,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,CAAA;QACzD,CAAC;QAED,IAAI,EAAE,CAAA;IACR,CAAC;IAED,UAAU,CAAC,MAAY,EAAE,QAAmB,EAAE,EAAa;QACzD,qBAAqB;QACrB,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,EAAE,EAAE,CAAA;QAC9B,oBAAoB;QACpB,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAA;IAClE,CAAC;IAED,WAAW,CACT,MAAY,EACZ,QAAmB,EACnB,SAAoB,EACpB,EAAa;QAEb,IAAI,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC;YAAE,OAAO,EAAE,EAAE,CAAA;QAC9C,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,EAAE,EAAE,CAAA;QAC9B,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CACjB,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,EAAE,CAAC,CAClD,CAAA;YACD,OAAM;QACR,CAAC;QACD,SAAS,CAAC,eAAe,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QAE3C,qEAAqE;QACrE,4DAA4D;QAC5D,yDAAyD;QACzD,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,IAAI,EAAE,KAAK,KAAK,CAAC;gBAAE,EAAE,EAAE,CAAA;QACzB,CAAC,CAAA;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,SAAQ;YAC9B,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACpC,CAAC;QAED,KAAK,MAAM,CAAC,IAAI,SAAS,CAAC,cAAc,EAAE,EAAE,CAAC;YAC3C,IAAI,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAC7D,SAAQ;YACV,CAAC;YACD,KAAK,EAAE,CAAA;YACP,MAAM,QAAQ,GAAG,CAAC,CAAC,WAAW,EAAE,CAAA;YAChC,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;QAChD,CAAC;QAED,IAAI,EAAE,CAAA;IACR,CAAC;IAED,WAAW,CACT,MAAY,EACZ,OAAe,EACf,SAAoB,EACpB,EAAa;QAEb,SAAS,GAAG,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;QAEpD,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,IAAI,EAAE,KAAK,KAAK,CAAC;gBAAE,EAAE,EAAE,CAAA;QACzB,CAAC,CAAA;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,SAAQ;YAC9B,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YAC9D,KAAK,EAAE,CAAA;YACP,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,CAAA;QAC7D,CAAC;QAED,IAAI,EAAE,CAAA;IACR,CAAC;CACF;AAED,MAAM,OAAO,UAEX,SAAQ,QAAW;IACnB,OAAO,GAAG,IAAI,GAAG,EAAa,CAAA;IAE9B,YAAY,QAAmB,EAAE,IAAU,EAAE,IAAO;QAClD,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;IAC7B,CAAC;IAED,SAAS,CAAC,CAAY;QACpB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;IACrB,CAAC;IAED,KAAK,CAAC,IAAI;QACR,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA;QAClD,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAA;QACzB,CAAC;QACD,MAAM,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC7B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE;gBACzC,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;oBACzB,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;gBACzB,CAAC;qBAAM,CAAC;oBACN,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;gBACnB,CAAC;YACH,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,QAAQ;QACN,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA;QAClD,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,4DAA4D;QAC5D,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE;YAC7C,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO;gBAAE,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA;QACpD,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF;AAED,MAAM,OAAO,UAEX,SAAQ,QAAW;IACnB,OAAO,CAAgC;IAEvC,YAAY,QAAmB,EAAE,IAAU,EAAE,IAAO;QAClD,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,QAAQ,CAAuB;YAChD,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,UAAU,EAAE,IAAI;SACjB,CAAC,CAAA;QACF,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAA;QAC7C,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAA;IAChD,CAAC;IAED,SAAS,CAAC,CAAY;QACpB,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QACrB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO;YAAE,IAAI,CAAC,KAAK,EAAE,CAAA;IACzC,CAAC;IAED,MAAM;QACJ,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAA;QACxB,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,MAAM,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;gBACvB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;YAC9D,CAAC,CAAC,CAAA;QACJ,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QAC9D,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,UAAU;QACR,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF","sourcesContent":["/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed? that'd speed\n// things up a lot. Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n absolute?: boolean\n allowWindowsEscape?: boolean\n cwd?: string | URL\n dot?: boolean\n dotRelative?: boolean\n follow?: boolean\n ignore?: string | string[] | IgnoreLike\n mark?: boolean\n matchBase?: boolean\n // Note: maxDepth here means \"maximum actual Path.depth()\",\n // not \"maximum depth beyond cwd\"\n maxDepth?: number\n nobrace?: boolean\n nocase?: boolean\n nodir?: boolean\n noext?: boolean\n noglobstar?: boolean\n platform?: NodeJS.Platform\n posix?: boolean\n realpath?: boolean\n root?: string\n stat?: boolean\n signal?: AbortSignal\n windowsPathsNoEscape?: boolean\n withFileTypes?: boolean\n includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n withFileTypes?: undefined\n}\n\nexport type Result =\n O extends GWOFileTypesTrue ? Path\n : O extends GWOFileTypesFalse ? string\n : O extends GWOFileTypesUnset ? string\n : Path | string\n\nexport type Matches =\n O extends GWOFileTypesTrue ? Set\n : O extends GWOFileTypesFalse ? Set\n : O extends GWOFileTypesUnset ? Set\n : Set\n\nexport type MatchStream = Minipass<\n Result,\n Result\n>\n\nconst makeIgnore = (\n ignore: string | string[] | IgnoreLike,\n opts: GlobWalkerOpts,\n): IgnoreLike =>\n typeof ignore === 'string' ? new Ignore([ignore], opts)\n : Array.isArray(ignore) ? new Ignore(ignore, opts)\n : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n path: Path\n patterns: Pattern[]\n opts: O\n seen: Set = new Set()\n paused: boolean = false\n aborted: boolean = false\n #onResume: (() => any)[] = []\n #ignore?: IgnoreLike\n #sep: '\\\\' | '/'\n signal?: AbortSignal\n maxDepth: number\n includeChildMatches: boolean\n\n constructor(patterns: Pattern[], path: Path, opts: O)\n constructor(patterns: Pattern[], path: Path, opts: O) {\n this.patterns = patterns\n this.path = path\n this.opts = opts\n this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n this.includeChildMatches = opts.includeChildMatches !== false\n if (opts.ignore || !this.includeChildMatches) {\n this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n if (\n !this.includeChildMatches &&\n typeof this.#ignore.add !== 'function'\n ) {\n const m = 'cannot ignore child matches, ignore lacks add() method.'\n throw new Error(m)\n }\n }\n // ignore, always set with maxDepth, but it's optional on the\n // GlobOptions type\n /* c8 ignore start */\n this.maxDepth = opts.maxDepth || Infinity\n /* c8 ignore stop */\n if (opts.signal) {\n this.signal = opts.signal\n this.signal.addEventListener('abort', () => {\n this.#onResume.length = 0\n })\n }\n }\n\n #ignored(path: Path): boolean {\n return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n }\n #childrenIgnored(path: Path): boolean {\n return !!this.#ignore?.childrenIgnored?.(path)\n }\n\n // backpressure mechanism\n pause() {\n this.paused = true\n }\n resume() {\n /* c8 ignore start */\n if (this.signal?.aborted) return\n /* c8 ignore stop */\n this.paused = false\n let fn: (() => any) | undefined = undefined\n while (!this.paused && (fn = this.#onResume.shift())) {\n fn()\n }\n }\n onResume(fn: () => any) {\n if (this.signal?.aborted) return\n /* c8 ignore start */\n if (!this.paused) {\n fn()\n } else {\n /* c8 ignore stop */\n this.#onResume.push(fn)\n }\n }\n\n // do the requisite realpath/stat checking, and return the path\n // to add or undefined to filter it out.\n async matchCheck(e: Path, ifDir: boolean): Promise {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || (await e.realpath())\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? await e.lstat() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = await s.realpath()\n /* c8 ignore start */\n if (target && (target.isUnknown() || this.opts.stat)) {\n await target.lstat()\n }\n /* c8 ignore stop */\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n return (\n e &&\n (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n (!ifDir || e.canReaddir()) &&\n (!this.opts.nodir || !e.isDirectory()) &&\n (!this.opts.nodir ||\n !this.opts.follow ||\n !e.isSymbolicLink() ||\n !e.realpathCached()?.isDirectory()) &&\n !this.#ignored(e)\n ) ?\n e\n : undefined\n }\n\n matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || e.realpathSync()\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? e.lstatSync() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = s.realpathSync()\n if (target && (target?.isUnknown() || this.opts.stat)) {\n target.lstatSync()\n }\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n abstract matchEmit(p: Result): void\n abstract matchEmit(p: string | Path): void\n\n matchFinish(e: Path, absolute: boolean) {\n if (this.#ignored(e)) return\n // we know we have an ignore if this is false, but TS doesn't\n if (!this.includeChildMatches && this.#ignore?.add) {\n const ign = `${e.relativePosix()}/**`\n this.#ignore.add(ign)\n }\n const abs =\n this.opts.absolute === undefined ? absolute : this.opts.absolute\n this.seen.add(e)\n const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n // ok, we have what we need!\n if (this.opts.withFileTypes) {\n this.matchEmit(e)\n } else if (abs) {\n const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n this.matchEmit(abs + mark)\n } else {\n const rel = this.opts.posix ? e.relativePosix() : e.relative()\n const pre =\n this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n '.' + this.#sep\n : ''\n this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n }\n }\n\n async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n const p = await this.matchCheck(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n const p = this.matchCheckSync(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const childrenCached = t.readdirCached()\n if (t.calledReaddir())\n this.walkCB3(t, childrenCached, processor, next)\n else {\n t.readdirCB(\n (_, entries) => this.walkCB3(t, entries, processor, next),\n true,\n )\n }\n }\n\n next()\n }\n\n walkCB3(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2(target, patterns, processor.child(), next)\n }\n\n next()\n }\n\n walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2Sync(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() =>\n this.walkCB2Sync(target, patterns, processor, cb),\n )\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const children = t.readdirSync()\n this.walkCB3Sync(t, children, processor, next)\n }\n\n next()\n }\n\n walkCB3Sync(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2Sync(target, patterns, processor.child(), next)\n }\n\n next()\n }\n}\n\nexport class GlobWalker<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n matches = new Set>()\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n }\n\n matchEmit(e: Result): void {\n this.matches.add(e)\n }\n\n async walk(): Promise>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n await this.path.lstat()\n }\n await new Promise((res, rej) => {\n this.walkCB(this.path, this.patterns, () => {\n if (this.signal?.aborted) {\n rej(this.signal.reason)\n } else {\n res(this.matches)\n }\n })\n })\n return this.matches\n }\n\n walkSync(): Set> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n // nothing for the callback to do, because this never pauses\n this.walkCBSync(this.path, this.patterns, () => {\n if (this.signal?.aborted) throw this.signal.reason\n })\n return this.matches\n }\n}\n\nexport class GlobStream<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n results: Minipass, Result>\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n this.results = new Minipass, Result>({\n signal: this.signal,\n objectMode: true,\n })\n this.results.on('drain', () => this.resume())\n this.results.on('resume', () => this.resume())\n }\n\n matchEmit(e: Result): void {\n this.results.write(e)\n if (!this.results.flowing) this.pause()\n }\n\n stream(): MatchStream {\n const target = this.path\n if (target.isUnknown()) {\n target.lstat().then(() => {\n this.walkCB(target, this.patterns, () => this.results.end())\n })\n } else {\n this.walkCB(target, this.patterns, () => this.results.end())\n }\n return this.results\n }\n\n streamSync(): MatchStream {\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n this.walkCBSync(this.path, this.patterns, () => this.results.end())\n return this.results\n }\n}\n"]}{ "author": "Isaac Z. Schlueter (https://blog.izs.me/)", "publishConfig": { "tag": "legacy-v10" }, "name": "glob", "description": "the most correct and second fastest glob implementation in JavaScript", "version": "10.4.5", "type": "module", "tshy": { "main": true, "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "bin": "./dist/esm/bin.mjs", "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "repository": { "type": "git", "url": "git://github.com/isaacs/node-glob.git" }, "files": [ "dist" ], "scripts": { "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "prepare": "tshy", "pretest": "npm run prepare", "presnap": "npm run prepare", "test": "tap", "snap": "tap", "format": "prettier --write . --log-level warn", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts", "prepublish": "npm run benchclean", "profclean": "rm -f v8.log profile.txt", "test-regen": "npm run profclean && TEST_REGEN=1 node --no-warnings --loader ts-node/esm test/00-setup.ts", "prebench": "npm run prepare", "bench": "bash benchmark.sh", "preprof": "npm run prepare", "prof": "bash prof.sh", "benchclean": "node benchclean.cjs" }, "prettier": { "experimentalTernaries": true, "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "devDependencies": { "@types/node": "^20.11.30", "memfs": "^3.4.13", "mkdirp": "^3.0.1", "prettier": "^3.2.5", "rimraf": "^5.0.7", "sync-content": "^1.0.2", "tap": "^19.0.0", "tshy": "^1.14.0", "typedoc": "^0.25.12" }, "tap": { "before": "test/00-setup.ts" }, "license": "ISC", "funding": { "url": "https://github.com/sponsors/isaacs" }, "module": "./dist/esm/index.js" } The ISC License Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' module.exports = clone var getPrototypeOf = Object.getPrototypeOf || function (obj) { return obj.__proto__ } function clone (obj) { if (obj === null || typeof obj !== 'object') return obj if (obj instanceof Object) var copy = { __proto__: getPrototypeOf(obj) } else var copy = Object.create(null) Object.getOwnPropertyNames(obj).forEach(function (key) { Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) }) return copy } var fs = require('fs') var polyfills = require('./polyfills.js') var legacy = require('./legacy-streams.js') var clone = require('./clone.js') var util = require('util') /* istanbul ignore next - node 0.x polyfill */ var gracefulQueue var previousSymbol /* istanbul ignore else - node 0.x polyfill */ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { gracefulQueue = Symbol.for('graceful-fs.queue') // This is used in testing by future versions previousSymbol = Symbol.for('graceful-fs.previous') } else { gracefulQueue = '___graceful-fs.queue' previousSymbol = '___graceful-fs.previous' } function noop () {} function publishQueue(context, queue) { Object.defineProperty(context, gracefulQueue, { get: function() { return queue } }) } var debug = noop if (util.debuglog) debug = util.debuglog('gfs4') else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) debug = function() { var m = util.format.apply(util, arguments) m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') console.error(m) } // Once time initialization if (!fs[gracefulQueue]) { // This queue can be shared by multiple loaded instances var queue = global[gracefulQueue] || [] publishQueue(fs, queue) // Patch fs.close/closeSync to shared queue version, because we need // to retry() whenever a close happens *anywhere* in the program. // This is essential when multiple graceful-fs instances are // in play at the same time. fs.close = (function (fs$close) { function close (fd, cb) { return fs$close.call(fs, fd, function (err) { // This function uses the graceful-fs shared queue if (!err) { resetQueue() } if (typeof cb === 'function') cb.apply(this, arguments) }) } Object.defineProperty(close, previousSymbol, { value: fs$close }) return close })(fs.close) fs.closeSync = (function (fs$closeSync) { function closeSync (fd) { // This function uses the graceful-fs shared queue fs$closeSync.apply(fs, arguments) resetQueue() } Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync }) return closeSync })(fs.closeSync) if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { process.on('exit', function() { debug(fs[gracefulQueue]) require('assert').equal(fs[gracefulQueue].length, 0) }) } } if (!global[gracefulQueue]) { publishQueue(global, fs[gracefulQueue]); } module.exports = patch(clone(fs)) if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { module.exports = patch(fs) fs.__patched = true; } function patch (fs) { // Everything that references the open() function needs to be in here polyfills(fs) fs.gracefulify = patch fs.createReadStream = createReadStream fs.createWriteStream = createWriteStream var fs$readFile = fs.readFile fs.readFile = readFile function readFile (path, options, cb) { if (typeof options === 'function') cb = options, options = null return go$readFile(path, options, cb) function go$readFile (path, options, cb, startTime) { return fs$readFile(path, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$writeFile = fs.writeFile fs.writeFile = writeFile function writeFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null return go$writeFile(path, data, options, cb) function go$writeFile (path, data, options, cb, startTime) { return fs$writeFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$appendFile = fs.appendFile if (fs$appendFile) fs.appendFile = appendFile function appendFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null return go$appendFile(path, data, options, cb) function go$appendFile (path, data, options, cb, startTime) { return fs$appendFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$copyFile = fs.copyFile if (fs$copyFile) fs.copyFile = copyFile function copyFile (src, dest, flags, cb) { if (typeof flags === 'function') { cb = flags flags = 0 } return go$copyFile(src, dest, flags, cb) function go$copyFile (src, dest, flags, cb, startTime) { return fs$copyFile(src, dest, flags, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$readdir = fs.readdir fs.readdir = readdir var noReaddirOptionVersions = /^v[0-5]\./ function readdir (path, options, cb) { if (typeof options === 'function') cb = options, options = null var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir (path, options, cb, startTime) { return fs$readdir(path, fs$readdirCallback( path, options, cb, startTime )) } : function go$readdir (path, options, cb, startTime) { return fs$readdir(path, options, fs$readdirCallback( path, options, cb, startTime )) } return go$readdir(path, options, cb) function fs$readdirCallback (path, options, cb, startTime) { return function (err, files) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([ go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now() ]) else { if (files && files.sort) files.sort() if (typeof cb === 'function') cb.call(this, err, files) } } } } if (process.version.substr(0, 4) === 'v0.8') { var legStreams = legacy(fs) ReadStream = legStreams.ReadStream WriteStream = legStreams.WriteStream } var fs$ReadStream = fs.ReadStream if (fs$ReadStream) { ReadStream.prototype = Object.create(fs$ReadStream.prototype) ReadStream.prototype.open = ReadStream$open } var fs$WriteStream = fs.WriteStream if (fs$WriteStream) { WriteStream.prototype = Object.create(fs$WriteStream.prototype) WriteStream.prototype.open = WriteStream$open } Object.defineProperty(fs, 'ReadStream', { get: function () { return ReadStream }, set: function (val) { ReadStream = val }, enumerable: true, configurable: true }) Object.defineProperty(fs, 'WriteStream', { get: function () { return WriteStream }, set: function (val) { WriteStream = val }, enumerable: true, configurable: true }) // legacy names var FileReadStream = ReadStream Object.defineProperty(fs, 'FileReadStream', { get: function () { return FileReadStream }, set: function (val) { FileReadStream = val }, enumerable: true, configurable: true }) var FileWriteStream = WriteStream Object.defineProperty(fs, 'FileWriteStream', { get: function () { return FileWriteStream }, set: function (val) { FileWriteStream = val }, enumerable: true, configurable: true }) function ReadStream (path, options) { if (this instanceof ReadStream) return fs$ReadStream.apply(this, arguments), this else return ReadStream.apply(Object.create(ReadStream.prototype), arguments) } function ReadStream$open () { var that = this open(that.path, that.flags, that.mode, function (err, fd) { if (err) { if (that.autoClose) that.destroy() that.emit('error', err) } else { that.fd = fd that.emit('open', fd) that.read() } }) } function WriteStream (path, options) { if (this instanceof WriteStream) return fs$WriteStream.apply(this, arguments), this else return WriteStream.apply(Object.create(WriteStream.prototype), arguments) } function WriteStream$open () { var that = this open(that.path, that.flags, that.mode, function (err, fd) { if (err) { that.destroy() that.emit('error', err) } else { that.fd = fd that.emit('open', fd) } }) } function createReadStream (path, options) { return new fs.ReadStream(path, options) } function createWriteStream (path, options) { return new fs.WriteStream(path, options) } var fs$open = fs.open fs.open = open function open (path, flags, mode, cb) { if (typeof mode === 'function') cb = mode, mode = null return go$open(path, flags, mode, cb) function go$open (path, flags, mode, cb, startTime) { return fs$open(path, flags, mode, function (err, fd) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } return fs } function enqueue (elem) { debug('ENQUEUE', elem[0].name, elem[1]) fs[gracefulQueue].push(elem) retry() } // keep track of the timeout between retry() calls var retryTimer // reset the startTime and lastTime to now // this resets the start of the 60 second overall timeout as well as the // delay between attempts so that we'll retry these jobs sooner function resetQueue () { var now = Date.now() for (var i = 0; i < fs[gracefulQueue].length; ++i) { // entries that are only a length of 2 are from an older version, don't // bother modifying those since they'll be retried anyway. if (fs[gracefulQueue][i].length > 2) { fs[gracefulQueue][i][3] = now // startTime fs[gracefulQueue][i][4] = now // lastTime } } // call retry to make sure we're actively processing the queue retry() } function retry () { // clear the timer and remove it to help prevent unintended concurrency clearTimeout(retryTimer) retryTimer = undefined if (fs[gracefulQueue].length === 0) return var elem = fs[gracefulQueue].shift() var fn = elem[0] var args = elem[1] // these items may be unset if they were added by an older graceful-fs var err = elem[2] var startTime = elem[3] var lastTime = elem[4] // if we don't have a startTime we have no way of knowing if we've waited // long enough, so go ahead and retry this item now if (startTime === undefined) { debug('RETRY', fn.name, args) fn.apply(null, args) } else if (Date.now() - startTime >= 60000) { // it's been more than 60 seconds total, bail now debug('TIMEOUT', fn.name, args) var cb = args.pop() if (typeof cb === 'function') cb.call(null, err) } else { // the amount of time between the last attempt and right now var sinceAttempt = Date.now() - lastTime // the amount of time between when we first tried, and when we last tried // rounded up to at least 1 var sinceStart = Math.max(lastTime - startTime, 1) // backoff. wait longer than the total time we've been retrying, but only // up to a maximum of 100ms var desiredDelay = Math.min(sinceStart * 1.2, 100) // it's been long enough since the last retry, do it again if (sinceAttempt >= desiredDelay) { debug('RETRY', fn.name, args) fn.apply(null, args.concat([startTime])) } else { // if we can't do this job yet, push it to the end of the queue // and let the next iteration check again fs[gracefulQueue].push(elem) } } // schedule our next run if one isn't already scheduled if (retryTimer === undefined) { retryTimer = setTimeout(retry, 0) } } var Stream = require('stream').Stream module.exports = legacy function legacy (fs) { return { ReadStream: ReadStream, WriteStream: WriteStream } function ReadStream (path, options) { if (!(this instanceof ReadStream)) return new ReadStream(path, options); Stream.call(this); var self = this; this.path = path; this.fd = null; this.readable = true; this.paused = false; this.flags = 'r'; this.mode = 438; /*=0666*/ this.bufferSize = 64 * 1024; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.encoding) this.setEncoding(this.encoding); if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.end === undefined) { this.end = Infinity; } else if ('number' !== typeof this.end) { throw TypeError('end must be a Number'); } if (this.start > this.end) { throw new Error('start must be <= end'); } this.pos = this.start; } if (this.fd !== null) { process.nextTick(function() { self._read(); }); return; } fs.open(this.path, this.flags, this.mode, function (err, fd) { if (err) { self.emit('error', err); self.readable = false; return; } self.fd = fd; self.emit('open', fd); self._read(); }) } function WriteStream (path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); Stream.call(this); this.path = path; this.fd = null; this.writable = true; this.flags = 'w'; this.encoding = 'binary'; this.mode = 438; /*=0666*/ this.bytesWritten = 0; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.start < 0) { throw new Error('start must be >= zero'); } this.pos = this.start; } this.busy = false; this._queue = []; if (this.fd === null) { this._open = fs.open; this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); this.flush(); } } } { "name": "graceful-fs", "description": "A drop-in replacement for fs, making various improvements.", "version": "4.2.11", "repository": { "type": "git", "url": "https://github.com/isaacs/node-graceful-fs" }, "main": "graceful-fs.js", "directories": { "test": "test" }, "scripts": { "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --follow-tags", "test": "nyc --silent node test.js | tap -c -", "posttest": "nyc report" }, "keywords": [ "fs", "module", "reading", "retry", "retries", "queue", "error", "errors", "handling", "EMFILE", "EAGAIN", "EINVAL", "EPERM", "EACCESS" ], "license": "ISC", "devDependencies": { "import-fresh": "^2.0.0", "mkdirp": "^0.5.0", "rimraf": "^2.2.8", "tap": "^16.3.4" }, "files": [ "fs.js", "graceful-fs.js", "legacy-streams.js", "polyfills.js", "clone.js" ], "tap": { "reporter": "classic" } } var constants = require('constants') var origCwd = process.cwd var cwd = null var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform process.cwd = function() { if (!cwd) cwd = origCwd.call(process) return cwd } try { process.cwd() } catch (er) {} // This check is needed until node.js 12 is required if (typeof process.chdir === 'function') { var chdir = process.chdir process.chdir = function (d) { cwd = null chdir.call(process, d) } if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) } module.exports = patch function patch (fs) { // (re-)implement some things that are known busted or missing. // lchmod, broken prior to 0.6.2 // back-port the fix here. if (constants.hasOwnProperty('O_SYMLINK') && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { patchLchmod(fs) } // lutimes implementation, or no-op if (!fs.lutimes) { patchLutimes(fs) } // https://github.com/isaacs/node-graceful-fs/issues/4 // Chown should not fail on einval or eperm if non-root. // It should not fail on enosys ever, as this just indicates // that a fs doesn't support the intended operation. fs.chown = chownFix(fs.chown) fs.fchown = chownFix(fs.fchown) fs.lchown = chownFix(fs.lchown) fs.chmod = chmodFix(fs.chmod) fs.fchmod = chmodFix(fs.fchmod) fs.lchmod = chmodFix(fs.lchmod) fs.chownSync = chownFixSync(fs.chownSync) fs.fchownSync = chownFixSync(fs.fchownSync) fs.lchownSync = chownFixSync(fs.lchownSync) fs.chmodSync = chmodFixSync(fs.chmodSync) fs.fchmodSync = chmodFixSync(fs.fchmodSync) fs.lchmodSync = chmodFixSync(fs.lchmodSync) fs.stat = statFix(fs.stat) fs.fstat = statFix(fs.fstat) fs.lstat = statFix(fs.lstat) fs.statSync = statFixSync(fs.statSync) fs.fstatSync = statFixSync(fs.fstatSync) fs.lstatSync = statFixSync(fs.lstatSync) // if lchmod/lchown do not exist, then make them no-ops if (fs.chmod && !fs.lchmod) { fs.lchmod = function (path, mode, cb) { if (cb) process.nextTick(cb) } fs.lchmodSync = function () {} } if (fs.chown && !fs.lchown) { fs.lchown = function (path, uid, gid, cb) { if (cb) process.nextTick(cb) } fs.lchownSync = function () {} } // on Windows, A/V software can lock the directory, causing this // to fail with an EACCES or EPERM if the directory contains newly // created files. Try again on failure, for up to 60 seconds. // Set the timeout this long because some Windows Anti-Virus, such as Parity // bit9, may lock files for up to a minute, causing npm package install // failures. Also, take care to yield the scheduler. Windows scheduling gives // CPU to a busy looping process, which can cause the program causing the lock // contention to be starved of CPU by node, so the contention doesn't resolve. if (platform === "win32") { fs.rename = typeof fs.rename !== 'function' ? fs.rename : (function (fs$rename) { function rename (from, to, cb) { var start = Date.now() var backoff = 0; fs$rename(from, to, function CB (er) { if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) { setTimeout(function() { fs.stat(to, function (stater, st) { if (stater && stater.code === "ENOENT") fs$rename(from, to, CB); else cb(er) }) }, backoff) if (backoff < 100) backoff += 10; return; } if (cb) cb(er) }) } if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) return rename })(fs.rename) } // if read() returns EAGAIN, then just try it again. fs.read = typeof fs.read !== 'function' ? fs.read : (function (fs$read) { function read (fd, buffer, offset, length, position, callback_) { var callback if (callback_ && typeof callback_ === 'function') { var eagCounter = 0 callback = function (er, _, __) { if (er && er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++ return fs$read.call(fs, fd, buffer, offset, length, position, callback) } callback_.apply(this, arguments) } } return fs$read.call(fs, fd, buffer, offset, length, position, callback) } // This ensures `util.promisify` works as it does for native `fs.read`. if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) return read })(fs.read) fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { var eagCounter = 0 while (true) { try { return fs$readSync.call(fs, fd, buffer, offset, length, position) } catch (er) { if (er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++ continue } throw er } } }})(fs.readSync) function patchLchmod (fs) { fs.lchmod = function (path, mode, callback) { fs.open( path , constants.O_WRONLY | constants.O_SYMLINK , mode , function (err, fd) { if (err) { if (callback) callback(err) return } // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. fs.fchmod(fd, mode, function (err) { fs.close(fd, function(err2) { if (callback) callback(err || err2) }) }) }) } fs.lchmodSync = function (path, mode) { var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. var threw = true var ret try { ret = fs.fchmodSync(fd, mode) threw = false } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } else { fs.closeSync(fd) } } return ret } } function patchLutimes (fs) { if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { fs.lutimes = function (path, at, mt, cb) { fs.open(path, constants.O_SYMLINK, function (er, fd) { if (er) { if (cb) cb(er) return } fs.futimes(fd, at, mt, function (er) { fs.close(fd, function (er2) { if (cb) cb(er || er2) }) }) }) } fs.lutimesSync = function (path, at, mt) { var fd = fs.openSync(path, constants.O_SYMLINK) var ret var threw = true try { ret = fs.futimesSync(fd, at, mt) threw = false } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } else { fs.closeSync(fd) } } return ret } } else if (fs.futimes) { fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } fs.lutimesSync = function () {} } } function chmodFix (orig) { if (!orig) return orig return function (target, mode, cb) { return orig.call(fs, target, mode, function (er) { if (chownErOk(er)) er = null if (cb) cb.apply(this, arguments) }) } } function chmodFixSync (orig) { if (!orig) return orig return function (target, mode) { try { return orig.call(fs, target, mode) } catch (er) { if (!chownErOk(er)) throw er } } } function chownFix (orig) { if (!orig) return orig return function (target, uid, gid, cb) { return orig.call(fs, target, uid, gid, function (er) { if (chownErOk(er)) er = null if (cb) cb.apply(this, arguments) }) } } function chownFixSync (orig) { if (!orig) return orig return function (target, uid, gid) { try { return orig.call(fs, target, uid, gid) } catch (er) { if (!chownErOk(er)) throw er } } } function statFix (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options, cb) { if (typeof options === 'function') { cb = options options = null } function callback (er, stats) { if (stats) { if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 } if (cb) cb.apply(this, arguments) } return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback) } } function statFixSync (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options) { var stats = options ? orig.call(fs, target, options) : orig.call(fs, target) if (stats) { if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 } return stats; } } // ENOSYS means that the fs doesn't support the op. Just ignore // that, because it doesn't matter. // // if there's no getuid, or if getuid() is something other // than 0, and the error is EINVAL or EPERM, then just ignore // it. // // This specific case is a silent failure in cp, install, tar, // and most other unix tools that manage permissions. // // When running as root, or if other types of errors are // encountered, then it's strict. function chownErOk (er) { if (!er) return true if (er.code === "ENOSYS") return true var nonroot = !process.getuid || process.getuid() !== 0 if (nonroot) { if (er.code === "EINVAL" || er.code === "EPERM") return true } return false } } Copyright (c) 2015, Rebecca Turner Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' const parseUrl = require('./parse-url') // look for github shorthand inputs, such as npm/cli const isGitHubShorthand = (arg) => { // it cannot contain whitespace before the first # // it cannot start with a / because that's probably an absolute file path // but it must include a slash since repos are username/repository // it cannot start with a . because that's probably a relative file path // it cannot start with an @ because that's a scoped package if it passes the other tests // it cannot contain a : before a # because that tells us that there's a protocol // a second / may not exist before a # const firstHash = arg.indexOf('#') const firstSlash = arg.indexOf('/') const secondSlash = arg.indexOf('/', firstSlash + 1) const firstColon = arg.indexOf(':') const firstSpace = /\s/.exec(arg) const firstAt = arg.indexOf('@') const spaceOnlyAfterHash = !firstSpace || (firstHash > -1 && firstSpace.index > firstHash) const atOnlyAfterHash = firstAt === -1 || (firstHash > -1 && firstAt > firstHash) const colonOnlyAfterHash = firstColon === -1 || (firstHash > -1 && firstColon > firstHash) const secondSlashOnlyAfterHash = secondSlash === -1 || (firstHash > -1 && secondSlash > firstHash) const hasSlash = firstSlash > 0 // if a # is found, what we really want to know is that the character // immediately before # is not a / const doesNotEndWithSlash = firstHash > -1 ? arg[firstHash - 1] !== '/' : !arg.endsWith('/') const doesNotStartWithDot = !arg.startsWith('.') return spaceOnlyAfterHash && hasSlash && doesNotEndWithSlash && doesNotStartWithDot && atOnlyAfterHash && colonOnlyAfterHash && secondSlashOnlyAfterHash } module.exports = (giturl, opts, { gitHosts, protocols }) => { if (!giturl) { return } const correctedUrl = isGitHubShorthand(giturl) ? `github:${giturl}` : giturl const parsed = parseUrl(correctedUrl, protocols) if (!parsed) { return } const gitHostShortcut = gitHosts.byShortcut[parsed.protocol] const gitHostDomain = gitHosts.byDomain[parsed.hostname.startsWith('www.') ? parsed.hostname.slice(4) : parsed.hostname] const gitHostName = gitHostShortcut || gitHostDomain if (!gitHostName) { return } const gitHostInfo = gitHosts[gitHostShortcut || gitHostDomain] let auth = null if (protocols[parsed.protocol]?.auth && (parsed.username || parsed.password)) { auth = `${parsed.username}${parsed.password ? ':' + parsed.password : ''}` } let committish = null let user = null let project = null let defaultRepresentation = null try { if (gitHostShortcut) { let pathname = parsed.pathname.startsWith('/') ? parsed.pathname.slice(1) : parsed.pathname const firstAt = pathname.indexOf('@') // we ignore auth for shortcuts, so just trim it out if (firstAt > -1) { pathname = pathname.slice(firstAt + 1) } const lastSlash = pathname.lastIndexOf('/') if (lastSlash > -1) { user = decodeURIComponent(pathname.slice(0, lastSlash)) // we want nulls only, never empty strings if (!user) { user = null } project = decodeURIComponent(pathname.slice(lastSlash + 1)) } else { project = decodeURIComponent(pathname) } if (project.endsWith('.git')) { project = project.slice(0, -4) } if (parsed.hash) { committish = decodeURIComponent(parsed.hash.slice(1)) } defaultRepresentation = 'shortcut' } else { if (!gitHostInfo.protocols.includes(parsed.protocol)) { return } const segments = gitHostInfo.extract(parsed) if (!segments) { return } user = segments.user && decodeURIComponent(segments.user) project = decodeURIComponent(segments.project) committish = decodeURIComponent(segments.committish) defaultRepresentation = protocols[parsed.protocol]?.name || parsed.protocol.slice(0, -1) } } catch (err) { /* istanbul ignore else */ if (err instanceof URIError) { return } else { throw err } } return [gitHostName, user, auth, project, committish, defaultRepresentation, opts] } /* eslint-disable max-len */ 'use strict' const maybeJoin = (...args) => args.every(arg => arg) ? args.join('') : '' const maybeEncode = (arg) => arg ? encodeURIComponent(arg) : '' const formatHashFragment = (f) => f.toLowerCase() .replace(/^\W+/g, '') // strip leading non-characters .replace(/(? `git@${domain}:${user}/${project}.git${maybeJoin('#', committish)}`, sshurltemplate: ({ domain, user, project, committish }) => `git+ssh://git@${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, edittemplate: ({ domain, user, project, committish, editpath, path }) => `https://${domain}/${user}/${project}${maybeJoin('/', editpath, '/', maybeEncode(committish || 'HEAD'), '/', path)}`, browsetemplate: ({ domain, user, project, committish, treepath }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}`, browsetreetemplate: ({ domain, user, project, committish, treepath, path, fragment, hashformat }) => `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || 'HEAD')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`, browseblobtemplate: ({ domain, user, project, committish, blobpath, path, fragment, hashformat }) => `https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish || 'HEAD')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`, docstemplate: ({ domain, user, project, treepath, committish }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}#readme`, httpstemplate: ({ auth, domain, user, project, committish }) => `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, filetemplate: ({ domain, user, project, committish, path }) => `https://${domain}/${user}/${project}/raw/${maybeEncode(committish || 'HEAD')}/${path}`, shortcuttemplate: ({ type, user, project, committish }) => `${type}:${user}/${project}${maybeJoin('#', committish)}`, pathtemplate: ({ user, project, committish }) => `${user}/${project}${maybeJoin('#', committish)}`, bugstemplate: ({ domain, user, project }) => `https://${domain}/${user}/${project}/issues`, hashformat: formatHashFragment, } const hosts = {} hosts.github = { // First two are insecure and generally shouldn't be used any more, but // they are still supported. protocols: ['git:', 'http:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'github.com', treepath: 'tree', blobpath: 'blob', editpath: 'edit', filetemplate: ({ auth, user, project, committish, path }) => `https://${maybeJoin(auth, '@')}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || 'HEAD')}/${path}`, gittemplate: ({ auth, domain, user, project, committish }) => `git://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish || 'HEAD')}`, extract: (url) => { let [, user, project, type, committish] = url.pathname.split('/', 5) if (type && type !== 'tree') { return } if (!type) { committish = url.hash.slice(1) } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish } }, } hosts.bitbucket = { protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'bitbucket.org', treepath: 'src', blobpath: 'src', editpath: '?mode=edit', edittemplate: ({ domain, user, project, committish, treepath, path, editpath }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish || 'HEAD'), '/', path, editpath)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/get/${maybeEncode(committish || 'HEAD')}.tar.gz`, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) if (['get'].includes(aux)) { return } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } }, } hosts.gitlab = { protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'gitlab.com', treepath: 'tree', blobpath: 'tree', editpath: '-/edit', httpstemplate: ({ auth, domain, user, project, committish }) => `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish || 'HEAD')}`, extract: (url) => { const path = url.pathname.slice(1) if (path.includes('/-/') || path.includes('/archive.tar.gz')) { return } const segments = path.split('/') let project = segments.pop() if (project.endsWith('.git')) { project = project.slice(0, -4) } const user = segments.join('/') if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } }, } hosts.gist = { protocols: ['git:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'gist.github.com', editpath: 'edit', sshtemplate: ({ domain, project, committish }) => `git@${domain}:${project}.git${maybeJoin('#', committish)}`, sshurltemplate: ({ domain, project, committish }) => `git+ssh://git@${domain}/${project}.git${maybeJoin('#', committish)}`, edittemplate: ({ domain, user, project, committish, editpath }) => `https://${domain}/${user}/${project}${maybeJoin('/', maybeEncode(committish))}/${editpath}`, browsetemplate: ({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`, browsetreetemplate: ({ domain, project, committish, path, hashformat }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`, browseblobtemplate: ({ domain, project, committish, path, hashformat }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`, docstemplate: ({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`, httpstemplate: ({ domain, project, committish }) => `git+https://${domain}/${project}.git${maybeJoin('#', committish)}`, filetemplate: ({ user, project, committish, path }) => `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin('/', maybeEncode(committish))}/${path}`, shortcuttemplate: ({ type, project, committish }) => `${type}:${project}${maybeJoin('#', committish)}`, pathtemplate: ({ project, committish }) => `${project}${maybeJoin('#', committish)}`, bugstemplate: ({ domain, project }) => `https://${domain}/${project}`, gittemplate: ({ domain, project, committish }) => `git://${domain}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ project, committish }) => `https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish || 'HEAD')}`, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) if (aux === 'raw') { return } if (!project) { if (!user) { return } project = user user = null } if (project.endsWith('.git')) { project = project.slice(0, -4) } return { user, project, committish: url.hash.slice(1) } }, hashformat: function (fragment) { return fragment && 'file-' + formatHashFragment(fragment) }, } hosts.sourcehut = { protocols: ['git+ssh:', 'https:'], domain: 'git.sr.ht', treepath: 'tree', blobpath: 'tree', filetemplate: ({ domain, user, project, committish, path }) => `https://${domain}/${user}/${project}/blob/${maybeEncode(committish) || 'HEAD'}/${path}`, httpstemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/archive/${maybeEncode(committish) || 'HEAD'}.tar.gz`, bugstemplate: () => null, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) // tarball url if (['archive'].includes(aux)) { return } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } }, } for (const [name, host] of Object.entries(hosts)) { hosts[name] = Object.assign({}, defaults, host) } module.exports = hosts 'use strict' const { LRUCache } = require('lru-cache') const hosts = require('./hosts.js') const fromUrl = require('./from-url.js') const parseUrl = require('./parse-url.js') const cache = new LRUCache({ max: 1000 }) class GitHost { constructor (type, user, auth, project, committish, defaultRepresentation, opts = {}) { Object.assign(this, GitHost.#gitHosts[type], { type, user, auth, project, committish, default: defaultRepresentation, opts, }) } static #gitHosts = { byShortcut: {}, byDomain: {} } static #protocols = { 'git+ssh:': { name: 'sshurl' }, 'ssh:': { name: 'sshurl' }, 'git+https:': { name: 'https', auth: true }, 'git:': { auth: true }, 'http:': { auth: true }, 'https:': { auth: true }, 'git+http:': { auth: true }, } static addHost (name, host) { GitHost.#gitHosts[name] = host GitHost.#gitHosts.byDomain[host.domain] = name GitHost.#gitHosts.byShortcut[`${name}:`] = name GitHost.#protocols[`${name}:`] = { name } } static fromUrl (giturl, opts) { if (typeof giturl !== 'string') { return } const key = giturl + JSON.stringify(opts || {}) if (!cache.has(key)) { const hostArgs = fromUrl(giturl, opts, { gitHosts: GitHost.#gitHosts, protocols: GitHost.#protocols, }) cache.set(key, hostArgs ? new GitHost(...hostArgs) : undefined) } return cache.get(key) } static parseUrl (url) { return parseUrl(url) } #fill (template, opts) { if (typeof template !== 'function') { return null } const options = { ...this, ...this.opts, ...opts } // the path should always be set so we don't end up with 'undefined' in urls if (!options.path) { options.path = '' } // template functions will insert the leading slash themselves if (options.path.startsWith('/')) { options.path = options.path.slice(1) } if (options.noCommittish) { options.committish = null } const result = template(options) return options.noGitPlus && result.startsWith('git+') ? result.slice(4) : result } hash () { return this.committish ? `#${this.committish}` : '' } ssh (opts) { return this.#fill(this.sshtemplate, opts) } sshurl (opts) { return this.#fill(this.sshurltemplate, opts) } browse (path, ...args) { // not a string, treat path as opts if (typeof path !== 'string') { return this.#fill(this.browsetemplate, path) } if (typeof args[0] !== 'string') { return this.#fill(this.browsetreetemplate, { ...args[0], path }) } return this.#fill(this.browsetreetemplate, { ...args[1], fragment: args[0], path }) } // If the path is known to be a file, then browseFile should be used. For some hosts // the url is the same as browse, but for others like GitHub a file can use both `/tree/` // and `/blob/` in the path. When using a default committish of `HEAD` then the `/tree/` // path will redirect to a specific commit. Using the `/blob/` path avoids this and // does not redirect to a different commit. browseFile (path, ...args) { if (typeof args[0] !== 'string') { return this.#fill(this.browseblobtemplate, { ...args[0], path }) } return this.#fill(this.browseblobtemplate, { ...args[1], fragment: args[0], path }) } docs (opts) { return this.#fill(this.docstemplate, opts) } bugs (opts) { return this.#fill(this.bugstemplate, opts) } https (opts) { return this.#fill(this.httpstemplate, opts) } git (opts) { return this.#fill(this.gittemplate, opts) } shortcut (opts) { return this.#fill(this.shortcuttemplate, opts) } path (opts) { return this.#fill(this.pathtemplate, opts) } tarball (opts) { return this.#fill(this.tarballtemplate, { ...opts, noCommittish: false }) } file (path, opts) { return this.#fill(this.filetemplate, { ...opts, path }) } edit (path, opts) { return this.#fill(this.edittemplate, { ...opts, path }) } getDefaultRepresentation () { return this.default } toString (opts) { if (this.default && typeof this[this.default] === 'function') { return this[this.default](opts) } return this.sshurl(opts) } } for (const [name, host] of Object.entries(hosts)) { GitHost.addHost(name, host) } module.exports = GitHost const url = require('url') const lastIndexOfBefore = (str, char, beforeChar) => { const startPosition = str.indexOf(beforeChar) return str.lastIndexOf(char, startPosition > -1 ? startPosition : Infinity) } const safeUrl = (u) => { try { return new url.URL(u) } catch { // this fn should never throw } } // accepts input like git:github.com:user/repo and inserts the // after the first : const correctProtocol = (arg, protocols) => { const firstColon = arg.indexOf(':') const proto = arg.slice(0, firstColon + 1) if (Object.prototype.hasOwnProperty.call(protocols, proto)) { return arg } const firstAt = arg.indexOf('@') if (firstAt > -1) { if (firstAt > firstColon) { return `git+ssh://${arg}` } else { return arg } } const doubleSlash = arg.indexOf('//') if (doubleSlash === firstColon + 1) { return arg } return `${arg.slice(0, firstColon + 1)}//${arg.slice(firstColon + 1)}` } // attempt to correct an scp style url so that it will parse with `new URL()` const correctUrl = (giturl) => { // ignore @ that come after the first hash since the denotes the start // of a committish which can contain @ characters const firstAt = lastIndexOfBefore(giturl, '@', '#') // ignore colons that come after the hash since that could include colons such as: // git@github.com:user/package-2#semver:^1.0.0 const lastColonBeforeHash = lastIndexOfBefore(giturl, ':', '#') if (lastColonBeforeHash > firstAt) { // the last : comes after the first @ (or there is no @) // like it would in: // proto://hostname.com:user/repo // username@hostname.com:user/repo // :password@hostname.com:user/repo // username:password@hostname.com:user/repo // proto://username@hostname.com:user/repo // proto://:password@hostname.com:user/repo // proto://username:password@hostname.com:user/repo // then we replace the last : with a / to create a valid path giturl = giturl.slice(0, lastColonBeforeHash) + '/' + giturl.slice(lastColonBeforeHash + 1) } if (lastIndexOfBefore(giturl, ':', '#') === -1 && giturl.indexOf('//') === -1) { // we have no : at all // as it would be in: // username@hostname.com/user/repo // then we prepend a protocol giturl = `git+ssh://${giturl}` } return giturl } module.exports = (giturl, protocols) => { const withProtocol = protocols ? correctProtocol(giturl, protocols) : giturl return safeUrl(withProtocol) || safeUrl(correctUrl(withProtocol)) } { "name": "hosted-git-info", "version": "8.0.2", "description": "Provides metadata and conversions from repository urls for GitHub, Bitbucket and GitLab", "main": "./lib/index.js", "repository": { "type": "git", "url": "git+https://github.com/npm/hosted-git-info.git" }, "keywords": [ "git", "github", "bitbucket", "gitlab" ], "author": "GitHub Inc.", "license": "ISC", "bugs": { "url": "https://github.com/npm/hosted-git-info/issues" }, "homepage": "https://github.com/npm/hosted-git-info", "scripts": { "posttest": "npm run lint", "snap": "tap", "test": "tap", "test:coverage": "tap --coverage-report=html", "lint": "npm run eslint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "dependencies": { "lru-cache": "^10.0.1" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.4", "tap": "^16.0.1" }, "files": [ "bin/", "lib/" ], "engines": { "node": "^18.17.0 || >=20.5.0" }, "tap": { "color": 1, "coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.4", "publish": "true" } } Copyright 2016-2018 Kornel LesiÅ„ski Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 'use strict'; // rfc7231 6.1 const statusCodeCacheableByDefault = new Set([ 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501, ]); // This implementation does not understand partial responses (206) const understoodStatuses = new Set([ 200, 203, 204, 300, 301, 302, 303, 307, 308, 404, 405, 410, 414, 501, ]); const errorStatusCodes = new Set([ 500, 502, 503, 504, ]); const hopByHopHeaders = { date: true, // included, because we add Age update Date connection: true, 'keep-alive': true, 'proxy-authenticate': true, 'proxy-authorization': true, te: true, trailer: true, 'transfer-encoding': true, upgrade: true, }; const excludedFromRevalidationUpdate = { // Since the old body is reused, it doesn't make sense to change properties of the body 'content-length': true, 'content-encoding': true, 'transfer-encoding': true, 'content-range': true, }; function toNumberOrZero(s) { const n = parseInt(s, 10); return isFinite(n) ? n : 0; } // RFC 5861 function isErrorResponse(response) { // consider undefined response as faulty if(!response) { return true } return errorStatusCodes.has(response.status); } function parseCacheControl(header) { const cc = {}; if (!header) return cc; // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale const parts = header.trim().split(/,/); for (const part of parts) { const [k, v] = part.split(/=/, 2); cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); } return cc; } function formatCacheControl(cc) { let parts = []; for (const k in cc) { const v = cc[k]; parts.push(v === true ? k : k + '=' + v); } if (!parts.length) { return undefined; } return parts.join(', '); } module.exports = class CachePolicy { constructor( req, res, { shared, cacheHeuristic, immutableMinTimeToLive, ignoreCargoCult, _fromObject, } = {} ) { if (_fromObject) { this._fromObject(_fromObject); return; } if (!res || !res.headers) { throw Error('Response headers missing'); } this._assertRequestHasHeaders(req); this._responseTime = this.now(); this._isShared = shared !== false; this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE this._immutableMinTtl = undefined !== immutableMinTimeToLive ? immutableMinTimeToLive : 24 * 3600 * 1000; this._status = 'status' in res ? res.status : 200; this._resHeaders = res.headers; this._rescc = parseCacheControl(res.headers['cache-control']); this._method = 'method' in req ? req.method : 'GET'; this._url = req.url; this._host = req.headers.host; this._noAuthorization = !req.headers.authorization; this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used this._reqcc = parseCacheControl(req.headers['cache-control']); // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, // so there's no point stricly adhering to the blindly copy&pasted directives. if ( ignoreCargoCult && 'pre-check' in this._rescc && 'post-check' in this._rescc ) { delete this._rescc['pre-check']; delete this._rescc['post-check']; delete this._rescc['no-cache']; delete this._rescc['no-store']; delete this._rescc['must-revalidate']; this._resHeaders = Object.assign({}, this._resHeaders, { 'cache-control': formatCacheControl(this._rescc), }); delete this._resHeaders.expires; delete this._resHeaders.pragma; } // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). if ( res.headers['cache-control'] == null && /no-cache/.test(res.headers.pragma) ) { this._rescc['no-cache'] = true; } } now() { return Date.now(); } storable() { // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. return !!( !this._reqcc['no-store'] && // A cache MUST NOT store a response to any request, unless: // The request method is understood by the cache and defined as being cacheable, and ('GET' === this._method || 'HEAD' === this._method || ('POST' === this._method && this._hasExplicitExpiration())) && // the response status code is understood by the cache, and understoodStatuses.has(this._status) && // the "no-store" cache directive does not appear in request or response header fields, and !this._rescc['no-store'] && // the "private" response directive does not appear in the response, if the cache is shared, and (!this._isShared || !this._rescc.private) && // the Authorization header field does not appear in the request, if the cache is shared, (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && // the response either: // contains an Expires header field, or (this._resHeaders.expires || // contains a max-age response directive, or // contains a s-maxage response directive and the cache is shared, or // contains a public response directive. this._rescc['max-age'] || (this._isShared && this._rescc['s-maxage']) || this._rescc.public || // has a status code that is defined as cacheable by default statusCodeCacheableByDefault.has(this._status)) ); } _hasExplicitExpiration() { // 4.2.1 Calculating Freshness Lifetime return ( (this._isShared && this._rescc['s-maxage']) || this._rescc['max-age'] || this._resHeaders.expires ); } _assertRequestHasHeaders(req) { if (!req || !req.headers) { throw Error('Request headers missing'); } } satisfiesWithoutRevalidation(req) { this._assertRequestHasHeaders(req); // When presented with a request, a cache MUST NOT reuse a stored response, unless: // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, // unless the stored response is successfully validated (Section 4.3), and const requestCC = parseCacheControl(req.headers['cache-control']); if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { return false; } if (requestCC['max-age'] && this.age() > requestCC['max-age']) { return false; } if ( requestCC['min-fresh'] && this.timeToLive() < 1000 * requestCC['min-fresh'] ) { return false; } // the stored response is either: // fresh, or allowed to be served stale if (this.stale()) { const allowsStale = requestCC['max-stale'] && !this._rescc['must-revalidate'] && (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge()); if (!allowsStale) { return false; } } return this._requestMatches(req, false); } _requestMatches(req, allowHeadMethod) { // The presented effective request URI and that of the stored response match, and return ( (!this._url || this._url === req.url) && this._host === req.headers.host && // the request method associated with the stored response allows it to be used for the presented request, and (!req.method || this._method === req.method || (allowHeadMethod && 'HEAD' === req.method)) && // selecting header fields nominated by the stored response (if any) match those presented, and this._varyMatches(req) ); } _allowsStoringAuthenticated() { // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. return ( this._rescc['must-revalidate'] || this._rescc.public || this._rescc['s-maxage'] ); } _varyMatches(req) { if (!this._resHeaders.vary) { return true; } // A Vary header field-value of "*" always fails to match if (this._resHeaders.vary === '*') { return false; } const fields = this._resHeaders.vary .trim() .toLowerCase() .split(/\s*,\s*/); for (const name of fields) { if (req.headers[name] !== this._reqHeaders[name]) return false; } return true; } _copyWithoutHopByHopHeaders(inHeaders) { const headers = {}; for (const name in inHeaders) { if (hopByHopHeaders[name]) continue; headers[name] = inHeaders[name]; } // 9.1. Connection if (inHeaders.connection) { const tokens = inHeaders.connection.trim().split(/\s*,\s*/); for (const name of tokens) { delete headers[name]; } } if (headers.warning) { const warnings = headers.warning.split(/,/).filter(warning => { return !/^\s*1[0-9][0-9]/.test(warning); }); if (!warnings.length) { delete headers.warning; } else { headers.warning = warnings.join(',').trim(); } } return headers; } responseHeaders() { const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); const age = this.age(); // A cache SHOULD generate 113 warning if it heuristically chose a freshness // lifetime greater than 24 hours and the response's age is greater than 24 hours. if ( age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24 ) { headers.warning = (headers.warning ? `${headers.warning}, ` : '') + '113 - "rfc7234 5.5.4"'; } headers.age = `${Math.round(age)}`; headers.date = new Date(this.now()).toUTCString(); return headers; } /** * Value of the Date response header or current time if Date was invalid * @return timestamp */ date() { const serverDate = Date.parse(this._resHeaders.date); if (isFinite(serverDate)) { return serverDate; } return this._responseTime; } /** * Value of the Age header, in seconds, updated for the current time. * May be fractional. * * @return Number */ age() { let age = this._ageValue(); const residentTime = (this.now() - this._responseTime) / 1000; return age + residentTime; } _ageValue() { return toNumberOrZero(this._resHeaders.age); } /** * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. * * For an up-to-date value, see `timeToLive()`. * * @return Number */ maxAge() { if (!this.storable() || this._rescc['no-cache']) { return 0; } // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default // so this implementation requires explicit opt-in via public header if ( this._isShared && (this._resHeaders['set-cookie'] && !this._rescc.public && !this._rescc.immutable) ) { return 0; } if (this._resHeaders.vary === '*') { return 0; } if (this._isShared) { if (this._rescc['proxy-revalidate']) { return 0; } // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. if (this._rescc['s-maxage']) { return toNumberOrZero(this._rescc['s-maxage']); } } // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. if (this._rescc['max-age']) { return toNumberOrZero(this._rescc['max-age']); } const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; const serverDate = this.date(); if (this._resHeaders.expires) { const expires = Date.parse(this._resHeaders.expires); // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). if (Number.isNaN(expires) || expires < serverDate) { return 0; } return Math.max(defaultMinTtl, (expires - serverDate) / 1000); } if (this._resHeaders['last-modified']) { const lastModified = Date.parse(this._resHeaders['last-modified']); if (isFinite(lastModified) && serverDate > lastModified) { return Math.max( defaultMinTtl, ((serverDate - lastModified) / 1000) * this._cacheHeuristic ); } } return defaultMinTtl; } timeToLive() { const age = this.maxAge() - this.age(); const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; } stale() { return this.maxAge() <= this.age(); } _useStaleIfError() { return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); } useStaleWhileRevalidate() { return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); } static fromObject(obj) { return new this(undefined, undefined, { _fromObject: obj }); } _fromObject(obj) { if (this._responseTime) throw Error('Reinitialized'); if (!obj || obj.v !== 1) throw Error('Invalid serialization'); this._responseTime = obj.t; this._isShared = obj.sh; this._cacheHeuristic = obj.ch; this._immutableMinTtl = obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; this._status = obj.st; this._resHeaders = obj.resh; this._rescc = obj.rescc; this._method = obj.m; this._url = obj.u; this._host = obj.h; this._noAuthorization = obj.a; this._reqHeaders = obj.reqh; this._reqcc = obj.reqcc; } toObject() { return { v: 1, t: this._responseTime, sh: this._isShared, ch: this._cacheHeuristic, imm: this._immutableMinTtl, st: this._status, resh: this._resHeaders, rescc: this._rescc, m: this._method, u: this._url, h: this._host, a: this._noAuthorization, reqh: this._reqHeaders, reqcc: this._reqcc, }; } /** * Headers for sending to the origin server to revalidate stale response. * Allows server to return 304 to allow reuse of the previous response. * * Hop by hop headers are always stripped. * Revalidation headers may be added or removed, depending on request. */ revalidationHeaders(incomingReq) { this._assertRequestHasHeaders(incomingReq); const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); // This implementation does not understand range requests delete headers['if-range']; if (!this._requestMatches(incomingReq, true) || !this.storable()) { // revalidation allowed via HEAD // not for the same resource, or wasn't allowed to be cached anyway delete headers['if-none-match']; delete headers['if-modified-since']; return headers; } /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ if (this._resHeaders.etag) { headers['if-none-match'] = headers['if-none-match'] ? `${headers['if-none-match']}, ${this._resHeaders.etag}` : this._resHeaders.etag; } // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. const forbidsWeakValidators = headers['accept-ranges'] || headers['if-match'] || headers['if-unmodified-since'] || (this._method && this._method != 'GET'); /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. Note: This implementation does not understand partial responses (206) */ if (forbidsWeakValidators) { delete headers['if-modified-since']; if (headers['if-none-match']) { const etags = headers['if-none-match'] .split(/,/) .filter(etag => { return !/^\s*W\//.test(etag); }); if (!etags.length) { delete headers['if-none-match']; } else { headers['if-none-match'] = etags.join(',').trim(); } } } else if ( this._resHeaders['last-modified'] && !headers['if-modified-since'] ) { headers['if-modified-since'] = this._resHeaders['last-modified']; } return headers; } /** * Creates new CachePolicy with information combined from the previews response, * and the new revalidation response. * * Returns {policy, modified} where modified is a boolean indicating * whether the response body has been modified, and old cached body can't be used. * * @return {Object} {policy: CachePolicy, modified: Boolean} */ revalidatedPolicy(request, response) { this._assertRequestHasHeaders(request); if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful return { modified: false, matches: false, policy: this, }; } if (!response || !response.headers) { throw Error('Response headers missing'); } // These aren't going to be supported exactly, since one CachePolicy object // doesn't know about all the other cached objects. let matches = false; if (response.status !== undefined && response.status != 304) { matches = false; } else if ( response.headers.etag && !/^\s*W\//.test(response.headers.etag) ) { // "All of the stored responses with the same strong validator are selected. // If none of the stored responses contain the same strong validator, // then the cache MUST NOT use the new response to update any stored responses." matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag; } else if (this._resHeaders.etag && response.headers.etag) { // "If the new response contains a weak validator and that validator corresponds // to one of the cache's stored responses, // then the most recent of those matching stored responses is selected for update." matches = this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag.replace(/^\s*W\//, ''); } else if (this._resHeaders['last-modified']) { matches = this._resHeaders['last-modified'] === response.headers['last-modified']; } else { // If the new response does not include any form of validator (such as in the case where // a client generates an If-Modified-Since request from a source other than the Last-Modified // response header field), and there is only one stored response, and that stored response also // lacks a validator, then that stored response is selected for update. if ( !this._resHeaders.etag && !this._resHeaders['last-modified'] && !response.headers.etag && !response.headers['last-modified'] ) { matches = true; } } if (!matches) { return { policy: new this.constructor(request, response), // Client receiving 304 without body, even if it's invalid/mismatched has no option // but to reuse a cached body. We don't have a good way to tell clients to do // error recovery in such case. modified: response.status != 304, matches: false, }; } // use other header fields provided in the 304 (Not Modified) response to replace all instances // of the corresponding header fields in the stored response. const headers = {}; for (const k in this._resHeaders) { headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k]; } const newResponse = Object.assign({}, response, { status: this._status, method: this._method, headers, }); return { policy: new this.constructor(request, newResponse, { shared: this._isShared, cacheHeuristic: this._cacheHeuristic, immutableMinTimeToLive: this._immutableMinTtl, }), modified: false, matches: true, }; } }; { "name": "http-cache-semantics", "version": "4.1.1", "description": "Parses Cache-Control and other headers. Helps building correct HTTP caches and proxies", "repository": "https://github.com/kornelski/http-cache-semantics.git", "main": "index.js", "scripts": { "test": "mocha" }, "files": [ "index.js" ], "author": "Kornel LesiÅ„ski (https://kornel.ski/)", "license": "BSD-2-Clause", "devDependencies": { "mocha": "^10.0" } } (The MIT License) Copyright (c) 2013 Nathan Rajlich 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. "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpProxyAgent = void 0; const net = __importStar(require("net")); const tls = __importStar(require("tls")); const debug_1 = __importDefault(require("debug")); const events_1 = require("events"); const agent_base_1 = require("agent-base"); const url_1 = require("url"); const debug = (0, debug_1.default)('http-proxy-agent'); /** * The `HttpProxyAgent` implements an HTTP Agent subclass that connects * to the specified "HTTP proxy server" in order to proxy HTTP requests. */ class HttpProxyAgent extends agent_base_1.Agent { constructor(proxy, opts) { super(opts); this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; this.proxyHeaders = opts?.headers ?? {}; debug('Creating new HttpProxyAgent instance: %o', this.proxy.href); // Trim off the brackets from IPv6 addresses const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === 'https:' ? 443 : 80; this.connectOpts = { ...(opts ? omit(opts, 'headers') : null), host, port, }; } addRequest(req, opts) { req._header = null; this.setRequestProps(req, opts); // @ts-expect-error `addRequest()` isn't defined in `@types/node` super.addRequest(req, opts); } setRequestProps(req, opts) { const { proxy } = this; const protocol = opts.secureEndpoint ? 'https:' : 'http:'; const hostname = req.getHeader('host') || 'localhost'; const base = `${protocol}//${hostname}`; const url = new url_1.URL(req.path, base); if (opts.port !== 80) { url.port = String(opts.port); } // Change the `http.ClientRequest` instance's "path" field // to the absolute path of the URL that will be requested. req.path = String(url); // Inject the `Proxy-Authorization` header if necessary. const headers = typeof this.proxyHeaders === 'function' ? this.proxyHeaders() : { ...this.proxyHeaders }; if (proxy.username || proxy.password) { const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; } if (!headers['Proxy-Connection']) { headers['Proxy-Connection'] = this.keepAlive ? 'Keep-Alive' : 'close'; } for (const name of Object.keys(headers)) { const value = headers[name]; if (value) { req.setHeader(name, value); } } } async connect(req, opts) { req._header = null; if (!req.path.includes('://')) { this.setRequestProps(req, opts); } // At this point, the http ClientRequest's internal `_header` field // might have already been set. If this is the case then we'll need // to re-generate the string since we just changed the `req.path`. let first; let endOfHeaders; debug('Regenerating stored HTTP header string for request'); req._implicitHeader(); if (req.outputData && req.outputData.length > 0) { debug('Patching connection write() output buffer with updated header'); first = req.outputData[0].data; endOfHeaders = first.indexOf('\r\n\r\n') + 4; req.outputData[0].data = req._header + first.substring(endOfHeaders); debug('Output buffer: %o', req.outputData[0].data); } // Create a socket connection to the proxy server. let socket; if (this.proxy.protocol === 'https:') { debug('Creating `tls.Socket`: %o', this.connectOpts); socket = tls.connect(this.connectOpts); } else { debug('Creating `net.Socket`: %o', this.connectOpts); socket = net.connect(this.connectOpts); } // Wait for the socket's `connect` event, so that this `callback()` // function throws instead of the `http` request machinery. This is // important for i.e. `PacProxyAgent` which determines a failed proxy // connection via the `callback()` function throwing. await (0, events_1.once)(socket, 'connect'); return socket; } } HttpProxyAgent.protocols = ['http', 'https']; exports.HttpProxyAgent = HttpProxyAgent; function omit(obj, ...keys) { const ret = {}; let key; for (key in obj) { if (!keys.includes(key)) { ret[key] = obj[key]; } } return ret; } //# sourceMappingURL=index.js.map{ "name": "http-proxy-agent", "version": "7.0.2", "description": "An HTTP(s) proxy `http.Agent` implementation for HTTP", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist" ], "repository": { "type": "git", "url": "https://github.com/TooTallNate/proxy-agents.git", "directory": "packages/http-proxy-agent" }, "keywords": [ "http", "proxy", "endpoint", "agent" ], "author": "Nathan Rajlich (http://n8.io/)", "license": "MIT", "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" }, "devDependencies": { "@types/debug": "^4.1.7", "@types/jest": "^29.5.1", "@types/node": "^14.18.45", "async-listen": "^3.0.0", "jest": "^29.5.0", "ts-jest": "^29.1.0", "typescript": "^5.0.4", "proxy": "2.1.1", "tsconfig": "0.0.0" }, "engines": { "node": ">= 14" }, "scripts": { "build": "tsc", "test": "jest --env node --verbose --bail", "lint": "eslint . --ext .ts", "pack": "node ../../scripts/pack.mjs" } }(The MIT License) Copyright (c) 2013 Nathan Rajlich 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."use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpsProxyAgent = void 0; const net = __importStar(require("net")); const tls = __importStar(require("tls")); const assert_1 = __importDefault(require("assert")); const debug_1 = __importDefault(require("debug")); const agent_base_1 = require("agent-base"); const url_1 = require("url"); const parse_proxy_response_1 = require("./parse-proxy-response"); const debug = (0, debug_1.default)('https-proxy-agent'); const setServernameFromNonIpHost = (options) => { if (options.servername === undefined && options.host && !net.isIP(options.host)) { return { ...options, servername: options.host, }; } return options; }; /** * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. * * Outgoing HTTP requests are first tunneled through the proxy server using the * `CONNECT` HTTP request method to establish a connection to the proxy server, * and then the proxy server connects to the destination target and issues the * HTTP request from the proxy server. * * `https:` requests have their socket connection upgraded to TLS once * the connection to the proxy server has been established. */ class HttpsProxyAgent extends agent_base_1.Agent { constructor(proxy, opts) { super(opts); this.options = { path: undefined }; this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; this.proxyHeaders = opts?.headers ?? {}; debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); // Trim off the brackets from IPv6 addresses const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === 'https:' ? 443 : 80; this.connectOpts = { // Attempt to negotiate http/1.1 for proxy servers that support http/2 ALPNProtocols: ['http/1.1'], ...(opts ? omit(opts, 'headers') : null), host, port, }; } /** * Called when the node-core HTTP client library is creating a * new HTTP request. */ async connect(req, opts) { const { proxy } = this; if (!opts.host) { throw new TypeError('No "host" provided'); } // Create a socket connection to the proxy server. let socket; if (proxy.protocol === 'https:') { debug('Creating `tls.Socket`: %o', this.connectOpts); socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); } else { debug('Creating `net.Socket`: %o', this.connectOpts); socket = net.connect(this.connectOpts); } const headers = typeof this.proxyHeaders === 'function' ? this.proxyHeaders() : { ...this.proxyHeaders }; const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; // Inject the `Proxy-Authorization` header if necessary. if (proxy.username || proxy.password) { const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; } headers.Host = `${host}:${opts.port}`; if (!headers['Proxy-Connection']) { headers['Proxy-Connection'] = this.keepAlive ? 'Keep-Alive' : 'close'; } for (const name of Object.keys(headers)) { payload += `${name}: ${headers[name]}\r\n`; } const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); socket.write(`${payload}\r\n`); const { connect, buffered } = await proxyResponsePromise; req.emit('proxyConnect', connect); this.emit('proxyConnect', connect, req); if (connect.statusCode === 200) { req.once('socket', resume); if (opts.secureEndpoint) { // The proxy is connecting to a TLS server, so upgrade // this socket connection to a TLS connection. debug('Upgrading socket connection to TLS'); return tls.connect({ ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), socket, }); } return socket; } // Some other status code that's not 200... need to re-play the HTTP // header "data" events onto the socket once the HTTP machinery is // attached so that the node core `http` can parse and handle the // error status code. // Close the original socket, and a new "fake" socket is returned // instead, so that the proxy doesn't get the HTTP request // written to it (which may contain `Authorization` headers or other // sensitive data). // // See: https://hackerone.com/reports/541502 socket.destroy(); const fakeSocket = new net.Socket({ writable: false }); fakeSocket.readable = true; // Need to wait for the "socket" event to re-play the "data" events. req.once('socket', (s) => { debug('Replaying proxy buffer for failed request'); (0, assert_1.default)(s.listenerCount('data') > 0); // Replay the "buffered" Buffer onto the fake `socket`, since at // this point the HTTP module machinery has been hooked up for // the user. s.push(buffered); s.push(null); }); return fakeSocket; } } HttpsProxyAgent.protocols = ['http', 'https']; exports.HttpsProxyAgent = HttpsProxyAgent; function resume(socket) { socket.resume(); } function omit(obj, ...keys) { const ret = {}; let key; for (key in obj) { if (!keys.includes(key)) { ret[key] = obj[key]; } } return ret; } //# sourceMappingURL=index.js.map"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseProxyResponse = void 0; const debug_1 = __importDefault(require("debug")); const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); function parseProxyResponse(socket) { return new Promise((resolve, reject) => { // we need to buffer any HTTP traffic that happens with the proxy before we get // the CONNECT response, so that if the response is anything other than an "200" // response code, then we can re-play the "data" events on the socket once the // HTTP parser is hooked up... let buffersLength = 0; const buffers = []; function read() { const b = socket.read(); if (b) ondata(b); else socket.once('readable', read); } function cleanup() { socket.removeListener('end', onend); socket.removeListener('error', onerror); socket.removeListener('readable', read); } function onend() { cleanup(); debug('onend'); reject(new Error('Proxy connection ended before receiving CONNECT response')); } function onerror(err) { cleanup(); debug('onerror %o', err); reject(err); } function ondata(b) { buffers.push(b); buffersLength += b.length; const buffered = Buffer.concat(buffers, buffersLength); const endOfHeaders = buffered.indexOf('\r\n\r\n'); if (endOfHeaders === -1) { // keep buffering debug('have not received end of HTTP headers yet...'); read(); return; } const headerParts = buffered .slice(0, endOfHeaders) .toString('ascii') .split('\r\n'); const firstLine = headerParts.shift(); if (!firstLine) { socket.destroy(); return reject(new Error('No header received from proxy CONNECT response')); } const firstLineParts = firstLine.split(' '); const statusCode = +firstLineParts[1]; const statusText = firstLineParts.slice(2).join(' '); const headers = {}; for (const header of headerParts) { if (!header) continue; const firstColon = header.indexOf(':'); if (firstColon === -1) { socket.destroy(); return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); } const key = header.slice(0, firstColon).toLowerCase(); const value = header.slice(firstColon + 1).trimStart(); const current = headers[key]; if (typeof current === 'string') { headers[key] = [current, value]; } else if (Array.isArray(current)) { current.push(value); } else { headers[key] = value; } } debug('got proxy server response: %o %o', firstLine, headers); cleanup(); resolve({ connect: { statusCode, statusText, headers, }, buffered, }); } socket.on('error', onerror); socket.on('end', onend); read(); }); } exports.parseProxyResponse = parseProxyResponse; //# sourceMappingURL=parse-proxy-response.js.map{ "name": "https-proxy-agent", "version": "7.0.6", "description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist" ], "repository": { "type": "git", "url": "https://github.com/TooTallNate/proxy-agents.git", "directory": "packages/https-proxy-agent" }, "keywords": [ "https", "proxy", "endpoint", "agent" ], "author": "Nathan Rajlich (http://n8.io/)", "license": "MIT", "dependencies": { "agent-base": "^7.1.2", "debug": "4" }, "devDependencies": { "@types/async-retry": "^1.4.5", "@types/debug": "4", "@types/jest": "^29.5.1", "@types/node": "^14.18.45", "async-listen": "^3.0.0", "async-retry": "^1.3.3", "jest": "^29.5.0", "ts-jest": "^29.1.0", "typescript": "^5.0.4", "proxy": "2.2.0", "tsconfig": "0.0.0" }, "engines": { "node": ">= 14" }, "scripts": { "build": "tsc", "test": "jest --env node --verbose --bail test/test.ts", "test-e2e": "jest --env node --verbose --bail test/e2e.test.ts", "lint": "eslint --ext .ts", "pack": "node ../../scripts/pack.mjs" } }Copyright (c) 2011 Alexander Shtuchkin 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. "use strict"; var Buffer = require("safer-buffer").Buffer; // Multibyte codec. In this scheme, a character is represented by 1 or more bytes. // Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. // To save memory and loading time, we read table files only when requested. exports._dbcs = DBCSCodec; var UNASSIGNED = -1, GB18030_CODE = -2, SEQ_START = -10, NODE_START = -1000, UNASSIGNED_NODE = new Array(0x100), DEF_CHAR = -1; for (var i = 0; i < 0x100; i++) UNASSIGNED_NODE[i] = UNASSIGNED; // Class DBCSCodec reads and initializes mapping tables. function DBCSCodec(codecOptions, iconv) { this.encodingName = codecOptions.encodingName; if (!codecOptions) throw new Error("DBCS codec is called without the data.") if (!codecOptions.table) throw new Error("Encoding '" + this.encodingName + "' has no data."); // Load tables. var mappingTable = codecOptions.table(); // Decode tables: MBCS -> Unicode. // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. // Trie root is decodeTables[0]. // Values: >= 0 -> unicode character code. can be > 0xFFFF // == UNASSIGNED -> unknown/unassigned sequence. // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. // <= NODE_START -> index of the next node in our trie to process next byte. // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. this.decodeTables = []; this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. this.decodeTableSeq = []; // Actual mapping tables consist of chunks. Use them to fill up decode tables. for (var i = 0; i < mappingTable.length; i++) this._addDecodeChunk(mappingTable[i]); // Load & create GB18030 tables when needed. if (typeof codecOptions.gb18030 === 'function') { this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. // Add GB18030 common decode nodes. var commonThirdByteNodeIdx = this.decodeTables.length; this.decodeTables.push(UNASSIGNED_NODE.slice(0)); var commonFourthByteNodeIdx = this.decodeTables.length; this.decodeTables.push(UNASSIGNED_NODE.slice(0)); // Fill out the tree var firstByteNode = this.decodeTables[0]; for (var i = 0x81; i <= 0xFE; i++) { var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]]; for (var j = 0x30; j <= 0x39; j++) { if (secondByteNode[j] === UNASSIGNED) { secondByteNode[j] = NODE_START - commonThirdByteNodeIdx; } else if (secondByteNode[j] > NODE_START) { throw new Error("gb18030 decode tables conflict at byte 2"); } var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]]; for (var k = 0x81; k <= 0xFE; k++) { if (thirdByteNode[k] === UNASSIGNED) { thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx; } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) { continue; } else if (thirdByteNode[k] > NODE_START) { throw new Error("gb18030 decode tables conflict at byte 3"); } var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]]; for (var l = 0x30; l <= 0x39; l++) { if (fourthByteNode[l] === UNASSIGNED) fourthByteNode[l] = GB18030_CODE; } } } } } this.defaultCharUnicode = iconv.defaultCharUnicode; // Encode tables: Unicode -> DBCS. // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). // == UNASSIGNED -> no conversion found. Output a default char. // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. this.encodeTable = []; // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key // means end of sequence (needed when one sequence is a strict subsequence of another). // Objects are kept separately from encodeTable to increase performance. this.encodeTableSeq = []; // Some chars can be decoded, but need not be encoded. var skipEncodeChars = {}; if (codecOptions.encodeSkipVals) for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { var val = codecOptions.encodeSkipVals[i]; if (typeof val === 'number') skipEncodeChars[val] = true; else for (var j = val.from; j <= val.to; j++) skipEncodeChars[j] = true; } // Use decode trie to recursively fill out encode tables. this._fillEncodeTable(0, 0, skipEncodeChars); // Add more encoding pairs when needed. if (codecOptions.encodeAdd) { for (var uChar in codecOptions.encodeAdd) if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); } DBCSCodec.prototype.encoder = DBCSEncoder; DBCSCodec.prototype.decoder = DBCSDecoder; // Decoder helpers DBCSCodec.prototype._getDecodeTrieNode = function(addr) { var bytes = []; for (; addr > 0; addr >>>= 8) bytes.push(addr & 0xFF); if (bytes.length == 0) bytes.push(0); var node = this.decodeTables[0]; for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. var val = node[bytes[i]]; if (val == UNASSIGNED) { // Create new node. node[bytes[i]] = NODE_START - this.decodeTables.length; this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); } else if (val <= NODE_START) { // Existing node. node = this.decodeTables[NODE_START - val]; } else throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); } return node; } DBCSCodec.prototype._addDecodeChunk = function(chunk) { // First element of chunk is the hex mbcs code where we start. var curAddr = parseInt(chunk[0], 16); // Choose the decoding node where we'll write our chars. var writeTable = this._getDecodeTrieNode(curAddr); curAddr = curAddr & 0xFF; // Write all other elements of the chunk to the table. for (var k = 1; k < chunk.length; k++) { var part = chunk[k]; if (typeof part === "string") { // String, write as-is. for (var l = 0; l < part.length;) { var code = part.charCodeAt(l++); if (0xD800 <= code && code < 0xDC00) { // Decode surrogate var codeTrail = part.charCodeAt(l++); if (0xDC00 <= codeTrail && codeTrail < 0xE000) writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); else throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); } else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) var len = 0xFFF - code + 2; var seq = []; for (var m = 0; m < len; m++) seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; this.decodeTableSeq.push(seq); } else writeTable[curAddr++] = code; // Basic char } } else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. var charCode = writeTable[curAddr - 1] + 1; for (var l = 0; l < part; l++) writeTable[curAddr++] = charCode++; } else throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); } if (curAddr > 0xFF) throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); } // Encoder helpers DBCSCodec.prototype._getEncodeBucket = function(uCode) { var high = uCode >> 8; // This could be > 0xFF because of astral characters. if (this.encodeTable[high] === undefined) this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. return this.encodeTable[high]; } DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { var bucket = this._getEncodeBucket(uCode); var low = uCode & 0xFF; if (bucket[low] <= SEQ_START) this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. else if (bucket[low] == UNASSIGNED) bucket[low] = dbcsCode; } DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { // Get the root of character tree according to first character of the sequence. var uCode = seq[0]; var bucket = this._getEncodeBucket(uCode); var low = uCode & 0xFF; var node; if (bucket[low] <= SEQ_START) { // There's already a sequence with - use it. node = this.encodeTableSeq[SEQ_START-bucket[low]]; } else { // There was no sequence object - allocate a new one. node = {}; if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. bucket[low] = SEQ_START - this.encodeTableSeq.length; this.encodeTableSeq.push(node); } // Traverse the character tree, allocating new nodes as needed. for (var j = 1; j < seq.length-1; j++) { var oldVal = node[uCode]; if (typeof oldVal === 'object') node = oldVal; else { node = node[uCode] = {} if (oldVal !== undefined) node[DEF_CHAR] = oldVal } } // Set the leaf to given dbcsCode. uCode = seq[seq.length-1]; node[uCode] = dbcsCode; } DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { var node = this.decodeTables[nodeIdx]; var hasValues = false; var subNodeEmpty = {}; for (var i = 0; i < 0x100; i++) { var uCode = node[i]; var mbCode = prefix + i; if (skipEncodeChars[mbCode]) continue; if (uCode >= 0) { this._setEncodeChar(uCode, mbCode); hasValues = true; } else if (uCode <= NODE_START) { var subNodeIdx = NODE_START - uCode; if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030). var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive. if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) hasValues = true; else subNodeEmpty[subNodeIdx] = true; } } else if (uCode <= SEQ_START) { this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); hasValues = true; } } return hasValues; } // == Encoder ================================================================== function DBCSEncoder(options, codec) { // Encoder state this.leadSurrogate = -1; this.seqObj = undefined; // Static data this.encodeTable = codec.encodeTable; this.encodeTableSeq = codec.encodeTableSeq; this.defaultCharSingleByte = codec.defCharSB; this.gb18030 = codec.gb18030; } DBCSEncoder.prototype.write = function(str) { var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), leadSurrogate = this.leadSurrogate, seqObj = this.seqObj, nextChar = -1, i = 0, j = 0; while (true) { // 0. Get next character. if (nextChar === -1) { if (i == str.length) break; var uCode = str.charCodeAt(i++); } else { var uCode = nextChar; nextChar = -1; } // 1. Handle surrogates. if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. if (uCode < 0xDC00) { // We've got lead surrogate. if (leadSurrogate === -1) { leadSurrogate = uCode; continue; } else { leadSurrogate = uCode; // Double lead surrogate found. uCode = UNASSIGNED; } } else { // We've got trail surrogate. if (leadSurrogate !== -1) { uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); leadSurrogate = -1; } else { // Incomplete surrogate pair - only trail surrogate found. uCode = UNASSIGNED; } } } else if (leadSurrogate !== -1) { // Incomplete surrogate pair - only lead surrogate found. nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. leadSurrogate = -1; } // 2. Convert uCode character. var dbcsCode = UNASSIGNED; if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence var resCode = seqObj[uCode]; if (typeof resCode === 'object') { // Sequence continues. seqObj = resCode; continue; } else if (typeof resCode == 'number') { // Sequence finished. Write it. dbcsCode = resCode; } else if (resCode == undefined) { // Current character is not part of the sequence. // Try default character for this sequence resCode = seqObj[DEF_CHAR]; if (resCode !== undefined) { dbcsCode = resCode; // Found. Write it. nextChar = uCode; // Current character will be written too in the next iteration. } else { // TODO: What if we have no default? (resCode == undefined) // Then, we should write first char of the sequence as-is and try the rest recursively. // Didn't do it for now because no encoding has this situation yet. // Currently, just skip the sequence and write current char. } } seqObj = undefined; } else if (uCode >= 0) { // Regular character var subtable = this.encodeTable[uCode >> 8]; if (subtable !== undefined) dbcsCode = subtable[uCode & 0xFF]; if (dbcsCode <= SEQ_START) { // Sequence start seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; continue; } if (dbcsCode == UNASSIGNED && this.gb18030) { // Use GB18030 algorithm to find character(s) to write. var idx = findIdx(this.gb18030.uChars, uCode); if (idx != -1) { var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; newBuf[j++] = 0x30 + dbcsCode; continue; } } } // 3. Write dbcsCode character. if (dbcsCode === UNASSIGNED) dbcsCode = this.defaultCharSingleByte; if (dbcsCode < 0x100) { newBuf[j++] = dbcsCode; } else if (dbcsCode < 0x10000) { newBuf[j++] = dbcsCode >> 8; // high byte newBuf[j++] = dbcsCode & 0xFF; // low byte } else if (dbcsCode < 0x1000000) { newBuf[j++] = dbcsCode >> 16; newBuf[j++] = (dbcsCode >> 8) & 0xFF; newBuf[j++] = dbcsCode & 0xFF; } else { newBuf[j++] = dbcsCode >>> 24; newBuf[j++] = (dbcsCode >>> 16) & 0xFF; newBuf[j++] = (dbcsCode >>> 8) & 0xFF; newBuf[j++] = dbcsCode & 0xFF; } } this.seqObj = seqObj; this.leadSurrogate = leadSurrogate; return newBuf.slice(0, j); } DBCSEncoder.prototype.end = function() { if (this.leadSurrogate === -1 && this.seqObj === undefined) return; // All clean. Most often case. var newBuf = Buffer.alloc(10), j = 0; if (this.seqObj) { // We're in the sequence. var dbcsCode = this.seqObj[DEF_CHAR]; if (dbcsCode !== undefined) { // Write beginning of the sequence. if (dbcsCode < 0x100) { newBuf[j++] = dbcsCode; } else { newBuf[j++] = dbcsCode >> 8; // high byte newBuf[j++] = dbcsCode & 0xFF; // low byte } } else { // See todo above. } this.seqObj = undefined; } if (this.leadSurrogate !== -1) { // Incomplete surrogate pair - only lead surrogate found. newBuf[j++] = this.defaultCharSingleByte; this.leadSurrogate = -1; } return newBuf.slice(0, j); } // Export for testing DBCSEncoder.prototype.findIdx = findIdx; // == Decoder ================================================================== function DBCSDecoder(options, codec) { // Decoder state this.nodeIdx = 0; this.prevBytes = []; // Static data this.decodeTables = codec.decodeTables; this.decodeTableSeq = codec.decodeTableSeq; this.defaultCharUnicode = codec.defaultCharUnicode; this.gb18030 = codec.gb18030; } DBCSDecoder.prototype.write = function(buf) { var newBuf = Buffer.alloc(buf.length*2), nodeIdx = this.nodeIdx, prevBytes = this.prevBytes, prevOffset = this.prevBytes.length, seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence. uCode; for (var i = 0, j = 0; i < buf.length; i++) { var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset]; // Lookup in current trie node. var uCode = this.decodeTables[nodeIdx][curByte]; if (uCode >= 0) { // Normal character, just use it. } else if (uCode === UNASSIGNED) { // Unknown char. // TODO: Callback with seq. uCode = this.defaultCharUnicode.charCodeAt(0); i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again. } else if (uCode === GB18030_CODE) { if (i >= 3) { var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30); } else { var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + (curByte-0x30); } var idx = findIdx(this.gb18030.gbChars, ptr); uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; } else if (uCode <= NODE_START) { // Go to next trie node. nodeIdx = NODE_START - uCode; continue; } else if (uCode <= SEQ_START) { // Output a sequence of chars. var seq = this.decodeTableSeq[SEQ_START - uCode]; for (var k = 0; k < seq.length - 1; k++) { uCode = seq[k]; newBuf[j++] = uCode & 0xFF; newBuf[j++] = uCode >> 8; } uCode = seq[seq.length-1]; } else throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); // Write the character to buffer, handling higher planes using surrogate pair. if (uCode >= 0x10000) { uCode -= 0x10000; var uCodeLead = 0xD800 | (uCode >> 10); newBuf[j++] = uCodeLead & 0xFF; newBuf[j++] = uCodeLead >> 8; uCode = 0xDC00 | (uCode & 0x3FF); } newBuf[j++] = uCode & 0xFF; newBuf[j++] = uCode >> 8; // Reset trie node. nodeIdx = 0; seqStart = i+1; } this.nodeIdx = nodeIdx; this.prevBytes = (seqStart >= 0) ? Array.prototype.slice.call(buf, seqStart) : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)); return newBuf.slice(0, j).toString('ucs2'); } DBCSDecoder.prototype.end = function() { var ret = ''; // Try to parse all remaining chars. while (this.prevBytes.length > 0) { // Skip 1 character in the buffer. ret += this.defaultCharUnicode; var bytesArr = this.prevBytes.slice(1); // Parse remaining as usual. this.prevBytes = []; this.nodeIdx = 0; if (bytesArr.length > 0) ret += this.write(bytesArr); } this.prevBytes = []; this.nodeIdx = 0; return ret; } // Binary search for GB18030. Returns largest i such that table[i] <= val. function findIdx(table, val) { if (table[0] > val) return -1; var l = 0, r = table.length; while (l < r-1) { // always table[l] <= val < table[r] var mid = l + ((r-l+1) >> 1); if (table[mid] <= val) l = mid; else r = mid; } return l; } "use strict"; // Description of supported double byte encodings and aliases. // Tables are not require()-d until they are needed to speed up library load. // require()-s are direct to support Browserify. module.exports = { // == Japanese/ShiftJIS ==================================================== // All japanese encodings are based on JIS X set of standards: // JIS X 0201 - Single-byte encoding of ASCII + Â¥ + Kana chars at 0xA1-0xDF. // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. // Has several variations in 1978, 1983, 1990 and 1997. // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. // 2 planes, first is superset of 0208, second - revised 0212. // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) // Byte encodings are: // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. // 0x00-0x7F - lower part of 0201 // 0x8E, 0xA1-0xDF - upper part of 0201 // (0xA1-0xFE)x2 - 0208 plane (94x94). // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. // Used as-is in ISO2022 family. // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, // 0201-1976 Roman, 0208-1978, 0208-1983. // * ISO2022-JP-1: Adds esc seq for 0212-1990. // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. // // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. // // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html 'shiftjis': { type: '_dbcs', table: function() { return require('./tables/shiftjis.json') }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, encodeSkipVals: [{from: 0xED40, to: 0xF940}], }, 'csshiftjis': 'shiftjis', 'mskanji': 'shiftjis', 'sjis': 'shiftjis', 'windows31j': 'shiftjis', 'ms31j': 'shiftjis', 'xsjis': 'shiftjis', 'windows932': 'shiftjis', 'ms932': 'shiftjis', '932': 'shiftjis', 'cp932': 'shiftjis', 'eucjp': { type: '_dbcs', table: function() { return require('./tables/eucjp.json') }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, }, // TODO: KDDI extension to Shift_JIS // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. // == Chinese/GBK ========================================================== // http://en.wikipedia.org/wiki/GBK // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 'gb2312': 'cp936', 'gb231280': 'cp936', 'gb23121980': 'cp936', 'csgb2312': 'cp936', 'csiso58gb231280': 'cp936', 'euccn': 'cp936', // Microsoft's CP936 is a subset and approximation of GBK. 'windows936': 'cp936', 'ms936': 'cp936', '936': 'cp936', 'cp936': { type: '_dbcs', table: function() { return require('./tables/cp936.json') }, }, // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. 'gbk': { type: '_dbcs', table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, }, 'xgbk': 'gbk', 'isoir58': 'gbk', // GB18030 is an algorithmic extension of GBK. // Main source: https://www.w3.org/TR/encoding/#gbk-encoder // http://icu-project.org/docs/papers/gb18030.html // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 'gb18030': { type: '_dbcs', table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, gb18030: function() { return require('./tables/gb18030-ranges.json') }, encodeSkipVals: [0x80], encodeAdd: {'€': 0xA2E3}, }, 'chinese': 'gb18030', // == Korean =============================================================== // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. 'windows949': 'cp949', 'ms949': 'cp949', '949': 'cp949', 'cp949': { type: '_dbcs', table: function() { return require('./tables/cp949.json') }, }, 'cseuckr': 'cp949', 'csksc56011987': 'cp949', 'euckr': 'cp949', 'isoir149': 'cp949', 'korean': 'cp949', 'ksc56011987': 'cp949', 'ksc56011989': 'cp949', 'ksc5601': 'cp949', // == Big5/Taiwan/Hong Kong ================================================ // There are lots of tables for Big5 and cp950. Please see the following links for history: // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html // Variations, in roughly number of defined chars: // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ // * Big5-2003 (Taiwan standard) almost superset of cp950. // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. // Plus, it has 4 combining sequences. // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. // Implementations are not consistent within browsers; sometimes labeled as just big5. // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt // // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. 'windows950': 'cp950', 'ms950': 'cp950', '950': 'cp950', 'cp950': { type: '_dbcs', table: function() { return require('./tables/cp950.json') }, }, // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. 'big5': 'big5hkscs', 'big5hkscs': { type: '_dbcs', table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, encodeSkipVals: [ // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe, 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca, 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62, 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef, 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed, // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce, ], }, 'cnbig5': 'big5hkscs', 'csbig5': 'big5hkscs', 'xxbig5': 'big5hkscs', }; "use strict"; // Update this array if you add/rename/remove files in this directory. // We support Browserify by skipping automatic module discovery and requiring modules directly. var modules = [ require("./internal"), require("./utf32"), require("./utf16"), require("./utf7"), require("./sbcs-codec"), require("./sbcs-data"), require("./sbcs-data-generated"), require("./dbcs-codec"), require("./dbcs-data"), ]; // Put all encoding/alias/codec definitions to single object and export it. for (var i = 0; i < modules.length; i++) { var module = modules[i]; for (var enc in module) if (Object.prototype.hasOwnProperty.call(module, enc)) exports[enc] = module[enc]; } "use strict"; var Buffer = require("safer-buffer").Buffer; // Export Node.js internal encodings. module.exports = { // Encodings utf8: { type: "_internal", bomAware: true}, cesu8: { type: "_internal", bomAware: true}, unicode11utf8: "utf8", ucs2: { type: "_internal", bomAware: true}, utf16le: "ucs2", binary: { type: "_internal" }, base64: { type: "_internal" }, hex: { type: "_internal" }, // Codec. _internal: InternalCodec, }; //------------------------------------------------------------------------------ function InternalCodec(codecOptions, iconv) { this.enc = codecOptions.encodingName; this.bomAware = codecOptions.bomAware; if (this.enc === "base64") this.encoder = InternalEncoderBase64; else if (this.enc === "cesu8") { this.enc = "utf8"; // Use utf8 for decoding. this.encoder = InternalEncoderCesu8; // Add decoder for versions of Node not supporting CESU-8 if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { this.decoder = InternalDecoderCesu8; this.defaultCharUnicode = iconv.defaultCharUnicode; } } } InternalCodec.prototype.encoder = InternalEncoder; InternalCodec.prototype.decoder = InternalDecoder; //------------------------------------------------------------------------------ // We use node.js internal decoder. Its signature is the same as ours. var StringDecoder = require('string_decoder').StringDecoder; if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. StringDecoder.prototype.end = function() {}; function InternalDecoder(options, codec) { this.decoder = new StringDecoder(codec.enc); } InternalDecoder.prototype.write = function(buf) { if (!Buffer.isBuffer(buf)) { buf = Buffer.from(buf); } return this.decoder.write(buf); } InternalDecoder.prototype.end = function() { return this.decoder.end(); } //------------------------------------------------------------------------------ // Encoder is mostly trivial function InternalEncoder(options, codec) { this.enc = codec.enc; } InternalEncoder.prototype.write = function(str) { return Buffer.from(str, this.enc); } InternalEncoder.prototype.end = function() { } //------------------------------------------------------------------------------ // Except base64 encoder, which must keep its state. function InternalEncoderBase64(options, codec) { this.prevStr = ''; } InternalEncoderBase64.prototype.write = function(str) { str = this.prevStr + str; var completeQuads = str.length - (str.length % 4); this.prevStr = str.slice(completeQuads); str = str.slice(0, completeQuads); return Buffer.from(str, "base64"); } InternalEncoderBase64.prototype.end = function() { return Buffer.from(this.prevStr, "base64"); } //------------------------------------------------------------------------------ // CESU-8 encoder is also special. function InternalEncoderCesu8(options, codec) { } InternalEncoderCesu8.prototype.write = function(str) { var buf = Buffer.alloc(str.length * 3), bufIdx = 0; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i); // Naive implementation, but it works because CESU-8 is especially easy // to convert from UTF-16 (which all JS strings are encoded in). if (charCode < 0x80) buf[bufIdx++] = charCode; else if (charCode < 0x800) { buf[bufIdx++] = 0xC0 + (charCode >>> 6); buf[bufIdx++] = 0x80 + (charCode & 0x3f); } else { // charCode will always be < 0x10000 in javascript. buf[bufIdx++] = 0xE0 + (charCode >>> 12); buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); buf[bufIdx++] = 0x80 + (charCode & 0x3f); } } return buf.slice(0, bufIdx); } InternalEncoderCesu8.prototype.end = function() { } //------------------------------------------------------------------------------ // CESU-8 decoder is not implemented in Node v4.0+ function InternalDecoderCesu8(options, codec) { this.acc = 0; this.contBytes = 0; this.accBytes = 0; this.defaultCharUnicode = codec.defaultCharUnicode; } InternalDecoderCesu8.prototype.write = function(buf) { var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, res = ''; for (var i = 0; i < buf.length; i++) { var curByte = buf[i]; if ((curByte & 0xC0) !== 0x80) { // Leading byte if (contBytes > 0) { // Previous code is invalid res += this.defaultCharUnicode; contBytes = 0; } if (curByte < 0x80) { // Single-byte code res += String.fromCharCode(curByte); } else if (curByte < 0xE0) { // Two-byte code acc = curByte & 0x1F; contBytes = 1; accBytes = 1; } else if (curByte < 0xF0) { // Three-byte code acc = curByte & 0x0F; contBytes = 2; accBytes = 1; } else { // Four or more are not supported for CESU-8. res += this.defaultCharUnicode; } } else { // Continuation byte if (contBytes > 0) { // We're waiting for it. acc = (acc << 6) | (curByte & 0x3f); contBytes--; accBytes++; if (contBytes === 0) { // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) if (accBytes === 2 && acc < 0x80 && acc > 0) res += this.defaultCharUnicode; else if (accBytes === 3 && acc < 0x800) res += this.defaultCharUnicode; else // Actually add character. res += String.fromCharCode(acc); } } else { // Unexpected continuation byte res += this.defaultCharUnicode; } } } this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; return res; } InternalDecoderCesu8.prototype.end = function() { var res = 0; if (this.contBytes > 0) res += this.defaultCharUnicode; return res; } "use strict"; var Buffer = require("safer-buffer").Buffer; // Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that // correspond to encoded bytes (if 128 - then lower half is ASCII). exports._sbcs = SBCSCodec; function SBCSCodec(codecOptions, iconv) { if (!codecOptions) throw new Error("SBCS codec is called without the data.") // Prepare char buffer for decoding. if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); if (codecOptions.chars.length === 128) { var asciiString = ""; for (var i = 0; i < 128; i++) asciiString += String.fromCharCode(i); codecOptions.chars = asciiString + codecOptions.chars; } this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); // Encoding buffer. var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); for (var i = 0; i < codecOptions.chars.length; i++) encodeBuf[codecOptions.chars.charCodeAt(i)] = i; this.encodeBuf = encodeBuf; } SBCSCodec.prototype.encoder = SBCSEncoder; SBCSCodec.prototype.decoder = SBCSDecoder; function SBCSEncoder(options, codec) { this.encodeBuf = codec.encodeBuf; } SBCSEncoder.prototype.write = function(str) { var buf = Buffer.alloc(str.length); for (var i = 0; i < str.length; i++) buf[i] = this.encodeBuf[str.charCodeAt(i)]; return buf; } SBCSEncoder.prototype.end = function() { } function SBCSDecoder(options, codec) { this.decodeBuf = codec.decodeBuf; } SBCSDecoder.prototype.write = function(buf) { // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. var decodeBuf = this.decodeBuf; var newBuf = Buffer.alloc(buf.length*2); var idx1 = 0, idx2 = 0; for (var i = 0; i < buf.length; i++) { idx1 = buf[i]*2; idx2 = i*2; newBuf[idx2] = decodeBuf[idx1]; newBuf[idx2+1] = decodeBuf[idx1+1]; } return newBuf.toString('ucs2'); } SBCSDecoder.prototype.end = function() { } "use strict"; // Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. module.exports = { "437": "cp437", "737": "cp737", "775": "cp775", "850": "cp850", "852": "cp852", "855": "cp855", "856": "cp856", "857": "cp857", "858": "cp858", "860": "cp860", "861": "cp861", "862": "cp862", "863": "cp863", "864": "cp864", "865": "cp865", "866": "cp866", "869": "cp869", "874": "windows874", "922": "cp922", "1046": "cp1046", "1124": "cp1124", "1125": "cp1125", "1129": "cp1129", "1133": "cp1133", "1161": "cp1161", "1162": "cp1162", "1163": "cp1163", "1250": "windows1250", "1251": "windows1251", "1252": "windows1252", "1253": "windows1253", "1254": "windows1254", "1255": "windows1255", "1256": "windows1256", "1257": "windows1257", "1258": "windows1258", "28591": "iso88591", "28592": "iso88592", "28593": "iso88593", "28594": "iso88594", "28595": "iso88595", "28596": "iso88596", "28597": "iso88597", "28598": "iso88598", "28599": "iso88599", "28600": "iso885910", "28601": "iso885911", "28603": "iso885913", "28604": "iso885914", "28605": "iso885915", "28606": "iso885916", "windows874": { "type": "_sbcs", "chars": "€����…�����������‘’“â€â€¢â€“—�������� à¸à¸‚ฃคฅฆงจฉชซฌà¸à¸Žà¸à¸à¸‘ฒณดตถทธนบปผà¸à¸žà¸Ÿà¸ à¸¡à¸¢à¸£à¸¤à¸¥à¸¦à¸§à¸¨à¸©à¸ªà¸«à¸¬à¸­à¸®à¸¯à¸°à¸±à¸²à¸³à¸´à¸µà¸¶à¸·à¸¸à¸¹à¸ºï¿½ï¿½ï¿½ï¿½à¸¿à¹€à¹à¹‚ใไๅๆ็่้๊๋์à¹à¹Žà¹à¹à¹‘๒๓๔๕๖๗๘๙๚๛����" }, "win874": "windows874", "cp874": "windows874", "windows1250": { "type": "_sbcs", "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“â€â€¢â€“—�™š›śťžź ˇ˘Å¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»ĽËľżŔÃÂĂÄĹĆÇČÉĘËĚÃÃŽÄŽÄŃŇÓÔÅÖ×ŘŮÚŰÜÃŢßŕáâăäĺćçÄéęëěíîÄđńňóôőö÷řůúűüýţ˙" }, "win1250": "windows1250", "cp1250": "windows1250", "windows1251": { "type": "_sbcs", "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋÐђ‘’“â€â€¢â€“—�™љ›њќћџ ЎўЈ¤Ò¦§Ð©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрÑтуфхцчшщъыьÑÑŽÑ" }, "win1251": "windows1251", "cp1251": "windows1251", "windows1252": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“â€â€¢â€“—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃÃÑÒÓÔÕÖרÙÚÛÜÃÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" }, "win1252": "windows1252", "cp1252": "windows1252", "windows1253": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“â€â€¢â€“—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎÎÎΑΒΓΔΕΖΗΘΙΚΛΜÎΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπÏςστυφχψωϊϋόÏώ�" }, "win1253": "windows1253", "cp1253": "windows1253", "windows1254": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“â€â€¢â€“—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" }, "win1254": "windows1254", "cp1254": "windows1254", "windows1255": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“â€â€¢â€“—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀×ׂ׃װױײ׳״�������×בגדהוזחטיךכל×מןנסעףפץצקרשת��‎â€ï¿½" }, "win1255": "windows1255", "cp1255": "windows1255", "windows1256": { "type": "_sbcs", "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“â€â€¢â€“—ک™ڑ›œ‌â€ÚºÂ ØŒÂ¢Â£Â¤Â¥Â¦Â§Â¨Â©Ú¾Â«Â¬Â­Â®Â¯Â°Â±Â²Â³Â´ÂµÂ¶Â·Â¸Â¹Ø›Â»Â¼Â½Â¾ØŸÛءآأؤإئابةتثجحخدذرزسشصض×طظعغـÙقكàلâمنهوçèéêëىيîïًٌÙَôÙÙ÷ّùْûü‎â€Û’" }, "win1256": "windows1256", "cp1256": "windows1256", "windows1257": { "type": "_sbcs", "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“â€â€¢â€“—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲÅŚŪÜŻŽßąįÄćäåęēÄéźėģķīļšńņóÅõö÷ųłśūüżž˙" }, "win1257": "windows1257", "cp1257": "windows1257", "windows1258": { "type": "_sbcs", "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“â€â€¢â€“—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÃÂĂÄÅÆÇÈÉÊË̀ÃÃŽÃÄÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêëÌíîïđṇ̃óôơö÷øùúûüư₫ÿ" }, "win1258": "windows1258", "cp1258": "windows1258", "iso88591": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃÃÑÒÓÔÕÖרÙÚÛÜÃÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" }, "cp28591": "iso88591", "iso88592": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ Ą˘Å¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťźËžżŔÃÂĂÄĹĆÇČÉĘËĚÃÃŽÄŽÄŃŇÓÔÅÖ×ŘŮÚŰÜÃŢßŕáâăäĺćçÄéęëěíîÄđńňóôőö÷řůúűüýţ˙" }, "cp28592": "iso88592", "iso88593": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÃÂ�ÄĊĈÇÈÉÊËÌÃÃŽÃ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ÄùúûüŭÅË™" }, "cp28593": "iso88593", "iso88594": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÃÂÃÄÅÆĮČÉĘËĖÃÎĪÄŅŌĶÔÕÖרŲÚÛÜŨŪßÄáâãäåæįÄéęëėíîīđņÅķôõö÷øųúûüũū˙" }, "cp28594": "iso88594", "iso88595": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ÐЂЃЄЅІЇЈЉЊЋЌ­ЎÐÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрÑтуфхцчшщъыьÑÑŽÑ№ёђѓєѕіїјљњћќ§ўџ" }, "cp28595": "iso88595", "iso88596": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـÙقكلمنهوىيًٌÙÙŽÙÙّْ�������������" }, "cp28596": "iso88596", "iso88597": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎÎÎΑΒΓΔΕΖΗΘΙΚΛΜÎΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπÏςστυφχψωϊϋόÏώ�" }, "cp28597": "iso88597", "iso88598": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗×בגדהוזחטיךכל×מןנסעףפץצקרשת��‎â€ï¿½" }, "cp28598": "iso88598", "iso88599": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" }, "cp28599": "iso88599", "iso885910": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ĄĒĢĪĨͧĻÄŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÃÂÃÄÅÆĮČÉĘËĖÃÃŽÃÃŅŌÓÔÕÖŨØŲÚÛÜÃÞßÄáâãäåæįÄéęëėíîïðņÅóôõöũøųúûüýþĸ" }, "cp28600": "iso885910", "iso885911": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ à¸à¸‚ฃคฅฆงจฉชซฌà¸à¸Žà¸à¸à¸‘ฒณดตถทธนบปผà¸à¸žà¸Ÿà¸ à¸¡à¸¢à¸£à¸¤à¸¥à¸¦à¸§à¸¨à¸©à¸ªà¸«à¸¬à¸­à¸®à¸¯à¸°à¸±à¸²à¸³à¸´à¸µà¸¶à¸·à¸¸à¸¹à¸ºï¿½ï¿½ï¿½ï¿½à¸¿à¹€à¹à¹‚ใไๅๆ็่้๊๋์à¹à¹Žà¹à¹à¹‘๒๓๔๕๖๗๘๙๚๛����" }, "cp28601": "iso885911", "iso885913": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ â€Â¢Â£Â¤â€žÂ¦Â§Ã˜Â©Å–«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲÅŚŪÜŻŽßąįÄćäåęēÄéźėģķīļšńņóÅõö÷ųłśūüżž’" }, "cp28603": "iso885913", "iso885914": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀá¹Â¶á¹–áºá¹—ẃṠỳẄẅṡÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃŴÑÒÓÔÕÖṪØÙÚÛÜÃŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" }, "cp28604": "iso885914", "iso885915": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃÃÑÒÓÔÕÖרÙÚÛÜÃÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" }, "cp28605": "iso885915", "iso885916": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ĄąÅ€„Чš©Ș«Ź­źŻ°±ČłŽâ€Â¶Â·Å¾Äș»ŒœŸżÀÃÂĂÄĆÆÇÈÉÊËÌÃÃŽÃÄŃÒÓÔÅÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" }, "cp28606": "iso885916", "cp437": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿âŒÂ¬Â½Â¼Â¡Â«Â»â–‘▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â " }, "ibm437": "cp437", "csibm437": "cp437", "cp737": { "type": "_sbcs", "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜÎΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπÏσςτυφχψ░▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀ωάέήϊίόÏϋώΆΈΉΊΌΎÎ±≥≤ΪΫ÷≈°∙·√â¿Â²â– Â " }, "ibm737": "cp737", "csibm737": "cp737", "cp775": { "type": "_sbcs", "chars": "ĆüéÄäģåćłēŖŗīŹÄÅÉæÆÅöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżźâ€Â¦Â©Â®Â¬Â½Â¼Å«»░▒▓│┤ĄČĘĖ╣║╗â•ĮŠâ”└┴┬├─┼ŲŪ╚╔╩╦╠â•╬ŽąÄęėįšųūž┘┌█▄▌â–▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " }, "ibm775": "cp775", "csibm775": "cp775", "cp850": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÃÂÀ©╣║╗â•¢¥â”└┴┬├─┼ãÃ╚╔╩╦╠â•╬¤ðÃÊËÈıÃÃŽÃ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýï´­±‗¾¶§÷¸°¨·¹³²■ " }, "ibm850": "cp850", "csibm850": "cp850", "cp852": { "type": "_sbcs", "chars": "ÇüéâäůćçłëÅőîŹÄĆÉĹĺôöĽľŚśÖÜŤťÅ×ÄáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÃÂĚŞ╣║╗╯żâ”└┴┬├─┼Ăă╚╔╩╦╠â•╬¤đÄĎËÄŇÃÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÃţ´­Ë˛ˇ˘§÷¸°¨˙űŘř■ " }, "ibm852": "cp852", "csibm852": "cp852", "cp855": { "type": "_sbcs", "chars": "ђЂѓЃёÐєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџÐюЮъЪаÐбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗â•йЙâ”└┴┬├─┼кК╚╔╩╦╠â•╬¤лЛмМнÐоОп┘┌█▄ПÑ▀ЯрРÑСтТуУжЖвВьЬ№­ыЫзЗшШÑЭщЩчЧ§■ " }, "ibm855": "cp855", "csibm855": "cp855", "cp856": { "type": "_sbcs", "chars": "×בגדהוזחטיךכל×מןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗â•¢¥â”└┴┬├─┼��╚╔╩╦╠â•╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " }, "ibm856": "cp856", "csibm856": "cp856", "cp857": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÃÂÀ©╣║╗â•¢¥â”└┴┬├─┼ãÃ╚╔╩╦╠â•╬¤ºªÊËÈ�ÃÃŽÃ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " }, "ibm857": "cp857", "csibm857": "cp857", "cp858": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÃÂÀ©╣║╗â•¢¥â”└┴┬├─┼ãÃ╚╔╩╦╠â•╬¤ðÃÊËÈ€ÃÃŽÃ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýï´­±‗¾¶§÷¸°¨·¹³²■ " }, "ibm858": "cp858", "csibm858": "cp858", "cp860": { "type": "_sbcs", "chars": "ÇüéâãàÃçêÊèÃÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â " }, "ibm860": "cp860", "csibm860": "cp860", "cp861": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèÃðÞÄÅÉæÆôöþûÃýÖÜø£Ø₧ƒáíóúÃÃÓÚ¿âŒÂ¬Â½Â¼Â¡Â«Â»â–‘▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â " }, "ibm861": "cp861", "csibm861": "cp861", "cp862": { "type": "_sbcs", "chars": "×בגדהוזחטיךכל×מןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿âŒÂ¬Â½Â¼Â¡Â«Â»â–‘▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â " }, "ibm862": "cp862", "csibm862": "cp862", "cp863": { "type": "_sbcs", "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÃûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯ÎâŒÂ¬Â½Â¼Â¾Â«Â»â–‘▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â " }, "ibm863": "cp863", "csibm863": "cp863", "cp864": { "type": "_sbcs", "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$Ùª&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴â”┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎïºïº•ﺙ،ïºïº¡ïº¥Ù Ù¡Ù¢Ù£Ù¤Ù¥Ù¦Ù§Ù¨Ù©ï»‘؛ﺱﺵﺹ؟¢ﺀïºïºƒïº…ﻊﺋïºïº‘ﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿï»ï»…ﻋï»Â¦Â¬Ã·Ã—ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎï»ï»¡ï¹½Ù‘ﻥﻩﻬﻰﻲï»ï»•ﻵﻶï»ï»™ï»±â– ï¿½" }, "ibm864": "cp864", "csibm864": "cp864", "cp865": { "type": "_sbcs", "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿âŒÂ¬Â½Â¼Â¡Â«Â¤â–‘▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â " }, "ibm865": "cp865", "csibm865": "cp865", "cp866": { "type": "_sbcs", "chars": "ÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀рÑтуфхцчшщъыьÑÑŽÑÐёЄєЇїЎў°∙·√№¤■ " }, "ibm866": "cp866", "csibm866": "cp866", "cp869": { "type": "_sbcs", "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Î²³ά£έήίϊÎÏŒÏΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜÎ╣║╗â•ΞΟâ”└┴┬├─┼ΠΡ╚╔╩╦╠â•╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπÏσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " }, "ibm869": "cp869", "csibm869": "cp869", "cp922": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÃÂÃÄÅÆÇÈÉÊËÌÃÎÊÑÒÓÔÕÖרÙÚÛÜÃŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" }, "ibm922": "cp922", "csibm922": "cp922", "cp1046": { "type": "_sbcs", "chars": "ﺈ×÷ﹱˆ■│─â”┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎï»ï»ï»¶ï»¸ï»ºï»¼Â ï£ºï£¹ï£¸Â¤ï£»ïº‹ïº‘ﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـÙقكلمنهوىيًٌÙÙŽÙÙّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" }, "ibm1046": "cp1046", "csibm1046": "cp1046", "cp1124": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ÐЂÒЄЅІЇЈЉЊЋЌ­ЎÐÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрÑтуфхцчшщъыьÑÑŽÑ№ёђґєѕіїјљњћќ§ўџ" }, "ibm1124": "cp1124", "csibm1124": "cp1124", "cp1125": { "type": "_sbcs", "chars": "ÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀рÑтуфхцчшщъыьÑÑŽÑÐÑ‘ÒґЄєІіЇї·√№¤■ " }, "ibm1125": "cp1125", "csibm1125": "cp1125", "cp1129": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÃÂĂÄÅÆÇÈÉÊË̀ÃÃŽÃÄÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêëÌíîïđṇ̃óôơö÷øùúûüư₫ÿ" }, "ibm1129": "cp1129", "csibm1129": "cp1129", "cp1133": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ àºàº‚ຄງຈສຊàºàº”ຕຖທນບປຜàºàºžàºŸàº¡àº¢àº£àº¥àº§àº«àº­àº®ï¿½ï¿½ï¿½àº¯àº°àº²àº³àº´àºµàº¶àº·àº¸àº¹àº¼àº±àº»àº½ï¿½ï¿½ï¿½à»€à»à»‚ໃໄ່້໊໋໌à»à»†ï¿½à»œà»â‚­ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½à»à»‘໒໓໔໕໖໗໘໙��¢¬¦�" }, "ibm1133": "cp1133", "csibm1133": "cp1133", "cp1161": { "type": "_sbcs", "chars": "��������������������������������่à¸à¸‚ฃคฅฆงจฉชซฌà¸à¸Žà¸à¸à¸‘ฒณดตถทธนบปผà¸à¸žà¸Ÿà¸ à¸¡à¸¢à¸£à¸¤à¸¥à¸¦à¸§à¸¨à¸©à¸ªà¸«à¸¬à¸­à¸®à¸¯à¸°à¸±à¸²à¸³à¸´à¸µà¸¶à¸·à¸¸à¸¹à¸ºà¹‰à¹Šà¹‹â‚¬à¸¿à¹€à¹à¹‚ใไๅๆ็่้๊๋์à¹à¹Žà¹à¹à¹‘๒๓๔๕๖๗๘๙๚๛¢¬¦ " }, "ibm1161": "cp1161", "csibm1161": "cp1161", "cp1162": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“â€â€¢â€“—˜™š›œÂžŸ à¸à¸‚ฃคฅฆงจฉชซฌà¸à¸Žà¸à¸à¸‘ฒณดตถทธนบปผà¸à¸žà¸Ÿà¸ à¸¡à¸¢à¸£à¸¤à¸¥à¸¦à¸§à¸¨à¸©à¸ªà¸«à¸¬à¸­à¸®à¸¯à¸°à¸±à¸²à¸³à¸´à¸µà¸¶à¸·à¸¸à¸¹à¸ºï¿½ï¿½ï¿½ï¿½à¸¿à¹€à¹à¹‚ใไๅๆ็่้๊๋์à¹à¹Žà¹à¹à¹‘๒๓๔๕๖๗๘๙๚๛����" }, "ibm1162": "cp1162", "csibm1162": "cp1162", "cp1163": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÃÂĂÄÅÆÇÈÉÊË̀ÃÃŽÃÄÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêëÌíîïđṇ̃óôơö÷øùúûüư₫ÿ" }, "ibm1163": "cp1163", "csibm1163": "cp1163", "maccroatian": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑âˆÅ¡âˆ«ÂªÂºâ„¦Å¾Ã¸Â¿Â¡Â¬âˆšÆ’≈ƫȅ ÀÃÕŒœÄ—“â€â€˜â€™Ã·â—Šï¿½Â©â„¤‹›Æ»–·‚„‰ÂćÃÄÈÃÃŽÃÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" }, "maccyrillic": { "type": "_sbcs", "chars": "ÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“â€â€˜â€™Ã·â€žÐŽÑžÐÑŸâ„–ÐÑ‘ÑабвгдежзийклмнопрÑтуфхцчшщъыьÑю¤" }, "macgreek": { "type": "_sbcs", "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάάΟΡ≈Τ«»… ΥΧΆΈœ–―“â€â€˜â€™Ã·Î‰ÎŠÎŒÎŽÎ­Î®Î¯ÏŒÎÏαβψδεφγηιξκλμνοπώÏστθωςχυζϊϋÎΰ�" }, "maciceland": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü𢣧•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑âˆÏ€âˆ«ÂªÂºâ„¦Ã¦Ã¸Â¿Â¡Â¬âˆšÆ’≈∆«»… ÀÃÕŒœ–—“â€â€˜â€™Ã·â—ŠÃ¿Å¸â„¤ÃðÞþý·‚„‰ÂÊÃËÈÃÃŽÃÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸Ë˛ˇ" }, "macroman": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑âˆÏ€âˆ«ÂªÂºâ„¦Ã¦Ã¸Â¿Â¡Â¬âˆšÆ’≈∆«»… ÀÃÕŒœ–—“â€â€˜â€™Ã·â—ŠÃ¿Å¸â„¤‹›ï¬ï¬‚‡·‚„‰ÂÊÃËÈÃÃŽÃÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸Ë˛ˇ" }, "macromania": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑âˆÏ€âˆ«ÂªÂºâ„¦ÄƒÅŸÂ¿Â¡Â¬âˆšÆ’≈∆«»… ÀÃÕŒœ–—“â€â€˜â€™Ã·â—ŠÃ¿Å¸â„¤‹›Ţţ‡·‚„‰ÂÊÃËÈÃÃŽÃÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸Ë˛ˇ" }, "macthai": { "type": "_sbcs", "chars": "«»…ï¢ï¢’“â€ï¢™ï¿½â€¢ï¢„ï¢ï¢ï¢“‘’� à¸à¸‚ฃคฅฆงจฉชซฌà¸à¸Žà¸à¸à¸‘ฒณดตถทธนบปผà¸à¸žà¸Ÿà¸ à¸¡à¸¢à¸£à¸¤à¸¥à¸¦à¸§à¸¨à¸©à¸ªà¸«à¸¬à¸­à¸®à¸¯à¸°à¸±à¸²à¸³à¸´à¸µà¸¶à¸·à¸¸à¸¹à¸ºï»¿â€‹â€“—฿เà¹à¹‚ใไๅๆ็่้๊๋์à¹â„¢à¹à¹à¹‘๒๓๔๕๖๗๘๙®©����" }, "macturkish": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑âˆÏ€âˆ«ÂªÂºâ„¦Ã¦Ã¸Â¿Â¡Â¬âˆšÆ’≈∆«»… ÀÃÕŒœ–—“â€â€˜â€™Ã·â—ŠÃ¿Å¸ÄžÄŸÄ°Ä±ÅžÅŸâ€¡Â·â€šâ€žâ€°Ã‚ÊÃËÈÃÃŽÃÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸Ë˛ˇ" }, "macukraine": { "type": "_sbcs", "chars": "ÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ò£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“â€â€˜â€™Ã·â€žÐŽÑžÐÑŸâ„–ÐÑ‘ÑабвгдежзийклмнопрÑтуфхцчшщъыьÑю¤" }, "koi8r": { "type": "_sbcs", "chars": "─│┌â”└┘├┤┬┴┼▀▄█▌â–░▒▓⌠■∙√≈≤≥ ⌡°²·÷â•║╒ё╓╔╕╖╗╘╙╚╛╜â•╞╟╠╡Ð╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопÑÑ€ÑтужвьызшÑщчъЮÐБЦДЕФГХИЙКЛМÐОПЯРСТУЖВЬЫЗШЭЩЧЪ" }, "koi8u": { "type": "_sbcs", "chars": "─│┌â”└┘├┤┬┴┼▀▄█▌â–░▒▓⌠■∙√≈≤≥ ⌡°²·÷â•║╒ёє╔ії╗╘╙╚╛ґâ•╞╟╠╡ÐЄ╣ІЇ╦╧╨╩╪Ò╬©юабцдефгхийклмнопÑÑ€ÑтужвьызшÑщчъЮÐБЦДЕФГХИЙКЛМÐОПЯРСТУЖВЬЫЗШЭЩЧЪ" }, "koi8ru": { "type": "_sbcs", "chars": "─│┌â”└┘├┤┬┴┼▀▄█▌â–░▒▓⌠■∙√≈≤≥ ⌡°²·÷â•║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ÐЄ╣ІЇ╦╧╨╩╪ÒЎ©юабцдефгхийклмнопÑÑ€ÑтужвьызшÑщчъЮÐБЦДЕФГХИЙКЛМÐОПЯРСТУЖВЬЫЗШЭЩЧЪ" }, "koi8t": { "type": "_sbcs", "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“â€â€¢â€“—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ð�Ӣ¶·�№�»���©юабцдефгхийклмнопÑÑ€ÑтужвьызшÑщчъЮÐБЦДЕФГХИЙКЛМÐОПЯРСТУЖВЬЫЗШЭЩЧЪ" }, "armscii8": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ �և։)(»«—.Õ,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհÕձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռÕÕ½ÕŽÕ¾ÕÕ¿ÕÖ€Õ‘ÖՒւՓփՔքՕօՖֆ՚�" }, "rk1048": { "type": "_sbcs", "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺÐђ‘’“â€â€¢â€“—�™љ›њқһџ ҰұӘ¤Ө¦§Ð©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрÑтуфхцчшщъыьÑÑŽÑ" }, "tcvn": { "type": "_sbcs", "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÃá»´\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÃẠẶẬÈẺẼÉẸỆÌỈĨÃỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯÄăâêôơưđẰ̀̉̃Ị̀àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹá»á»ƒá»…ếệìỉỄẾỒĩíịòỔá»ÃµÃ³á»á»“ổỗốộá»á»Ÿá»¡á»›á»£Ã¹á»–ủũúụừửữứựỳỷỹýỵá»" }, "georgianacademy": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“â€â€¢â€“—˜™š›œÂžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿áƒáƒ‘გდევზთიკლმნáƒáƒžáƒŸáƒ áƒ¡áƒ¢áƒ£áƒ¤áƒ¥áƒ¦áƒ§áƒ¨áƒ©áƒªáƒ«áƒ¬áƒ­áƒ®áƒ¯áƒ°áƒ±áƒ²áƒ³áƒ´áƒµáƒ¶Ã§Ã¨Ã©ÃªÃ«Ã¬Ã­Ã®Ã¯Ã°Ã±Ã²Ã³Ã´ÃµÃ¶Ã·Ã¸Ã¹ÃºÃ»Ã¼Ã½Ã¾Ã¿" }, "georgianps": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“â€â€¢â€“—˜™š›œÂžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿áƒáƒ‘გდევზჱთიკლმნჲáƒáƒžáƒŸáƒ áƒ¡áƒ¢áƒ³áƒ£áƒ¤áƒ¥áƒ¦áƒ§áƒ¨áƒ©áƒªáƒ«áƒ¬áƒ­áƒ®áƒ´áƒ¯áƒ°áƒµÃ¦Ã§Ã¨Ã©ÃªÃ«Ã¬Ã­Ã®Ã¯Ã°Ã±Ã²Ã³Ã´ÃµÃ¶Ã·Ã¸Ã¹ÃºÃ»Ã¼Ã½Ã¾Ã¿" }, "pt154": { "type": "_sbcs", "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“â€â€¢â€“—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ð©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫÒÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрÑтуфхцчшщъыьÑÑŽÑ" }, "viscii": { "type": "_sbcs", "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013á»¶\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dá»´\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆá»á»’ỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếá»á»ƒá»…ệốồổỗỠƠộá»á»Ÿá»‹á»°á»¨á»ªá»¬Æ¡á»›Æ¯Ã€ÃÂÃẢĂẳẵÈÉÊẺÌÃĨỳÄứÒÓÔạỷừửÙÚỹỵÃỡưàáâãảăữẫèéêẻìíĩỉđựòóôõá»á»á»¥Ã¹ÃºÅ©á»§Ã½á»£á»®" }, "iso646cn": { "type": "_sbcs", "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#Â¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" }, "iso646jp": { "type": "_sbcs", "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[Â¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" }, "hproman8": { "type": "_sbcs", "chars": "€Â‚ƒ„…†‡ˆ‰Š‹ŒÂŽ‘’“”•–—˜™š›œÂžŸ ÀÂÈÊËÎôˋˆ¨˜ÙÛ₤¯Ãý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÃÃãÃðÃÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" }, "macintosh": { "type": "_sbcs", "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑âˆÏ€âˆ«ÂªÂºâ„¦Ã¦Ã¸Â¿Â¡Â¬âˆšÆ’≈∆«»… ÀÃÕŒœ–—“â€â€˜â€™Ã·â—ŠÃ¿Å¸â„¤‹›ï¬ï¬‚‡·‚„‰ÂÊÃËÈÃÃŽÃÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸Ë˛ˇ" }, "ascii": { "type": "_sbcs", "chars": "��������������������������������������������������������������������������������������������������������������������������������" }, "tis620": { "type": "_sbcs", "chars": "���������������������������������à¸à¸‚ฃคฅฆงจฉชซฌà¸à¸Žà¸à¸à¸‘ฒณดตถทธนบปผà¸à¸žà¸Ÿà¸ à¸¡à¸¢à¸£à¸¤à¸¥à¸¦à¸§à¸¨à¸©à¸ªà¸«à¸¬à¸­à¸®à¸¯à¸°à¸±à¸²à¸³à¸´à¸µà¸¶à¸·à¸¸à¸¹à¸ºï¿½ï¿½ï¿½ï¿½à¸¿à¹€à¹à¹‚ใไๅๆ็่้๊๋์à¹à¹Žà¹à¹à¹‘๒๓๔๕๖๗๘๙๚๛����" } }"use strict"; // Manually added data to be used by sbcs codec in addition to generated one. module.exports = { // Not supported by iconv, not sure why. "10029": "maccenteuro", "maccenteuro": { "type": "_sbcs", "chars": "ÄĀÄÉĄÖÜáąČäÄĆć鏟ĎíÄĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňÅÕőŌ–—“â€â€˜â€™Ã·â—ŠÅŔŕŘ‹›řŖŗŠ‚„šŚśÃŤťÃŽžŪÓÔūŮÚůŰűŲųÃýķŻÅżĢˇ" }, "808": "cp808", "ibm808": "cp808", "cp808": { "type": "_sbcs", "chars": "ÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀рÑтуфхцчшщъыьÑÑŽÑÐёЄєЇїЎў°∙·√№€■ " }, "mik": { "type": "_sbcs", "chars": "ÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрÑтуфхцчшщъыьÑÑŽÑ└┴┬├─┼╣║╚╔╩╦╠â•╬â”░▒▓│┤№§╗â•┘┌█▄▌â–▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â " }, "cp720": { "type": "_sbcs", "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗â•╜╛â”└┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌â–▀ضطظعغÙµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√â¿Â²â– \u00a0" }, // Aliases of generated encodings. "ascii8bit": "ascii", "usascii": "ascii", "ansix34": "ascii", "ansix341968": "ascii", "ansix341986": "ascii", "csascii": "ascii", "cp367": "ascii", "ibm367": "ascii", "isoir6": "ascii", "iso646us": "ascii", "iso646irv": "ascii", "us": "ascii", "latin1": "iso88591", "latin2": "iso88592", "latin3": "iso88593", "latin4": "iso88594", "latin5": "iso88599", "latin6": "iso885910", "latin7": "iso885913", "latin8": "iso885914", "latin9": "iso885915", "latin10": "iso885916", "csisolatin1": "iso88591", "csisolatin2": "iso88592", "csisolatin3": "iso88593", "csisolatin4": "iso88594", "csisolatincyrillic": "iso88595", "csisolatinarabic": "iso88596", "csisolatingreek" : "iso88597", "csisolatinhebrew": "iso88598", "csisolatin5": "iso88599", "csisolatin6": "iso885910", "l1": "iso88591", "l2": "iso88592", "l3": "iso88593", "l4": "iso88594", "l5": "iso88599", "l6": "iso885910", "l7": "iso885913", "l8": "iso885914", "l9": "iso885915", "l10": "iso885916", "isoir14": "iso646jp", "isoir57": "iso646cn", "isoir100": "iso88591", "isoir101": "iso88592", "isoir109": "iso88593", "isoir110": "iso88594", "isoir144": "iso88595", "isoir127": "iso88596", "isoir126": "iso88597", "isoir138": "iso88598", "isoir148": "iso88599", "isoir157": "iso885910", "isoir166": "tis620", "isoir179": "iso885913", "isoir199": "iso885914", "isoir203": "iso885915", "isoir226": "iso885916", "cp819": "iso88591", "ibm819": "iso88591", "cyrillic": "iso88595", "arabic": "iso88596", "arabic8": "iso88596", "ecma114": "iso88596", "asmo708": "iso88596", "greek" : "iso88597", "greek8" : "iso88597", "ecma118" : "iso88597", "elot928" : "iso88597", "hebrew": "iso88598", "hebrew8": "iso88598", "turkish": "iso88599", "turkish8": "iso88599", "thai": "iso885911", "thai8": "iso885911", "celtic": "iso885914", "celtic8": "iso885914", "isoceltic": "iso885914", "tis6200": "tis620", "tis62025291": "tis620", "tis62025330": "tis620", "10000": "macroman", "10006": "macgreek", "10007": "maccyrillic", "10079": "maciceland", "10081": "macturkish", "cspc8codepage437": "cp437", "cspc775baltic": "cp775", "cspc850multilingual": "cp850", "cspcp852": "cp852", "cspc862latinhebrew": "cp862", "cpgr": "cp869", "msee": "cp1250", "mscyrl": "cp1251", "msansi": "cp1252", "msgreek": "cp1253", "msturk": "cp1254", "mshebr": "cp1255", "msarab": "cp1256", "winbaltrim": "cp1257", "cp20866": "koi8r", "20866": "koi8r", "ibm878": "koi8r", "cskoi8r": "koi8r", "cp21866": "koi8u", "21866": "koi8u", "ibm1168": "koi8u", "strk10482002": "rk1048", "tcvn5712": "tcvn", "tcvn57121": "tcvn", "gb198880": "iso646cn", "cn": "iso646cn", "csiso14jisc6220ro": "iso646jp", "jisc62201969ro": "iso646jp", "jp": "iso646jp", "cshproman8": "hproman8", "r8": "hproman8", "roman8": "hproman8", "xroman8": "hproman8", "ibm1051": "hproman8", "mac": "macintosh", "csmacintosh": "macintosh", }; [ ["8740","ä°ä°²ä˜ƒä–¦ä•¸ð§‰§äµ·ä–³ð§²±ä³¢ð§³…㮕䜶ä„䱇䱀𤊿𣘗ð§’𦺋𧃒䱗ðª‘ä䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡æ™å›»"], ["8767","ç¶•å¤ð¨®¹ã·´éœ´ð§¯¯å¯›ð¡µžåª¤ã˜¥ð©º°å«‘å®·å³¼æ®è–“ð©¥…ç‘¡ç’㡵𡵓𣚞𦀡㻬"], ["87a1","𥣞㫵竼龗𤅡ð¨¤ð£‡ªð ªŠð£‰žäŒŠè’„é¾–é¯ä¤°è˜“墖éŠéˆ˜ç§ç¨²æ™ æ¨©è¢ç‘Œç¯…枂稬å‰é†ã“¦ç„𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥è®äš®ð¦ºˆä†ð¥¶™ç®®ð¢’¼é¿ˆð¢“𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿æ‹ç®é¿‹"], ["8840","㇀",4,"𠄌㇅𠃑ð ƒã‡†ã‡‡ð ƒ‹ð¡¿¨ã‡ˆð ƒŠã‡‰ã‡Šã‡‹ã‡Œð „Žã‡ã‡ŽÄ€ÃÇÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊÄáǎàɑēéěèīíÇìÅóǒòūúǔùǖǘǚ"], ["88a1","ǜü࿿ê̄ế࿿ê̌á»ÃªÉ¡âšâ›"], ["8940","𪎩𡅅"], ["8943","攊"], ["8946","丽æ»éµŽé‡Ÿ"], ["894c","𧜵撑会伨侨兖兴农凤务动医åŽå‘å˜å›¢å£°å¤„备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织ç»ç»Ÿç¼†ç¼·è‰ºè‹è¯è§†è®¾è¯¢è½¦è½§è½®"], ["89a1","ç‘ç³¼ç·æ¥†ç«‰åˆ§"], ["89ab","醌碸酞肼"], ["89b0","贋胶𠧧"], ["89b5","肟黇ä³é·‰é¸Œä°¾ð©·¶ð§€Žé¸Šðª„³ã—"], ["89c1","溚舾甙"], ["89c5","䤑马éªé¾™ç¦‡ð¨‘¬ð¡·Šð —𢫦两äºäº€äº‡äº¿ä»«ä¼·ã‘Œä¾½ã¹ˆå€ƒå‚ˆã‘½ã’“㒥円夅凛凼刅争剹åŠåŒ§ã—‡åŽ©ã•‘åŽ°ã•“å‚å£ã•­ã•²ãšå’“咣咴咹å“哯唘唣唨㖘唿㖥㖿嗗㗅"], ["8a40","𧶄唥"], ["8a43","𠱂𠴕𥄫å–𢳆㧬ð è¹†ð¤¶¸ð©“¥ä“𨂾çºð¢°¸ã¨´äŸ•ð¨…𦧲𤷪æ“𠵼𠾴𠳕𡃴æ’蹾𠺖𠰋𠽤𢲩𨉖𤓓"], ["8a64","𠵆ð©©ð¨ƒ©äŸ´ð¤º§ð¢³‚骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], ["8a76","ä™ð¦‚¥æ’´å“£ð¢µŒð¢¯Šð¡·ã§»ð¡¯"], ["8aa1","𦛚𦜖𧦠擪ð¥’𠱃蹨𢆡𨭌𠜱"], ["8aac","䠋𠆩㿺塳ð¢¶"], ["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], ["8abb","䪴𢩦ð¡‚膪飵𠶜æ¹ã§¾ð¢µè·€å𡿑¼ã¹ƒ"], ["8ac9","ðª˜ð ¸‰ð¢«ð¢³‰"], ["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], ["8adf","𧕴𢺋𢈈𪙛ð¨³ð ¹ºð °´ð¦ œç¾“ð¡ƒð¢ ƒð¢¤¹ã—»ð¥‡£ð ºŒð ¾ð ºªã¾“𠼰𠵇ð¡…𠹌"], ["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖æ²ð ¾­"], ["8b40","ð£´ð§˜¹ð¢¯Žð µ¾ð µ¿ð¢±‘𢱕㨘𠺘𡃇𠼮𪘲ð¦­ð¨³’𨶙𨳊閪哌苄喹"], ["8b55","𩻃鰦骶ð§žð¢·®ç…€è…­èƒ¬å°œð¦•²è„´ãž—åŸð¨‚½é†¶ð »ºð ¸ð ¹·ð »»ã—𤷫㘉𠳖嚯𢞵𡃉ð ¸ð ¹¸ð¡¸ð¡…ˆð¨ˆ‡ð¡‘•ð ¹¹ð¤¹ð¢¶¤å©”ð¡€ð¡€žð¡ƒµð¡ƒ¶åžœð ¸‘"], ["8ba1","ð§š”ð¨‹ð ¾µð ¹»ð¥…¾ãœƒð ¾¶ð¡†€ð¥‹˜ðªŠ½ð¤§šð¡ ºð¤…·ð¨‰¼å¢™å‰¨ã˜šð¥œ½ç®²å­¨ä €ä¬¬é¼§ä§§é°Ÿé®ð¥­´ð£„½å—»ã—²åš‰ä¸¨å¤‚ð¡¯ð¯¡¸é‘𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺ç¬çˆ«ä¸¬çŠ­ð¤£©ç½’ç¤»ç³¹ç½“ð¦‰ªã“"], ["8bde","ð¦‹è€‚肀𦘒𦥑å衤è§ð§¢²è® è´é’…镸长门ð¨¸éŸ¦é¡µé£Žé£žé¥£ð© é±¼é¸Ÿé»„æ­¯ï¤‡ä¸·ð ‚‡é˜æˆ·é’¢"], ["8c40","倻淾𩱳龦㷉è¢ð¤…Žç·å³µä¬ ð¥‡ã•™ð¥´°æ„¢ð¨¨²è¾§é‡¶ç†‘朙玺ð£Šðª„‡ã²‹ð¡¦€ä¬ç£¤ç‚冮ð¨œä€‰æ©£ðªŠºäˆ£è˜ð ©¯ç¨ªð©¥‡ð¨«ªé•ç匤ð¢¾é´ç›™ð¨§£é¾§çŸäº£ä¿°å‚¼ä¸¯ä¼—龨å´ç¶‹å¢’å£ð¡¶¶åº’庙忂𢜒斋"], ["8ca1","ð£¹æ¤™æ©ƒð£±£æ³¿"], ["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩è¢é¾ªèº¹é¾«è¿è•Ÿé§ éˆ¡é¾¬ð¨¶¹ð¡¿ä±äŠ¢å¨š"], ["8cc9","顨æ«ä‰¶åœ½"], ["8cce","藖𤥻芿ð§„ä²ð¦µ´åµ»ð¦¬•𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], ["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤ð¦±è«Œä¾´ð ˆ¹å¦¿è…¬é¡–𩣺弻"], ["8d40","𠮟"], ["8d42","ð¢‡ð¨¥­ä„‚äš»ð©¹ã¼‡é¾³ðª†µäƒ¸ãŸ–䛷𦱆䅼𨚲ð§¿ä•­ã£”𥒚䕡䔛䶉䱻䵶䗪㿈ð¤¬ã™¡ä“žä’½ä‡­å´¾åµˆåµ–ã·¼ã å¶¤å¶¹ã  ã ¸å¹‚åº½å¼¥å¾ƒã¤ˆã¤”ã¤¿ã¥æƒ—愽峥㦉憷憹æ‡ã¦¸æˆ¬æŠæ‹¥æŒ˜ã§¸åš±"], ["8da1","ã¨ƒæ¢æ»æ‡æ‘šã©‹æ“€å´•å˜¡é¾Ÿãª—æ–†ãª½æ—¿æ™“ã«²æš’ã¬¢æœ–ã­‚æž¤æ €ã­˜æ¡Šæ¢„ã­²ã­±ã­»æ¤‰æ¥ƒç‰œæ¥¤æ¦Ÿæ¦…ã®¼æ§–ã¯æ©¥æ©´æ©±æª‚ã¯¬æª™ã¯²æª«æªµæ«”æ«¶æ®æ¯æ¯ªæ±µæ²ªã³‹æ´‚洆洦æ¶ã³¯æ¶¤æ¶±æ¸•æ¸˜æ¸©æº†ð¨§€æº»æ»¢æ»šé½¿æ»¨æ»©æ¼¤æ¼´ãµ†ð£½æ¾æ¾¾ãµªãµµç†·å²™ã¶Šç€¬ã¶‘çç”ç¯ç¿ç‚‰ð Œ¥ä㗱𠻘"], ["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑ð¦’䇊竚ç«ç«ªä‡¯å’²ð¥°ç¬‹ç­•笩𥌎𥳾箢筯莜𥮴𦱿ç¯è¡ç®’箸𥴠㶭𥱥蒒篺簆簵ð¥³ç±„粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], ["8ea1","ç¹§ä”𦹄çµð¦»–ç’綉綫焵綳緒ð¤—𦀩緤㴓緵𡟹緥ð¨­ç¸ð¦„¡ð¦…šç¹®çº’䌫鑬縧罀ç½ç½‡ç¤¶ð¦‹é§¡ç¾—ð¦‘羣𡙡ð ¨ä•œð£¦ä”ƒð¨Œºç¿ºð¦’‰è€…耈è€è€¨è€¯ðª‚‡ð¦³ƒè€»è€¼è¡ð¢œ”䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩ð ¬ð¦©’𣵾俹𡓽蓢è¢ð¦¬Šð¤¦§ð£”°ð¡³ð£·¸èŠªæ¤›ð¯¦”ä‡›"], ["8f40","è•‹è‹èŒšð ¸–𡞴ã›ð£…½ð£•šè‰»è‹¢èŒ˜ð£º‹ð¦¶£ð¦¬…𦮗𣗎㶿èŒå—¬èŽ…ä”‹ð¦¶¥èŽ¬èè“㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞è莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], ["8fa1","𨘥𨘻è—𧂈蘂𡖂ð§ƒð¯¦²ä•ªè˜¨ã™ˆð¡¢¢å·ð§Žšè™¾è±ðªƒ¸èŸ®ð¢°§èž±èŸšè å™¡è™¬æ¡–ä˜è¡…衆𧗠𣶹𧗤衞袜䙛袴袵æè£…ç·ð§œè¦‡è¦Šè¦¦è¦©è¦§è¦¼ð¨¨¥è§§ð§¤¤ð§ª½èªœçž“釾èªð§©™ç«©ð§¬ºð£¾äœ“𧬸煼謌謟ð¥°ð¥•¥è¬¿è­Œè­èª©ð¤©ºè®è®›èª¯ð¡›Ÿä˜•è¡è²›ð§µ”ð§¶ð¯§”㜥𧵓賖𧶘𧶽贒贃ð¡¤è³›çœè´‘𤳉ã»èµ·"], ["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭ð¨¥ð¨’辥錃𪊟ð ©è¾³ä¤ªð¨§žð¨”½ð£¶»å»¸ð£‰¢è¿¹ðª€”𨚼ð¨”𢌥㦀𦻗逷𨔼𧪾é¡ð¨•¬ð¨˜‹é‚¨ð¨œ“郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟é‰é‰¢ð¥–¹éŠ¹ð¨«†ð£²›ð¨¬Œð¥—›"], ["90a1","𠴱錬é«ð¨«¡ð¨¯«ç‚嫃𨫢𨫥䥥鉄𨯬𨰹𨯿é³é‘›èº¼é–…é–¦é¦é– æ¿¶äŠ¹ð¢™ºð¨›˜ð¡‰¼ð£¸®ä§Ÿæ°œé™»éš–ä…¬éš£ð¦»•æ‡šéš¶ç£µð¨« éš½åŒä¦¡ð¦²¸ð ‰´ð¦ð©‚¯ð©ƒ¥ð¤«‘𡤕𣌊霱虂霶ä¨ä”½ä–…𤫩çµå­éœ›éœð©‡•é—孊𩇫éŸé¥åƒð£‚·ð£‚¼éž‰éžŸéž±éž¾éŸ€éŸ’韠𥑬韮çœð©³éŸ¿éŸµð©ð§¥ºä«‘頴頳顋顦㬎𧅵㵑𠘰𤅜"], ["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬é¸é¤¹ð¤¨©ä­²ð©¡—𩤅駵騌騻é¨é©˜ð¥œ¥ã›„𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃ð£½é­é­€ð©´¾å©…𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], ["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴éºéº•麞麢䴴麪麯ð¤¤é»ã­ ã§¥ã´ä¼²ãž¾ð¨°«é¼‚鼈䮖é¤ð¦¶¢é¼—鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸ð¤ˆð¤©‘玞𨯚𡣺禟𨥾𨸶é©é³ð¨©„鋬éŽé‹ð¨¥¬ð¤’¹çˆ—㻫ç²ç©ƒçƒð¤‘³ð¤¸ç…¾ð¡Ÿ¯ç‚£ð¡¢¾ð£–™ã»‡ð¡¢…ð¥¯ð¡Ÿ¸ãœ¢ð¡›»ð¡ ¹ã›¡ð¡´ð¡£‘𥽋㜣𡛀å›ð¤¨¥ð¡¾ð¡Š¨"], ["9240","ð¡†ð¡’¶è”ƒð£š¦è”ƒè‘•𤦔𧅥𣸱𥕜𣻻ð§’䓴𣛮ð©¦ð¦¼¦æŸ¹ãœ³ã°•㷧塬𡤢æ ä—𣜿𤃡𤂋ð¤„𦰡哋嚞𦚱嚒𠿟𠮨ð ¸é†ð¨¬“鎜仸儫㠙ð¤¶äº¼ð ‘¥ð ¿ä½‹ä¾Šð¥™‘婨𠆫ð ‹ã¦™ð ŒŠð ”ãµä¼©ð ‹€ð¨º³ð ‰µè«šð ˆŒäº˜"], ["92a1","åƒå„侢伃𤨎𣺊佂倮å¬å‚俌俥å˜åƒ¼å…™å…›å…兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠ä“𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡é®ä™ºç†Œð¤ŽŒð ° ð¤¦¬ð¡ƒ¤æ§‘ð ¸ç‘¹ã»žç’™ç”瑖玘䮎𤪼ð¤‚åã–„çˆð¤ƒ‰å–´ð …å“𠯆åœé‰é›´é¦åŸåžå¿ã˜¾å£‹åª™ð¨©†ð¡›ºð¡¯ð¡œå¨¬å¦¸éŠå©¾å«å¨’𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], ["9340","åªð¨¯—ð “é ç’Œð¡Œƒç„…䥲éˆð¨§»éŽ½ãž å°žå²žå¹žå¹ˆð¡¦–ð¡¥¼ð£«®å»å­ð¡¤ƒð¡¤„ãœð¡¢ ã›ð¡›¾ã›“脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠æ¾ð¢¡ ð¢˜«å¿›ãº¸ð¢–¯ð¢–¾ð©‚ˆð¦½³æ‡€ð €¾ð †ð¢˜›æ†™æ†˜æµð¢²›ð¢´‡ð¤›”ð©…"], ["93a1","摱𤙥𢭪㨩𢬢ð£‘𩣪𢹸挷𪑛撶挱æ‘ð¤§£ð¢µ§æŠ¤ð¢²¡æ»æ•«æ¥²ã¯´ð£‚Žð£Š­ð¤¦‰ð£Š«å”ð£‹ ð¡£™ð©¿æ›Žð£Š‰ð£†³ã« ä†ð¥–„𨬢ð¥–𡛼𥕛ð¥¥ç£®ð£„ƒð¡ ªð£ˆ´ã‘¤ð£ˆð£†‚𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢ð£¾ç“ã®–æžð¤˜ªæ¢¶æ žã¯„檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], ["9440","éŠ‰ð¨€žð¨§œé‘§æ¶¥æ¼‹ð¤§¬æµ§ð£½¿ã¶æ¸„𤀼娽渊塇洤硂焻𤌚𤉶烱ç‰çŠ‡çŠ”ð¤žð¤œ¥å…¹ð¤ª¤ð —«ç‘ºð£»¸ð£™Ÿð¤©Šð¤¤—𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌ç¼éއç·ä’Ÿð¦·ªä•‘疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], ["94a1","ã·ð¤©Žã»¿ð¤§…𤣳釺圲é‚𨫣𡡤僟𥈡𥇧ç¸ð£ˆ²çœŽçœç»ð¤š—ð£žã©žð¤£°ç¸ç’›ãº¿ð¤ªºð¤«‡äƒˆð¤ª–𦆮錇ð¥–ç žç¢ç¢ˆç£’ç祙ð§ð¥›£ä„Žç¦›è’–禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺ð¡®ã–—啫㕰㚪𠇔ð °ç«¢å©™ð¢›µð¥ª¯ð¥ªœå¨ð ‰›ç£°å¨ªð¥¯†ç«¾ä‡¹ç±ç±­äˆ‘𥮳𥺼𥺦ç³ð¤§¹ð¡ž°ç²Žç±¼ç²®æª²ç·œç¸‡ç·“罎𦉡"], ["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖ð Žð£—埄ð¦’ð¦¸ð¤¥¢ç¿ç¬§ð  ¬ð¥«©ð¥µƒç¬Œð¥¸Žé§¦è™…驣樜ð£¿ã§¢ð¤§·ð¦–­é¨Ÿð¦– è’€ð§„§ð¦³‘䓪脷ä‚胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧è˜ð§ˆ›åª†ä…¿ð¡¡€å¬«ð¡¢¡å«¤ð¡£˜èš ð¯¦¼ð£¶è ­ð§¢å¨‚"], ["95a1","衮佅袇袿裦襥è¥ð¥šƒè¥”𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵ä›ãŸ²è¨½è¨œð©‘ˆå½éˆ«ð¤Š„旔焩烄𡡅鵭貟賩𧷜妚矃姰ä®ã›”踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻é„𨩋ä¢ð¨«¼é§ð¨°ð¨°»è“¥è¨«é–™é–§é–—閖𨴴瑅㻂𤣿𤩂ð¤ªã»§ð£ˆ¥éšð¨»§ð¨¹¦ð¨¹¥ã»Œð¤§­ð¤©¸ð£¿®ç’瑫㻼éð©‚°"], ["9640","桇ä¨ð©‚“𥟟éé¨ð¨¦‰ð¨°¦ð¨¬¯ð¦Ž¾éŠºå¬‘è­©ä¤¼ç¹ð¤ˆ›éž›é±é¤¸ð ¼¦å·ð¨¯…𤪲頟𩓚鋶𩗗釥䓀ð¨­ð¤©§ð¨­¤é£œð¨©…㼀鈪䤥è”餻é¥ð§¬†ã·½é¦›ä­¯é¦ªé©œð¨­¥ð¥£ˆæªé¨¡å«¾é¨¯ð©£±ä®ð©¥ˆé¦¼ä®½ä®—é½å¡²ð¡Œ‚堢𤦸"], ["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧æ…ð¢žð¢¥«æ„‡é±é±“鱻鰵é°é­¿é¯ð©¸­é®Ÿðª‡µðªƒ¾é´¡ä²®ð¤„„鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰è è—®ð¦¸€ð£Ÿ—ð¦¤ç§¢ð£–œð£™€ä¤­ð¤§žãµ¢é›éоéˆð Š¿ç¢¹é‰·é‘俤㑀é¤ð¥•砽硔碶硋ð¡—𣇉ð¤¥ãššä½²æ¿šæ¿™ç€žç€žå”𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], ["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖ð ¼è‘²ð¦³€ð¡“𤋺𢰦ð¤å¦”𣶷ð¦ç¶¨ð¦…›ð¦‚¤ð¤¦¹ð¤¦‹ð¨§ºé‹¥ç¢ã»©ç’´ð¨­£ð¡¢Ÿã»¡ð¤ª³æ«˜ç³ç»ã»–𤨾𤪔𡟙𤩦𠎧ð¡¤ð¤§¥ç‘ˆð¤¤–炥𤥶銄ç¦éŸð “¾éŒ±ð¨«Žð¨¨–鎆𨯧𥗕䤵𨪂煫"], ["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂ð¤©ð¡¡’ä”®é㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹ð¨ªð¡¡¢é´ã³ð ª´äª–㦊僴㵩㵌𡎜煵䋻𨈘æ¸ð©ƒ¤ä“«æµ—ð§¹ç§æ²¯ã³–𣿭𣸭渂漌㵯ð µç•‘㚼㓈䚀㻚䡱姄鉮䤾è½ð¨°œð¦¯€å ’埈㛖𡑒烾ð¤¢ð¤©±ð¢¿£ð¡Š°ð¢Ž½æ¢¹æ¥§ð¡Ž˜ð£“¥ð§¯´ð£›Ÿð¨ªƒð£Ÿ–ð£ºð¤²Ÿæ¨šð£š­ð¦²·è¾ä“Ÿä“Ž"], ["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺è­ð¦²€ð§“ð¡Ÿ›å¦‰åª‚ð¡ž³å©¡å©±ð¡¤…ð¤‡¼ãœ­å§¯ð¡œ¼ã›‡ç†ŽéŽæššð¤Š¥å©®å¨«ð¤Š“樫𣻹𧜶𤑛𤋊ç„𤉙𨧡侰𦴨峂𤓎ð§¹ð¤Ž½æ¨Œð¤‰–𡌄炦焳ð¤©ã¶¥æ³Ÿð¯ ¥ð¤©ç¹¥å§«å´¯ã·³å½œð¤©ð¡ŸŸç¶¤è¦"], ["98a1","咅𣫺𣌀𠈔å¾ð £•𠘙㿥𡾞𪊶瀃𩅛嵰çŽç³“𨩙ð© ä¿ˆç¿§ç‹çŒð§«´çŒ¸çŒ¹ð¥›¶ççˆãº©ð§¬˜é¬ç‡µð¤£²ç¡è‡¶ã»ŠçœŒã»‘沢国ç™çžçŸã»¢ã»°ã»´ã»ºç““㼎㽓畂畭畲ç–㽼痈痜㿀ç™ã¿—癴㿜発𤽜熈嘣覀塩ä€çƒä€¹æ¡ä…㗛瞘äªä¯å±žçž¾çŸ‹å£²ç ˜ç‚¹ç œä‚¨ç ¹ç¡‡ç¡‘硦葈𥔵礳栃礲䄃"], ["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄ç«ç«›ä‡ä¸¡ç­¢ç­¬ç­»ç°’簛䉠䉺类粜䊌粸䊔糭输烀ð ³ç·ç·”ç·ç·½ç¾®ç¾´çŠŸäŽ—è€ è€¥ç¬¹è€®è€±è”㷌垴炠肷胩ä­è„ŒçŒªè„Žè„’ç• è„”ä㬹腖腙腚"], ["99a1","ä“堺腼膄ä¥è†“ä­è†¥åŸ¯è‡è‡¤è‰”ä’芦艶苊苘苿䒰è—险榊è…烵葤惣蒈䔄蒾蓡蓸è”蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘å”蹱嗵躰䠷軎転軤軭軲辷è¿è¿Šè¿Œé€³é§„䢭飠鈓䤞鈨鉘鉫銱銮銿"], ["9a40","鋣鋫鋳鋴鋽éƒéŽ„éŽ­ä¥…ä¥‘éº¿é—åŒéé­é¾ä¥ªé‘”鑹锭関䦧间阳䧥枠䨤é€ä¨µéž²éŸ‚噔䫤惨颹䬙飱塄餎餙冴餜餷饂é¥é¥¢ä­°é§…ä®é¨¼é¬çªƒé­©é®é¯é¯±é¯´ä±­é° ã¯ð¡¯‚鵉鰺"], ["9aa1","黾å™é¶“鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀é“㞹𠗕𠘕𠙶𡚺å—煳𠫂ð «ð ®¿å‘ªð¯ »ð ¯‹å’žð ¯»ð °»ð ±“𠱥𠱼惧ð ²å™ºð ²µð ³ð ³­ð µ¯ð ¶²ð ·ˆæ¥•鰯螥𠸄𠸎𠻗ð ¾ð ¼­ð ¹³å° ð ¾¼å¸‹ð¡œð¡ð¡¶æœžð¡»ð¡‚ˆð¡‚–㙇𡂿𡃓𡄯𡄻å¤è’­ð¡‹£ð¡µð¡Œ¶è®ð¡•·ð¡˜™ð¡Ÿƒð¡Ÿ‡ä¹¸ç‚»ð¡ ­ð¡¥ª"], ["9b40","ð¡¨­ð¡©…ð¡°ªð¡±°ð¡²¬ð¡»ˆæ‹ƒð¡»•ð¡¼•ç†˜æ¡•ð¢…æ§©ã›ˆð¢‰¼ð¢—ð¢ºð¢œªð¢¡±ð¢¥è‹½ð¢¥§ð¢¦“𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], ["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳ð£¦ð£ŒŸð£žå¾±æ™ˆæš¿ð§©¹ð£•§ð£—³çˆð¤¦ºçŸ—𣘚𣜖纇ð †å¢µæœŽ"], ["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚ä£äª¸ð¤„™ð¨ªšð¤‹®ð¤Œð¤€»ð¤Œ´ð¤Ž–𤩅𠗊凒𠘑妟𡺨㮾𣳿ð¤„𤓖垈𤙴㦛𤜯𨗨𩧉ã¢ð¢‡ƒè­žð¨­Žé§–𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆ð ¹è»šð¥€¬åŠåœ¿ç…±ð¥Š™ð¥™ð£½Šð¤ª§å–¼ð¥‘†ð¥‘®ð¦­’釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿ð¥¡å¦ã“»ð£Œæƒžð¥¤ƒä¼ð¨¥ˆð¥ª®ð¥®‰ð¥°†ð¡¶åž¡ç…‘澶𦄂𧰒é–𦆲𤾚譢ð¦‚𦑊"], ["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧ð¯£ä¾»åš¹ð¤”¡ð¦›¼ä¹ªð¤¤´é™–æ¶ð¦²½ã˜˜è¥·ð¦ž™ð¦¡®ð¦‘𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙èð¦®ä›ð¦²¤ç”»è¡¥ð¦¶®å¢¶"], ["9ca1","㜜ð¢–ð§‹ð§‡ã±”𧊀𧊅éŠð¢…ºð§Š‹éŒ°ð§‹¦ð¤§æ°¹é’Ÿð§‘𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹å°ç§£ä”¿æš¶ð©²­ð©¢¤è¥ƒð§ŸŒð§¡˜å›–䃟𡘊㦡𣜯𨃨ð¡…熭è¦ð§§ð©†¨å©§ä²·ð§‚¯ð¨¦«ð§§½ð§¨Šð§¬‹ð§µ¦ð¤…ºç­ƒç¥¾ð¨€‰æ¾µðª‹Ÿæ¨ƒð¨Œ˜åŽ¢ð¦¸‡éŽ¿æ ¶é𨅯𨀣𦦵ð¡­ð£ˆ¯ð¨ˆå¶…𨰰𨂃圕頣𨥉嶫𤦈斾槕å’𤪥ð£¾ã°‘朶ð¨‚𨃴𨄮𡾡ð¨…"], ["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺æ¦ð¨¥–砈鉕𨦸ä²ð¨§§äŸð¨§¨ð¨­†ð¨¯”姸𨰉輋𨿅𩃬筑ð©„𩄼㷷𩅞𤫊è¿çŠåš‹ð©“§ð©—©ð©–°ð©–¸ð©œ²ð©£‘𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达å—"], ["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬ð§¢ãœºèº€ð¡Ÿµð¨€¤ð¨­¬ð¨®™ð§¨¾ð¦š¯ã·«ð§™•𣲷𥘵𥥖亚ð¥ºð¦‰˜åš¿ð ¹­è¸Žå­­ð£ºˆð¤²žæžæ‹ð¡Ÿ¶ð¡¡»æ”°å˜­ð¥±Šåšð¥Œ‘㷆𩶘䱽嘢嘞罉𥻘奵𣵀è°ä¸œð ¿ªð µ‰ð£šºè„—鵞贘瘻鱅癎瞹é…å²è…ˆè‹·å˜¥è„²è˜è‚½å—ªç¥¢å™ƒå–ð ºã—Žå˜…嗱曱𨋢㘭甴嗰喺咗啲ð ±ð ²–å»ð¥…ˆð ¹¶ð¢±¢"], ["9e40","ð º¢éº«çµšå—žð¡µæŠé­å’”è³ç‡¶é…¶æ¼æŽ¹æ¾å•©ð¢­ƒé±²ð¢º³å†šã“Ÿð ¶§å†§å‘唞唓癦踭𦢊疱肶蠄螆裇膶èœð¡ƒä“¬çŒ„𤜆å®èŒ‹ð¦¢“噻𢛴𧴯𤆣𧵳ð¦»ð§Š¶é…°ð¡‡™éˆˆð£³¼ðªš©ð º¬ð »¹ç‰¦ð¡²¢äŽð¤¿‚𧿹𠿫䃺"], ["9ea1","鱿”Ÿð¢¶ ä£³ð¤Ÿ ð©µ¼ð ¿¬ð ¸Šæ¢ð§–£ð ¿­"], ["9ead","ð¦ˆð¡†‡ç†£çºŽéµä¸šä¸„ã•·å¬æ²²å§ãš¬ã§œå½ãš¥ð¤˜˜å¢šð¤­®èˆ­å‘‹åžªð¥ª•ð ¥¹"], ["9ec5","㩒𢑥ç´ð©º¬ä´‰é¯­ð£³¾ð©¼°ä±›ð¤¾©ð©–žð©¿žè‘œð£¶¶ð§Š²ð¦ž³ð£œ æŒ®ç´¥ð£»·ð£¸¬ã¨ªé€ˆå‹Œã¹´ã™ºä—©ð ’Žç™€å«°ð º¶ç¡ºð§¼®å¢§ä‚¿å™¼é®‹åµ´ç™”ðª´éº…䳡痹㟻愙𣃚ð¤²"], ["9ef5","å™ð¡Š©åž§ð¤¥£ð©¸†åˆ´ð§‚®ã–­æ±Šéµ¼"], ["9f40","籖鬹埞ð¡¬å±“æ““ð©“𦌵𧅤蚭𠴨𦴢𤫢𠵱"], ["9f4f","凾ð¡¼å¶Žéœƒð¡·‘éºéŒç¬Ÿé¬‚峑箣扨挵髿ç¯é¬ªç±¾é¬®ç±‚粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑å§å–妷帒韈鶫轜呩鞴饀鞺匬愰"], ["9fa1","椬åšé°Šé´‚䰻陿¦€å‚¦ç•†ð¡­é§šå‰³"], ["9fae","é…™éšé…œ"], ["9fb2","酑𨺗æ¿ð¦´£æ«Šå˜‘醎畺抅ð ¼ç籰𥰡𣳽"], ["9fc1","𤤙盖é®ä¸ªð ³”莾衂"], ["9fc9","届槀僭åºåˆŸå·µä»Žæ°±ð ‡²ä¼¹å’œå“šåŠšè¶‚ã—¾å¼Œã—³"], ["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], ["9fe7","毺蠘罸"], ["9feb","嘠𪙊蹷齓"], ["9ff0","è·”è¹é¸œè¸æŠ‚ð¨½è¸¨è¹µç«“𤩷稾磘泪詧瘇"], ["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢ç±è¬­çŒ‚瓱賫𤪻蘯徺袠䒷"], ["a055","𡠻𦸅"], ["a058","詾𢔛"], ["a05b","惽癧髗鵄é®é®èŸµ"], ["a063","è è³·çŒ¬éœ¡é®°ã—–犲䰇籑饊𦅙慙䰄麖慽"], ["a073","åŸæ…¯æŠ¦æˆ¹æ‹Žã©œæ‡¢åŽªð£µæ¤æ ‚ã—’"], ["a0a1","嵗𨯂迚𨸹"], ["a0a6","僙𡵆礆匲阸𠼻ä¥"], ["a0ae","矾"], ["a0b0","糂𥼚糚稭è¦è£çµç”…瓲覔舚朌è¢ð§’†è›ç“°è„ƒçœ¤è¦‰ð¦ŸŒç•“𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], ["a0d4","覩瑨涹èŸð¤€‘瓧㷛煶悤憜㳑煢æ·"], ["a0e2","ç½±ð¨¬­ç‰æƒ©ä­¾åˆ ã°˜ð£³‡ð¥»—𧙖𥔱𡥄𡋾𩤃𦷜𧂭å³ð¦†­ð¨¨ð£™·ð ƒ®ð¦¡†ð¤¼Žä•¢å¬Ÿð¦Œé½éº¦ð¦‰«"], ["a3c0","â€",31,"â¡"], ["c6a1","â‘ ",9,"â‘´",9,"â…°",9,"丶丿亅亠冂冖冫勹匸å©åŽ¶å¤Šå®€å·›â¼³å¹¿å»´å½å½¡æ”´æ— ç–’癶辵隶¨ˆヽヾã‚ゞ〃ä»ã€…〆〇ー[]✽ã",23], ["c740","ã™",58,"ァアィイ"], ["c7a1","ã‚¥",81,"Ð",5,"ÐЖ",4], ["c840","Л",26,"ёж",25,"⇧↸↹ã‡ð ƒŒä¹šð ‚Šåˆ‚ä’‘"], ["c8a1","龰冈龱𧘇"], ["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌âºâº•⺜âºâº¥âº§âºªâº¬âº®âº¶âº¼âº¾â»†â»Šâ»Œâ»â»â»–⻗⻞⻣"], ["c8f5","ʃÉɛɔɵœøŋʊɪ"], ["f9fe","ï¿­"], ["fa40","𠕇鋛𠗟𣿅蕌䊵ç¯å†µã™‰ð¤¥‚𨧤é„ð¡§›è‹®ð£³ˆç ¼æ„æ‹Ÿð¤¤³ð¨¦ªð Š ð¦®³ð¡Œ…侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩ð ¾å¾¤ð Ž€ð ‡æ»›ð Ÿå½å„㑺儎顬ãƒè–𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂è½ð –³ð£²™å†²å†¸"], ["faa1","鴴凉å‡å‡‘㳜凓𤪦决凢å‚å‡­èæ¤¾ð£œ­å½»åˆ‹åˆ¦åˆ¼åŠµå‰—åŠ”åŠ¹å‹…ç°•è•‚å‹ è˜ð¦¬“包𨫞啉滙𣾀𠥔𣿬匳å„ð ¯¢æ³‹ð¡œ¦æ ›ç•æŠãºªã£Œð¡›¨ç‡ä’¢å­å´ð¨š«å¾å¿ð¡––𡘓矦厓𨪛厠厫厮玧ð¥²ã½™çŽœåå…æ±‰ä¹‰åŸ¾å™ãª«ð ®å ð£¿«ð¢¶£å¶ð ±·å“ç¹å”«æ™—浛呭𦭓𠵴å•å’咤䞦ð¡œð »ã¶´ð µ"], ["fb40","𨦼𢚘啇䳭å¯ç—å–†å–©å˜…ð¡£—ð¤€ºä•’ð¤µæš³ð¡‚´å˜·æ›ð£ŠŠæš¤æš­å™å™ç£±å›±éž‡å¾åœ€å›¯å›­ð¨­¦ã˜£ð¡‰å†ð¤†¥æ±®ç‚‹å‚㚱𦱾埦ð¡–堃𡑔ð¤£å ¦ð¤¯µå¡œå¢ªã•¡å£ å£œð¡ˆ¼å£»å¯¿åƒðª…𤉸é“㖡够梦㛃湙"], ["fba1","𡘾娤啓𡚒蔅姉𠵎ð¦²ð¦´ªð¡Ÿœå§™ð¡Ÿ»ð¡ž²ð¦¶¦æµ±ð¡ ¨ð¡›•姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広å‹å­¶æ–ˆå­¼ð§¨Žä€„ä¡ð ˆ„寕慠𡨴𥧌𠖥寳å®ä´å°…ð¡­„å°“çŽå°”𡲥𦬨屉ä£å²…峩峯嶋𡷹𡸷å´å´˜åµ†ð¡º¤å²ºå·—苼㠭ð¤¤ð¢‰ð¢…³èŠ‡ã ¶ã¯‚å¸®æªŠå¹µå¹ºð¤’¼ð ³“åŽ¦äº·å»åލð¡±å¸‰å»´ð¨’‚"], ["fc40","廹廻㢠廼栾é›å¼ð ‡ð¯¢”㫞䢮𡌺强𦢈ð¢å½˜ð¢‘±å½£éž½ð¦¹®å½²é€ð¨¨¶å¾§å¶¶ãµŸð¥‰ð¡½ªð§ƒ¸ð¢™¨é‡–𠊞𨨩怱暅𡡷㥣㷇㘹åžð¢ž´ç¥±ã¹€æ‚žæ‚¤æ‚³ð¤¦‚ð¤¦ð§©“ç’¤åƒ¡åª æ…¤è¤æ…‚慈𦻒æ†å‡´ð ™–憇宪𣾷"], ["fca1","𢡟懓ð¨®ð©¥æ‡ã¤²ð¢¦€ð¢£æ€£æ…œæ”žæŽ‹ð „˜æ‹…ð¡°æ‹•ð¢¸æ¬ð¤§Ÿã¨—æ¸æ¸ð¡ŽŽð¡Ÿ¼æ’æ¾Šð¢¸¶é ”ð¤‚Œð¥œæ“¡æ“¥é‘»ã©¦æºã©—æ•æ¼–ð¤¨¨ð¤¨£æ–…æ•­æ•Ÿð£¾æ–µð¤¥€ä¬·æ—‘äƒ˜ð¡ ©æ— æ—£å¿Ÿð£€æ˜˜ð£‡·ð£‡¸æ™„ð£†¤ð£†¥æ™‹ð ¹µæ™§ð¥‡¦æ™³æ™´ð¡¸½ð£ˆ±ð¨—´ð£‡ˆð¥Œ“çŸ…ð¢£·é¦¤æœ‚ð¤Žœð¤¨¡ã¬«æ§ºð£Ÿ‚æžæ§æ¢ð¤‡ð©ƒ­æŸ—ä“©æ ¢æ¹éˆ¼æ ð£¦ð¦¶ æ¡"], ["fd40","ð£‘¯æ§¡æ¨‹ð¨«Ÿæ¥³æ£ƒð£—æ¤æ¤€ã´²ã¨ð£˜¼ã®€æž¬æ¥¡ð¨©Šä‹¼æ¤¶æ¦˜ã®¡ð ‰è£å‚槹𣙙𢄪橅𣜃æªã¯³æž±æ«ˆð©†œã°æ¬ð ¤£æƒžæ¬µæ­´ð¢Ÿæºµð£«›ð Žµð¡¥˜ã€å¡ð£­šæ¯¡ð£»¼æ¯œæ°·ð¢’‹ð¤£±ð¦­‘汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], ["fda1","ð£³‰ã›¥ã³«ð ´²é®ƒð£‡¹ð¢’‘ç¾æ ·ð¦´¥ð¦¶¡ð¦·«æ¶–浜湼漄𤥿𤂅𦹲蔳𦽴凇沜æ¸è®ð¨¬¡æ¸¯ð£¸¯ç‘“𣾂秌æ¹åª‘ð£‹æ¿¸ãœæ¾ð£¸°æ»ºð¡’—ð¤€½ä••é°æ½„潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀ð¦‡ç‹ç¾ç‚§ç‚烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜ð¤¥ç…é¢ð¤‹ç„¬ð¤‘šð¤¨§ð¤¨¢ç†ºð¨¯¨ç‚½çˆŽ"], ["fe40","鑂爕夑鑃爤éð¥˜…çˆ®ç‰€ð¤¥´æ¢½ç‰•ç‰—ã¹•ð£„æ æ¼½çŠ‚çŒªçŒ«ð¤ £ð¨ «ä£­ð¨ „çŒ¨çŒ®ç玪𠰺𦨮ç‰ç‘‰ð¤‡¢ð¡›§ð¤¨¤æ˜£ã›…𤦷ð¤¦ð¤§»ç·ç•椃𤨦ç¹ð —ƒã»—瑜𢢭瑠𨺲瑇ç¤ç‘¶èŽ¹ç‘¬ãœ°ç‘´é±æ¨¬ç’‚䥓𤪌"], ["fea1","𤅟𤩹ð¨®å­†ð¨°ƒð¡¢žç“ˆð¡¦ˆç”Žç“©ç”žð¨»™ð¡©‹å¯—𨺬鎅ç•畊畧畮𤾂㼄𤴓疎ç‘疞疴瘂瘬癑ç™ç™¯ç™¶ð¦µçšè‡¯ãŸ¸ð¦¤‘𦤎皡皥皷盌𦾟葢ð¥‚ð¥…½ð¡¸œçœžçœ¦ç€æ’¯ð¥ˆ ç˜ð£Š¬çž¯ð¨¥¤ð¨¥¨ð¡›çŸ´ç ‰ð¡¶ð¤¨’棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗ç¦ð§¬¹ç¤¼ç¦©æ¸ªð§„¦ãº¨ç§†ð©„ç§”"] ] [ ["0","\u0000",127,"€"], ["8140","丂丄丅丆ä¸ä¸’丗丟丠両丣並丩丮丯丱丳丵丷丼乀ä¹ä¹‚乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], ["8180","äºäº–亗亙亜äºäºžäº£äºªäº¯äº°äº±äº´äº¶äº·äº¸äº¹äº¼äº½äº¾ä»ˆä»Œä»ä»ä»’仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜ä¼ä¼¡ä¼£ä¼¨ä¼©ä¼¬ä¼­ä¼®ä¼±ä¼³ä¼µä¼·ä¼¹ä¼»ä¼¾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀ä¾ä¾‚侅來侇侊侌侎ä¾ä¾’侓侕侖侘侙侚侜侞侟価侢"], ["8240","侤侫侭侰",4,"ä¾¶",8,"ä¿€ä¿ä¿‚俆俇俈俉俋俌ä¿ä¿’",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], ["8280","個倎å€å€‘倓倕倖倗倛å€å€žå€ å€¢å€£å€¤å€§å€«å€¯",10,"倻倽倿å€åå‚å„å…å†å‰åŠå‹åå",4,"å–å—å˜å™å›å",7,"å¦",5,"å­",8,"å¸å¹åºå¼å½å‚傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], ["8340","傽",17,"åƒ",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], ["8380","儉儊儌",5,"å„“",13,"å„¢",28,"兂兇兊兌兎å…å…兒兓兗兘兙兛å…",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎å†å†å†‘冓冔冘冚å†å†žå†Ÿå†¡å†£å†¦",4,"冭冮冴冸冹冺冾冿å‡å‡‚凃凅凈凊å‡å‡Žå‡å‡’",5], ["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌åˆåˆåˆ“刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎å‰å‰’剓剕剗剘"], ["8480","剙剚剛å‰å‰Ÿå‰ å‰¢å‰£å‰¤å‰¦å‰¨å‰«å‰¬å‰­å‰®å‰°å‰±å‰³",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"å‹€å‹å‹‚勄勅勆勈勊勌å‹å‹Žå‹å‹‘勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽åŒåŒ‚匃匄匇匉匊匋匌匎"], ["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽å€å‚å„å†å‹åŒååå”å˜å™å›åå¥å¨åªå¬å­å²å¶å¹å»å¼å½å¾åŽ€åŽåŽƒåŽ‡åŽˆåŽŠåŽŽåŽ"], ["8580","åŽ",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾å€åƒ",4,"åŽååå’å“å•åšåœååžå¡å¢å§å´åºå¾å¿å€å‚å…å‡å‹å”å˜å™åšåœå¢å¤å¥åªå°å³å¶å·åºå½å¿å‘呂呄呅呇呉呌å‘呎å‘呑呚å‘",4,"呣呥呧呩",7,"呴呹呺呾呿å’咃咅咇咈咉咊å’咑咓咗咘咜咞咟咠咡"], ["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜å”唞唟唡唥唦"], ["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"å•啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌å–å–Žå–喒喓喕喖喗喚喛喞喠",6,"å–¨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎å—å—å—•å——",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], ["8740","嘆嘇嘊嘋å˜å˜",7,"嘙嘚嘜å˜å˜ å˜¡å˜¢å˜¥å˜¦å˜¨å˜©å˜ªå˜«å˜®å˜¯å˜°å˜³å˜µå˜·å˜¸å˜ºå˜¼å˜½å˜¾å™€",11,"å™",4,"噕噖噚噛å™",4], ["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"åšåš‘åš’åš”",14,"嚤",10,"åš°",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀åœåœ‚圅圇國",6], ["8840","園",9,"åœåœžåœ åœ¡åœ¢åœ¤åœ¥åœ¦åœ§åœ«åœ±åœ²åœ´",4,"圼圽圿ååƒå„å…å†åˆå‰å‹å’",4,"å˜å™å¢å£å¥å§å¬å®å°å±å²å´åµå¸å¹åºå½å¾å¿åž€"], ["8880","åžåž‡åžˆåž‰åžŠåž",4,"åž”",6,"åžœåžåžžåžŸåž¥åž¨åžªåž¬åž¯åž°åž±åž³åžµåž¶åž·åž¹",8,"埄",6,"埌åŸåŸåŸ‘埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿å å ƒå „堅堈堉堊堌堎å å å ’堓堔堖堗堘堚堛堜å å Ÿå ¢å £å ¥",4,"å «",4,"報堲堳場堶",7], ["8940","å ¾",5,"å¡…",6,"塎å¡å¡å¡’å¡“å¡•å¡–å¡—å¡™",4,"塟",5,"塦",4,"å¡­",16,"塿墂墄墆墇墈墊墋墌"], ["8980","å¢",4,"墔",4,"墛墜å¢å¢ ",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎å¤å¤‘夒夓夗夘夛å¤å¤žå¤ å¤¡å¤¢å¤£å¤¦å¤¨å¤¬å¤°å¤²å¤³å¤µå¤¶å¤»"], ["8a40","夽夾夿奀奃奅奆奊奌å¥å¥å¥’奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎å¦å¦å¦‘妔妕妘妚妛妜å¦å¦Ÿå¦ å¦¡å¦¢å¦¦"], ["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌å§å§Žå§å§•姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋å¨å¨Žå¨å¨å¨’娔娕娖娗娙娚娛å¨å¨žå¨¡å¨¢å¨¤å¨¦å¨§å¨¨å¨ª",6,"娳娵娷",4,"娽娾娿å©",4,"婇婈婋",9,"婖婗婘婙婛",5], ["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], ["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋å«",4,"嫓嫕嫗嫙嫚嫛å«å«žå«Ÿå«¢å«¤å«¥å«§å«¨å«ªå«¬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"å­",6], ["8c40","å­ˆ",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊å®å®Žå®å®‘宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀å¯å¯ƒå¯ˆå¯‰å¯Šå¯‹å¯å¯Žå¯"], ["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌å°å°Žå°å°’尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌å±å±’屓屔屖屗屘屚屛屜å±å±Ÿå±¢å±¤å±§",6,"å±°å±²",6,"屻屼屽屾岀岃",4,"岉岊岋岎å²å²’岓岕å²",4,"岤",4], ["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"å³¼",4], ["8d80","å´å´„å´…å´ˆ",5,"å´",4,"崕崗崘崙崚崜å´å´Ÿ",4,"崥崨崪崫崬崯",4,"å´µ",7,"å´¿",7,"嵈嵉åµ",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], ["8e40","å¶¡",21,"嶸",12,"å·†",6,"å·Ž",12,"巜巟巠巣巤巪巬巭"], ["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋å¸å¸Žå¸’帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀å¹å¹ƒå¹†",5,"å¹",6,"å¹–",4,"幜å¹å¹Ÿå¹ å¹£",14,"幵幷幹幾åºåº‚広庅庈庉庌åºåºŽåº’庘庛åºåº¡åº¢åº£åº¤åº¨",4,"庮",4,"庴庺庻庼庽庿",6], ["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌å¼å¼Žå¼å¼’弔弖弙弚弜å¼å¼žå¼¡å¼¢å¼£å¼¤"], ["8f80","弨弫弬弮弰弲",6,"弻弽弾弿å½",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆å¾å¾Žå¾å¾‘従徔徖徚徛å¾å¾žå¾Ÿå¾ å¾¢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], ["9040","æ€ˆæ€‰æ€‹æ€Œæ€æ€‘怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"æ€½æ€¾æ€æ„",6,"æŒæŽææ‘æ“æ”æ–æ—æ˜æ›æœæžæŸæ æ¡æ¥æ¦æ®æ±æ²æ´æµæ·æ¾æ‚€"], ["9080","æ‚æ‚‚æ‚…æ‚†æ‚‡æ‚ˆæ‚Šæ‚‹æ‚Žæ‚æ‚悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌æ„",4,"æ„–æ„—æ„˜æ„™æ„›æ„œæ„æ„žæ„¡æ„¢æ„¥æ„¨æ„©æ„ªæ„¬",18,"æ…€",6], ["9140","æ…‡æ…‰æ…‹æ…æ…æ…æ…’慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"æ†Œæ†æ†",4,"憕"], ["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"æ†¿æ‡€æ‡æ‡ƒ",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"æˆ‡æˆ‰æˆ“æˆ”æˆ™æˆœæˆæˆžæˆ æˆ£æˆ¦æˆ§æˆ¨æˆ©æˆ«æˆ­æˆ¯æˆ°æˆ±æˆ²æˆµæˆ¶æˆ¸",4,"扂扄扅扆扊"], ["9240","æ‰æ‰æ‰•扖扗扙扚扜",6,"æ‰¤æ‰¥æ‰¨æ‰±æ‰²æ‰´æ‰µæ‰·æ‰¸æ‰ºæ‰»æ‰½æŠæŠ‚æŠƒæŠ…æŠ†æŠ‡æŠˆæŠ‹",5,"æŠ”æŠ™æŠœæŠæŠžæŠ£æŠ¦æŠ§æŠ©æŠªæŠ­æŠ®æŠ¯æŠ°æŠ²æŠ³æŠ´æŠ¶æŠ·æŠ¸æŠºæŠ¾æ‹€æ‹"], ["9280","æ‹ƒæ‹‹æ‹æ‹‘æ‹•æ‹æ‹žæ‹ æ‹¡æ‹¤æ‹ªæ‹«æ‹°æ‹²æ‹µæ‹¸æ‹¹æ‹ºæ‹»æŒ€æŒƒæŒ„æŒ…æŒ†æŒŠæŒ‹æŒŒæŒæŒæŒæŒ’挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"æŒ»æŒ¼æŒ¾æŒ¿æ€ææ„æ‡æˆæŠæ‘æ’æ“æ”æ–",7,"æ æ¤æ¥æ¦æ¨æªæ«æ¬æ¯æ°æ²æ³æ´æµæ¸æ¹æ¼æ½æ¾æ¿æŽæŽƒæŽ„æŽ…æŽ†æŽ‹æŽæŽ‘æŽ“æŽ”æŽ•æŽ—æŽ™",6,"採掤掦掫掯掱掲掵掶掹掻掽掿æ€"], ["9340","ææ‚æƒæ…æ‡æˆæŠæ‹æŒæ‘æ“æ”æ•æ—",6,"æŸæ¢æ¤",4,"æ«æ¬æ®æ¯æ°æ±æ³æµæ·æ¹æºæ»æ¼æ¾æƒæ„æ†",4,"ææŽæ‘æ’æ•",5,"ææŸæ¢æ£æ¤"], ["9380","æ¥æ§æ¨æ©æ«æ®",5,"æµ",4,"æ»æ¼æ¾æ‘€æ‘‚摃摉摋",6,"æ‘“æ‘•æ‘–æ‘—æ‘™",4,"摟",7,"摨摪摫摬摮",9,"æ‘»",6,"撃撆撈",8,"æ’“æ’”æ’—æ’˜æ’šæ’›æ’œæ’æ’Ÿ",4,"æ’¥æ’¦æ’§æ’¨æ’ªæ’«æ’¯æ’±æ’²æ’³æ’´æ’¶æ’¹æ’»æ’½æ’¾æ’¿æ“æ“ƒæ“„擆",6,"æ“æ“‘擓擔擕擖擙據"], ["9440","æ“›æ“œæ“æ“Ÿæ“ æ“¡æ“£æ“¥æ“§",24,"æ”",7,"攊",7,"攓",4,"æ”™",8], ["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"æ•†æ•‡æ•Šæ•‹æ•æ•Žæ•敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"æ–ˆæ–‰æ–Šæ–æ–Žæ–æ–’æ–”æ–•æ––æ–˜æ–šæ–æ–žæ– æ–¢æ–£æ–¦æ–¨æ–ªæ–¬æ–®æ–±",7,"æ–ºæ–»æ–¾æ–¿æ—€æ—‚æ—‡æ—ˆæ—‰æ—Šæ—æ—旑旓旔旕旘",7,"旡旣旤旪旫"], ["9540","旲旳旴旵旸旹旻",4,"æ˜æ˜„æ˜…æ˜‡æ˜ˆæ˜‰æ˜‹æ˜æ˜æ˜‘昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"æ™æ™Žæ™æ™‘晘"], ["9580","æ™™æ™›æ™œæ™æ™žæ™ æ™¢æ™£æ™¥æ™§æ™©",4,"æ™±æ™²æ™³æ™µæ™¸æ™¹æ™»æ™¼æ™½æ™¿æš€æšæšƒæš…æš†æšˆæš‰æšŠæš‹æšæšŽæšæšæš’æš“暔暕暘",4,"æšž",8,"æš©",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"æ›±æ›µæ›¶æ›¸æ›ºæ›»æ›½æœæœ‚會"], ["9640","æœ„æœ…æœ†æœ‡æœŒæœŽæœæœ‘朒朓朖朘朙朚朜朞朠",5,"æœ§æœ©æœ®æœ°æœ²æœ³æœ¶æœ·æœ¸æœ¹æœ»æœ¼æœ¾æœ¿ææ„æ…æ‡æŠæ‹ææ’æ”æ•æ—",4,"ææ¢æ£æ¤æ¦æ§æ«æ¬æ®æ±æ´æ¶"], ["9680","æ¸æ¹æºæ»æ½æž€æž‚æžƒæž…æž†æžˆæžŠæžŒæžæžŽæžæž‘枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"æŸ¾æ æ ‚æ ƒæ „æ †æ æ æ ’栔栕栘",4,"æ žæ Ÿæ  æ ¢",6,"æ «",6,"æ ´æ µæ ¶æ ºæ »æ ¿æ¡‡æ¡‹æ¡æ¡æ¡’æ¡–",5], ["9740","æ¡œæ¡æ¡žæ¡Ÿæ¡ªæ¡¬",7,"桵桸",8,"梂梄梇",7,"æ¢æ¢‘梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], ["9780","梹",6,"æ£æ£ƒ",5,"æ£Šæ£Œæ£Žæ£æ£æ£‘棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"æ¤Œæ¤æ¤‘椓",11,"椡椢椣椥",7,"æ¤®æ¤¯æ¤±æ¤²æ¤³æ¤µæ¤¶æ¤·æ¤¸æ¤ºæ¤»æ¤¼æ¤¾æ¥€æ¥æ¥ƒ",16,"楕楖楘楙楛楜楟"], ["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"æ¥ºæ¥»æ¥½æ¥¾æ¥¿æ¦æ¦ƒæ¦…榊榋榌榎",5,"榖榗榙榚æ¦",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], ["9880","榾榿槀槂",7,"æ§‹æ§æ§æ§‘æ§’æ§“æ§•",5,"æ§œæ§æ§žæ§¡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"æ©‘",6,"橚"], ["9940","橜",4,"橢橣橤橦",10,"橲",6,"æ©ºæ©»æ©½æ©¾æ©¿æªæª‚檃檅",8,"æªæª’",4,"檘",7,"檡",5], ["9980","檧檨檪檭",114,"欥欦欨",6], ["9a40","æ¬¯æ¬°æ¬±æ¬³æ¬´æ¬µæ¬¶æ¬¸æ¬»æ¬¼æ¬½æ¬¿æ­€æ­æ­‚歄歅歈歊歋æ­",11,"æ­š",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], ["9a80","æ®Œæ®Žæ®æ®æ®‘殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"æ¯Œæ¯Žæ¯æ¯‘毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"æ°ˆ",4,"æ°Žæ°’æ°—æ°œæ°æ°žæ° æ°£æ°¥æ°«æ°¬æ°­æ°±æ°³æ°¶æ°·æ°¹æ°ºæ°»æ°¼æ°¾æ°¿æ±ƒæ±„汅汈汋",4,"汑汒汓汖汘"], ["9b40","汙汚汢汣汥汦汧汫",4,"æ±±æ±³æ±µæ±·æ±¸æ±ºæ±»æ±¼æ±¿æ²€æ²„æ²‡æ²Šæ²‹æ²æ²Žæ²‘æ²’æ²•æ²–æ²—æ²˜æ²šæ²œæ²æ²žæ² æ²¢æ²¨æ²¬æ²¯æ²°æ²´æ²µæ²¶æ²·æ²ºæ³€æ³æ³‚æ³ƒæ³†æ³‡æ³ˆæ³‹æ³æ³Žæ³æ³‘泒泘"], ["9b80","æ³™æ³šæ³œæ³æ³Ÿæ³¤æ³¦æ³§æ³©æ³¬æ³­æ³²æ³´æ³¹æ³¿æ´€æ´‚æ´ƒæ´…æ´†æ´ˆæ´‰æ´Šæ´æ´æ´æ´‘æ´“æ´”æ´•æ´–æ´˜æ´œæ´æ´Ÿ",5,"æ´¦æ´¨æ´©æ´¬æ´­æ´¯æ´°æ´´æ´¶æ´·æ´¸æ´ºæ´¿æµ€æµ‚æµ„æµ‰æµŒæµæµ•æµ–æµ—æµ˜æµ›æµæµŸæµ¡æµ¢æµ¤æµ¥æµ§æµ¨æµ«æµ¬æµ­æµ°æµ±æµ²æµ³æµµæµ¶æµ¹æµºæµ»æµ½",4,"æ¶ƒæ¶„æ¶†æ¶‡æ¶Šæ¶‹æ¶æ¶æ¶æ¶’æ¶–",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"æ·æ·‚淃淈淉淊"], ["9c40","æ·æ·Žæ·æ·æ·’淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"æ¸†æ¸‡æ¸ˆæ¸‰æ¸‹æ¸æ¸’渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], ["9c80","渶渷渹渻",7,"æ¹…",7,"æ¹æ¹æ¹‘æ¹’æ¹•æ¹—æ¹™æ¹šæ¹œæ¹æ¹žæ¹ ",10,"湬湭湯",14,"æº€æºæº‚溄溇溈溊",4,"溑",6,"æº™æºšæº›æºæºžæº æº¡æº£æº¤æº¦æº¨æº©æº«æº¬æº­æº®æº°æº³æºµæº¸æº¹æº¼æº¾æº¿æ»€æ»ƒæ»„æ»…æ»†æ»ˆæ»‰æ»Šæ»Œæ»æ»Žæ»æ»’æ»–æ»˜æ»™æ»›æ»œæ»æ»£æ»§æ»ª",5], ["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"æ¼æ¼‘æ¼’æ¼–",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"æ¼¿æ½€æ½æ½‚"], ["9d80","潃潄潅潈潉潊潌潎",9,"æ½™æ½šæ½›æ½æ½Ÿæ½ æ½¡æ½£æ½¤æ½¥æ½§",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋æ¾",12,"æ¾æ¾žæ¾Ÿæ¾ æ¾¢",4,"澨",10,"澴澵澷澸澺",5,"æ¿æ¿ƒ",5,"濊",6,"æ¿“",10,"濟濢濣濤濥"], ["9e40","濦",7,"æ¿°",32,"瀒",7,"瀜",6,"瀤",6], ["9e80","瀫",9,"瀶瀷瀸瀺",17,"ççŽç",13,"çŸ",11,"ç®ç±ç²ç³ç´ç·ç¹çºç»ç½ç‚炂炃炄炆炇炈炋炌ç‚ç‚ç‚炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], ["9f40","烜çƒçƒžçƒ çƒ¡çƒ¢çƒ£çƒ¥çƒªçƒ®çƒ°",6,"烸烺烻烼烾",10,"ç„‹",4,"焑焒焔焗焛",10,"ç„§",7,"焲焳焴"], ["9f80","焵焷",13,"煆煇煈煉煋ç…ç…",12,"ç…ç…Ÿ",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌ç†ç†Žç†ç†‘熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"ç‡",4], ["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], ["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎ç‰ç‰ç‰‘牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎çŠçŠ‘çŠ“",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌ç‹ç‹‘狓狔狕狖狘狚狛"], ["a1a1"," ã€ã€‚·ˉˇ¨〃々—~‖…‘’“â€ã€”〕〈",7,"〖〗ã€ã€‘±×÷∶∧∨∑âˆâˆªâˆ©âˆˆâˆ·âˆšâŠ¥âˆ¥âˆ âŒ’âŠ™âˆ«âˆ®â‰¡â‰Œâ‰ˆâˆ½âˆâ‰ â‰®â‰¯â‰¤â‰¥âˆžâˆµâˆ´â™‚♀°′″℃$¤¢£‰§№☆★○â—◎◇◆□■△▲※→â†â†‘↓〓"], ["a2a1","â…°",9], ["a2b1","â’ˆ",19,"â‘´",19,"â‘ ",9], ["a2e5","㈠",9], ["a2f1","â… ",11], ["a3a1","ï¼ï¼‚#¥%",88,"ï¿£"], ["a4a1","ã",82], ["a5a1","ã‚¡",85], ["a6a1","Α",16,"Σ",6], ["a6c1","α",16,"σ",6], ["a6e0","︵︶︹︺︿﹀︽︾ï¹ï¹‚﹃﹄"], ["a6ee","︻︼︷︸︱"], ["a6f4","︳︴"], ["a7a1","Ð",5,"ÐЖ",25], ["a7d1","а",5,"ёж",25], ["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿â•",35,"â–",6], ["a880","â–ˆ",7,"▓▔▕▼▽◢◣◤◥☉⊕〒ã€ã€ž"], ["a8a1","ÄáǎàēéěèīíÇìÅóǒòūúǔùǖǘǚǜüêɑ"], ["a8bd","ńň"], ["a8c0","É¡"], ["a8c5","ã„…",36], ["a940","〡",8,"㊣㎎ãŽãŽœãŽãŽžãŽ¡ã„ãŽã‘ã’ã•︰¬¦"], ["a959","℡㈱"], ["a95c","â€"], ["a960","ー゛゜ヽヾ〆ã‚ゞ﹉",9,"﹔﹕﹖﹗﹙",8], ["a980","ï¹¢",4,"﹨﹩﹪﹫"], ["a996","〇"], ["a9a4","─",75], ["aa40","狜ç‹ç‹Ÿç‹¢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌çŒçŒçŒçŒ‘猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽ç€",8], ["aa80","ç‰çŠç‹çŒçŽçç‘ç“ç”ç•ç–ç˜",7,"ç¡",10,"ç®ç°ç±"], ["ab40","ç²",11,"ç¿",4,"玅玆玈玊玌çŽçŽçŽçŽ’çŽ“çŽ”çŽ•çŽ—çŽ˜çŽ™çŽšçŽœçŽçŽžçŽ çŽ¡çŽ£",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿ççƒ",4], ["ab80","ç‹çŒçŽç’",6,"çšç›çœççŸç¡ç¢ç£ç¤ç¦ç¨çªç«ç¬ç®ç¯ç°ç±ç³",4], ["ac40","ç¸",10,"ç„ç‡çˆç‹çŒççŽç‘",8,"çœ",5,"ç£ç¤ç§ç©ç«ç­ç¯ç±ç²ç·",4,"ç½ç¾ç¿ç‘€ç‘‚",11], ["ac80","瑎",6,"瑖瑘ç‘ç‘ ",12,"瑮瑯瑱",4,"瑸瑹瑺"], ["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌ç’ç’ç’‘",10,"ç’ç’Ÿ",7,"ç’ª",15,"ç’»",12], ["ad80","瓈",9,"ç““",8,"ç“瓟瓡瓥瓧",6,"瓰瓱瓲"], ["ae40","瓳瓵瓸",6,"甀ç”甂甃甅",7,"甎ç”甒甔甕甖甗甛ç”甞甠",4,"甦甧甪甮甴甶甹甼甽甿ç•畂畃畄畆畇畉畊ç•ç•畑畒畓畕畖畗畘"], ["ae80","ç•",7,"畧畨畩畫",6,"畳畵當畷畺",4,"ç–€ç–ç–‚ç–„ç–…ç–‡"], ["af40","疈疉疊疌ç–ç–Žç–疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀ç—痆痋痌痎ç—ç—痑痓痗痙痚痜ç—痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], ["af80","瘈瘉瘋ç˜ç˜Žç˜ç˜‘瘒瘓瘔瘖瘚瘜ç˜ç˜žç˜¡ç˜£ç˜§ç˜¨ç˜¬ç˜®ç˜¯ç˜±ç˜²ç˜¶ç˜·ç˜¹ç˜ºç˜»ç˜½ç™ç™‚癄"], ["b040","ç™…",6,"癎",5,"癕癗",4,"ç™ç™Ÿç™ ç™¡ç™¢ç™¤",6,"癬癭癮癰",7,"癹発發癿皀çšçšƒçš…皉皊皌çšçšçšçš’皔皕皗皘皚皛"], ["b080","çšœ",7,"皥",8,"皯皰皳皵",9,"盀ç›ç›ƒå•Šé˜¿åŸƒæŒ¨å“Žå”‰å“€çš‘癌蔼矮艾ç¢çˆ±éš˜éžæ°¨å®‰ä¿ºæŒ‰æš—å²¸èƒºæ¡ˆè‚®æ˜‚ç›Žå‡¹æ•–ç†¬ç¿±è¢„å‚²å¥¥æ‡Šæ¾³èŠ­æŒæ‰’å­å§ç¬†å…«ç–¤å·´æ‹”è·‹é¶æŠŠè€™å霸罢爸白æŸç™¾æ‘†ä½°è´¥æ‹œç¨—æ–‘ç­æ¬æ‰³èˆ¬é¢æ¿ç‰ˆæ‰®æ‹Œä¼´ç“£åŠåŠžç»Šé‚¦å¸®æ¢†æ¦œè†€ç»‘æ£’ç£…èšŒé•‘å‚谤苞胞包褒剥"], ["b140","盄盇盉盋盌盓盕盙盚盜ç›ç›žç› ",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜çœçœžçœ¡çœ£çœ¤çœ¥çœ§çœªçœ«"], ["b180","眬眮眰",4,"眹眻眽眾眿ç‚ç„ç…ç†çˆ",7,"ç’",7,"çœè–„雹ä¿å ¡é¥±å®æŠ±æŠ¥æš´è±¹é²çˆ†æ¯ç¢‘悲å‘北辈背è´é’¡å€ç‹ˆå¤‡æƒ«ç„™è¢«å¥”苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖å¸åº‡ç—¹é—­æ•弊必辟å£è‡‚é¿é™›éž­è¾¹ç¼–è´¬æ‰ä¾¿å˜åžè¾¨è¾©è¾«é标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], ["b240","ççžçŸç ç¤ç§ç©çªç­",11,"çºç»ç¼çžçž‚瞃瞆",5,"çžçžçž“",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], ["b280","瞼瞾矀",12,"矎",8,"矘矙矚çŸ",4,"çŸ¤ç—…å¹¶çŽ»è æ’­æ‹¨é’µæ³¢åšå‹ƒæé“‚箔伯帛舶脖膊渤泊驳æ•åœå“ºè¡¥åŸ ä¸å¸ƒæ­¥ç°¿éƒ¨æ€–æ“¦çŒœè£ææ‰è´¢ç¬è¸©é‡‡å½©èœè”¡é¤å‚蚕残惭惨ç¿è‹èˆ±ä»“æ²§è—æ“糙槽曹è‰åŽ•ç­–ä¾§å†Œæµ‹å±‚è¹­æ’å‰èŒ¬èŒ¶æŸ¥ç¢´æ½å¯Ÿå²”å·®è¯§æ‹†æŸ´è±ºæ€æŽºè‰é¦‹è°—缠铲产é˜é¢¤æ˜ŒçŒ–"], ["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"ç Šç ‹ç Žç ç ç “砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿ç¡ç¡‚硃硄硆硈硉硊硋ç¡ç¡ç¡‘硓硔硘硙硚"], ["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场å°å¸¸é•¿å¿è‚ åŽ‚æ•žç•…å”±å€¡è¶…æŠ„é’žæœå˜²æ½®å·¢åµç‚’车扯撤掣彻澈郴臣辰尘晨忱沉陈è¶è¡¬æ’‘称城橙æˆå‘ˆä¹˜ç¨‹æƒ©æ¾„诚承逞骋秤åƒç—´æŒåŒ™æ± è¿Ÿå¼›é©°è€»é½¿ä¾ˆå°ºèµ¤ç¿…斥炽充冲虫崇宠抽酬畴踌稠æ„筹仇绸瞅丑臭åˆå‡ºæ©±åŽ¨èº‡é”„é›æ»é™¤æ¥š"], ["b440","碄碅碆碈碊碋ç¢ç¢ç¢’碔碕碖碙ç¢ç¢žç¢ ç¢¢ç¢¤ç¢¦ç¢¨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌ç£ç£Žç£ç£‘磒磓磖磗磘磚",9], ["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗æè§¦å¤„æ£å·ç©¿æ¤½ä¼ èˆ¹å–˜ä¸²ç–®çª—幢床闯创å¹ç‚Šæ¶é”¤åž‚春椿醇唇淳纯蠢戳绰疵茨ç£é›Œè¾žæ…ˆç“·è¯æ­¤åˆºèµæ¬¡èªè‘±å›±åŒ†ä»Žä¸›å‡‘粗醋簇促蹿篡窜摧崔催脆ç˜ç²¹æ·¬ç¿ æ‘å­˜å¯¸ç£‹æ’®æ“æŽªæŒ«é”™æ­è¾¾ç­”瘩打大呆歹傣戴带殆代贷袋待逮"], ["b540","ç¤",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], ["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌ç¦ç¦Žç¦ç¦‘禒怠耽担丹å•éƒ¸æŽ¸èƒ†æ—¦æ°®ä½†æƒ®æ·¡è¯žå¼¹è›‹å½“æŒ¡å…šè¡æ¡£åˆ€æ£è¹ˆå€’岛祷导到稻悼é“盗德得的蹬ç¯ç™»ç­‰çžªå‡³é‚“堤低滴迪敌笛狄涤翟嫡抵底地蒂第å¸å¼Ÿé€’缔颠掂滇碘点典é›åž«ç”µä½ƒç”¸åº—惦奠淀殿碉å¼é›•å‡‹åˆæŽ‰åŠé’“调跌爹碟è¶è¿­è°å "], ["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎ç§ç§ç§“秔秖秗秙",5,"秠秡秢秥秨秪"], ["b680","秬秮秱",6,"秹秺秼秾秿ç¨ç¨„稅稇稈稉稊稌ç¨",4,"稕稖稘稙稛稜ä¸ç›¯å®é’‰é¡¶é¼Žé”­å®šè®¢ä¸¢ä¸œå†¬è‘£æ‡‚动栋侗æ«å†»æ´žå…œæŠ–æ–—é™¡è±†é€—ç—˜éƒ½ç£æ¯’犊独读堵ç¹èµŒæœé•€è‚šåº¦æ¸¡å¦’端短锻段断缎堆兑队对墩å¨è¹²æ•¦é¡¿å›¤é’ç›¾éæŽ‡å“†å¤šå¤ºåž›èº²æœµè·ºèˆµå‰æƒ°å •蛾峨鹅俄é¢è®¹å¨¥æ¶åŽ„æ‰¼é鄂饿æ©è€Œå„¿è€³å°”饵洱二"], ["b740","ç¨ç¨Ÿç¨¡ç¨¢ç¨¤",14,"稴稵稶稸稺稾穀",5,"穇",9,"ç©’",4,"穘",16], ["b780","ç©©",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎çªçªçª“窔窙窚窛窞窡窢贰å‘罚ç­ä¼ä¹é˜€æ³•ç藩帆番翻樊矾钒ç¹å‡¡çƒ¦å返范贩犯饭泛åŠèŠ³æ–¹è‚ªæˆ¿é˜²å¦¨ä»¿è®¿çººæ”¾è²éžå•¡é£žè‚¥åŒªè¯½å è‚ºåºŸæ²¸è´¹èŠ¬é…šå©æ°›åˆ†çº·åŸç„šæ±¾ç²‰å¥‹ä»½å¿¿æ„¤ç²ªä¸°å°æž«èœ‚峰锋风疯烽逢冯ç¼è®½å¥‰å‡¤ä½›å¦å¤«æ•·è‚¤å­µæ‰¶æ‹‚è¾å¹…氟符ä¼ä¿˜æœ"], ["b840","窣窤窧窩窪窫窮",4,"窴",10,"ç«€",10,"竌",9,"竗竘竚竛竜ç«ç«¡ç«¢ç«¤ç«§",5,"竮竰竱竲竳"], ["b880","ç«´",4,"竻竼竾笀ç¬ç¬‚笅笇笉笌ç¬ç¬Žç¬ç¬’笓笖笗笘笚笜ç¬ç¬Ÿç¬¡ç¬¢ç¬£ç¬§ç¬©ç¬­æµ®æ¶ªç¦è¢±å¼—甫抚辅俯釜斧脯腑府è…赴副覆赋å¤å‚…付阜父腹负富讣附妇缚å’å™¶å˜Žè¯¥æ”¹æ¦‚é’™ç›–æº‰å¹²ç”˜æ†æŸ‘ç«¿è‚赶感秆敢赣冈刚钢缸肛纲岗港æ ç¯™çš‹é«˜è†ç¾”糕æžé•ç¨¿å‘Šå“¥æ­Œææˆˆé¸½èƒ³ç–™å‰²é©è‘›æ ¼è›¤é˜éš”铬个å„给根跟耕更庚羹"], ["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊ç­ç­Žç­“筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿ç®ç®‚箃箄箆",6,"箎ç®"], ["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功æ­é¾šä¾›èº¬å…¬å®«å¼“巩汞拱贡共钩勾沟苟狗垢构购够辜è‡å’•ç®ä¼°æ²½å­¤å§‘鼓å¤è›Šéª¨è°·è‚¡æ•…顾固雇刮瓜å‰å¯¡æŒ‚è¤‚ä¹–æ‹æ€ªæ£ºå…³å®˜å† è§‚ç®¡é¦†ç½æƒ¯çŒè´¯å…‰å¹¿é€›ç‘°è§„圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚æ£é”…郭国果裹过哈"], ["ba40","篅篈築篊篋ç¯ç¯Žç¯ç¯ç¯’篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊ç°ç°Žç°",5,"簗簘簙"], ["ba80","ç°š",4,"ç° ",5,"簨簩簫",12,"ç°¹",5,"ç±‚éª¸å­©æµ·æ°¦äº¥å®³éª‡é…£æ†¨é‚¯éŸ©å«æ¶µå¯’å‡½å–Šç½•ç¿°æ’¼ææ—±æ†¾æ‚焊汗汉夯æ­èˆªå£•嚎豪毫éƒå¥½è€—å·æµ©å‘µå–è·è核禾和何åˆç›’貉阂河涸赫è¤é¹¤è´ºå˜¿é»‘痕很狠æ¨å“¼äº¨æ¨ªè¡¡æ’轰哄烘虹鸿洪å®å¼˜çº¢å–‰ä¾¯çŒ´å¼åŽšå€™åŽå‘¼ä¹Žå¿½ç‘šå£¶è‘«èƒ¡è´ç‹ç³Šæ¹–"], ["bb40","籃",9,"籎",36,"ç±µ",5,"ç±¾",9], ["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗åŽçŒ¾æ»‘ç”»åˆ’åŒ–è¯æ§å¾Šæ€€æ·®åæ¬¢çŽ¯æ¡“è¿˜ç¼“æ¢æ‚£å”¤ç—ªè±¢ç„•æ¶£å®¦å¹»è’æ…Œé»„磺è—簧皇凰惶煌晃幌æè°Žç°æŒ¥è¾‰å¾½æ¢è›”å›žæ¯æ‚”æ…§å‰æƒ æ™¦è´¿ç§½ä¼šçƒ©æ±‡è®³è¯²ç»˜è¤æ˜å©šé­‚æµ‘æ··è±æ´»ä¼™ç«èŽ·æˆ–æƒ‘éœè´§ç¥¸å‡»åœ¾åŸºæœºç•¸ç¨½ç§¯ç®•"], ["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛ç³ç³žç³¡",6,"糩",5,"ç³°",7,"糹糺糼",13,"ç´‹",5], ["bc80","ç´‘",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"è‚Œé¥¥è¿¹æ¿€è®¥é¸¡å§¬ç»©ç¼‰å‰æžæ£˜è¾‘ç±é›†åŠæ€¥ç–¾æ±²å³å«‰çº§æŒ¤å‡ è„Šå·±è“ŸæŠ€å†€å­£ä¼Žç¥­å‰‚悸济寄寂计记既忌际妓继纪嘉枷夹佳家加èšé¢Šè´¾ç”²é’¾å‡ç¨¼ä»·æž¶é©¾å«æ­¼ç›‘åšå°–笺间煎兼肩艰奸缄茧检柬碱硷拣æ¡ç®€ä¿­å‰ªå‡è槛鉴践贱è§é”®ç®­ä»¶"], ["bd40","ç´·",54,"絯",7], ["bd80","絸",32,"å¥èˆ°å‰‘é¥¯æ¸æº…涧建僵姜将浆江疆蒋桨奖讲匠酱é™è•‰æ¤’ç¤ç„¦èƒ¶äº¤éƒŠæµ‡éª„娇嚼æ…铰矫侥脚狡角饺缴绞剿教酵轿较å«çª–æ­æŽ¥çš†ç§¸è¡—é˜¶æˆªåŠ«èŠ‚æ¡”æ°æ·ç«ç«­æ´ç»“è§£å§æˆ’è—‰èŠ¥ç•Œå€Ÿä»‹ç–¥è¯«å±Šå·¾ç­‹æ–¤é‡‘ä»Šæ´¥è¥Ÿç´§é”¦ä»…è°¨è¿›é³æ™‹ç¦è¿‘烬浸"], ["be40","ç¶™",12,"ç¶§",6,"綯",42], ["be80","ç·š",32,"尽劲è†å…¢èŒŽç›æ™¶é²¸äº¬æƒŠç²¾ç²³ç»äº•警景颈é™å¢ƒæ•¬é•œå¾„ç—‰é–竟竞净炯窘æªç©¶çº çŽ–éŸ­ä¹…ç¸ä¹é…’厩救旧臼舅咎就疚鞠拘狙疽居驹èŠå±€å’€çŸ©ä¸¾æ²®èšæ‹’æ®å·¨å…·è·è¸žé”¯ä¿±å¥æƒ§ç‚¬å‰§æé¹ƒå¨Ÿå€¦çœ·å·ç»¢æ’…攫抉掘倔爵觉决诀ç»å‡èŒé’§å†›å›å³»"], ["bf40","ç·»",62], ["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡éªå–€å’–å¡å’¯å¼€æ©æ¥·å‡¯æ…¨åˆŠå ªå‹˜åŽç çœ‹åº·æ…·ç³ æ‰›æŠ—亢炕考拷烤é å·è‹›æŸ¯æ£µç£•é¢—ç§‘å£³å’³å¯æ¸´å…‹åˆ»å®¢è¯¾è‚¯å•ƒåž¦æ³å‘å­ç©ºæå­”æŽ§æŠ å£æ‰£å¯‡æž¯å“­çªŸè‹¦é…·åº“裤夸垮挎跨胯å—筷侩快宽款匡ç­ç‹‚框矿眶旷况äºç›”岿窥葵奎é­å‚€"], ["c040","繞",35,"纃",23,"纜çºçºž"], ["c080","纮纴纻纼绖绤绬绹缊ç¼ç¼žç¼·ç¼¹ç¼»",6,"罃罆",9,"ç½’ç½“é¦ˆæ„§æºƒå¤æ˜†æ†å›°æ‹¬æ‰©å»“阔垃拉喇蜡腊辣啦莱æ¥èµ–è“å©ªæ æ‹¦ç¯®é˜‘兰澜谰æ½è§ˆæ‡’ç¼†çƒ‚æ»¥ç…æ¦”狼廊郎朗浪æžåŠ³ç‰¢è€ä½¬å§¥é…ªçƒ™æ¶å‹’ä¹é›·é•­è•¾ç£Šç´¯å„¡åž’擂肋类泪棱楞冷厘梨çŠé»Žç¯±ç‹¸ç¦»æ¼“ç†æŽé‡Œé²¤ç¤¼èމè”åæ —丽厉励砾历利傈例ä¿"], ["c140","罖罙罛罜ç½ç½žç½ ç½£",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋ç¾ç¾",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"ç¾±"], ["c180","ç¾³",4,"羺羻羾翀翂翃翄翆翇翈翉翋ç¿ç¿",4,"ç¿–ç¿—ç¿™",5,"翢翣痢立粒沥隶力璃哩俩è”莲连镰廉怜涟帘敛脸链æ‹ç‚¼ç»ƒç²®å‡‰æ¢ç²±è‰¯ä¸¤è¾†é‡æ™¾äº®è°…æ’©èŠåƒšç–—ç‡Žå¯¥è¾½æ½¦äº†æ’‚é•£å»–æ–™åˆ—è£‚çƒˆåŠ£çŒŽç³æž—磷霖临邻鳞淋凛èµå拎玲è±é›¶é¾„铃伶羚凌çµé™µå²­é¢†å¦ä»¤æºœç‰æ¦´ç¡«é¦ç•™åˆ˜ç˜¤æµæŸ³å…­é¾™è‹å’™ç¬¼çª¿"], ["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎è€è€‘耓耚耛è€è€žè€Ÿè€¡è€£è€¤è€«",5,"耲耴耹耺耼耾è€èè„è…è‡èˆè‰èŽèèè‘è“è•è–è—"], ["c280","è™è›",13,"è«",5,"è²",11,"隆垄拢陇楼娄æ‚篓æ¼é™‹èЦå¢é¢…åºç‚‰æŽ³å¤è™é²éº“碌露路赂鹿潞禄录陆戮驴å•é“侣旅履屡缕虑氯律率滤绿峦挛孪滦åµä¹±æŽ ç•¥æŠ¡è½®ä¼¦ä»‘沦纶论èèžºç½—é€»é”£ç®©éª¡è£¸è½æ´›éª†ç»œå¦ˆéº»çŽ›ç èš‚马骂嘛å—埋买麦å–迈脉瞒馒蛮满蔓曼慢漫"], ["c340","è¾è‚肂肅肈肊è‚",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"èƒ",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀è„脃脄脅脇脈脋"], ["c380","脌脕脗脙脛脜è„脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆å¯èŒ‚å†’å¸½è²Œè´¸ä¹ˆçŽ«æžšæ¢…é…¶éœ‰ç…¤æ²¡çœ‰åª’é•æ¯ç¾Žæ˜§å¯å¦¹åªšé—¨é—·ä»¬èŒè’™æª¬ç›Ÿé”°çŒ›æ¢¦å­Ÿçœ¯é†šé¡ç³œè¿·è°œå¼¥ç±³ç§˜è§…泌蜜密幂棉眠绵冕å…勉娩缅é¢è‹—æçž„è—ç§’æ¸ºåº™å¦™è”‘ç­æ°‘æŠ¿çš¿æ•æ‚¯é—½æ˜ŽèžŸé¸£é“­å命谬摸"], ["c440","è…€",5,"腇腉è…è…Žè…腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸è†è†ƒ",4,"膉膋膌è†è†Žè†è†’",5,"膙膚膞",4,"膤膥"], ["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋è‡",6,"æ‘¹è˜‘æ¨¡è†œç£¨æ‘©é­”æŠ¹æœ«èŽ«å¢¨é»˜æ²«æ¼ å¯žé™Œè°‹ç‰ŸæŸæ‹‡ç‰¡äº©å§†æ¯å¢“暮幕募慕木目ç¦ç‰§ç©†æ‹¿å“ªå‘钠那娜纳氖乃奶è€å¥ˆå—男难囊挠脑æ¼é—¹æ·–å‘¢é¦å†…嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵æ»å¿µå¨˜é…¿é¸Ÿå°¿æè‚å­½å•®é•Šé•æ¶…您柠狞å‡å®"], ["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎èˆèˆ‘舓舕",5,"èˆèˆ èˆ¤èˆ¥èˆ¦èˆ§èˆ©èˆ®èˆ²èˆºèˆ¼èˆ½èˆ¿"], ["c580","艀è‰è‰‚艃艅艆艈艊艌è‰è‰Žè‰",7,"艙艛艜è‰è‰žè‰ ",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖è™ç–ŸæŒªæ‡¦ç³¯è¯ºå“¦æ¬§é¸¥æ®´è—•å‘•å¶æ²¤å•ªè¶´çˆ¬å¸•æ€•ç¶æ‹æŽ’牌徘湃派攀潘盘ç£ç›¼ç•”判å›ä¹“庞æ—耪胖抛咆刨炮è¢è·‘泡呸胚培裴赔陪é…ä½©æ²›å–·ç›†ç °æŠ¨çƒ¹æ¾Žå½­è“¬æ£šç¡¼ç¯·è†¨æœ‹é¹æ§ç¢°å¯ç ’éœ¹æ‰¹æŠ«åŠˆçµæ¯—"], ["c640","艪艫艬艭艱艵艶艷艸艻艼芀èŠèŠƒèŠ…èŠ†èŠ‡èŠ‰èŠŒèŠèŠ“èŠ”èŠ•èŠ–èŠšèŠ›èŠžèŠ èŠ¢èŠ£èŠ§èŠ²èŠµèŠ¶èŠºèŠ»èŠ¼èŠ¿è‹€è‹‚è‹ƒè‹…è‹†è‹‰è‹è‹–苙苚è‹è‹¢è‹§è‹¨è‹©è‹ªè‹¬è‹­è‹®è‹°è‹²è‹³è‹µè‹¶è‹¸"], ["c680","苺苼",4,"茊茋èŒèŒèŒ’茓茖茘茙èŒ",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻å±è­¬ç¯‡å片骗飘漂瓢票撇瞥拼频贫å“è˜ä¹’åªè‹¹è平凭瓶评å±å¡æ³¼é¢‡å©†ç ´é­„迫粕剖扑铺仆莆葡è©è’²åŸ”朴圃普浦谱æ›ç€‘期欺栖戚妻七凄漆柒æ²å…¶æ£‹å¥‡æ­§ç•¦å´Žè„齿——祈ç¥éª‘起岂乞ä¼å¯å¥‘砌器气迄弃汽泣讫æŽ"], ["c740","茾茿èè‚è„è…èˆèŠ",4,"è“è•",4,"èè¢è°",6,"è¹èºè¾",6,"莇莈莊莋莌èŽèŽèŽèŽ‘èŽ”èŽ•èŽ–èŽ—èŽ™èŽšèŽèŽŸèŽ¡",6,"莬莭莮"], ["c780","莯莵莻莾莿è‚èƒè„è†èˆè‰è‹èèŽèè‘è’è“è•è—è™èšè›èžè¢è£è¤è¦è§è¨è«è¬è­æ°æ´½ç‰µæ‰¦é’Žé“…åƒè¿ç­¾ä»Ÿè°¦ä¹¾é»”钱钳剿½œé£æµ…谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭ä¿çªåˆ‡èŒ„且怯窃钦侵亲秦ç´å‹¤èŠ¹æ“’ç¦½å¯æ²é’è½»æ°¢å€¾å¿æ¸…擎晴氰情顷请庆ç¼ç©·ç§‹ä¸˜é‚±çƒæ±‚囚酋泅趋区蛆曲躯屈驱渠"], ["c840","è®è¯è³",4,"èºè»è¼è¾è¿è€è‚è…è‡èˆè‰èŠèè’",5,"è™èšè›èž",5,"è©",7,"è²",5,"è¹èºè»è¾",7,"葇葈葉"], ["c880","葊",6,"è‘’",4,"葘è‘葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼å–娶龋趣去圈颧æƒé†›æ³‰å…¨ç—Šæ‹³çŠ¬åˆ¸åŠç¼ºç‚”瘸å´é¹Šæ¦·ç¡®é›€è£™ç¾¤ç„¶ç‡ƒå†‰æŸ“瓤壤攘嚷让饶扰绕惹热壬ä»äººå¿éŸ§ä»»è®¤åˆƒå¦Šçº«æ‰”仿—¥æˆŽèŒ¸è“‰è£èžç†”æº¶å®¹ç»’å†—æ‰æŸ”肉茹蠕儒孺如辱乳æ±å…¥è¤¥è½¯é˜®è•Šç‘žé”闰润若弱撒洒è¨è…®é³ƒå¡žèµ›ä¸‰å"], ["c940","葽",4,"蒃蒄蒅蒆蒊è’è’",7,"蒘蒚蒛è’è’žè’Ÿè’ è’¢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎è“蓒蓔蓕蓗"], ["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀è”蔂伞散桑嗓丧æ”骚扫嫂瑟色涩森僧莎砂æ€åˆ¹æ²™çº±å‚»å•¥ç…žç­›æ™’çŠè‹«æ‰å±±åˆ ç…½è¡«é—ªé™•æ“…èµ¡è†³å–„æ±•æ‰‡ç¼®å¢’ä¼¤å•†èµæ™Œä¸Šå°šè£³æ¢¢æŽç¨çƒ§èŠå‹ºéŸ¶å°‘哨邵ç»å¥¢èµŠè›‡èˆŒèˆèµ¦æ‘„射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲å‡ç»³"], ["ca40","蔃",8,"è”蔎è”è”蔒蔔蔕蔖蔘蔙蔛蔜è”蔞蔠蔢",8,"è”­",9,"蔾",4,"蕄蕅蕆蕇蕋",10], ["ca80","蕗蕘蕚蕛蕜è•蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀è–çœç››å‰©èƒœåœ£å¸ˆå¤±ç‹®æ–½æ¹¿è¯—尸虱å石拾时什食蚀实识å²çŸ¢ä½¿å±Žé©¶å§‹å¼ç¤ºå£«ä¸–柿事拭誓é€åŠ¿æ˜¯å—œå™¬é€‚ä»•ä¾é‡Šé¥°æ°å¸‚æƒå®¤è§†è¯•收手首守寿授售å—瘦兽蔬枢梳殊抒输å”舒淑ç–书赎孰熟薯暑曙署蜀é»é¼ å±žæœ¯è¿°æ ‘æŸæˆç«–墅庶数漱"], ["cb40","薂薃薆薈",6,"è–",10,"è–",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"è—‚",6,"è—Š",4,"è—‘è—’"], ["cb80","藔藖",5,"è—",6,"藥藦藧藨藪",14,"æ•åˆ·è€æ‘”衰甩帅栓拴霜åŒçˆ½è°æ°´ç¡ç¨Žå®çž¬é¡ºèˆœè¯´ç¡•æœ”çƒæ–¯æ’•嘶æ€ç§å¸ä¸æ­»è‚†å¯ºå—£å››ä¼ºä¼¼é¥²å·³æ¾è€¸æ€‚颂é€å®‹è®¼è¯µæœè‰˜æ“žå—½è‹é…¥ä¿—素速粟僳塑溯宿诉肃酸蒜算虽隋éšç»¥é«“碎å²ç©—é‚隧祟孙æŸç¬‹è“‘梭唆缩çç´¢é”æ‰€å¡Œä»–它她塔"], ["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], ["cc80","è™",11,"虒虓處",4,"虛虜è™è™Ÿè™ è™¡è™£",7,"ç­æŒžè¹‹è¸èƒŽè‹”æŠ¬å°æ³°é…žå¤ªæ€æ±°åæ‘Šè´ªç˜«æ»©å›æª€ç—°æ½­è°­è°ˆå¦æ¯¯è¢’碳探å¹ç‚­æ±¤å¡˜æªå ‚棠膛å”ç³–å€˜èººæ·Œè¶Ÿçƒ«æŽæ¶›æ»”ç»¦è„æ¡ƒé€ƒæ·˜é™¶è®¨å¥—特藤腾疼誊梯剔踢锑æé¢˜è¹„å•¼ä½“æ›¿åšæƒ•涕剃屉天添填田甜æ¬èˆ”腆挑æ¡è¿¢çœºè·³è´´é“帖厅å¬çƒƒ"], ["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"èšž",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"è›è›‚蛃蛅蛈蛌è›è›’蛓蛕蛖蛗蛚蛜"], ["cd80","è›è› è›¡è›¢è›£è›¥è›¦è›§è›¨è›ªè›«è›¬è›¯è›µè›¶è›·è›ºè›»è›¼è›½è›¿èœèœ„蜅蜆蜋蜌蜎èœèœèœ‘蜔蜖汀廷åœäº­åº­æŒºè‰‡é€šæ¡é…®çž³åŒé“œå½¤ç«¥æ¡¶æ…ç­’ç»Ÿç—›å·æŠ•å¤´é€å‡¸ç§ƒçªå›¾å¾’途涂屠土åå…”æ¹å›¢æŽ¨é¢“腿蜕褪退åžå±¯è‡€æ‹–托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄å¨"], ["ce40","蜙蜛èœèœŸèœ èœ¤èœ¦èœ§èœ¨èœªèœ«èœ¬èœ­èœ¯èœ°èœ²èœ³èœµèœ¶èœ¸èœ¹èœºèœ¼èœ½è€",6,"èŠè‹èèèè‘è’è”è•è–è˜èš",5,"è¡è¢è¦",7,"è¯è±è²è³èµ"], ["ce80","è·è¸è¹èºè¿èž€èžèž„螆螇螉螊螌螎",4,"螔螕螖螘",6,"èž ",4,"å·å¾®å±éŸ¦è¿æ¡…围唯惟为æ½ç»´è‹‡èŽå§”伟伪尾纬未蔚味ç•胃喂é­ä½æ¸­è°“尉慰å«ç˜Ÿæ¸©èšŠæ–‡é—»çº¹å»ç¨³ç´Šé—®å—¡ç¿ç“®æŒèœ—æ¶¡çªæˆ‘æ–¡å§æ¡æ²ƒå·«å‘œé’¨ä¹Œæ±¡è¯¬å±‹æ— èŠœæ¢§å¾å´æ¯‹æ­¦äº”æ‚åˆèˆžä¼ä¾®åžæˆŠé›¾æ™¤ç‰©å‹¿åŠ¡æ‚Ÿè¯¯æ˜”ç†™æžè¥¿ç¡’矽晰嘻å¸é”¡ç‰º"], ["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿èŸ",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜èŸèŸžèŸŸèŸ¡èŸ¢èŸ£èŸ¤èŸ¦èŸ§èŸ¨èŸ©èŸ«èŸ¬èŸ­èŸ¯",9], ["cf80","蟺蟻蟼蟽蟿蠀è è ‚è „",5,"è ‹",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀æ¯å¸Œæ‚‰è†å¤•惜熄烯溪æ±çŠ€æª„è¢­å¸­ä¹ åª³å–œé“£æ´—ç³»éš™æˆç»†çžŽè™¾åŒ£éœžè¾–暇峡侠狭下厦å¤å“掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷é™çº¿ç›¸åŽ¢é•¶é¦™ç®±è¥„æ¹˜ä¹¡ç¿”ç¥¥è¯¦æƒ³å“享项巷橡åƒå‘象è§ç¡éœ„削哮嚣销消宵淆晓"], ["d040","è ¤",13,"è ³",5,"蠺蠻蠽蠾蠿è¡è¡‚衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], ["d080","衻衼袀袃袆袇袉袊袌袎è¢è¢è¢‘袓袔袕袗",4,"è¢",4,"袣袥",5,"å°å­æ ¡è‚–啸笑效楔些歇èŽéž‹å挟æºé‚ªæ–œèƒè°å†™æ¢°å¸èŸ¹æ‡ˆæ³„æ³»è°¢å±‘è–ªèŠ¯é”Œæ¬£è¾›æ–°å¿»å¿ƒä¿¡è¡…æ˜Ÿè…¥çŒ©æƒºå…´åˆ‘åž‹å½¢é‚¢è¡Œé†’å¹¸ææ€§å§“兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须å¾è®¸è“„酗噿—­åºç•œæ¤çµ®å©¿ç»ªç»­è½©å–§å®£æ‚¬æ—‹çŽ„"], ["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌è£è£è£è£‘裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀è¤è¤ƒ",5], ["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚é´è–›å­¦ç©´é›ªè¡€å‹‹ç†å¾ªæ—¬è¯¢å¯»é©¯å·¡æ®‰æ±›è®­è®¯é€Šè¿…压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹ç›ä¸¥ç ”èœ’å²©å»¶è¨€é¢œé˜Žç‚Žæ²¿å¥„æŽ©çœ¼è¡æ¼”艳堰燕厌砚é›å”å½¦ç„°å®´è°šéªŒæ®ƒå¤®é¸¯ç§§æ¨æ‰¬ä½¯ç–¡ç¾Šæ´‹é˜³æ°§ä»°ç—’养样漾邀腰妖瑶"], ["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], ["d280","襽襾覀覂覄覅覇",26,"摇尧é¥çª‘谣姚咬舀è¯è¦è€€æ¤°å™Žè€¶çˆ·é‡Žå†¶ä¹Ÿé¡µæŽ–ä¸šå¶æ›³è…‹å¤œæ¶²ä¸€å£¹åŒ»æ–铱ä¾ä¼Šè¡£é¢å¤·é—ç§»ä»ªèƒ°ç–‘æ²‚å®œå§¨å½æ¤…èšå€šå·²ä¹™çŸ£ä»¥è‰ºæŠ‘æ˜“é‚‘å±¹äº¿å½¹è‡†é€¸è‚„ç–«äº¦è£”æ„æ¯…忆义益溢诣议谊译异翼翌绎茵è«å› æ®·éŸ³é˜´å§»åŸé“¶æ·«å¯…饮尹引éš"], ["d340","覢",30,"觃è§è§“觔觕觗觘觙觛è§è§Ÿè§ è§¡è§¢è§¤è§§è§¨è§©è§ªè§¬è§­è§®è§°è§±è§²è§´",6], ["d380","è§»",4,"è¨",5,"計",21,"å°è‹±æ¨±å©´é¹°åº”缨莹è¤è¥è§è‡è¿Žèµ¢ç›ˆå½±é¢–硬映哟拥佣臃痈庸é›è¸Šè›¹å’泳涌永æ¿å‹‡ç”¨å¹½ä¼˜æ‚ å¿§å°¤ç”±é‚®é“€çŠ¹æ²¹æ¸¸é…‰æœ‰å‹å³ä½‘釉诱åˆå¹¼è¿‚æ·¤äºŽç›‚æ¦†è™žæ„šèˆ†ä½™ä¿žé€¾é±¼æ„‰æ¸æ¸”隅予娱雨与屿禹宇语羽玉域芋éƒåé‡å–»å³ªå¾¡æ„ˆæ¬²ç‹±è‚²èª‰"], ["d440","訞",31,"訿",8,"詉",21], ["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣è¢åŽŸæ´è¾•园员圆猿æºç¼˜è¿œè‹‘愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨å…è¿è•´é…晕韵孕åŒç ¸æ‚栽哉ç¾å®°è½½å†åœ¨å’±æ”’暂赞赃è„葬é­ç³Ÿå‡¿è—»æž£æ—©æ¾¡èš¤èºå™ªé€ çš‚ç¶ç‡¥è´£æ‹©åˆ™æ³½è´¼æ€Žå¢žæ†Žæ›¾èµ æ‰Žå–³æ¸£æœ­è½§"], ["d540","èª",7,"誋",7,"誔",46], ["d580","諃",32,"铡闸眨栅榨咋ä¹ç‚¸è¯ˆæ‘˜æ–‹å®…çª„å€ºå¯¨çž»æ¯¡è©¹ç²˜æ²¾ç›æ–©è¾—å´­å±•è˜¸æ ˆå æˆ˜ç«™æ¹›ç»½æ¨Ÿç« å½°æ¼³å¼ æŽŒæ¶¨æ–丈å¸è´¦ä»—胀瘴障招昭找沼赵照罩兆肇å¬é®æŠ˜å“²è›°è¾™è€…é”—è”—è¿™æµ™çæ–ŸçœŸç”„砧臻贞针侦枕疹诊震振镇阵蒸挣çå¾ç‹°äº‰æ€”整拯正政"], ["d640","諤",34,"謈",27], ["d680","謤謥謧",30,"帧症郑è¯èŠæžæ”¯å±èœ˜çŸ¥è‚¢è„‚æ±ä¹‹ç»‡èŒç›´æ¤æ®–æ‰§å€¼ä¾„å€æŒ‡æ­¢è¶¾åªæ—¨çº¸å¿—挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终ç§è‚¿é‡ä»²ä¼—èˆŸå‘¨å·žæ´²è¯Œç²¥è½´è‚˜å¸šå’’çš±å®™æ˜¼éª¤ç æ ªè››æœ±çŒªè¯¸è¯›é€ç«¹çƒ›ç…®æ‹„瞩嘱主著柱助蛀贮铸筑"], ["d740","è­†",31,"è­§",4,"è­­",25], ["d780","讇",24,"讬讱讻诇è¯è¯ªè°‰è°žä½æ³¨ç¥é©»æŠ“爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘å ç¼€è°†å‡†æ‰æ‹™å“桌ç¢èŒé…Œå•„ç€ç¼æµŠå…¹å’¨èµ„姿滋淄孜紫仔籽滓å­è‡ªæ¸å­—é¬ƒæ£•è¸ªå®—ç»¼æ€»çºµé‚¹èµ°å¥æç§Ÿè¶³å’æ—ç¥–è¯…é˜»ç»„é’»çº‚å˜´é†‰æœ€ç½ªå°Šéµæ˜¨å·¦ä½æŸžåšä½œå座"], ["d840","è°¸",8,"豂豃豄豅豈豊豋è±",7,"豖豗豘豙豛",5,"è±£",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], ["d880","貈貋è²",6,"貕貖貗貙",20,"äºä¸Œå…€ä¸å»¿å…ä¸•äº˜ä¸žé¬²å­¬å™©ä¸¨ç¦ºä¸¿åŒ•ä¹‡å¤­çˆ»å®æ°å›Ÿèƒ¤é¦—毓ç¾é¼—丶亟é¼ä¹œä¹©äº“芈孛啬å˜ä»„åŽåŽåŽ£åŽ¥åŽ®é¥èµåŒšåµåŒ¦åŒ®åŒ¾èµœå¦å£åˆ‚刈刎刭刳刿剀剌剞剡剜蒯剽劂åŠåŠåŠ“å†‚ç½”äº»ä»ƒä»‰ä»‚ä»¨ä»¡ä»«ä»žä¼›ä»³ä¼¢ä½¤ä»µä¼¥ä¼§ä¼‰ä¼«ä½žä½§æ”¸ä½šä½"], ["d940","è²®",62], ["d980","è³­",32,"佟佗伲伽佶佴侑侉侃ä¾ä½¾ä½»ä¾ªä½¼ä¾¬ä¾”俦俨俪俅俚俣俜俑俟俸倩åŒä¿³å€¬å€å€®å€­ä¿¾å€œå€Œå€¥å€¨å¾åƒå•åˆåŽå¬å»å‚¥å‚§å‚©å‚ºåƒ–å„†åƒ­åƒ¬åƒ¦åƒ®å„‡å„‹ä»æ°½ä½˜ä½¥ä¿Žé¾ æ±†ç±´å…®å·½é»‰é¦˜å†å¤”勹åŒè¨‡åŒå‡«å¤™å…•亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], ["da40","è´Ž",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"è¶’è¶“è¶•",9,"è¶ è¶¡"], ["da80","趢趤",12,"趲趶趷趹趻趽跀è·è·‚跅跇跈跉跊è·è·è·’跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋è¯è¯Žè¯’诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌è°è°‘谒谔谕谖谙谛谘è°è°Ÿè° è°¡è°¥è°§è°ªè°«è°®è°¯è°²è°³è°µè°¶å©åºé˜é˜¢é˜¡é˜±é˜ªé˜½é˜¼é™‚陉陔陟陧陬陲陴隈éšéš—éš°é‚—é‚›é‚邙邬邡邴邳邶邺"], ["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋è¸è¸Žè¸è¸‘踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], ["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰éƒéƒ…邾éƒéƒ„郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆åˆå¥‚劢劬劭劾哿å‹å‹–å‹°åŸç‡®çŸå»´å‡µå‡¼é¬¯å޶å¼ç•šå·¯åŒåž©åž¡å¡¾å¢¼å£…壑圩圬圪圳圹圮圯åœåœ»å‚å©åž…å«åž†å¼å»å¨å­å¶å³åž­åž¤åžŒåž²åŸåž§åž´åž“垠埕埘埚埙埒垸埴埯埸埤åŸ"], ["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"èºèºŸ",11,"躭躮躰躱躳",6,"躻",7], ["dc80","軃",10,"è»",21,"å ‹å åŸ½åŸ­å €å žå ™å¡„堠塥塬å¢å¢‰å¢šå¢€é¦¨é¼™æ‡¿è‰¹è‰½è‰¿èŠèŠŠèŠ¨èŠ„èŠŽèŠ‘èŠ—èŠ™èŠ«èŠ¸èŠ¾èŠ°è‹ˆè‹Šè‹£èŠ˜èŠ·èŠ®è‹‹è‹Œè‹èŠ©èŠ´èŠ¡èŠªèŠŸè‹„è‹ŽèŠ¤è‹¡èŒ‰è‹·è‹¤èŒèŒ‡è‹œè‹´è‹’苘茌苻苓茑茚茆茔茕苠苕茜è‘è›èœèŒˆèŽ’èŒ¼èŒ´èŒ±èŽ›èžèŒ¯èè‡èƒèŸè€èŒ—è èŒ­èŒºèŒ³è¦è¥"], ["dd40","軥",62], ["dd80","輤",32,"è¨èŒ›è©è¬èªè­è®èްè¸èŽ³èŽ´èŽ èŽªèŽ“èŽœèŽ…è¼èŽ¶èŽ©è½èޏè»èŽ˜èŽžèŽ¨èŽºèŽ¼èèè¥è˜å ‡è˜è‹èè½è–èœè¸è‘è†è”èŸèèƒè¸è¹èªè…è€è¦è°è¡è‘œè‘‘葚葙葳蒇蒈葺蒉葸è¼è‘†è‘©è‘¶è’Œè’Žè±è‘­è“è“è“蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌ç”蔸蓰蔹蔟蔺"], ["de40","è½…",32,"轪辀辌辒è¾è¾ è¾¡è¾¢è¾¤è¾¥è¾¦è¾§è¾ªè¾¬è¾­è¾®è¾¯è¾²è¾³è¾´è¾µè¾·è¾¸è¾ºè¾»è¾¼è¾¿è¿€è¿ƒè¿†"], ["de80","迉",4,"è¿è¿’迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇è–蕹薮薜薅薹薷薰藓è—藜藿蘧蘅蘩蘖蘼廾弈夼å¥è€·å¥•奚奘åŒå°¢å°¥å°¬å°´æ‰Œæ‰ªæŠŸæŠ»æ‹Šæ‹šæ‹—æ‹®æŒ¢æ‹¶æŒ¹æ‹æƒæŽ­æ¶æ±æºæŽŽæŽ´æ­æŽ¬æŽŠæ©æŽ®æŽ¼æ²æ¸æ æ¿æ„æžæŽæ‘’æ†æŽ¾æ‘…æ‘æ‹æ›æ æŒæ¦æ¡æ‘žæ’„æ‘­æ’–"], ["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿é€éƒé…é†éˆ",4,"éŽé”é•é–é™éšéœ",5,"é¤é¦é§é©éªé«é¬é¯",4,"é¶",6,"é¾é‚"], ["df80","還邅邆邇邉邊邌",4,"é‚’é‚”é‚–é‚˜é‚šé‚œé‚žé‚Ÿé‚ é‚¤é‚¥é‚§é‚¨é‚©é‚«é‚­é‚²é‚·é‚¼é‚½é‚¿éƒ€æ‘ºæ’·æ’¸æ’™æ’ºæ“€æ“æ“—擤擢攉攥攮弋忒甙弑åŸå±å½å©å¨å»å’å–å†å‘‹å‘’呓呔呖呃å¡å‘—å‘™å£å²å’‚咔呷呱呤咚咛咄呶呦å’å“咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤å“å“哞唛哧唠哽唔哳唢唣å”唑唧唪啧å–喵啉啭å•啕唿å•唼"], ["e040","郂郃郆郈郉郋郌éƒéƒ’郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀é„鄃鄅",19,"鄚鄛鄜"], ["e080","é„鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈å–喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦å—嗄嗯嗥嗲嗳嗌å—嗨嗵嗤辔嘞嘈嘌å˜å˜¤å˜£å—¾å˜€å˜§å˜­å™˜å˜¹å™—嘬å™å™¢å™™å™œå™Œå™”嚆噤噱噫噻噼嚅嚓嚯囔囗å›å›¡å›µå›«å›¹å›¿åœ„圊圉圜å¸å¸™å¸”帑帱帻帼"], ["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎é†é†“",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], ["e180","醼",10,"釈釋é‡é‡’",9,"é‡",8,"帷幄幔幛幞幡岌屺å²å²å²–岈岘岙岑岚岜岵岢岽岬岫岱岣å³å²·å³„峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯åµåµ«åµ‹åµŠåµ©åµ´å¶‚å¶™å¶è±³å¶·å·…彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃ç‹ç‹Žç‹ç‹’狨狯狩狲狴狷çŒç‹³çŒƒç‹º"], ["e240","釦",62], ["e280","鈥",32,"狻猗猓猡猊猞çŒçŒ•猢猹猥猬猸猱ççç—ç ç¬ç¯ç¾èˆ›å¤¥é£§å¤¤å¤‚饣饧",5,"饴饷饽馀馄馇馊é¦é¦é¦‘é¦“é¦”é¦•åº€åº‘åº‹åº–åº¥åº åº¹åºµåº¾åº³èµ“å»’å»‘å»›å»¨å»ªè†ºå¿„å¿‰å¿–å¿æ€ƒå¿®æ€„å¿¡å¿¤å¿¾æ€…æ€†å¿ªå¿­å¿¸æ€™æ€µæ€¦æ€›æ€æ€æ€©æ€«æ€Šæ€¿æ€¡æ¸æ¹æ»æºæ‚"], ["e340","鉆",45,"鉵",16], ["e380","銆",7,"éŠ",24,"æªæ½æ‚–æ‚šæ‚­æ‚æ‚ƒæ‚’æ‚Œæ‚›æƒ¬æ‚»æ‚±æƒæƒ˜æƒ†æƒšæ‚´æ„ æ„¦æ„•愣惴愀愎愫慊慵憬憔憧憷懔懵å¿éš³é—©é—«é—±é—³é—µé—¶é—¼é—¾é˜ƒé˜„阆阈阊阋阌é˜é˜é˜’é˜•é˜–é˜—é˜™é˜šä¸¬çˆ¿æˆ•æ°µæ±”æ±œæ±Šæ²£æ²…æ²æ²”æ²Œæ±¨æ±©æ±´æ±¶æ²†æ²©æ³æ³”沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], ["e440","銨",5,"銯",24,"鋉",31], ["e480","é‹©",32,"æ´¹æ´§æ´Œæµƒæµˆæ´‡æ´„æ´™æ´Žæ´«æµæ´®æ´µæ´šæµæµ’æµ”æ´³æ¶‘æµ¯æ¶žæ¶ æµžæ¶“æ¶”æµœæµ æµ¼æµ£æ¸šæ·‡æ·…æ·žæ¸Žæ¶¿æ· æ¸‘æ·¦æ·æ·™æ¸–æ¶«æ¸Œæ¶®æ¸«æ¹®æ¹Žæ¹«æº²æ¹Ÿæº†æ¹“æ¹”æ¸²æ¸¥æ¹„æ»Ÿæº±æº˜æ» æ¼­æ»¢æº¥æº§æº½æº»æº·æ»—æº´æ»æºæ»‚æºŸæ½¢æ½†æ½‡æ¼¤æ¼•æ»¹æ¼¯æ¼¶æ½‹æ½´æ¼ªæ¼‰æ¼©æ¾‰æ¾æ¾Œæ½¸æ½²æ½¼æ½ºæ¿‘"], ["e540","錊",51,"錿",10], ["e580","éŠ",31,"髿¿‰æ¾§æ¾¹æ¾¶æ¿‚濡濮濞濠濯瀚瀣瀛瀹瀵ççžå®€å®„宕宓宥宸甯骞æ´å¯¤å¯®è¤°å¯°è¹‡è¬‡è¾¶è¿“迕迥迮迤迩迦迳迨逅逄逋逦逑é€é€–逡逵逶逭逯é„é‘é’éé¨é˜é¢é›æš¹é´é½é‚‚邈邃邋å½å½—彖彘尻咫å±å±™å­±å±£å±¦ç¾¼å¼ªå¼©å¼­è‰´å¼¼é¬»å±®å¦å¦ƒå¦å¦©å¦ªå¦£"], ["e640","é¬",34,"éŽ",27], ["e680","鎬",29,"é‹éŒé妗姊妫妞妤姒妲妯姗妾娅娆å§å¨ˆå§£å§˜å§¹å¨Œå¨‰å¨²å¨´å¨‘娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀éªéª…骈骊éªéª’骓骖骘骛骜éªéªŸéª éª¢éª£éª¥éª§çºŸçº¡çº£çº¥çº¨çº©"], ["e740","éŽ",7,"é—",54], ["e780","éŽ",32,"纭纰纾绀ç»ç»‚绉绋绌ç»ç»”绗绛绠绡绨绫绮绯绱绲ç¼ç»¶ç»ºç»»ç»¾ç¼ç¼‚缃缇缈缋缌ç¼ç¼‘缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟çç‚ç‘玷玳ç€ç‰çˆç¥ç™é¡¼çŠç©ç§çžçŽºç²ççªç‘›ç¦ç¥ç¨ç°ç®ç¬"], ["e840","é¯",14,"é¿",43,"鑬鑭鑮鑯"], ["e880","é‘°",20,"钑钖钘铇é“铓铔铚铦铻锜锠ç›çšç‘瑜瑗瑕瑙瑷瑭瑾璜璎璀ç’璇璋璞璨璩ç’ç’§ç“’ç’ºéŸªéŸ«éŸ¬æŒæ“æžæˆæ©æž¥æž‡æªæ³æž˜æž§æµæž¨æžžæž­æž‹æ·æ¼æŸ°æ ‰æŸ˜æ ŠæŸ©æž°æ ŒæŸ™æžµæŸšæž³æŸæ €æŸƒæž¸æŸ¢æ ŽæŸæŸ½æ ²æ ³æ¡ æ¡¡æ¡Žæ¡¢æ¡„æ¡¤æ¢ƒæ æ¡•æ¡¦æ¡æ¡§æ¡€æ ¾æ¡Šæ¡‰æ ©æ¢µæ¢æ¡´æ¡·æ¢“桫棂楮棼椟椠棹"], ["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"é–€",42], ["e980","é–«",32,"æ¤¤æ£°æ¤‹æ¤æ¥—æ££æ¤æ¥±æ¤¹æ¥ æ¥‚æ¥æ¦„æ¥«æ¦€æ¦˜æ¥¸æ¤´æ§Œæ¦‡æ¦ˆæ§Žæ¦‰æ¥¦æ¥£æ¥¹æ¦›æ¦§æ¦»æ¦«æ¦­æ§”æ¦±æ§æ§Šæ§Ÿæ¦•æ§ æ¦æ§¿æ¨¯æ§­æ¨—æ¨˜æ©¥æ§²æ©„æ¨¾æª æ©æ©›æ¨µæªŽæ©¹æ¨½æ¨¨æ©˜æ©¼æª‘æªæª©æª—æª«çŒ·ç’æ®æ®‚æ®‡æ®„æ®’æ®“æ®æ®šæ®›æ®¡æ®ªè½«è½­è½±è½²è½³è½µè½¶è½¸è½·è½¹è½ºè½¼è½¾è¾è¾‚辄辇辋"], ["ea40","é—Œ",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾é™é™ƒé™Šé™Žé™é™‘陒陓陖陗"], ["ea80","陘陙陚陜é™é™žé™ é™£é™¥é™¦é™«é™­",4,"陳陸",12,"隇隉隊è¾è¾Žè¾è¾˜è¾šè»Žæˆ‹æˆ—戛戟戢戡戥戤戬臧瓯瓴瓿ç”ç”‘ç”“æ”´æ—®æ—¯æ—°æ˜Šæ˜™æ²æ˜ƒæ˜•æ˜€ç‚…æ›·æ˜æ˜´æ˜±æ˜¶æ˜µè€†æ™Ÿæ™”æ™æ™æ™–æ™¡æ™—æ™·æš„æšŒæš§æšæš¾æ››æ›œæ›¦æ›©è´²è´³è´¶è´»è´½èµ€èµ…赆赈赉赇èµèµ•赙觇觊觋觌觎è§è§è§‘牮犟ç‰ç‰¦ç‰¯ç‰¾ç‰¿çŠ„çŠ‹çŠçŠçŠ’æŒˆæŒ²æŽ°"], ["eb40","隌階隑隒隓隕隖隚際éš",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋é›é›‘雓雔雖",9,"雡",6,"雫"], ["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌éœéœ‘霒霔霕霗",4,"éœéœŸéœ æ¿æ“˜è€„æ¯ªæ¯³æ¯½æ¯µæ¯¹æ°…æ°‡æ°†æ°æ°•氘氙氚氡氩氤氪氲攵敕敫ç‰ç‰’牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙èƒèƒ—æœèƒèƒ«èƒ±èƒ´èƒ­è„脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧å¡åªµè†ˆè†‚膑滕膣膪臌朦臊膻"], ["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"é”é•é—é˜éšéœééŸé£é¤é¦é§é¨éª",7], ["ec80","é²éµé·",4,"é½",7,"鞆",4,"鞌鞎éžéžéž“鞕鞖鞗鞙",4,"è‡è†¦æ¬¤æ¬·æ¬¹æ­ƒæ­†æ­™é£‘飒飓飕飙飚殳彀毂觳æ–齑斓於旆旄旃旌旎旒旖炀炜炖ç‚炻烀炷炫炱烨烊ç„焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹çˆçˆ¨ç¬ç„˜ç…¦ç†¹æˆ¾æˆ½æ‰ƒæ‰ˆæ‰‰ç¤»ç¥€ç¥†ç¥‰ç¥›ç¥œç¥“祚祢祗祠祯祧祺禅禊禚禧禳忑å¿"], ["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], ["ed80","韤韥韨韮",4,"韴韷",23,"æ€¼ææšæ§ææ™æ£æ‚«æ„†æ„æ…æ†©æ†æ‡‹æ‡‘æˆ†è‚€è¿æ²“泶淼矶矸砀砉砗砘砑斫砭砜ç ç ¹ç ºç »ç Ÿç ¼ç ¥ç ¬ç £ç ©ç¡Žç¡­ç¡–ç¡—ç ¦ç¡ç¡‡ç¡Œç¡ªç¢›ç¢“碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄çœç›¹çœ‡çœˆçœšçœ¢çœ™çœ­çœ¦çœµçœ¸çç‘ç‡çƒçšç¨"], ["ee40","é ",62], ["ee80","顎",32,"ç¢ç¥ç¿çžç½çž€çžŒçž‘瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹ç¾ç½¾ç›ç›¥è ²é’…钆钇钋钊钌é’é’é’钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"é“铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], ["ef40","顯",5,"颋颎颒颕颙颣風",37,"é£é£é£”飖飗飛飜é£é£ ",4], ["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊é”锎é”é”’",4,"锘锛é”锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎é•镒镓镔镖镗镘镙镛镞镟é•镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], ["f040","餈",4,"餎é¤é¤‘",28,"餯",26], ["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑é»é¦¥ç©°çšˆçšŽçš“皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾é¹é¹‚鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠ç–疬疣疳疴疸痄疱疰痃痂痖ç—痣痨痦痤痫痧瘃痱痼痿ç˜ç˜€ç˜…瘌瘗瘊瘥瘘瘕瘙"], ["f140","馌馎馚",10,"馦馧馩",47], ["f180","é§™",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳ç™ç™žç™”癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶è¥è¥¦è¥»ç–‹èƒ¥çš²çš´çŸœè€’耔耖耜耠耢耥耦耧耩耨耱耋耵èƒè†èè’è©è±è¦ƒé¡¸é¢€é¢ƒ"], ["f240","駺",62], ["f280","騹",32,"颉颌é¢é¢é¢”颚颛颞颟颡颢颥颦è™è™”虬虮虿虺虼虻蚨èšèš‹èš¬èšèš§èš£èšªèš“蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉è›èš´è›©è›±è›²è›­è›³è›èœ“蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊èœèœ‰èœ£èœ»èœžèœ¥èœ®èœšèœ¾èˆèœ´èœ±èœ©èœ·èœ¿èž‚蜢è½è¾è»è è°èŒè®èž‹è“è£è¼è¤è™è¥èž“螯螨蟒"], ["f340","驚",17,"驲骃骉éªéªŽéª”骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"é«é«Žé«é«é«’體髕髖髗髙髚髛髜"], ["f380","é«é«žé« é«¢é«£é«¤é«¥é«§é«¨é«©é«ªé«¬é«®é«°",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅èˆç«ºç«½ç¬ˆç¬ƒç¬„笕笊笫ç¬ç­‡ç¬¸ç¬ªç¬™ç¬®ç¬±ç¬ ç¬¥ç¬¤ç¬³ç¬¾ç¬žç­˜ç­šç­…筵筌ç­ç­ ç­®ç­»ç­¢ç­²ç­±ç®ç®¦ç®§ç®¸ç®¬ç®ç®¨ç®…箪箜箢箫箴篑ç¯ç¯Œç¯ç¯šç¯¥ç¯¦ç¯ªç°Œç¯¾ç¯¼ç°ç°–ç°‹"], ["f440","鬇鬉",5,"é¬é¬‘鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎é­é­’é­“é­•",5], ["f480","é­›",32,"簟簪簦簸ç±ç±€è‡¾èˆèˆ‚舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋è‰è‰šè‰Ÿè‰¨è¡¾è¢…袈裘裟襞ç¾ç¾Ÿç¾§ç¾¯ç¾°ç¾²ç±¼æ•‰ç²‘ç²ç²œç²žç²¢ç²²ç²¼ç²½ç³ç³‡ç³Œç³ç³ˆç³…糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊é…é…Žé…é…¤"], ["f540","é­¼",62], ["f580","é®»",32,"酢酡酰酩酯酽酾酲酴酹醌醅é†é†é†‘醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎è·è·›è·†è·¬è··è·¸è·£è·¹è·»è·¤è¸‰è·½è¸”è¸è¸Ÿè¸¬è¸®è¸£è¸¯è¸ºè¹€è¸¹è¸µè¸½è¸±è¹‰è¹è¹‚蹑蹒蹊蹰蹶蹼蹯蹴躅èºèº”èºèºœèºžè±¸è²‚貊貅貘貔斛觖觞觚觜"], ["f640","鯜",62], ["f680","é°›",32,"觥觫觯訾謦é“雩雳雯霆éœéœˆéœéœŽéœªéœ­éœ°éœ¾é¾€é¾ƒé¾…",5,"龌黾鼋é¼éš¹éš¼éš½é›Žé›’瞿雠銎銮鋈錾éªéŠéŽé¾é‘«é±¿é²‚鲅鲆鲇鲈稣鲋鲎é²é²‘鲒鲔鲕鲚鲛鲞",5,"é²¥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], ["f740","é°¼",62], ["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌é²é²“鲖鲗鲘鲙é²é²ªé²¬é²¯é²¹é²¾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜é³é³Ÿé³¢é¼éž…鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼é«é«€é«…髂髋髌髑魅魃魇魉魈é­é­‘飨é¤é¤®é¥•饔髟髡髦髯髫髻髭髹鬈é¬é¬“鬟鬣麽麾縻麂麇麈麋麒é–éºéºŸé»›é»œé»é» é»Ÿé»¢é»©é»§é»¥é»ªé»¯é¼¢é¼¬é¼¯é¼¹é¼·é¼½é¼¾é½„"], ["f840","é³£",62], ["f880","é´¢",32], ["f940","鵃",62], ["f980","é¶‚",32], ["fa40","é¶£",62], ["fa80","é·¢",32], ["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀é¹é¹é¹’鹓鹔鹖鹙é¹é¹Ÿé¹ é¹¡é¹¢é¹¥é¹®é¹¯é¹²é¹´",9,"麀"], ["fb80","éºéºƒéº„麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], ["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌é»é»’黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], ["fc80","鼆",4,"鼌é¼é¼‘鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], ["fd40","é¼²",4,"鼸鼺鼼鼿",4,"é½…",10,"é½’",38], ["fd80","é½¹",5,"é¾é¾‚é¾",11,"龜é¾é¾žé¾¡",4,"郎凉秊裏隣"], ["fe40","兀ï¨ï¨Žï¨ï¨‘﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] ] [ ["0","\u0000",127], ["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], ["8161","갵갶갷갺갻갽갾갿ê±",9,"걌걎",5,"걕"], ["8181","걖걗걙걚걛ê±",18,"걲걳걵걶걹걻",4,"겂겇겈ê²ê²Žê²ê²‘겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋ê³",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿ê´ê´‚괃괅괇",4,"ê´Žê´ê´’ê´“"], ["8241","괔괕괖괗괙괚괛ê´ê´žê´Ÿê´¡",7,"괪괫괮",5], ["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], ["8281","êµ™",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"ê¶Šê¶‹ê¶ê¶Žê¶ê¶‘",10,"ê¶ž",5,"ê¶¥",17,"궸",7,"귂귃귅귆귇귉",6,"ê·’ê·”",7,"ê·ê·žê·Ÿê·¡ê·¢ê·£ê·¥",18], ["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], ["8361","ê¸",18,"긲긳긵긶긹긻긼"], ["8381","긽긾긿깂깄깇깈깉깋ê¹ê¹‘깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"êº",46,"꺿ê»ê»‚껃껅",6,"껎껒",5,"껚껛ê»",8], ["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], ["8461","꼆꼉꼊꼋꼌꼎ê¼ê¼‘",18], ["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"ê¾ê¾‚꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"ê¾",26,"꾺꾻꾽꾾"], ["8541","꾿ê¿",5,"꿊꿌ê¿",4,"ê¿•",6,"ê¿",4], ["8561","ê¿¢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], ["8581","뀅",6,"ë€ë€Žë€ë€‘뀒뀓뀕",6,"뀞",9,"뀩",26,"ë†ë‡ë‰ë‹ëëëë‘ë’ë–ë˜ëšë›ëœëž",29,"ë¾ë¿ë‚낂낃낅",6,"낎ë‚ë‚’",5,"ë‚›ë‚낞낣낤"], ["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], ["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], ["8681","냱",22,"넊ë„넎ë„넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛ë…ë…žë…Ÿë…¡",22,"녺녻녽녾녿ë†ë†ƒ",4,"놊놌놎ë†ë†ë†‘놕놖놗놙놚놛ë†"], ["8741","놞",9,"놩",15], ["8761","놹",18,"ë‡ë‡Žë‡ë‡‘뇒뇓뇕"], ["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊ëˆ",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛ë‰ë‰žë‰Ÿë‰¡",6,"뉪",4], ["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], ["8861","ëŠëŠ’ëŠ“ëŠ•ëŠ–ëŠ—ëŠ›",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], ["8881","늸",15,"닊닋ë‹ë‹Žë‹ë‹‘ë‹“",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"ëŒ",54,"ë—ë™ëšëë ë¡ë¢ë£"], ["8941","ë¦ë¨ëªë¬ë­ë¯ë²ë³ëµë¶ë·ë¹",6,"뎂뎆",5,"ëŽ"], ["8961","뎎ëŽëŽ‘ëŽ’ëŽ“ëŽ•",10,"뎢",5,"뎩뎪뎫뎭"], ["8981","뎮",21,"ë†ë‡ë‰ëŠëëë‘ë’ë“ë–ë˜ëšëœëžëŸë¡ë¢ë£ë¥ë¦ë§ë©",18,"ë½",18,"ë‘",6,"ë™ëšë›ëëžëŸë¡",6,"ëªë¬",7,"ëµ",15], ["8a41","ë‘…",10,"ë‘’ë‘“ë‘•ë‘–ë‘—ë‘™",6,"둢둤둦"], ["8a61","ë‘§",4,"ë‘­",18,"ë’ë’‚"], ["8a81","ë’ƒ",4,"ë’‰",19,"ë’ž",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"ë“듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚ë”"], ["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], ["8b61","땇땈땉땊땎ë•ë•‘ë•’ë•“ë••",6,"땞땢",8], ["8b81","ë•«",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿ë—뗂뗃뗅",6,"ë—Žë—’",5,"ë—™",18,"ë—­",18], ["8c41","똀",15,"똒똓똕똖똗똙",4], ["8c61","똞",6,"똦",5,"똭",6,"똵",5], ["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], ["8d41","뛃",16,"뛕",8], ["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], ["8d81","ë›»",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"ë…ë†ë‡ë‰ëŠë‹ë",6,"ë–",9,"ë¡ë¢ë£ë¥ë¦ë§ë©",6,"ë²ë´ë¶",5,"ë¾ë¿ëžëž‚랃랅",6,"랎랓랔랕랚랛ëžëžž"], ["8e41","랟랡",6,"랪랮",5,"ëž¶ëž·ëž¹",8], ["8e61","럂",4,"럈럊",19], ["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"ë Šë ‹ë ë Žë ë ‘",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"ë ¶ë º",5,"ë¡ë¡‚롃롅",11,"ë¡’ë¡”",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], ["8f41","뢅",7,"뢎",17], ["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], ["8f81","뢾뢿룂룄룆",5,"ë£ë£Žë£ë£‘룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿ë¥ë¥‚륃륅",6,"ë¥ë¥Žë¥ë¥’",5], ["9041","륚륛ë¥ë¥žë¥Ÿë¥¡",6,"륪륬륮",5,"륶륷륹륺륻륽"], ["9061","륾",5,"릆릈릋릌ë¦",15], ["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"ë§Šë§‹ë§ë§“",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"ë§¶ë§»",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿ë©ë©ƒë©„멅멆"], ["9141","멇멊멌ë©ë©ë©‘멒멖멗멙멚멛ë©",6,"멦멪",5], ["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋ëª",5], ["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿ë¬ë¬‚묃묅",7,"묎ë¬ë¬’",5,"묙묚묛ë¬ë¬žë¬Ÿë¬¡",6], ["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], ["9261","ë­“ë­•ë­–ë­—ë­™",7,"뭢뭤",7,"ë­­",4], ["9281","ë­²",21,"뮉뮊뮋ë®ë®Žë®ë®‘",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"ë¯ë¯‚믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾ë°"], ["9341","ë°ƒ",4,"ë°Šë°Žë°ë°’밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], ["9361","ë°¶ë°·ë°¹",6,"뱂뱆뱇뱈뱊뱋뱎ë±ë±‘",8], ["9381","뱚뱛뱜뱞",37,"벆벇벉벊ë²ë²",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿ë³ë³‚볃볅",7,"볎볒볓볔볖볗볙볚볛ë³",22,"볷볹볺볻볽"], ["9441","ë³¾",5,"봆봈봊",5,"ë´‘ë´’ë´“ë´•",8], ["9461","ë´ž",5,"ë´¥",6,"ë´­",12], ["9481","ë´º",5,"ëµ",6,"뵊뵋ëµëµŽëµëµ‘",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛ë¶",6,"ë¶¥",10,"ë¶±",6,"ë¶¹",24], ["9541","뷒뷓뷖뷗뷙뷚뷛ë·",11,"ë·ª",5,"ë·±"], ["9561","뷲뷳뷵뷶뷷뷹",6,"ë¸ë¸‚븄븆",5,"븎ë¸ë¸‘븒븓"], ["9581","븕",6,"븞븠",35,"빆빇빉빊빋ë¹ë¹",4,"빖빘빜ë¹ë¹žë¹Ÿë¹¢ë¹£ë¹¥ë¹¦ë¹§ë¹©ë¹«",4,"빲빶",4,"빾빿ëºëº‚뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], ["9641","뺸",23,"뻒뻓"], ["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"ë»­",8], ["9681","ë»¶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], ["9741","뾃",16,"뾕",8], ["9761","뾞",17,"ë¾±",7], ["9781","ë¾¹",11,"뿆",5,"뿎ë¿ë¿‘ë¿’ë¿“ë¿•",6,"ë¿ë¿žë¿ ë¿¢",89,"쀽쀾쀿"], ["9841","ì€",16,"ì’",5,"ì™ìšì›"], ["9861","ììžìŸì¡",6,"ìª",15], ["9881","ìº",21,"ì‚’ì‚“ì‚•ì‚–ì‚—ì‚™",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋ìƒìƒŽìƒìƒ‘",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"ì„섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], ["9941","섲섳섴섵섷섺섻섽섾섿ì…",6,"ì…Šì…Ž",5,"ì…–ì…—"], ["9961","셙셚셛ì…",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], ["9981","ì…¼",8,"솆",5,"ì†ì†‘솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋ì‡",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿ìˆìˆ‚숃숅",6,"숎ìˆìˆ’",5,"숚숛ìˆìˆžìˆ¡ìˆ¢ìˆ£"], ["9a41","숤숥숦숧숪숬숮숰숳숵",16], ["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], ["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿ìŒ",6,"쌊쌋쌎ìŒ"], ["9b41","ìŒìŒ‘쌒쌖쌗쌙쌚쌛ìŒ",6,"쌦쌧쌪",8], ["9b61","쌳",17,"ì†",7], ["9b81","ìŽ",25,"ìªì«ì­ì®ì¯ì±ì³",4,"ìºì»ì¾",5,"쎅쎆쎇쎉쎊쎋ìŽ",50,"ì",22,"ìš"], ["9c41","ì›ììžì¡ì£",4,"ìªì«ì¬ì®",5,"ì¶ì·ì¹",5], ["9c61","ì¿",8,"ì‰",6,"ì‘",9], ["9c81","ì›",8,"ì¥",6,"ì­ì®ì¯ì±ì²ì³ìµ",6,"ì¾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"ì’",18,"ì’•",6,"ì’",12], ["9d41","ì’ª",13,"쒹쒺쒻쒽",8], ["9d61","쓆",25], ["9d81","ì“ ",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"ì”씎ì”씑씒씓씕",6,"ì”",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋ì•ì•앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿ì–얂얃얅얆얈얉얊얋얎ì–ì–’ì–“ì–”"], ["9e41","얖얙얚얛ì–ì–žì–Ÿì–¡",7,"ì–ª",9,"ì–¶"], ["9e61","얷얺얿",4,"ì—‹ì—ì—ì—’ì—“ì—•ì—–ì——ì—™",6,"엢엤엦엧"], ["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋ì˜ì˜Žì˜ì˜‘",6,"옚ì˜",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"ì™’ì™–",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿ìš",6,"욊욌욎",5,"욖욗욙욚욛ìš",6,"욦"], ["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], ["9f61","ì›ì›‘웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], ["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋ìœ",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿ìì‚ìƒì…",4,"ì‹ìŽìì™ìšì›ììžìŸì¡",6,"ì©ìªì¬",7,"ì¶ì·ì¹ìºì»ì¿ìž€ìžìž‚잆잋잌ìžìžìž’잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], ["a041","잸잹잺잻잾쟂",5,"쟊쟋ìŸìŸìŸ‘",6,"쟙쟚쟛쟜"], ["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], ["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿ì¡",6,"졊졋졎",5,"ì¡•",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], ["a141","좥좦좧좩",18,"좾좿죀ì£"], ["a161","죂죃죅죆죇죉죊죋ì£",6,"죖죘죚",5,"죢죣죥"], ["a181","죦",14,"죶",5,"죾죿ì¤ì¤‚줃줇",4,"줎 ã€ã€‚·‥…¨〃­―∥\∼‘’“â€ã€”〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○â—◎◇◆□■△▲▽▼→â†â†‘↓↔〓≪≫√∽âˆâˆµâˆ«âˆ¬âˆˆâˆ‹âŠ†âŠ‡âŠ‚âŠƒâˆªâˆ©âˆ§âˆ¨ï¿¢"], ["a241","ì¤ì¤’",5,"줙",18], ["a261","줭",6,"줵",18], ["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘Ë˚˙¸˛¡¿Ë∮∑âˆÂ¤â„‰â€°â—◀▷▶♤♠♡♥♧♣⊙◈▣â—◑▒▤▥▨▧▦▩♨â˜â˜Žâ˜œâ˜žÂ¶â€ â€¡â†•↗↙↖↘♭♩♪♬㉿㈜№ã‡â„¢ã‚ã˜â„¡â‚¬Â®"], ["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋ì¦ì¦Žì¦"], ["a361","즑",6,"즚즜즞",16], ["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛ï¼",58,"₩]",32,"ï¿£"], ["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿ì¨ì¨‚쨃쨄"], ["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], ["a481","쨦쨧쨨쨪",28,"ㄱ",93], ["a541","쩇",4,"쩎ì©ì©‘ì©’ì©“ì©•",6,"쩞쩢",5,"쩩쩪"], ["a561","ì©«",17,"쩾",5,"쪅쪆"], ["a581","쪇",16,"쪙",14,"â…°",9], ["a5b0","â… ",9], ["a5c1","Α",16,"Σ",6], ["a5e1","α",16,"σ",6], ["a641","쪨",19,"쪾쪿ì«ì«‚쫃쫅"], ["a661","쫆",5,"쫎ì«ì«’쫔쫕쫖쫗쫚",5,"ì«¡",6], ["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌â”┘└├┬┤┴┼â”┃â”┓┛┗┣┳┫┻╋┠┯┨┷┿â”┰┥┸╂┒┑┚┙┖┕┎â”┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀â•╃",7], ["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], ["a761","쬪",22,"쭂쭃쭄"], ["a781","쭅쭆쭇쭊쭋ì­ì­Žì­ì­‘",6,"쭚쭛쭜쭞",5,"ì­¥",7,"㎕㎖㎗ℓ㎘ã„㎣㎤㎥㎦㎙",9,"ãŠãŽãŽŽãŽã㎈㎉ãˆãŽ§ãŽ¨ãŽ°",9,"㎀",4,"㎺",5,"ãŽ",4,"Ωã€ã㎊㎋㎌ã–ã…㎭㎮㎯ã›ãŽ©ãŽªãŽ«ãŽ¬ããã“ãƒã‰ãœã†"], ["a841","ì­­",10,"ì­º",14], ["a861","쮉",18,"ì®",6], ["a881","쮤",19,"쮹",11,"ÆÃªĦ"], ["a8a6","IJ"], ["a8a8","Ä¿ÅØŒºÞŦŊ"], ["a8b1","㉠",27,"â“",25,"â‘ ",14,"½⅓⅔¼¾⅛⅜â…â…ž"], ["a941","쯅",14,"쯕",10], ["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], ["a981","쯽",14,"ì°Žì°ì°‘ì°’ì°“ì°•",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"â’œ",25,"â‘´",14,"¹²³â´â¿â‚₂₃₄"], ["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋ì±ì±Ž"], ["aa61","ì±",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], ["aa81","챳챴챶",29,"ã",82], ["ab41","첔첕첖첗첚첛ì²ì²žì²Ÿì²¡",6,"첪첮",5,"ì²¶ì²·ì²¹"], ["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], ["ab81","ì³›",8,"ì³¥",6,"쳭쳮쳯쳱",12,"ã‚¡",85], ["ac41","쳾쳿촀촂",5,"ì´Šì´‹ì´ì´Žì´ì´‘",6,"촚촜촞촟촠"], ["ac61","촡촢촣촥촦촧촩촪촫촭",11,"ì´º",4], ["ac81","ì´¿",28,"ìµìµžìµŸÐ",5,"ÐЖ",25], ["acd1","а",5,"ёж",25], ["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"ìµ¹",7], ["ad61","ì¶",6,"춉",10,"춖춗춙춚춛ì¶ì¶žì¶Ÿ"], ["ad81","춠춡춢춣춦춨춪",5,"ì¶±",18,"ì·…"], ["ae41","ì·†",5,"ì·ì·Žì·ì·‘",16], ["ae61","ì·¢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], ["ae81","츃츅츆츇츉츊츋ì¸",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], ["af41","츬츭츮츯츲츴츶",19], ["af61","칊",13,"칚칛ì¹ì¹žì¹¢",5,"칪칬"], ["af81","ì¹®",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], ["b041","캚",5,"캢캦",5,"캮",12], ["b061","캻",5,"컂",19], ["b081","ì»–",13,"컦컧컩컪컭",6,"컶컺",5,"ê°€ê°ê°„갇갈갉갊ê°",7,"ê°™",4,"갠갤갬갭갯갰갱갸갹갼걀걋ê±ê±”걘걜거걱건걷걸걺검ê²ê²ƒê²„겅겆겉겊겋게ê²ê²”겜ê²ê²Ÿê² ê²¡ê²¨ê²©ê²ªê²¬ê²¯ê²°ê²¸ê²¹ê²»ê²¼ê²½ê³ê³„곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], ["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"ì¼ì¼žì¼Ÿì¼¡ì¼¢ì¼£"], ["b161","ì¼¥",6,"켮켲",5,"ì¼¹",11], ["b181","ì½…",14,"콖콗콙콚콛ì½",6,"콦콨콪콫콬괌ê´ê´ê´‘괘괜괠괩괬괭괴괵괸괼굄굅굇굉êµêµ”굘굡굣구국군굳굴굵굶굻굼굽굿ê¶ê¶‚궈궉권ê¶ê¶œê¶ê¶¤ê¶·ê·€ê·ê·„ê·ˆê·ê·‘귓규균귤그극근귿글ê¸ê¸ˆê¸‰ê¸‹ê¸ê¸”기긱긴긷길긺김ê¹ê¹ƒê¹…깆깊까ê¹ê¹Žê¹ê¹”깖깜ê¹ê¹Ÿê¹ ê¹¡ê¹¥ê¹¨ê¹©ê¹¬ê¹°ê¹¸"], ["b241","콭콮콯콲콳콵콶콷콹",6,"ì¾ì¾‚쾃쾄쾆",5,"ì¾"], ["b261","쾎",18,"ì¾¢",5,"쾩"], ["b281","쾪",5,"ì¾±",18,"ì¿…",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌ê»ê»ê»ê»‘께껙껜껨껫껭껴껸껼꼇꼈ê¼ê¼ê¼¬ê¼­ê¼°ê¼²ê¼´ê¼¼ê¼½ê¼¿ê½ê½‚꽃꽈꽉ê½ê½œê½ê½¤ê½¥ê½¹ê¾€ê¾„꾈ê¾ê¾‘꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋ê¿ê¿Žê¿”꿜꿨꿩꿰꿱꿴꿸뀀ë€ë€„뀌ë€ë€”뀜ë€ë€¨ë„ë…ëˆëŠëŒëŽë“ë”ë•ë—ë™"], ["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], ["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿í€í€‚퀃퀅",5], ["b381","퀋",5,"퀒",5,"퀙",19,"ëë¼ë½ë‚€ë‚„낌ë‚ë‚낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉ëƒëƒ‘냔냘냠냥너넉넋넌ë„넒넓넘넙넛넜ë„넣네넥넨넬넴넵넷넸넹녀ë…ë…„ë…ˆë…녑녔녕녘녜녠노녹논놀놂놈놉놋ë†ë†’놓놔놘놜놨뇌ë‡ë‡”뇜ë‡"], ["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"í†íˆíŠ",5], ["b461","í‘í’í“í•í–í—í™",6,"í¡",10,"í®í¯"], ["b481","í±í²í³íµ",6,"í¾í¿í‚€í‚‚",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉ëŠëŠ‘ëŠ”ëŠ˜ëŠ™ëŠšëŠ ëŠ¡ëŠ£ëŠ¥ëŠ¦ëŠªëŠ¬ëŠ°ëŠ´ë‹ˆë‹‰ë‹Œë‹ë‹’님닙닛ë‹ë‹¢ë‹¤ë‹¥ë‹¦ë‹¨ë‹«",4,"닳담답닷",4,"닿대ëŒëŒ„댈ëŒëŒ‘댓댔댕댜ë”ë•ë–ë˜ë›ëœëžëŸë¤ë¥"], ["b541","í‚•",14,"킦킧킩킪킫킭",5], ["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], ["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"ë§ë©ë«ë®ë°ë±ë´ë¸ëŽ€ëŽëŽƒëŽ„ëŽ…ëŽŒëŽëŽ”ëŽ ëŽ¡ëŽ¨ëŽ¬ë„ë…ëˆë‹ëŒëŽëë”ë•ë—ë™ë›ëë ë¤ë¨ë¼ëë˜ëœë ë¨ë©ë«ë´ë‘둑둔둘둠둡둣둥둬뒀뒈ë’뒤뒨뒬뒵뒷뒹듀듄듈ë“듕드ë“든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], ["b641","í„…",7,"턎",17], ["b661","í„ ",15,"턲턳턵턶턷턹턻턼턽턾"], ["b681","í„¿í…‚í…†",5,"í…Ží…í…‘í…’í…“í…•",6,"í…ží… í…¢",5,"텩텪텫텭땀ë•땃땄땅땋때ë•ë•땔땜ë•땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌ë—ë—ë—뗑뗘뗬ë˜ë˜‘똔똘똥똬똴뙈뙤뙨뚜ëšëš ëš¤ëš«ëš¬ëš±ë›”뛰뛴뛸뜀ëœëœ…뜨뜩뜬뜯뜰뜸뜹뜻ë„ëˆëŒë”ë•ë ë¤ë¨ë°ë±ë³ëµë¼ë½ëž€ëž„람ëžëžëžëž‘ëž’ëž–ëž—"], ["b741","í…®",13,"í…½",6,"톅톆톇톉톊"], ["b761","톋",20,"톢톣톥톦톧"], ["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿í‡",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀ë ë ‡ë ˆë ‰ë Œë ë ˜ë ™ë ›ë ë ¤ë ¥ë ¨ë ¬ë ´ë µë ·ë ¸ë ¹ë¡€ë¡„롑롓로ë¡ë¡ ë¡¤ë¡¬ë¡­ë¡¯ë¡±ë¡¸ë¡¼ë¢ë¢¨ë¢°ë¢´ë¢¸ë£€ë£ë£ƒë£…료ë£ë£”ë£ë£Ÿë£¡ë£¨ë£©ë£¬ë£°ë£¸ë£¹ë£»ë£½ë¤„뤘뤠뤼뤽륀륄륌ë¥ë¥‘류륙륜률륨륩"], ["b841","í‡",7,"퇙",17], ["b861","퇫",8,"퇵퇶퇷퇹",13], ["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊ë¦ë¦Žë¦¬ë¦­ë¦°ë¦´ë¦¼ë¦½ë¦¿ë§ë§ˆë§‰ë§Œë§Ž",4,"맘맙맛ë§ë§žë§¡ë§£ë§¤ë§¥ë§¨ë§¬ë§´ë§µë§·ë§¸ë§¹ë§ºë¨€ë¨ë¨ˆë¨•머먹먼멀멂멈멉멋ë©ë©Žë©“메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], ["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], ["b961","í‰",14,"í‰",6,"퉥퉦퉧퉨"], ["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄ë¬ë¬ë¬‘묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉ë­ë­ë­ë­”뭘뭡뭣뭬뮈뮌ë®ë®¤ë®¨ë®¬ë®´ë®·ë¯€ë¯„믈ë¯ë¯“미믹민믿밀밂밈밉밋밌ë°ë°ë°‘ë°”",4,"ë°›",4,"밤밥밧방밭배백밴밸뱀ë±ë±ƒë±„뱅뱉뱌ë±ë±ë±ë²„벅번벋벌벎범법벗"], ["ba41","íŠíŠŽíŠíŠ’íŠ“íŠ”íŠ–",5,"íŠíŠžíŠŸíŠ¡íŠ¢íŠ£íŠ¥",6,"튭"], ["ba61","튮튯튰튲",5,"튺튻튽튾í‹í‹ƒ",4,"틊틌",5], ["ba81","틒틓틕틖틗틙틚틛í‹",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별ë³ë³ë³ë³‘볕볘볜보복볶본볼봄봅봇봉ë´ë´”봤봬뵀뵈뵉뵌ëµëµ˜ëµ™ëµ¤ëµ¨ë¶€ë¶ë¶„붇불붉붊ë¶ë¶‘붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브ë¸ë¸ë¸”븜ë¸ë¸Ÿë¹„빅빈빌빎빔빕빗빙빚빛빠빡빤"], ["bb41","í‹»",4,"팂팄팆",5,"íŒíŒ‘팒팓팕팗",4,"팞팢팣"], ["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"í†í‡íˆí‰"], ["bb81","íŠ",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌ëºëºëºëº‘뺘뺙뺨ë»ë»‘뻔뻗뻘뻠뻣뻤뻥뻬ë¼ë¼ˆë¼‰ë¼˜ë¼™ë¼›ë¼œë¼ë½€ë½ë½„뽈ë½ë½‘뽕뾔뾰뿅뿌ë¿ë¿ë¿”뿜뿟뿡쀼ì‘ì˜ìœì ì¨ì©ì‚삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀ìƒìƒ…새색샌ìƒìƒ˜ìƒ™ìƒ›ìƒœìƒìƒ¤"], ["bc41","íª",17,"í¾í¿íŽíŽ‚íŽƒíŽ…íŽ†íŽ‡"], ["bc61","펈펉펊펋펎펒",5,"펚펛íŽíŽžíŽŸíŽ¡",6,"펪펬펮"], ["bc81","펯",4,"펵펶펷펹펺펻펽",6,"í†í‡íŠ",5,"í‘",5,"샥샨샬샴샵샷샹섀섄섈ì„섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌ì…셔셕션셜셤셥셧셨셩셰셴셸솅소ì†ì†Žì†ì†”솖솜ì†ì†Ÿì†¡ì†¥ì†¨ì†©ì†¬ì†°ì†½ì‡„쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌ìˆìˆìˆ‘수숙순숟술숨숩숫숭"], ["bd41","í—í™",7,"í¢í¤",7,"í®í¯í±í²í³íµí¶í·"], ["bd61","í¸í¹íºí»í¾í€í‚",5,"í‰",13], ["bd81","í—",5,"íž",25,"숯숱숲숴쉈ì‰ì‰‘쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿ìŠìŠˆìŠ‰ìŠìŠ˜ìŠ›ìŠìŠ¤ìŠ¥ìŠ¨ìŠ¬ìŠ­ìŠ´ìŠµìŠ·ìŠ¹ì‹œì‹ì‹ ì‹£ì‹¤ì‹«ì‹¬ì‹­ì‹¯ì‹±ì‹¶ì‹¸ì‹¹ì‹»ì‹¼ìŒ€ìŒˆìŒ‰ìŒŒìŒìŒ“쌔쌕쌘쌜쌤쌥쌨쌩ì…ì¨ì©ì¬ì°ì²ì¸ì¹ì¼ì½ìŽ„ìŽˆìŽŒì€ì˜ì™ìœìŸì ì¢ì¨ì©ì­ì´ìµì¸ìˆìì¤ì¬ì°"], ["be41","í¸",7,"í‘푂푃푅",14], ["be61","í‘”",7,"í‘푞푟푡푢푣푥",7,"푮푰푱푲"], ["be81","푳",4,"푺푻푽푾í’í’ƒ",4,"풊풌풎",5,"í’•",8,"ì´ì¼ì½ì‘ˆì‘¤ì‘¥ì‘¨ì‘¬ì‘´ì‘µì‘¹ì’€ì’”쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀ì”씌ì”씔씜씨씩씬씰씸씹씻씽아악안앉않알ì•앎앓암압앗았앙ì•앞애액앤앨앰앱앳앴앵야약얀얄얇얌ì–ì–양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], ["bf41","í’ž",10,"í’ª",14], ["bf61","í’¹",18,"í“퓎í“í“‘í“’í““í“•"], ["bf81","í“–",5,"í“퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼ì—엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌ì˜ì˜˜ì˜™ì˜›ì˜œì˜¤ì˜¥ì˜¨ì˜¬ì˜­ì˜®ì˜°ì˜³ì˜´ì˜µì˜·ì˜¹ì˜»ì™€ì™ì™„왈ì™ì™‘왓왔왕왜ì™ì™ ì™¬ì™¯ì™±ì™¸ì™¹ì™¼ìš€ìšˆìš‰ìš‹ìšìš”욕욘욜욤욥욧용우욱운울욹욺움ì›ì›ƒì›…워ì›ì›ì›”웜ì›ì› ì›¡ì›¨"], ["c041","퓾",5,"픅픆픇픉픊픋í”",6,"픖픘",5], ["c061","픞",25], ["c081","픸픹픺픻픾픿í•핂핃핅",6,"핎í•í•’",5,"핚핛í•핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽ì€ì„ìŠìŒììì‘",7,"ìœì ì¨ì«ì´ìµì¸ì¼ì½ì¾ìžƒìž„입잇있잉잊잎ìžìž‘잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀ìŸìŸˆìŸ‰ìŸŒìŸŽìŸìŸ˜ìŸìŸ¤ìŸ¨ìŸ¬ì €ì ì „절젊"], ["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], ["c161","í–Œí–í–Ží–í–‘",19,"햦햧"], ["c181","í–¨",31,"ì ì ‘ì “ì •ì –ì œì ì  ì ¤ì ¬ì ­ì ¯ì ±ì ¸ì ¼ì¡€ì¡ˆì¡‰ì¡Œì¡ì¡”조족존졸졺좀ì¢ì¢ƒì¢…좆좇좋좌ì¢ì¢”ì¢ì¢Ÿì¢¡ì¢¨ì¢¼ì¢½ì£„죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌ì¤ì¤ì¤‘줘줬줴ì¥ì¥‘쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌ì¦ì¦˜ì¦™ì¦›ì¦ì§€ì§ì§„짇질짊ì§ì§‘ì§“"], ["c241","í—Ší—‹í—í—Ží—í—‘í—“",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], ["c261","í—¯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], ["c281","혖",5,"í˜í˜ží˜Ÿí˜¡í˜¢í˜£í˜¥",7,"혮",9,"혺혻징짖짙짚짜ì§ì§ ì§¢ì§¤ì§§ì§¬ì§­ì§¯ì§°ì§±ì§¸ì§¹ì§¼ì¨€ì¨ˆì¨‰ì¨‹ì¨Œì¨ì¨”쨘쨩쩌ì©ì©ì©”쩜ì©ì©Ÿì© ì©¡ì©¨ì©½ìª„쪘쪼쪽쫀쫄쫌ì«ì«ì«‘쫓쫘쫙쫠쫬쫴쬈ì¬ì¬”쬘쬠쬡ì­ì­ˆì­‰ì­Œì­ì­˜ì­™ì­ì­¤ì­¸ì­¹ì®œì®¸ì¯”쯤쯧쯩찌ì°ì°ì°”ì°œì°ì°¡ì°¢ì°§ì°¨ì°©ì°¬ì°®ì°°ì°¸ì°¹ì°»"], ["c341","혽혾혿í™í™‚홃홄홆홇홊홌홎í™í™í™’홓홖홗홙홚홛í™",4], ["c361","홢",4,"홨홪",5,"홲홳홵",11], ["c381","íšíš‚횄횆",5,"횎íšíš‘횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉ì³ì³”쳤쳬쳰ì´ì´ˆì´‰ì´Œì´ì´˜ì´™ì´›ì´ì´¤ì´¨ì´¬ì´¹ìµœìµ ìµ¤ìµ¬ìµ­ìµ¯ìµ±ìµ¸ì¶ˆì¶”축춘출춤춥춧충춰췄췌ì·ì·¨ì·¬ì·°ì·¸ì·¹ì·»ì·½ì¸„츈츌츔츙츠측츤츨츰츱츳층"], ["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], ["c461","í›í›Ží›í›í›’훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], ["c481","훮훯훱훲훳훴훶",5,"훾훿íœíœ‚휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉ìºìº‘캔캘캠캡캣캤캥캬캭ì»ì»¤ì»¥ì»¨ì»«ì»¬ì»´ì»µì»·ì»¸ì»¹ì¼€ì¼ì¼„켈ì¼ì¼‘켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], ["c541","휕휖휗휚휛íœíœžíœŸíœ¡",6,"휪휬휮",5,"휶휷휹"], ["c561","휺휻휽",6,"í…í†íˆíŠ",5,"í’í“í•íš",4], ["c581","íŸí¢í¤í¦í§í¨íªí«í­í®í¯í±í²í³íµ",6,"í¾í¿íž€íž‚",5,"힊힋í„í…í‡í‰íí”í˜í í¬í­í°í´í¼í½í‚키킥킨킬킴킵킷킹타íƒíƒ„탈탉íƒíƒ‘탓탔탕태íƒíƒ íƒ¤íƒ¬íƒ­íƒ¯íƒ°íƒ±íƒ¸í„터턱턴털턺텀í…텃텄텅테í…í…텔템í…텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉íˆíˆ¬íˆ­íˆ°íˆ´íˆ¼íˆ½íˆ¿í‰í‰ˆí‰œ"], ["c641","ížížŽížíž‘",6,"힚힜힞",5], ["c6a1","퉤튀íŠíŠ„íŠˆíŠíŠ‘íŠ•íŠœíŠ íŠ¤íŠ¬íŠ±íŠ¸íŠ¹íŠ¼íŠ¿í‹€í‹‚í‹ˆí‹‰í‹‹í‹”í‹˜í‹œí‹¤í‹¥í‹°í‹±í‹´í‹¸íŒ€íŒíŒƒíŒ…파íŒíŒŽíŒíŒ”팖팜íŒíŒŸíŒ íŒ¡íŒ¥íŒ¨íŒ©íŒ¬íŒ°íŒ¸íŒ¹íŒ»íŒ¼íŒ½í„í…í¼í½íŽ€íŽ„íŽŒíŽíŽíŽíŽ‘íŽ˜íŽ™íŽœíŽ íŽ¨íŽ©íŽ«íŽ­íŽ´íŽ¸íŽ¼í„í…íˆí‰íí˜í¡í£í¬í­í°í´í¼í½í¿í"], ["c7a1","íˆí푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋í’풔풩퓌í“퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌í•í•핑하학한할핥함합핫항해핵핸핼햄햅햇했행í–향허헉헌í—헒험헙헛í—헤헥헨헬헴헵헷헹혀í˜í˜„혈í˜í˜‘혓혔형혜혠"], ["c8a1","혤혭호혹혼홀홅홈홉홋í™í™‘화확환활홧황홰홱홴횃횅회íšíšíš”íšíšŸíš¡íš¨íš¬íš°íš¹íš»í›„훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼í„í‡í‰íí‘í”í–í—í˜í™í í¡í£í¥í©í¬í°í´í¼í½ížížˆíž‰ížŒížíž˜íž™íž›íž"], ["caa1","伽佳å‡åƒ¹åŠ å¯å‘µå“¥å˜‰å«å®¶æš‡æž¶æž·æŸ¯æ­Œç‚痂稼苛茄街袈訶賈è·è»»è¿¦é§•刻å´å„æªæ…¤æ®¼çè„šè¦ºè§’é–£ä¾ƒåˆŠå¢¾å¥¸å§¦å¹²å¹¹æ‡‡æ€æ†æŸ¬æ¡¿æ¾—癎看磵稈竿簡è‚è‰®è‰±è««é–“ä¹«å–æ›·æ¸´ç¢£ç«­è‘›è¤èŽéž¨å‹˜åŽå ªåµŒæ„Ÿæ†¾æˆ¡æ•¢æŸ‘橄減甘疳監瞰紺邯鑑鑒龕"], ["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑è¥è¬›é‹¼é™é±‡ä»‹ä»·å€‹å‡±å¡æ„·æ„¾æ…¨æ”¹æ§ªæ¼‘疥皆盖箇芥蓋豈鎧開喀客å‘ï¤ç²³ç¾¹é†µå€¨åŽ»å±…å·¨æ‹’æ®æ“šæ“§æ¸ ç‚¬ç¥›è·è¸žï¤‚é½é‰…鋸乾件å¥å·¾å»ºæ„†æ¥—腱虔蹇éµé¨«ä¹žå‚‘æ°æ¡€å„‰åŠåŠ’æª¢"], ["cca1","çž¼éˆé»”åŠ«æ€¯è¿²åˆæ†©æ­æ“Šæ ¼æª„激膈覡隔堅牽犬甄絹繭肩見譴é£éµ‘抉決潔çµç¼ºè¨£å…¼æ…Šç®è¬™é‰—鎌京俓倞傾儆å‹å‹å¿å°å¢ƒåºšå¾‘慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕é¡é ƒé ¸é©šé¯¨ä¿‚啓堺契季屆悸戒桂械"], ["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄å¤å©å‘Šå‘±å›ºå§‘å­¤å°»åº«æ‹·æ”·æ•…æ•²æš æž¯æ§æ²½ç—¼çšç¾ç¨¿ç¾”考股è†è‹¦è‹½è°è—蠱袴誥賈辜錮雇顧高鼓哭斛曲æ¢ç©€è°·éµ å›°å¤å´‘æ˜†æ¢±æ£æ»¾ç¨è¢žé¯¤æ±¨ï¤„éª¨ä¾›å…¬å…±åŠŸå­”å·¥ææ­æ‹±æŽ§æ”»ç™ç©ºèš£è²¢éžä¸²å¯¡æˆˆæžœç“œ"], ["cea1","ç§‘è“誇課跨éŽé‹é¡†å»“槨藿郭串冠官寬慣棺款çŒç¯ç“˜ç®¡ç½è…è§€è²«é—œé¤¨åˆ®ææ‹¬é€‚侊光匡壙廣曠洸炚狂ç–ç­èƒ±é‘›å¦æŽ›ç½«ä¹–å‚€å¡Šå£žæ€ªæ„§æ‹æ§é­å®ç´˜è‚±è½Ÿäº¤åƒ‘咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久ä¹ä»‡ä¿±å…·å‹¾"], ["cfa1","å€å£å¥å’Žå˜”åµåž¢å¯‡å¶‡å»æ‡¼æ‹˜æ•‘æž¸æŸ©æ§‹æ­æ¯†æ¯¬æ±‚æºç¸ç‹—玖çƒçž¿çŸ©ç©¶çµ¿è€‰è‡¼èˆ…舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局èŠéž éž«éº´å›çª˜ç¾¤è£™è»éƒ¡å €å±ˆæŽ˜çªŸå®®å¼“穹窮芎躬倦券勸å·åœˆæ‹³æ²æ¬Šæ·ƒçœ·åŽ¥ç—蕨蹶闕机櫃潰詭軌饋句晷歸貴"], ["d0a1","鬼龜å«åœ­å¥Žæ†æ§»çªç¡…窺竅糾葵è¦èµ³é€µé–¨å‹»å‡ç•‡ç­ èŒéˆžï¤ˆæ©˜å…‹å‰‹åŠ‡æˆŸæ£˜æ¥µéš™åƒ…åŠ¤å‹¤æ‡ƒæ–¤æ ¹æ§¿ç‘¾ç­‹èŠ¹è«è¦²è¬¹è¿‘饉契今妗擒昑檎ç´ç¦ç¦½èŠ©è¡¾è¡¿è¥Ÿï¤ŠéŒ¦ä¼‹åŠæ€¥æ‰±æ±²ç´šçµ¦äº˜å…¢çŸœè‚¯ä¼ä¼Žå…¶å†€å—œå™¨åœ»åŸºåŸ¼å¤”奇妓寄å²å´Žå·±å¹¾å¿ŒæŠ€æ——æ—£"], ["d1a1","æœžæœŸæžæ£‹æ£„機欺氣汽沂淇玘ç¦çªç’‚璣畸畿ç¢ç£¯ç¥ç¥‡ç¥ˆç¥ºç®•紀綺羈耆耭肌記è­è±ˆèµ·éŒ¡éŒ¤é£¢é¥‘騎é¨é©¥éº’ç·Šä½¶å‰æ‹®æ¡”é‡‘å–«å„ºï¤‹ï¤Œå¨œæ‡¦ï¤æ‹æ‹¿ï¤Ž",5,"那樂",4,"諾酪駱亂卵暖ï¤ç…–ï¤žï¤Ÿé›£ï¤ ææºå—ï¤¡æžæ¥ æ¹³ï¤¢ç”·ï¤£ï¤¤ï¤¥"], ["d2a1","ç´ï¤¦ï¤§è¡²å›Šå¨˜ï¤¨",4,"乃來內奈柰è€ï¤®å¥³å¹´æ’šç§Šå¿µæ¬æ‹ˆæ»å¯§å¯—努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥æ»ç´ï¥’",5,"能菱陵尼泥匿溺多茶"], ["d3a1","丹亶但單團壇彖斷旦檀段æ¹çŸ­ç«¯ç°žç·žè›‹è¢’鄲雿’»æ¾¾çºç–¸é”啖忆ºæ“”曇淡湛潭澹痰èƒè†½è•覃談譚錟沓畓答è¸éå”堂塘幢戇撞棠當糖螳黨代垈å®å¤§å°å²±å¸¶å¾…æˆ´æ“¡çŽ³è‡ºè¢‹è²¸éšŠé»›å®…å¾·æ‚³å€’åˆ€åˆ°åœ–å µå¡—å°Žå± å³¶å¶‹åº¦å¾’æ‚¼æŒ‘æŽ‰æ—æ¡ƒ"], ["d4a1","棹櫂淘渡滔濤燾盜ç¹ç¦±ç¨»è„覩賭跳蹈逃途é“都é陶韜毒瀆牘犢ç¨ç£ç¦¿ç¯¤çº›è®€å¢©æƒ‡æ•¦æ—½æš¾æ²Œç„žç‡‰è±šé “ä¹­çªä»å†¬å‡å‹•åŒæ†§æ±æ¡æ£Ÿæ´žæ½¼ç–¼çž³ç«¥èƒ´è‘£éŠ…å…œæ–—æœæž“痘竇è³ï¥šè±†é€—頭屯臀芚éé¯éˆå¾—å¶æ©™ç‡ˆç™»ç­‰è—¤è¬„鄧騰喇懶拏癩羅"], ["d5a1","蘿螺裸é‚樂洛烙çžçµ¡è½ï¥é…ªé§±ï¥žäº‚嵿¬„æ¬’ç€¾çˆ›è˜­é¸žå‰Œè¾£åµæ“¥æ”¬æ¬–濫籃纜è—襤覽拉臘蠟廊朗浪狼ç…瑯螂郞來å´å¾ èŠå†·æŽ ç•¥äº®å€†å…©å‡‰æ¢æ¨‘粮粱糧良諒輛é‡ä¾¶å„·å‹µå‘‚廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷ç€ç¤«è½¢é‚æ†æˆ€æ”£æ¼£"], ["d6a1","煉璉練è¯è“®è¼¦é€£éŠå†½åˆ—劣洌烈裂廉斂殮濂簾çµä»¤ä¼¶å›¹ï¥Ÿå²ºå¶ºæ€œçŽ²ç¬­ç¾šç¿Žè†é€žéˆ´é›¶éˆé ˜é½¡ä¾‹æ¾§ç¦®é†´éš·å‹žï¥ æ’ˆæ“„櫓潞瀘çˆç›§è€è˜†è™œè·¯è¼…露魯鷺鹵碌祿綠è‰éŒ„鹿麓論壟弄朧瀧ç“ç± è¾å„¡ç€¨ç‰¢ç£Šè³‚賚賴雷了僚寮廖料燎療瞭èŠè“¼"], ["d7a1","é¼é¬§é¾å£˜å©å±¢æ¨“æ·šæ¼ç˜»ç´¯ç¸·è”žè¤¸é¤é™‹åŠ‰æ—’æŸ³æ¦´æµæºœç€ç‰ç‘ ç•™ç˜¤ç¡«è¬¬é¡žå…­æˆ®é™¸ä¾–倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾è±é™µä¿šåˆ©åŽ˜åå”Žå±¥æ‚§æŽæ¢¨æµ¬çŠç‹¸ç†ç’ƒï¥¢ç—¢ç±¬ç½¹ç¾¸èމè£è£¡é‡Œé‡é›¢é¯‰åæ½¾ç‡ç’˜è—ºèºªéš£é±—麟林淋ç³è‡¨éœ–ç ¬"], ["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万å娩巒彎慢挽晩曼滿漫ç£çžžè¬è”“蠻輓饅鰻唜抹末沫茉襪éºäº¡å¦„å¿˜å¿™æœ›ç¶²ç½”èŠ’èŒ«èŽ½è¼žé‚™åŸ‹å¦¹åª’å¯æ˜§æžšæ¢…æ¯ç…¤ç½µè²·è³£é‚魅脈貊陌驀麥孟氓猛盲盟èŒå†ªè¦“å…冕勉棉沔眄眠綿緬é¢éºµæ»…"], ["d9a1","蔑冥åå‘½æ˜Žæšæ¤§æºŸçš¿çž‘èŒ—è“‚èžŸé…©éŠ˜é³´è¢‚ä¾®å†’å‹Ÿå§†å¸½æ…•æ‘¸æ‘¹æš®æŸæ¨¡æ¯æ¯›ç‰Ÿç‰¡ç‘眸矛耗芼茅謀謨貌木æ²ç‰§ç›®ç¦ç©†é¶©æ­¿æ²’夢朦蒙å¯å¢“å¦™å»Ÿææ˜´æ³æ¸ºçŒ«ç«—苗錨務巫憮懋戊拇撫无楙武毋無ç·ç•繆舞茂蕪誣貿霧鵡墨默們刎å»å•æ–‡"], ["daa1","æ±¶ç´Šç´‹èžèšŠé–€é›¯å‹¿æ²•物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷é¡é»´å²·æ‚¶æ„æ†«æ•æ—»æ—¼æ°‘泯玟ç‰ç·¡é–”密蜜è¬å‰åšæ‹ææ’²æœ´æ¨¸æ³Šç€ç’žç®”粕縛膊舶薄迫雹é§ä¼´åŠå囿‹Œæ¬æ”€æ–‘槃泮潘ç­ç•”瘢盤盼ç£ç£»ç¤¬çµ†èˆ¬èŸ è¿”頒飯勃拔撥渤潑"], ["dba1","發跋醱鉢髮魃倣å‚åŠå¦¨å°¨å¹‡å½·æˆ¿æ”¾æ–¹æ—昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防é¾å€ä¿³ï¥£åŸ¹å¾˜æ‹œæŽ’æ¯æ¹ƒç„™ç›ƒèƒŒèƒšè£´è£µè¤™è³ è¼©é…é™ªä¼¯ä½°å¸›æŸæ ¢ç™½ç™¾é­„幡樊煩燔番磻ç¹è•ƒè—©é£œä¼ç­ç½°é–¥å‡¡å¸†æ¢µæ°¾æ±Žæ³›çŠ¯ç¯„èŒƒæ³•çºåƒ»åŠˆå£æ“˜æª—ç’§ç™–"], ["dca1","碧蘗闢霹便åžå¼è®Šè¾¨è¾¯é‚Šåˆ¥çž¥é±‰é¼ˆä¸™å€‚兵屛幷昞昺柄棅炳ç”病秉ç«è¼§é¤ é¨ˆä¿å ¡å ±å¯¶æ™®æ­¥æ´‘湺潽ç¤ç”«è©è£œè¤“譜輔ä¼åƒ•åŒåœå®“復æœç¦è…¹èŒ¯è””複覆輹輻馥鰒本乶俸奉å°å³¯å³°æ§æ£’烽熢ç«ç¸«è“¬èœ‚逢鋒鳳ä¸ä»˜ä¿¯å‚…剖副å¦å’埠夫婦"], ["dda1","孚孵富府復扶敷斧浮溥父符簿缶è…腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分å©å™´å¢³å¥”å¥®å¿¿æ†¤æ‰®æ˜æ±¾ç„šç›†ç²‰ç³žç´›èЬè³é›°ï¥§ä½›å¼—彿拂崩朋棚硼繃鵬丕備匕匪å‘å¦ƒå©¢åº‡æ‚²æ†Šæ‰‰æ‰¹æ–æž‡æ¦§æ¯”毖毗毘沸泌çµç—ºç ’碑秕秘粃緋翡肥"], ["dea1","脾臂è²èœšè£¨èª¹è­¬è²»é„™éžé£›é¼»åš¬å¬ªå½¬æ–Œæª³æ®¯æµœæ¿±ç€•ç‰çŽ­è²§è³“é »æ†‘æ°·è˜é¨ä¹äº‹äº›ä»•伺似使俟僿å²å¸å”†å—£å››å£«å¥¢å¨‘å¯«å¯ºå°„å·³å¸«å¾™æ€æ¨æ–œæ–¯æŸ¶æŸ»æ¢­æ­»æ²™æ³—渣瀉ç…砂社祀祠ç§ç¯©ç´—絲肆èˆèŽŽè“‘è›‡è£Ÿè©è©žè¬è³œèµ¦è¾­é‚ªé£¼é§Ÿéºå‰Šï¥©æœ”索"], ["dfa1","傘刪山散汕çŠç”£ç–ç®—è’œé…¸éœ°ä¹·æ’’æ®ºç…žè–©ä¸‰ï¥«æ‰æ£®æ¸—èŠŸè”˜è¡«æ·æ¾éˆ’颯上傷åƒå„Ÿå•†å–ªå˜—孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼åºåº¶å¾æ•æŠ’æ¿æ•暑曙書栖棲犀瑞筮絮緖署"], ["e0a1","胥舒薯西誓é€é‹¤é»é¼ å¤•å¥­å¸­æƒœæ˜”æ™³æžæ±æ·…潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽ç瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣é¸éŠ‘é¥é¥é®®å¨å±‘楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾è´é–ƒé™æ”æ¶‰ç‡®ï¥®åŸŽå§“å®¬æ€§æƒºæˆæ˜Ÿæ™ŸçŒ©ç¹ç››çœç­¬"], ["e1a1","è–è²è…¥èª é†’世勢歲洗稅笹細說貰å¬å˜¯å¡‘宵å°å°‘å·¢æ‰€æŽƒæ”æ˜­æ¢³æ²¼æ¶ˆæº¯ç€Ÿç‚¤ç‡’甦ç–疎瘙笑篠簫素紹蔬蕭蘇訴é€é¡é‚µéŠ·éŸ¶é¨·ä¿—å±¬æŸæ¶‘粟續謖贖速孫巽æè“€éœé£¡çŽ‡å®‹æ‚šæ¾æ·žè¨Ÿèª¦é€é Œåˆ·ï¥°ç‘碎鎖衰釗修å—嗽囚垂壽嫂守岫峀帥æ„"], ["e2a1","æˆæ‰‹æŽˆæœæ”¶æ•¸æ¨¹æ®Šæ°´æ´™æ¼±ç‡§ç‹©ç¸ç‡ç’²ç˜¦ç¡ç§€ç©—竪粹ç¶ç¶¬ç¹¡ç¾žè„©èŒ±è’蓚藪袖誰è®è¼¸é‚邃酬銖銹隋隧隨雖需須首髓鬚å”塾夙孰宿淑潚熟ç¡ç’¹è‚…è½å·¡å¾‡å¾ªæ‚旬栒楯橓殉洵淳ç£ç›¾çž¬ç­ç´”脣舜è€è“´è•£è©¢è«„醇錞順馴戌術述鉥崇崧"], ["e3a1","嵩瑟è†è¨æ¿•拾習褶襲丞乘僧å‹å‡æ‰¿æ˜‡ç¹©è …陞ä¾åŒ™å˜¶å§‹åª¤å°¸å±Žå±å¸‚å¼‘æƒæ–½æ˜¯æ™‚枾柴猜矢示翅蒔è“è¦–è©¦è©©è«¡è±•è±ºåŸ´å¯”å¼æ¯æ‹­æ¤æ®–湜熄篒è•識軾食飾伸ä¾ä¿¡å‘»å¨ å®¸æ„¼æ–°æ™¨ç‡¼ç”³ç¥žç´³è…Žè‡£èŽ˜è–ªè—Žèœƒè¨Šèº«è¾›ï¥±è¿…å¤±å®¤å¯¦æ‚‰å¯©å°‹å¿ƒæ²"], ["e4a1","沈深瀋甚芯諶什å拾雙æ°äºžä¿„兒啞娥峨我牙芽莪蛾衙è¨é˜¿é›…餓鴉éµå Šå²³å¶½å¹„æƒ¡æ„•æ¡æ¨‚渥鄂é”顎é°é½·å®‰å²¸æŒ‰æ™æ¡ˆçœ¼é›éžé¡”鮟斡è¬è»‹é–¼å”µå²©å·–庵暗癌è´é—‡å£“æŠ¼ç‹Žé´¨ä»°å¤®æ€æ˜»æ®ƒç§§é´¦åŽ“å“€åŸƒå´–æ„›æ›–æ¶¯ç¢è‰¾éš˜é„厄扼掖液縊腋é¡"], ["e5a1","æ«»ç½Œé¶¯é¸šä¹Ÿå€»å†¶å¤œæƒ¹æ¶æ¤°çˆºè€¶ï¥´é‡Žå¼±ï¥µï¥¶ç´„若葯蒻藥èºï¥·ä½¯ï¥¸ï¥¹å£¤å­ƒæ™æšæ”˜æ•­æš˜ï¥ºæ¥Šæ¨£æ´‹ç€ç…¬ç—’ç˜ç¦³ç©°ï¥»ç¾Šï¥¼è¥„諒讓釀陽量養圄御於æ¼ç˜€ç¦¦èªžé¦­é­šé½¬å„„憶抑æªè‡†åƒå °å½¦ç„‰è¨€è«ºå­¼è˜–俺儼嚴奄掩淹嶪業円予余勵呂ï¦å¦‚廬"], ["e6a1","旅歟æ±ï¦„璵礖礪與艅茹輿è½ï¦†é¤˜ï¦‡ï¦ˆï¦‰äº¦ï¦ŠåŸŸå½¹æ˜“曆歷疫繹譯ï¦é€†é©›åš¥å §å§¸å¨Ÿå®´ï¦Žå»¶ï¦ï¦ææŒ»ï¦‘椽沇沿涎涓淵演漣烟然煙煉燃燕璉ç¡ç¡¯ï¦•筵緣練縯聯è¡è»Ÿï¦˜ï¦™ï¦šé‰›ï¦›é³¶ï¦œï¦ï¦žæ‚…涅烈熱裂說閱厭廉念捻染殮炎焰ç°è‰¶è‹’"], ["e7a1","簾閻髥鹽曄獵ç‡è‘‰ï¦¨ï¦©å¡‹ï¦ªï¦«å¶¸å½±ï¦¬æ˜ æšŽæ¥¹æ¦®æ°¸æ³³æ¸¶æ½æ¿šç€›ç€¯ç…營ç°ï¦­ç‘›ï¦®ç“”盈穎纓羚聆英詠迎鈴éˆï¦²éœ™ï¦³ï¦´ä¹‚å€ªï¦µåˆˆå¡æ›³æ±­æ¿ŠçŒŠç¿ç©¢èŠ®è—蘂禮裔詣譽豫醴銳隸霓é äº”ä¼ä¿‰å‚²åˆå¾å³å—šå¡¢å¢ºå¥§å¨›å¯¤æ‚Ÿï¦¹æ‡Šæ•–旿晤梧汚澳"], ["e8a1","çƒç†¬ç’筽蜈誤鰲鼇屋沃ç„玉鈺溫瑥瘟穩縕蘊兀壅æ“瓮甕癰ç¿é‚•é›é¥”渦瓦窩窪臥蛙è¸è¨›å©‰å®Œå®›æ¢¡æ¤€æµ£çŽ©ç“ç¬ç¢—緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬å·çŒ¥ç•ï¦ºï¦»åƒ¥å‡¹å ¯å¤­å¦–å§šå¯¥ï¦¼ï¦½å¶¢æ‹—æ–æ’“擾料曜樂橈燎燿瑤ï§"], ["e9a1","窈窯繇繞耀腰蓼蟯è¦è¬ é™ï§ƒé‚€é¥’慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬è³èŒ¸è“‰è¸ŠéŽ”éžï§„于佑å¶å„ªåˆå‹å³å®‡å¯“尤愚憂旴牛玗瑀盂ç¥ç¦‘禹紆羽芋藕虞迂é‡éƒµé‡ªéš…雨雩勖彧旭昱栯煜稶éƒé Šäº‘暈橒殞æ¾ç†‰è€˜èŠ¸è•“"], ["eaa1","é‹éš•雲韻蔚鬱äºç†Šé›„å…ƒåŽŸå“¡åœ“åœ’åž£åª›å«„å¯ƒæ€¨æ„¿æ´æ²…洹湲æºçˆ°çŒ¿ç‘—è‹‘è¢è½…é ï§†é™¢é¡˜é´›æœˆè¶Šé‰žä½å‰åƒžå±åœå§”å¨å°‰æ…°æšæ¸­çˆ²ç‘‹ç·¯èƒƒèŽè‘¦è”¿èŸè¡›è¤˜è¬‚é•韋é­ä¹³ä¾‘å„’å…ªï§‡å”¯å–©å­ºå®¥å¹¼å¹½åº¾æ‚ æƒŸæ„ˆæ„‰æ„æ”¸æœ‰ï§ˆæŸ”柚柳楡楢油洧流游溜"], ["eba1","濡猶猷琉瑜由ï§ç™’ï§Žï§ç¶­è‡¾è¸è£•誘諛諭踰蹂éŠé€¾éºé…‰é‡‰é®ï§ï§‘堉戮毓肉育陸倫å…奫尹崙淪潤玧胤贇輪鈗é–ï§˜ï§™ï§šï§›è¿æˆŽç€œçµ¨èžï§œåž æ©æ…‡æ®·èª¾éŠ€éš±ä¹™åŸæ·«è”­é™°éŸ³é£®æ–æ³£é‚‘å‡æ‡‰è†ºé·¹ä¾å€šå„€å®œæ„懿擬椅毅疑矣義艤è–蟻衣誼"], ["eca1","議醫二以伊ï§ï§žå¤·å§¨ï§Ÿå·²å¼›å½›æ€¡ï§ ï§¡ï§¢ï§£çˆ¾ç¥ï§¤ç•°ç—痢移罹而耳肄苡è‘裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人ä»åˆƒå°ï§­å’½å› å§»å¯…å¼•å¿æ¹®ï§®ï§¯çµªèŒµï§°èš“èªï§±é­é·ï§²ï§³ä¸€ä½šä½¾å£¹æ—¥æº¢é€¸éŽ°é¦¹ä»»å£¬å¦Šå§™æï§´ï§µç¨”ï§¶è賃入å„"], ["eda1","立笠粒ä»å‰©å­•芿仔刺咨姉姿å­å­—å­œæ£æ…ˆæ»‹ç‚™ç…®çŽ†ç“·ç–µç£ç´«è€…自茨蔗藉諮資雌作勺嚼斫昨ç¼ç‚¸çˆµç¶½èŠé…Œé›€éµ²å­±æ£§æ®˜æ½ºç›žå²‘æš«æ½›ç®´ç°ªè ¶é›œä¸ˆä»—åŒ å ´å¢»å£¯å¥¬å°‡å¸³åº„å¼µæŽŒæš²æ–æ¨Ÿæª£æ¬Œæ¼¿ç‰†ï§ºç璋章粧腸臟臧莊葬蔣薔è—è£è´“醬長"], ["eea1","éšœå†å“‰åœ¨å®°æ‰ææ ½æ¢“渽滓ç½ç¸¡è£è²¡è¼‰é½‹é½Žçˆ­ç®è«éŒšä½‡ä½Žå„²å’€å§åº•æŠµæµæ¥®æ¨—沮渚狙猪疽箸紵苧è¹è‘—藷詛貯躇這邸雎齟勣åŠå«¡å¯‚摘敵滴狄炙的ç©ç¬›ç±ç¸¾ç¿Ÿè»è¬«è³Šèµ¤è·¡è¹Ÿè¿ªè¿¹é©é‘佃佺傳全典å‰å‰ªå¡¡å¡¼å¥ å°ˆå±•廛悛戰栓殿氈澱"], ["efa1","ç…Žç ç”°ç”¸ç•‘癲筌箋箭篆çºè©®è¼¾è½‰éˆ¿éŠ“éŒ¢é«é›»é¡šé¡«é¤žåˆ‡æˆªæŠ˜æµ™ç™¤ç«Šç¯€çµ¶å å²¾åº—漸点粘霑鮎點接摺è¶ä¸äº•亭åœåµå‘ˆå§ƒå®šå¹€åº­å»·å¾æƒ…挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎ç½ç”ºç›ç¢‡ç¦Žç¨‹ç©½ç²¾ç¶Žè‰‡è¨‚諪貞鄭酊釘鉦鋌錠霆é–"], ["f0a1","éœé ‚鼎制劑啼堤å¸å¼Ÿæ‚Œææ¢¯æ¿Ÿç¥­ç¬¬è‡è–ºè£½è«¸è¹„é†é™¤éš›éœ½é¡Œé½Šä¿Žå…†å‡‹åŠ©å˜²å¼”å½«æŽªæ“æ—©æ™æ›ºæ›¹æœæ¢æ£—槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙èºé€ é­é‡£é˜»é›•é³¥æ—簇足éƒå­˜å°Šå’æ‹™çŒå€§å®—從悰慫棕淙ç®ç¨®çµ‚綜縱腫"], ["f1a1","踪踵é¾é˜ä½å左座挫罪主ä½ä¾åšå§èƒ„呪周嗾å¥å®™å·žå»šæ™æœ±æŸ±æ ªæ³¨æ´²æ¹Šæ¾ç‚·ç ç–‡ç±Œç´‚紬綢舟蛛註誅走躊輳週酎酒鑄é§ç«¹ç²¥ä¿Šå„准埈寯峻晙樽浚準濬焌畯竣蠢逡éµé›‹é§¿èŒä¸­ä»²è¡†é‡å½æ«›æ¥«æ±è‘ºå¢žæ†Žæ›¾æ‹¯çƒç”‘症繒蒸證贈之åª"], ["f2a1","咫地å€å¿—æŒæŒ‡æ‘¯æ”¯æ—¨æ™ºæžæž³æ­¢æ± æ²šæ¼¬çŸ¥ç ¥ç¥‰ç¥—紙肢脂至èŠèŠ·èœ˜èªŒï§¼è´„è¶¾é²ç›´ç¨™ç¨·ç¹”è·å”‡å—”å¡µæŒ¯æ¢æ™‰æ™‹æ¡­æ¦›æ®„津溱ç瑨璡畛疹盡眞瞋秦縉ç¸è‡»è”¯è¢—診賑軫辰進鎭陣陳震侄å±å§ªå«‰å¸™æ¡Žç“†ç–¾ç§©çª’膣蛭質跌迭斟朕什執潗ç·è¼¯"], ["f3a1","é¶é›†å¾µæ‡²æ¾„且侘借å‰å—Ÿåµ¯å·®æ¬¡æ­¤ç£‹ç®šï§¾è¹‰è»Šé®æ‰æ¾ç€çª„錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽é¤é¥Œåˆ¹å¯Ÿæ“¦æœ­ç´®åƒ­åƒå¡¹æ…˜æ…™æ‡ºæ–¬ç«™è®’è®–å€‰å€¡å‰µå”±å¨¼å» å½°æ„´æ•žæ˜Œæ˜¶æš¢æ§æ»„漲猖瘡窓脹艙è–蒼債埰寀寨彩採砦綵èœè”¡é‡‡é‡µå†ŠæŸµç­–"], ["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟åƒå–˜å¤©å·æ“…泉淺玔穿舛薦賤è¸é·é‡§é—¡é˜¡éŸ†å‡¸å“²å–†å¾¹æ’¤æ¾ˆç¶´è¼Ÿè½éµåƒ‰å°–沾添甛瞻簽籤詹諂堞妾帖æ·ç‰’ç–Šç«è«œè²¼è¼’廳晴淸è½èè«‹é‘鯖切剃替涕滯締諦逮éžé«”åˆå‰¿å“¨æ†”抄招梢"], ["f5a1","椒楚樵炒焦ç¡ç¤ç¤Žç§’ç¨è‚–艸苕è‰è•‰è²‚超酢醋醮促囑燭矗蜀觸寸忖æ‘邨å¢å¡šå¯µæ‚¤æ†æ‘ ç¸½è°è”¥éŠƒæ’®å‚¬å´”æœ€å¢œæŠ½æŽ¨æ¤Žæ¥¸æ¨žæ¹«çšºç§‹èŠ»è©è«è¶¨è¿½é„’酋醜éŒéŒ˜éŽšé››é¨¶é°ä¸‘畜ç¥ç«ºç­‘ç¯‰ç¸®è“„è¹™è¹´è»¸é€æ˜¥æ¤¿ç‘ƒå‡ºæœ®é»œå……忠沖蟲è¡è¡·æ‚´è†µèƒ"], ["f6a1","è´…å–å¹å˜´å¨¶å°±ç‚Šç¿ èšè„†è‡­è¶£é†‰é©Ÿé·²å´ä»„åŽ æƒ»æ¸¬å±¤ä¾ˆå€¤å—¤å³™å¹Ÿæ¥æ¢”治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸ç›ç §é‡é¼èŸ„秤稱快他咤唾墮妥惰打拖朶楕舵陀馱é§å€¬å“å•„å¼ï¨æ‰˜ï¨‚æ“¢æ™«æŸæ¿æ¿¯ç¢ç¸è¨—"], ["f7a1","é¸å‘‘嘆å¦å½ˆæ†šæ­Žç˜ç‚­ç¶»èª•å¥ªè„«æŽ¢çœˆè€½è²ªå¡”æ­æ¦»å®•帑湯糖蕩兌å°å¤ªæ€ æ…‹æ®†æ±°æ³°ç¬žèƒŽè‹”跆邰颱宅擇澤撑攄兎å土討慟桶洞痛筒統通堆槌腿褪退頹å¸å¥—妬投é€é¬ªæ…特闖å¡å©†å·´æŠŠæ’­æ“ºæ·æ³¢æ´¾çˆ¬ç¶ç ´ç½·èŠ­è·›é —åˆ¤å‚æ¿ç‰ˆç“£è²©è¾¦éˆ‘"], ["f8a1","é˜ªå…«å­æŒä½©å”„悖敗沛浿牌狽稗覇è²å½­æ¾Žçƒ¹è†¨æ„Žä¾¿åæ‰ç‰‡ç¯‡ç·¨ç¿©é鞭騙貶åªå¹³æž°èè©•å å¬–幣廢弊斃肺蔽閉陛佈包åŒåŒå’†å“ºåœƒå¸ƒæ€–抛抱æ•暴泡浦疱砲胞脯苞葡蒲è¢è¤’逋鋪飽鮑幅暴æ›ç€‘çˆ†ï¨‡ä¿µå‰½å½ªæ…“æ“æ¨™æ¼‚瓢票表豹飇飄驃"], ["f9a1","å“稟楓諷豊風馮彼披疲皮被é¿é™‚匹弼必泌çŒç•¢ç–‹ç­†è‹¾é¦ä¹é€¼ä¸‹ä½•厦å¤å»ˆæ˜°æ²³ç‘•è·è¦è³€é霞鰕壑學è™è¬”é¶´å¯’æ¨æ‚旱汗漢澣瀚罕翰閑閒é™éŸ“割轄函å«å’¸å•£å–Šæª»æ¶µç·˜è‰¦éŠœé™·é¹¹åˆå“ˆç›’è›¤é–¤é—”é™œäº¢ä¼‰å§®å«¦å··æ’æŠ—æ­æ¡æ²†æ¸¯ç¼¸è‚›èˆª"], ["faa1","行降項亥å•咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸æè‡è¡Œäº«å‘åš®ç¦é„•響餉饗香噓墟虛許憲櫶ç»è»’歇險驗奕爀赫é©ä¿”峴弦懸晛泫炫玄玹ç¾çœ©ç絃絢縣舷衒見賢鉉顯孑穴血é å«Œä¿ å”夾峽挾浹狹脅脇莢é‹é °äº¨å…„刑型"], ["fba1","形泂滎瀅ç炯熒ç©ç‘©èŠèž¢è¡¡é€ˆé‚¢éŽ£é¦¨å…®å½—æƒ æ…§æš³è•™è¹Šé†¯éž‹ä¹Žäº’å‘¼å£•å£ºå¥½å²µå¼§æˆ¶æ‰ˆæ˜Šæ™§æ¯«æµ©æ·æ¹–滸澔濠濩çç‹ç¥ç‘šç“ çš“祜糊縞胡芦葫蒿虎號è´è­·è±ªéŽ¬é €é¡¥æƒ‘æˆ–é…·å©šæ˜æ··æ¸¾ç¿é­‚忽惚ç¬å“„弘汞泓洪烘紅虹訌鴻化和嬅樺ç«ç•µ"], ["fca1","ç¦ç¦¾èбè¯è©±è­è²¨é´ï¨‹æ“´æ”«ç¢ºç¢»ç©«ä¸¸å–šå¥å®¦å¹»æ‚£æ›æ­¡æ™¥æ¡“渙煥環紈還驩鰥活滑猾è±é—Šå‡°å¹Œå¾¨ææƒ¶æ„°æ…Œæ™ƒæ™„æ¦¥æ³æ¹Ÿæ»‰æ½¢ç…Œç’œçš‡ç¯ç°§è’è—é‘éšé»ƒåŒ¯å›žå»»å¾Šæ¢æ‚”懷晦會檜淮澮ç°çªç¹ªè†¾èŒ´è›”誨賄劃ç²å®–æ©«é„å“®åš†å­æ•ˆæ–…æ›‰æ¢Ÿæ¶æ·†"], ["fda1","爻肴酵é©ä¾¯å€™åŽšåŽå¼å–‰å—…帿後朽煦ç逅勛勳塤壎焄ç†ç‡»è–°è¨“暈薨喧暄煊è±å‰å–™æ¯å½™å¾½æ®æš‰ç…‡è«±è¼éº¾ä¼‘æºçƒ‹ç•¦è™§æ¤è­Žé·¸å…‡å‡¶åŒˆæ´¶èƒ¸é»‘昕欣炘痕åƒå±¹ç´‡è¨–æ¬ æ¬½æ­†å¸æ°æ´½ç¿•興僖凞喜噫å›å§¬å¬‰å¸Œæ†™æ†˜æˆ±æ™žæ›¦ç†™ç†¹ç†ºçŠ§ç¦§ç¨€ç¾²è©°"] ] [ ["0","\u0000",127], ["a140"," ,ã€ã€‚.‧;:?ï¼ï¸°â€¦â€¥ï¹ï¹‘﹒·﹔﹕﹖﹗|–︱—︳╴︴ï¹ï¼ˆï¼‰ï¸µï¸¶ï½›ï½ï¸·ï¸¸ã€”〕︹︺ã€ã€‘︻︼《》︽︾〈〉︿﹀「ã€ï¹ï¹‚『ã€ï¹ƒï¹„﹙﹚"], ["a1a1","﹛﹜ï¹ï¹žâ€˜â€™â€œâ€ã€ã€žâ€µâ€²ï¼ƒï¼†ï¼Šâ€»Â§ã€ƒâ—‹â—△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_Ë﹉﹊ï¹ï¹Žï¹‹ï¹Œï¹Ÿï¹ ï¹¡ï¼‹ï¼Ã—÷±√<>ï¼â‰¦â‰§â‰ âˆžâ‰’≡﹢",4,"~∩∪⊥∠∟⊿ã’ã‘∫∮∵∴♀♂⊕⊙↑↓â†â†’↖↗↙↘∥∣ï¼"], ["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫ã•㎜ãŽãŽžãŽãŽ¡ãŽŽãŽã„°兙兛兞å…兡兣嗧瓩糎â–",7,"â–â–Žâ–▌▋▊▉┼┴┬┤├▔─│▕┌â”└┘╭"], ["a2a1","╮╰╯â•╞╪╡◢◣◥◤╱╲╳ï¼",9,"â… ",9,"〡",8,"åå„å…A",25,"ï½",21], ["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ã„…",10], ["a3a1","ã„",25,"˙ˉˊˇˋ"], ["a3e1","€"], ["a440","一乙ä¸ä¸ƒä¹ƒä¹äº†äºŒäººå„¿å…¥å…«å‡ åˆ€åˆåŠ›åŒ•ååœåˆä¸‰ä¸‹ä¸ˆä¸Šä¸«ä¸¸å‡¡ä¹…么也乞于亡兀刃勺åƒå‰å£åœŸå£«å¤•大女å­å­‘孓寸å°å°¢å°¸å±±å·å·¥å·±å·²å·³å·¾å¹²å»¾å¼‹å¼“æ‰"], ["a4a1","丑ä¸ä¸ä¸­ä¸°ä¸¹ä¹‹å°¹äºˆäº‘井互五亢ä»ä»€ä»ƒä»†ä»‡ä»ä»Šä»‹ä»„å…ƒå…內六兮公冗凶分切刈勻勾勿化匹åˆå‡å…åžåŽ„å‹åŠåå£¬å¤©å¤«å¤ªå¤­å­”å°‘å°¤å°ºå±¯å·´å¹»å»¿å¼”å¼•å¿ƒæˆˆæˆ¶æ‰‹æ‰Žæ”¯æ–‡æ–—æ–¤æ–¹æ—¥æ›°æœˆæœ¨æ¬ æ­¢æ­¹æ¯‹æ¯”æ¯›æ°æ°´ç«çˆªçˆ¶çˆ»ç‰‡ç‰™ç‰›çŠ¬çŽ‹ä¸™"], ["a540","世丕且丘主ä¹ä¹ä¹Žä»¥ä»˜ä»”仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北åŒä»ŸåŠå‰å¡å å¯å®åŽ»å¯å¤å³å¬å®å©å¨å¼å¸åµå«å¦åªå²å±å°å¥å­å»å››å›šå¤–"], ["a5a1","央失奴奶孕它尼巨巧左市布平幼å¼å¼˜å¼—å¿…æˆŠæ‰“æ‰”æ‰’æ‰‘æ–¥æ—¦æœ®æœ¬æœªæœ«æœ­æ­£æ¯æ°‘æ°æ°¸æ±æ±€æ°¾çŠ¯çŽ„çŽ‰ç“œç“¦ç”˜ç”Ÿç”¨ç”©ç”°ç”±ç”²ç”³ç–‹ç™½çš®çš¿ç›®çŸ›çŸ¢çŸ³ç¤ºç¦¾ç©´ç«‹ä¸žä¸Ÿä¹’ä¹“ä¹©äº™äº¤äº¦äº¥ä»¿ä¼‰ä¼™ä¼Šä¼•ä¼ä¼ä¼‘ä¼ä»²ä»¶ä»»ä»°ä»³ä»½ä¼ä¼‹å…‰å…‡å…†å…ˆå…¨"], ["a640","å…±å†å†°åˆ—刑划刎刖劣匈匡匠å°å±å‰ååŒåŠååå‹å„å‘ååˆåƒåŽå†å’因回å›åœ³åœ°åœ¨åœ­åœ¬åœ¯åœ©å¤™å¤šå¤·å¤¸å¦„奸妃好她如å¦å­—存宇守宅安寺尖屹州帆并年"], ["a6a1","å¼å¼›å¿™å¿–æˆŽæˆŒæˆæˆæ‰£æ‰›æ‰˜æ”¶æ—©æ—¨æ—¬æ—­æ›²æ›³æœ‰æœ½æœ´æœ±æœµæ¬¡æ­¤æ­»æ°–æ±æ±—æ±™æ±Ÿæ± æ±æ±•æ±¡æ±›æ±æ±Žç°ç‰Ÿç‰ç™¾ç«¹ç±³ç³¸ç¼¶ç¾Šç¾½è€è€ƒè€Œè€’耳è¿è‚‰è‚‹è‚Œè‡£è‡ªè‡³è‡¼èˆŒèˆ›èˆŸè‰®è‰²è‰¾è™«è¡€è¡Œè¡£è¥¿é˜¡ä¸²äº¨ä½ä½ä½‡ä½—佞伴佛何估ä½ä½‘伽伺伸佃佔似但佣"], ["a740","作你伯低伶余ä½ä½ˆä½šå…Œå…‹å…兵冶冷別判利刪刨劫助努劬匣å³åµåå­åžå¾å¦å‘Žå§å‘†å‘ƒå³å‘ˆå‘‚å›å©å‘Šå¹å»å¸å®åµå¶å å¼å‘€å±å«åŸå¬å›ªå›°å›¤å›«åŠå‘å€å"], ["a7a1","å‡åŽåœ¾åå圻壯夾å¦å¦’妨妞妣妙妖å¦å¦¤å¦“妊妥å­å­œå­šå­›å®Œå®‹å®å°¬å±€å±å°¿å°¾å²å²‘岔岌巫希åºåº‡åºŠå»·å¼„弟彤形彷役忘忌志å¿å¿±å¿«å¿¸å¿ªæˆ’æˆ‘æŠ„æŠ—æŠ–æŠ€æ‰¶æŠ‰æ‰­æŠŠæ‰¼æ‰¾æ‰¹æ‰³æŠ’æ‰¯æŠ˜æ‰®æŠ•æŠ“æŠ‘æŠ†æ”¹æ”»æ”¸æ—±æ›´æŸæŽæææ‘æœæ–æžæ‰æ†æ "], ["a840","æ“æ—æ­¥æ¯æ±‚æ±žæ²™æ²æ²ˆæ²‰æ²…æ²›æ±ªæ±ºæ²æ±°æ²Œæ±¨æ²–æ²’æ±½æ²ƒæ±²æ±¾æ±´æ²†æ±¶æ²æ²”沘沂ç¶ç¼ç½ç¸ç‰¢ç‰¡ç‰ ç‹„狂玖甬甫男甸皂盯矣ç§ç§€ç¦¿ç©¶ç³»ç½•è‚–è‚“è‚肘肛肚育良芒"], ["a8a1","芋èŠè¦‹è§’言谷豆豕è²èµ¤èµ°è¶³èº«è»Šè¾›è¾°è¿‚迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯ä¾ä¾ä½³ä½¿ä½¬ä¾›ä¾‹ä¾†ä¾ƒä½°ä½µä¾ˆä½©ä½»ä¾–ä½¾ä¾ä¾‘佺兔兒兕兩具其典冽函刻券刷刺到刮制å‰åŠ¾åŠ»å’å”å“å‘å¦å·å¸å¹å–å”å—味呵"], ["a940","咖呸咕咀呻呷咄咒咆呼å’呱呶和咚呢周咋命咎固垃å·åªå©å¡å¦å¤å¼å¤œå¥‰å¥‡å¥ˆå¥„奔妾妻委妹妮姑姆å§å§å§‹å§“姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], ["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往å¾å½¿å½¼å¿å¿ å¿½å¿µå¿¿æ€æ€”æ€¯æ€µæ€–æ€ªæ€•æ€¡æ€§æ€©æ€«æ€›æˆ–æˆ•æˆ¿æˆ¾æ‰€æ‰¿æ‹‰æ‹Œæ‹„æŠ¿æ‹‚æŠ¹æ‹’æ‹›æŠ«æ‹“æ‹”æ‹‹æ‹ˆæŠ¨æŠ½æŠ¼æ‹æ‹™æ‹‡æ‹æŠµæ‹šæŠ±æ‹˜æ‹–æ‹—æ‹†æŠ¬æ‹Žæ”¾æ–§æ–¼æ—ºæ˜”æ˜“æ˜Œæ˜†æ˜‚æ˜Žæ˜€æ˜æ˜•昊"], ["aa40","æ˜‡æœæœ‹æ­æž‹æž•æ±æžœæ³æ·æž‡æžæž—æ¯æ°æ¿æž‰æ¾æžæµæžšæž“æ¼æªæ²æ¬£æ­¦æ­§æ­¿æ°“æ°›æ³£æ³¨æ³³æ²±æ³Œæ³¥æ²³æ²½æ²¾æ²¼æ³¢æ²«æ³•æ³“æ²¸æ³„æ²¹æ³æ²®æ³—泅泱沿治泡泛泊沬泯泜泖泠"], ["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗ç‹çŽ©çŽ¨çŽŸçŽ«çŽ¥ç”½ç–疙疚的盂盲直知矽社祀ç¥ç§‰ç§ˆç©ºç©¹ç«ºç³¾ç½”羌羋者肺肥肢肱股肫肩肴肪肯臥臾èˆèгèŠèŠ™èŠ­èŠ½èŠŸèŠ¹èŠ±èŠ¬èŠ¥èŠ¯èŠ¸èŠ£èŠ°èŠ¾èŠ·è™Žè™±åˆè¡¨è»‹è¿Žè¿”近邵邸邱邶采金長門阜陀阿阻附"], ["ab40","陂隹雨é’éžäºŸäº­äº®ä¿¡ä¾µä¾¯ä¾¿ä¿ ä¿‘ä¿ä¿ä¿ƒä¾¶ä¿˜ä¿Ÿä¿Šä¿—ä¾®ä¿ä¿„係俚俎俞侷兗冒冑冠剎剃削å‰å‰Œå‰‹å‰‡å‹‡å‹‰å‹ƒå‹åŒå—å»åŽšå›å’¬å“€å’¨å“Žå“‰å’¸å’¦å’³å“‡å“‚咽咪å“"], ["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契å¥å¥Žå¥å§œå§˜å§¿å§£å§¨å¨ƒå§¥å§ªå§šå§¦å¨å§»å­©å®£å®¦å®¤å®¢å®¥å°å±Žå±å±å±‹å³™å³’å··å¸å¸¥å¸Ÿå¹½åº åº¦å»ºå¼ˆå¼­å½¥å¾ˆå¾…å¾Šå¾‹å¾‡å¾Œå¾‰æ€’æ€æ€ æ€¥æ€Žæ€¨ææ°æ¨æ¢æ†æƒæ¬æ«æªæ¤æ‰æ‹œæŒ–æŒ‰æ‹¼æ‹­æŒæ‹®æ‹½æŒ‡æ‹±æ‹·"], ["ac40","æ‹¯æ‹¬æ‹¾æ‹´æŒ‘æŒ‚æ”¿æ•…æ–«æ–½æ—¢æ˜¥æ˜­æ˜ æ˜§æ˜¯æ˜Ÿæ˜¨æ˜±æ˜¤æ›·æŸ¿æŸ“æŸ±æŸ”æŸæŸ¬æž¶æž¯æŸµæŸ©æŸ¯æŸ„æŸ‘æž´æŸšæŸ¥æž¸æŸæŸžæŸ³æž°æŸ™æŸ¢æŸæŸ’æ­ªæ®ƒæ®†æ®µæ¯’æ¯—æ°Ÿæ³‰æ´‹æ´²æ´ªæµæ´¥æ´Œæ´±æ´žæ´—"], ["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷çŠçŽ»çŽ²çç€çŽ³ç”šç”­ç•界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅çœç›¹ç›¸çœ‰çœ‹ç›¾ç›¼çœ‡çŸœç ‚研砌ç ç¥†ç¥‰ç¥ˆç¥‡ç¦¹ç¦ºç§‘ç§’ç§‹ç©¿çªç«¿ç«½ç±½ç´‚紅紀紉紇約紆缸美羿耄"], ["ad40","è€è€è€‘耶胖胥胚胃胄背胡胛胎胞胤èƒè‡´èˆ¢è‹§èŒƒèŒ…苣苛苦茄若茂茉苒苗英èŒè‹œè‹”苑苞苓苟苯茆è™è™¹è™»è™ºè¡è¡«è¦è§”計訂訃貞負赴赳趴è»è»Œè¿°è¿¦è¿¢è¿ªè¿¥"], ["ada1","迭迫迤迨郊郎éƒéƒƒé…‹é…Šé‡é–‚é™é™‹é™Œé™é¢é©éŸ‹éŸ­éŸ³é é¢¨é£›é£Ÿé¦–香乘亳倌å€å€£ä¿¯å€¦å€¥ä¿¸å€©å€–倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢å‡å‡Œå‡†å‡‹å‰–剜剔剛å‰åŒªå¿åŽŸåŽåŸå“¨å”å”唷哼哥哲唆哺唔哩哭員唉哮哪"], ["ae40","哦唧唇哽å”圃圄埂埔埋埃堉å¤å¥—奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展å±å³­å³½å³»å³ªå³¨å³°å³¶å´å³´å·®å¸­å¸«åº«åº­åº§å¼±å¾’徑徿™"], ["aea1","æ£æ¥ææ•æ­æ©æ¯æ‚„æ‚Ÿæ‚šæ‚æ‚”æ‚Œæ‚…æ‚–æ‰‡æ‹³æŒˆæ‹¿æŽæŒ¾æŒ¯æ•æ‚æ†ææ‰æŒºææŒ½æŒªæŒ«æŒ¨ææŒæ•ˆæ•‰æ–™æ—æ—…æ™‚æ™‰æ™æ™ƒæ™’æ™Œæ™…æ™æ›¸æœ”æœ•æœ—æ ¡æ ¸æ¡ˆæ¡†æ¡“æ ¹æ¡‚æ¡”æ ©æ¢³æ —æ¡Œæ¡‘æ ½æŸ´æ¡æ¡€æ ¼æ¡ƒæ ªæ¡…æ “æ ˜æ¡æ®Šæ®‰æ®·æ°£æ°§æ°¨æ°¦æ°¤æ³°æµªæ¶•消涇浦浸海浙涓"], ["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈çƒçˆ¹ç‰¹ç‹¼ç‹¹ç‹½ç‹¸ç‹·çކç­ç‰ç®ç çªçžç•”ç•畜畚留疾病症疲疳疽疼疹痂疸皋皰益ç›ç›Žçœ©çœŸçœ çœ¨çŸ©ç °ç §ç ¸ç ç ´ç ·"], ["afa1","砥砭砠砟砲祕ç¥ç¥ ç¥Ÿç¥–神ç¥ç¥—祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純ç´ç´•ç´šç´œç´ç´™ç´›ç¼ºç½Ÿç¾”ç¿…ç¿è€†è€˜è€•耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀èˆèˆªèˆ«èˆ¨èˆ¬èŠ»èŒ«è’è”èŠèŒ¸èè‰èŒµèŒ´è茲茹茶茗è€èŒ±èŒ¨èƒ"], ["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷è¢è¢‚衽衹記è¨è¨Žè¨Œè¨•訊託訓訖è¨è¨‘豈豺豹財貢起躬軒軔è»è¾±é€é€†è¿·é€€è¿ºè¿´é€ƒè¿½é€…迸邕郡éƒéƒ¢é…’é…酌釘é‡é‡—釜釙閃院陣陡"], ["b0a1","é™›é™é™¤é™˜é™žéš»é£¢é¦¬éª¨é«˜é¬¥é¬²é¬¼ä¹¾åºå½åœå‡åƒåŒåšå‰å¥å¶åŽå•åµå´å·åå€å¯å­å…œå†•凰剪副勒務勘動åŒåŒåŒ™åŒ¿å€åŒ¾åƒæ›¼å•†å•ªå•¦å•„啞啡啃啊唱啖å•啕唯啤唸售啜唬啣唳å•啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶å©å©‰å©¦å©ªå©€"], ["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜å±å´‡å´†å´Žå´›å´–å´¢å´‘å´©å´”å´™å´¤å´§å´—å·¢å¸¸å¸¶å¸³å¸·åº·åº¸åº¶åºµåº¾å¼µå¼·å½—å½¬å½©å½«å¾—å¾™å¾žå¾˜å¾¡å¾ å¾œæ¿æ‚£æ‚‰æ‚ æ‚¨æƒ‹æ‚´æƒ¦æ‚½"], ["b1a1","æƒ…æ‚»æ‚µæƒœæ‚¼æƒ˜æƒ•æƒ†æƒŸæ‚¸æƒšæƒ‡æˆšæˆ›æ‰ˆæŽ æŽ§æ²æŽ–æŽ¢æŽ¥æ·æ§æŽ˜æŽªæ±æŽ©æŽ‰æŽƒæŽ›æ«æŽ¨æŽ„æŽˆæŽ™æŽ¡æŽ¬æŽ’æŽæŽ€æ»æ©æ¨æºæ•æ•–æ•‘æ•™æ•—å•Ÿæ•æ•˜æ••æ•”æ–œæ–›æ–¬æ—æ—‹æ—Œæ—Žæ™æ™šæ™¤æ™¨æ™¦æ™žæ›¹å‹—æœ›æ¢æ¢¯æ¢¢æ¢“æ¢µæ¡¿æ¡¶æ¢±æ¢§æ¢—æ¢°æ¢ƒæ£„æ¢­æ¢†æ¢…æ¢”æ¢æ¢¨æ¢Ÿæ¢¡æ¢‚欲殺"], ["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽çŠçŒœçŒ›çŒ–猓猙率ç…çŠçƒç†ç¾çç“ ç“¶"], ["b2a1","瓷甜產略畦畢異ç–痔痕疵痊ç—皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜èŠè†è„¯è„–脣脫脩脰脤舂舵舷舶船莎莞莘è¸èŽ¢èŽ–èŽ½èŽ«èŽ’èŽŠèŽ“èŽ‰èŽ è·è»è¼"], ["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖è¢è¢‹è¦“è¦è¨ªè¨è¨£è¨¥è¨±è¨­è¨Ÿè¨›è¨¢è±‰è±šè²©è²¬è²«è²¨è²ªè²§èµ§èµ¦è¶¾è¶ºè»›è»Ÿé€™é€é€šé€—連速é€é€é€•逞造é€é€¢é€–逛途"], ["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢å‚傅備傑傀傖傘傚最凱割剴創剩勞å‹å‹›åšåŽ¥å•»å–€å–§å•¼å–Šå–喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙åœå ¯å ªå ´å ¤å °å ±å ¡å å  å£¹å£ºå¥ "], ["b440","婷媚婿媒媛媧孳孱寒富寓å¯å°Šå°‹å°±åµŒåµå´´åµ‡å·½å¹…帽幀幃幾廊å»å»‚å»„å¼¼å½­å¾©å¾ªå¾¨æƒ‘æƒ¡æ‚²æ‚¶æƒ æ„œæ„£æƒºæ„•æƒ°æƒ»æƒ´æ…¨æƒ±æ„Žæƒ¶æ„‰æ„€æ„’æˆŸæ‰‰æŽ£æŽŒææ€æ©æ‰æ†æ"], ["b4a1","æ’æ£ææ¡æ–æ­æ®æ¶æ´æªæ›æ‘’æšæ¹æ•žæ•¦æ•¢æ•£æ–‘æ–æ–¯æ™®æ™°æ™´æ™¶æ™¯æš‘æ™ºæ™¾æ™·æ›¾æ›¿æœŸæœæ£ºæ£•æ£ æ£˜æ£—æ¤…æ£Ÿæ£µæ£®æ£§æ£¹æ£’æ£²æ££æ£‹æ£æ¤æ¤’æ¤Žæ£‰æ£šæ¥®æ£»æ¬¾æ¬ºæ¬½æ®˜æ®–æ®¼æ¯¯æ°®æ°¯æ°¬æ¸¯æ¸¸æ¹”æ¸¡æ¸²æ¹§æ¹Šæ¸ æ¸¥æ¸£æ¸›æ¹›æ¹˜æ¸¤æ¹–æ¹®æ¸­æ¸¦æ¹¯æ¸´æ¹æ¸ºæ¸¬æ¹ƒæ¸æ¸¾æ»‹"], ["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩çºçªç³ç¢ç¥çµç¶ç´ç¯ç›ç¦ç¨ç”¥ç”¦ç•«ç•ªç—¢ç—›ç—£ç—™ç—˜ç—žç— ç™»ç™¼çš–皓皴盜ç短ç¡ç¡¬ç¡¯ç¨ç¨ˆç¨‹ç¨…稀窘"], ["b5a1","窗窖童竣等策筆ç­ç­’ç­”ç­ç­‹ç­ç­‘粟粥絞çµçµ¨çµ•紫絮絲絡給絢絰絳善翔翕耋è’肅腕腔腋腑腎脹腆脾腌腓腴舒舜è©èƒè¸èè è…è‹èè¯è±è´è‘—èŠè°èŒèŒè½è²èŠè¸èŽè„èœè‡è”èŸè™›è›Ÿè›™è›­è›”蛛蛤è›è›žè¡—è£è£‚袱覃視註詠評詞証è©"], ["b640","詔詛è©è©†è¨´è¨ºè¨¶è©–象貂貯貼貳貽è³è²»è³€è²´è²·è²¶è²¿è²¸è¶Šè¶…è¶è·Žè·è·‹è·šè·‘跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥é‡éˆ”鈕鈣鈉鈞éˆéˆéˆ‡éˆ‘é–”é–é–‹é–‘"], ["b6a1","間閒閎隊階隋陽隅隆éšé™²éš„é›é›…雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃é»é»‘亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧å«å«‰å«Œåª¾åª½åª¼"], ["b740","åª³å«‚åª²åµ©åµ¯å¹Œå¹¹å»‰å»ˆå¼’å½™å¾¬å¾®æ„šæ„æ…ˆæ„Ÿæƒ³æ„›æƒ¹æ„æ„ˆæ…Žæ…Œæ…„æ…æ„¾æ„´æ„§æ„æ„†æ„·æˆ¡æˆ¢æ“æ¾æžæªæ­æ½æ¬ææœæ”ææ¶æ–æ—æ†æ•¬æ–Ÿæ–°æš—æš‰æš‡æšˆæš–æš„æš˜æšæœƒæ¦”業"], ["b7a1","æ¥šæ¥·æ¥ æ¥”æ¥µæ¤°æ¦‚æ¥Šæ¥¨æ¥«æ¥žæ¥“æ¥¹æ¦†æ¥æ¥£æ¥›æ­‡æ­²æ¯€æ®¿æ¯“æ¯½æº¢æº¯æ»“æº¶æ»‚æºæºæ»‡æ»…溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷ç…猿猾瑯瑚瑕瑟瑞ç‘ç¿ç‘™ç‘›ç‘œç•¶ç•¸ç˜€ç—°ç˜ç—²ç—±ç—ºç—¿ç—´ç—³ç›žç›Ÿç›ç«ç¦çžç£"], ["b840","ç¹çªç¬çœç¥ç¨ç¢çŸ®ç¢Žç¢°ç¢—碘碌碉硼碑碓硿祺祿ç¦è¬ç¦½ç¨œç¨šç¨ ç¨”稟稞窟窠筷節筠筮筧粱粳粵經絹綑ç¶ç¶çµ›ç½®ç½©ç½ªç½²ç¾©ç¾¨ç¾¤è–è˜è‚†è‚„腱腰腸腥腮腳腫"], ["b8a1","腹腺腦舅艇蒂葷è½è±è‘µè‘¦è‘«è‘‰è‘¬è‘›è¼èµè‘¡è‘£è‘©è‘­è‘†è™žè™œè™Ÿè›¹èœ“蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘è£è£¡è£Šè£•裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], ["b940","辟農é‹éŠé“é‚é”逼é•éé‡ééŽéé‘逾é鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉é‰é‰…鈹鈿鉚閘隘隔隕é›é›‹é›‰é›Šé›·é›»é›¹é›¶é–é´é¶é é ‘頓頊頒頌飼飴"], ["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕åƒåƒ‘僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉å˜å˜Žå—·å˜–嘟嘈å˜å—¶åœ˜åœ–塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察å°å±¢å¶„嶇幛幣幕幗幔廓廖弊彆彰徹慇"], ["ba40","æ„¿æ…‹æ…·æ…¢æ…£æ…Ÿæ…šæ…˜æ…µæˆªæ’‡æ‘˜æ‘”æ’¤æ‘¸æ‘Ÿæ‘ºæ‘‘æ‘§æ´æ‘­æ‘»æ•²æ–¡æ——æ—–æš¢æš¨æšæ¦œæ¦¨æ¦•æ§æ¦®æ§“æ§‹æ¦›æ¦·æ¦»æ¦«æ¦´æ§æ§æ¦­æ§Œæ¦¦æ§ƒæ¦£æ­‰æ­Œæ°³æ¼³æ¼”æ»¾æ¼“æ»´æ¼©æ¼¾æ¼ æ¼¬æ¼æ¼‚æ¼¢"], ["baa1","æ»¿æ»¯æ¼†æ¼±æ¼¸æ¼²æ¼£æ¼•æ¼«æ¼¯æ¾ˆæ¼ªæ»¬æ¼æ»²æ»Œæ»·ç†”熙煽熊熄熒爾犒犖ç„ç瑤瑣瑪瑰瑭甄疑瘧ç˜ç˜‹ç˜‰ç˜“盡監瞄ç½ç¿ç¡ç£ç¢Ÿç¢§ç¢³ç¢©ç¢£ç¦Žç¦ç¦ç¨®ç¨±çªªçª©ç«­ç«¯ç®¡ç®•箋筵算ç®ç®”ç®ç®¸ç®‡ç®„粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], ["bb40","罰翠翡翟èžèšè‚‡è…膀è†è†ˆè†Šè…¿è†‚臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓è’蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘è•蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣èªèª¡èª“誤"], ["bba1","說誥誨誘誑誚誧豪è²è²Œè³“賑賒赫趙趕跼輔輒輕輓辣é é˜éœé£é™éžé¢éé›é„™é„˜é„žé…µé…¸é…·é…´é‰¸éŠ€éŠ…éŠ˜éŠ–é‰»éŠ“éŠœéŠ¨é‰¼éŠ‘é–¡é–¨é–©é–£é–¥é–¤éš™éšœéš›é›Œé›’éœ€é¼éž…韶頗領颯颱餃餅餌餉é§éª¯éª°é«¦é­é­‚鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], ["bc40","劇劈劉åŠåŠŠå‹°åŽ²å˜®å˜»å˜¹å˜²å˜¿å˜´å˜©å™“å™Žå™—å™´å˜¶å˜¯å˜°å¢€å¢Ÿå¢žå¢³å¢œå¢®å¢©å¢¦å¥­å¬‰å«»å¬‹å«µå¬Œå¬ˆå¯®å¯¬å¯©å¯«å±¤å±¥å¶å¶”幢幟幡廢廚廟å»å»£å» å½ˆå½±å¾·å¾µæ…¶æ…§æ…®æ…慕憂"], ["bca1","æ…¼æ…°æ…«æ…¾æ†§æ†æ†«æ†Žæ†¬æ†šæ†¤æ†”æ†®æˆ®æ‘©æ‘¯æ‘¹æ’žæ’²æ’ˆæ’æ’°æ’¥æ’“æ’•æ’©æ’’æ’®æ’­æ’«æ’šæ’¬æ’™æ’¢æ’³æ•µæ•·æ•¸æš®æš«æš´æš±æ¨£æ¨Ÿæ§¨æ¨æ¨žæ¨™æ§½æ¨¡æ¨“æ¨Šæ§³æ¨‚æ¨…æ§­æ¨‘æ­æ­Žæ®¤æ¯…毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛çŽç—ç‘©ç’‹ç’ƒ"], ["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼ç£ç¨¿ç¨¼ç©€ç¨½ç¨·ç¨»çª¯çª®ç®­ç®±ç¯„箴篆篇ç¯ç® ç¯Œç³Šç· ç·´ç·¯ç·»ç·˜ç·¬ç·ç·¨ç·£ç·šç·žç·©ç¶žç·™ç·²ç·¹ç½µç½·ç¾¯"], ["bda1","翩耦膛膜è†è† è†šè†˜è”—蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂è´è¶è è¦è¸è¨è™è—èŒè“è¡›è¡è¤è¤‡è¤’褓褕褊誼諒談諄誕請諸課諉諂調誰論è«èª¶èª¹è«›è±Œè±Žè±¬è³ è³žè³¦è³¤è³¬è³­è³¢è³£è³œè³ªè³¡èµ­è¶Ÿè¶£è¸«è¸è¸è¸¢è¸è¸©è¸Ÿè¸¡è¸žèººè¼è¼›è¼Ÿè¼©è¼¦è¼ªè¼œè¼ž"], ["be40","è¼¥é©é®é¨é­é·é„°é„­é„§é„±é†‡é†‰é†‹é†ƒé‹…銻銷鋪銬鋤é‹éŠ³éŠ¼é‹’é‹‡é‹°éŠ²é–­é–±éœ„éœ†éœ‡éœ‰é éžéž‹éžé ¡é «é œé¢³é¤Šé¤“餒餘é§é§é§Ÿé§›é§‘駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], ["bea1","鴃麩麾黎墨齒儒儘儔å„儕冀冪å‡åŠ‘åŠ“å‹³å™™å™«å™¹å™©å™¤å™¸å™ªå™¨å™¥å™±å™¯å™¬å™¢å™¶å£å¢¾å£‡å£…奮å¬å¬´å­¸å¯°å°Žå½Šæ†²æ†‘æ†©æ†Šæ‡æ†¶æ†¾æ‡Šæ‡ˆæˆ°æ“…æ“æ“‹æ’»æ’¼æ“šæ“„æ“‡æ“‚æ“æ’¿æ“’擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], ["bf40","æ¿ƒæ¾¤æ¿æ¾§æ¾³æ¿€æ¾¹æ¾¶æ¾¦æ¾ æ¾´ç†¾ç‡‰ç‡ç‡’燈燕熹燎燙燜燃燄ç¨ç’œç’£ç’˜ç’Ÿç’žç“¢ç”Œç”瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦ç©ç©Žç©†ç©Œç©‹çªºç¯™ç°‘築篤篛篡篩篦糕糖縊"], ["bfa1","縑縈縛縣縞ç¸ç¸‰ç¸ç½¹ç¾²ç¿°ç¿±ç¿®è€¨è†³è†©è†¨è‡»èˆˆè‰˜è‰™è•Šè•™è•ˆè•¨è•©è•ƒè•‰è•­è•ªè•žèžƒèžŸèžžèž¢èžè¡¡è¤ªè¤²è¤¥è¤«è¤¡è¦ªè¦¦è«¦è«ºè««è«±è¬€è«œè«§è«®è«¾è¬è¬‚諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦éµé´é¸é²é¼éºé„´é†’錠錶鋸錳錯錢鋼錫錄錚"], ["c040","éŒéŒ¦éŒ¡éŒ•錮錙閻隧隨險雕霎霑霖éœéœ“éœé›éœé¦éž˜é °é ¸é »é ·é ­é ¹é ¤é¤é¤¨é¤žé¤›é¤¡é¤šé§­é§¢é§±éª¸éª¼é«»é«­é¬¨é®‘鴕鴣鴦鴨鴒鴛默黔é¾é¾œå„ªå„Ÿå„¡å„²å‹µåšŽåš€åšåš…嚇"], ["c0a1","åšå£•å£“å£‘å£Žå¬°å¬ªå¬¤å­ºå°·å±¨å¶¼å¶ºå¶½å¶¸å¹«å½Œå¾½æ‡‰æ‡‚æ‡‡æ‡¦æ‡‹æˆ²æˆ´æ“Žæ“Šæ“˜æ“ æ“°æ“¦æ“¬æ“±æ“¢æ“­æ–‚æ–ƒæ›™æ›–æª€æª”æª„æª¢æªœæ«›æª£æ©¾æª—æªæª æ­œæ®®æ¯šæ°ˆæ¿˜æ¿±æ¿Ÿæ¿ æ¿›æ¿¤æ¿«æ¿¯æ¾€æ¿¬æ¿¡æ¿©æ¿•濮濰燧營燮燦燥燭燬燴燠爵牆ç°ç²ç’©ç’°ç’¦ç’¨ç™†ç™‚癌盪瞳瞪瞰瞬"], ["c140","瞧瞭矯磷磺磴磯ç¤ç¦§ç¦ªç©—窿簇ç°ç¯¾ç¯·ç°Œç¯ ç³ ç³œç³žç³¢ç³Ÿç³™ç³ç¸®ç¸¾ç¹†ç¸·ç¸²ç¹ƒç¸«ç¸½ç¸±ç¹…ç¹ç¸´ç¸¹ç¹ˆç¸µç¸¿ç¸¯ç½„翳翼è±è²è°è¯è³è‡†è‡ƒè†ºè‡‚臀膿膽臉膾臨舉艱薪"], ["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠è¬è¬„è¬è±è°¿è±³è³ºè³½è³¼è³¸è³»è¶¨è¹‰è¹‹è¹ˆè¹Šè½„輾轂轅輿é¿é½é‚„é‚邂邀鄹醣醞醜é鎂錨éµéŠé¥é‹éŒ˜é¾é¬é›é°éšé”闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵é¨"], ["c240","駿鮮鮫鮪鮭鴻鴿麋é»é»žé»œé»é»›é¼¾é½‹å¢åš•åš®å£™å£˜å¬¸å½æ‡£æˆ³æ“´æ“²æ“¾æ”†æ“ºæ“»æ“·æ–·æ›œæœ¦æª³æª¬æ«ƒæª»æª¸æ«‚檮檯歟歸殯瀉瀋濾瀆濺瀑ç€ç‡»ç‡¼ç‡¾ç‡¸ç·çµç’§ç’¿ç”•癖癘"], ["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻è·è¶è‡è‡èˆŠè—è–©è—è—藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫è±è´…蹙蹣蹦蹤蹟蹕軀轉è½é‚‡é‚ƒé‚ˆé†«é†¬é‡éŽ”éŽŠéŽ–éŽ¢éŽ³éŽ®éŽ¬éŽ°éŽ˜éŽšéŽ—é—”é—–é—闕離雜雙雛雞霤鞣鞦"], ["c340","鞭韹é¡é¡é¡Œé¡Žé¡“颺餾餿餽餮馥騎é«é¬ƒé¬†é­é­Žé­é¯Šé¯‰é¯½é¯ˆé¯€éµ‘éµéµ é» é¼•鼬儳嚥壞壟壢寵é¾å»¬æ‡²æ‡·æ‡¶æ‡µæ”€æ”æ› æ›æ«¥æ«æ«šæ«“瀛瀟瀨瀚ç€ç€•瀘爆çˆç‰˜çŠ¢ç¸"], ["c3a1","çºç’½ç“Šç“£ç–‡ç–†ç™Ÿç™¡çŸ‡ç¤™ç¦±ç©«ç©©ç°¾ç°¿ç°¸ç°½ç°·ç±€ç¹«ç¹­ç¹¹ç¹©ç¹ªç¾…繳羶羹羸臘藩è—藪藕藤藥藷蟻蠅è èŸ¹èŸ¾è¥ è¥Ÿè¥–襞è­è­œè­˜è­‰è­šè­Žè­è­†è­™è´ˆè´Šè¹¼è¹²èº‡è¹¶è¹¬è¹ºè¹´è½”轎辭邊邋醱醮é¡é‘éŸéƒéˆéœéé–é¢éé˜é¤é—é¨é—œéš´é›£éœªéœ§é¡éŸœéŸ»é¡ž"], ["c440","願顛颼饅饉騖騙é¬é¯¨é¯§é¯–鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲çˆç»ç“癢癥礦礪礬礫竇競籌籃ç±ç³¯ç³°è¾®ç¹½ç¹¼"], ["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫è´è´èº‰èºèº…躂醴釋é˜éƒé½é—¡éœ°é£„饒饑馨騫騰騷騵鰓é°é¹¹éºµé»¨é¼¯é½Ÿé½£é½¡å„·å„¸å›å›€å›‚夔屬巿‡¼æ‡¾æ”攜斕曩櫻欄櫺殲çŒçˆ›çŠ§ç“–ç“”ç™©çŸ“ç±çºçºŒç¾¼è˜—蘭蘚蠣蠢蠡蠟襪襬覽譴"], ["c540","護譽贓躊èºèº‹è½Ÿè¾¯é†ºé®é³éµéºé¸é²é«é—¢éœ¸éœ¹éœ²éŸ¿é¡§é¡¥é¥—驅驃驀騾é«é­”魑鰭鰥鶯鶴鷂鶸éºé»¯é¼™é½œé½¦é½§å„¼å„»å›ˆå›Šå›‰å­¿å·”巒彎懿攤權歡ç‘ç˜çŽ€ç“¤ç–Šç™®ç™¬"], ["c5a1","禳籠籟è¾è½è‡Ÿè¥²è¥¯è§¼è®€è´–贗躑躓轡酈鑄鑑鑒霽霾韃éŸé¡«é¥•é©•é©é«’鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬æ¬ç“šç«Šç±¤ç±£ç±¥çº“纖纔臢蘸蘿蠱變é‚é‚鑣鑠鑤é¨é¡¯é¥œé©šé©›é©—髓體髑鱔鱗鱖鷥麟黴囑壩攬çžç™±ç™²çŸ—ç½ç¾ˆè ¶è ¹è¡¢è®“è®’"], ["c640","讖艷贛釀鑪é‚éˆé„韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖ç£ç±¬ç±®è »è§€èº¡é‡é‘²é‘°é¡±é¥žé«–鬣黌ç¤çŸšè®šé‘·éŸ‰é©¢é©¥çºœè®œèºªé‡…鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], ["c940","乂乜凵匚厂万丌乇äºå›—兀屮彳ä¸å†‡ä¸Žä¸®äº“仂仉仈冘勼å¬åŽ¹åœ å¤ƒå¤¬å°å·¿æ—¡æ®³æ¯Œæ°”爿丱丼仨仜仩仡ä»ä»šåˆŒåŒœåŒåœ¢åœ£å¤—夯å®å®„å°’å°»å±´å±³å¸„åº€åº‚å¿‰æˆ‰æ‰æ°•"], ["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈ä¼ä¼‚伅伢伓伄仴伒冱刓刉åˆåŠ¦åŒ¢åŒŸå厊å‡å›¡å›Ÿåœ®åœªåœ´å¤¼å¦€å¥¼å¦…å¥»å¥¾å¥·å¥¿å­–å°•å°¥å±¼å±ºå±»å±¾å·Ÿå¹µåº„å¼‚å¼šå½´å¿•å¿”å¿æ‰œæ‰žæ‰¤æ‰¡æ‰¦æ‰¢æ‰™æ‰ æ‰šæ‰¥æ—¯æ—®æœ¾æœ¹æœ¸æœ»æœºæœ¿æœ¼æœ³æ°˜æ±†æ±’æ±œæ±æ±Šæ±”汋"], ["ca40","汌ç±ç‰žçŠ´çŠµçŽŽç”ªç™¿ç©µç½‘è‰¸è‰¼èŠ€è‰½è‰¿è™è¥¾é‚™é‚—邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟ä½ä½˜ä¼­ä¼³ä¼¿ä½¡å†å†¹åˆœåˆžåˆ¡åŠ­åŠ®åŒ‰å£å²åŽŽåŽå°å·åªå‘”å‘…å™åœå¥å˜"], ["caa1","å½å‘å‘å¨å¤å‘‡å›®å›§å›¥åå…åŒå‰å‹å’夆奀妦妘妠妗妎妢å¦å¦å¦§å¦¡å®Žå®’尨尪å²å²å²ˆå²‹å²‰å²’岊岆岓岕巠帊帎庋庉庌庈åºå¼…å¼å½¸å½¶å¿’å¿‘å¿å¿­å¿¨å¿®å¿³å¿¡å¿¤å¿£å¿ºå¿¯å¿·å¿»æ€€å¿´æˆºæŠƒæŠŒæŠŽæŠæŠ”æŠ‡æ‰±æ‰»æ‰ºæ‰°æŠæŠˆæ‰·æ‰½æ‰²æ‰´æ”·æ—°æ—´æ—³æ—²æ—µæ…æ‡"], ["cb40","æ™æ•æŒæˆæææšæ‹æ¯æ°™æ°šæ±¸æ±§æ±«æ²„æ²‹æ²æ±±æ±¯æ±©æ²šæ±­æ²‡æ²•沜汦汳汥汻沎ç´çºç‰£çŠ¿çŠ½ç‹ƒç‹†ç‹çŠºç‹…çŽ•çŽ—çŽ“çŽ”çŽ’ç”ºç”¹ç–”ç–•çšç¤½è€´è‚•è‚™è‚肒肜èŠèŠèŠ…èŠŽèŠ‘èŠ“"], ["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹ä¾ä½¸ä¾ä¾œä¾”侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿å’咑咂咈呫呺呾呥呬呴呦å’呯呡呠咘呣呧呤囷囹å¯å²å­å«å±å°å¶åž€åµå»å³å´å¢"], ["cc40","å¨å½å¤Œå¥…妵妺å§å§Žå¦²å§Œå§å¦¶å¦¼å§ƒå§–妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧å²å²¥å²¶å²°å²¦å¸—帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], ["cca1","æ€´æ€Šæ€—æ€³æ€šæ€žæ€¬æ€¢æ€æ€æ€®æ€“æ€‘æ€Œæ€‰æ€œæˆ”æˆ½æŠ­æŠ´æ‹‘æŠ¾æŠªæŠ¶æ‹ŠæŠ®æŠ³æŠ¯æŠ»æŠ©æŠ°æŠ¸æ”½æ–¨æ–»æ˜‰æ—¼æ˜„æ˜’æ˜ˆæ—»æ˜ƒæ˜‹æ˜æ˜…æ—½æ˜‘æ˜æ›¶æœŠæž…æ¬æžŽæž’æ¶æ»æž˜æž†æž„æ´æžæžŒæºæžŸæž‘æž™æžƒæ½æžæ¸æ¹æž”æ¬¥æ®€æ­¾æ¯žæ°æ²“æ³¬æ³«æ³®æ³™æ²¶æ³”æ²­æ³§æ²·æ³æ³‚沺泃泆泭泲"], ["cd40","æ³’æ³æ²´æ²Šæ²æ²€æ³žæ³€æ´°æ³æ³‡æ²°æ³¹æ³æ³©æ³‘炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬çŽç“瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], ["cda1","矷祂礿秅穸穻竻籵糽耵è‚肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓è¿è¿–迕迗邲邴邯邳邰阹阽阼阺陃ä¿ä¿…俓侲俉俋ä¿ä¿”俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽å¼åŽ—åŽ–åŽ™åŽ˜å’ºå’¡å’­å’¥å“"], ["ce40","哃èŒå’·å’®å“–咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗åžåž›åž”垘åžåž™åž¥åžšåž•壴å¤å¥“姡姞姮娀姱å§å§ºå§½å§¼å§¶å§¤å§²å§·å§›å§©å§³å§µå§ å§¾å§´å§­å®¨å±Œå³å³˜å³Œå³—峋峛"], ["cea1","峞峚峉峇峊峖峓峔å³å³ˆå³†å³Žå³Ÿå³¸å·¹å¸¡å¸¢å¸£å¸ å¸¤åº°åº¤åº¢åº›åº£åº¥å¼‡å¼®å½–å¾†æ€·æ€¹æ”æ²æžæ…æ“æ‡æ‰æ›æŒæ€æ‚æŸæ€¤æ„æ˜æ¦æ®æ‰‚æ‰ƒæ‹æŒæŒ‹æ‹µæŒŽæŒƒæ‹«æ‹¹æŒæŒŒæ‹¸æ‹¶æŒ€æŒ“æŒ”æ‹ºæŒ•æ‹»æ‹°æ•æ•ƒæ–ªæ–¿æ˜¶æ˜¡æ˜²æ˜µæ˜œæ˜¦æ˜¢æ˜³æ˜«æ˜ºæ˜æ˜´æ˜¹æ˜®æœæœæŸæŸ²æŸˆæžº"], ["cf40","æŸœæž»æŸ¸æŸ˜æŸ€æž·æŸ…æŸ«æŸ¤æŸŸæžµæŸæž³æŸ·æŸ¶æŸ®æŸ£æŸ‚æž¹æŸŽæŸ§æŸ°æž²æŸ¼æŸ†æŸ­æŸŒæž®æŸ¦æŸ›æŸºæŸ‰æŸŠæŸƒæŸªæŸ‹æ¬¨æ®‚æ®„æ®¶æ¯–æ¯˜æ¯ æ° æ°¡æ´¨æ´´æ´­æ´Ÿæ´¼æ´¿æ´’æ´Šæ³šæ´³æ´„æ´™æ´ºæ´šæ´‘æ´€æ´æµ‚"], ["cfa1","æ´æ´˜æ´·æ´ƒæ´æµ€æ´‡æ´ æ´¬æ´ˆæ´¢æ´‰æ´ç‚·ç‚Ÿç‚¾ç‚±ç‚°ç‚¡ç‚´ç‚µç‚©ç‰ç‰‰ç‰Šç‰¬ç‰°ç‰³ç‰®ç‹Šç‹¤ç‹¨ç‹«ç‹Ÿç‹ªç‹¦ç‹£çŽ…çŒç‚çˆç…玹玶玵玴ç«çŽ¿ç‡ç޾çƒç†çޏç‹ç“¬ç“®ç”®ç•‡ç•ˆç–§ç–ªç™¹ç›„眈眃眄眅眊盷盻盺矧矨砆砑砒砅ç ç ç Žç ‰ç ƒç “祊祌祋祅祄秕ç§ç§ç§–秎窀"], ["d040","穾竑笀ç¬ç±ºç±¸ç±¹ç±¿ç²€ç²ç´ƒç´ˆç´ç½˜ç¾‘ç¾ç¾¾è€‡è€Žè€è€”耷胘胇胠胑胈胂èƒèƒ…胣胙胜胊胕胉èƒèƒ—胦èƒè‡¿èˆ¡èŠ”è‹™è‹¾è‹¹èŒ‡è‹¨èŒ€è‹•èŒºè‹«è‹–è‹´è‹¬è‹¡è‹²è‹µèŒŒè‹»è‹¶è‹°è‹ª"], ["d0a1","苤苠苺苳苭虷虴虼虳è¡è¡Žè¡§è¡ªè¡©è§“訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔é™é™‘陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢å‹åŒŽåŽžå”¦å“¢å”—å”’å“§å“³å“¤å”šå“¿å”„å”ˆå“«å”‘å”…å“±"], ["d140","唊哻哷哸哠唎唃唋åœåœ‚埌堲埕埒垺埆垽垼垸垶垿埇åŸåž¹åŸå¤Žå¥Šå¨™å¨–娭娮娕å¨å¨—å¨Šå¨žå¨³å­¬å®§å®­å®¬å°ƒå±–å±”å³¬å³¿å³®å³±å³·å´€å³¹å¸©å¸¨åº¨åº®åºªåº¬å¼³å¼°å½§ææšæ§"], ["d1a1","ææ‚¢æ‚ˆæ‚€æ‚’æ‚æ‚æ‚ƒæ‚•æ‚›æ‚—æ‚‡æ‚œæ‚Žæˆ™æ‰†æ‹²æŒæ–æŒ¬æ„æ…æŒ¶æƒæ¤æŒ¹æ‹æŠæŒ¼æŒ©ææŒ´æ˜æ”æ™æŒ­æ‡æŒ³æšæ‘æŒ¸æ—æ€æˆæ•Šæ•†æ—†æ—ƒæ—„æ—‚æ™Šæ™Ÿæ™‡æ™‘æœ’æœ“æ Ÿæ šæ¡‰æ ²æ ³æ »æ¡‹æ¡æ –æ ±æ œæ µæ «æ ­æ ¯æ¡Žæ¡„æ ´æ æ ’æ ”æ ¦æ ¨æ ®æ¡æ ºæ ¥æ  æ¬¬æ¬¯æ¬­æ¬±æ¬´æ­­è‚‚殈毦毤"], ["d240","æ¯¨æ¯£æ¯¢æ¯§æ°¥æµºæµ£æµ¤æµ¶æ´æµ¡æ¶’æµ˜æµ¢æµ­æµ¯æ¶‘æ¶æ·¯æµ¿æ¶†æµžæµ§æµ æ¶—浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵æ¶çƒœçƒ“烑çƒçƒ‹ç¼¹çƒ¢çƒ—烒烞烠烔çƒçƒ…烆烇烚烎烡牂牸"], ["d2a1","牷牶猀狺狴狾狶狳狻çŒç“ç™ç¥ç–玼ç§ç£ç©çœç’ç›ç”ççšç—ç˜ç¨ç“žç“Ÿç“´ç“µç”¡ç•›ç•Ÿç–°ç—疻痄痀疿疶疺皊盉çœçœ›çœçœ“眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛ç¥ç¥œç¥“祒祑秫秬秠秮秭秪秜秞ç§çª†çª‰çª…窋窌窊窇竘ç¬"], ["d340","笄笓笅ç¬ç¬ˆç¬Šç¬Žç¬‰ç¬’粄粑粊粌粈ç²ç²…ç´žç´ç´‘紎紘紖紓紟紒ç´ç´Œç½œç½¡ç½žç½ ç½ç½›ç¾–羒翃翂翀耖耾耹胺胲胹胵è„胻脀èˆèˆ¯èˆ¥èŒ³èŒ­è„茙è‘茥è–茿è茦茜茢"], ["d3a1","è‚èŽèŒ›èŒªèŒˆèŒ¼è茖茤茠茷茯茩è‡è…èŒè“茞茬è‹èŒ§èˆè™“虒蚢蚨蚖èšèš‘蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎èšèšèš”衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤é…"], ["d440","é…Žé…釕釢釚陜陟隼飣髟鬯乿å°åªå¡åžå å“å‹åå²åˆååå›åŠå¢å€•å…åŸå©å«å£å¤å†å€å®å³å—å‘å‡å‰«å‰­å‰¬å‰®å‹–勓匭厜啵啶唼å•å•唴唪啑啢唶唵唰啒啅"], ["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳åŸå ‡åŸ®åŸ£åŸ²åŸ¥åŸ¬åŸ¡å ŽåŸ¼å åŸ§å å ŒåŸ±åŸ©åŸ°å å „奜婠婘婕婧婞娸娵婭å©å©Ÿå©¥å©¬å©“婤婗婃å©å©’婄婛婈媎娾å©å¨¹å©Œå©°å©©å©‡å©‘婖婂婜孲孮å¯å¯€å±™å´žå´‹å´å´šå´ å´Œå´¨å´å´¦å´¥å´"], ["d540","å´°å´’å´£å´Ÿå´®å¸¾å¸´åº±åº´åº¹åº²åº³å¼¶å¼¸å¾›å¾–å¾Ÿæ‚Šæ‚æ‚†æ‚¾æ‚°æ‚ºæƒ“æƒ”æƒæƒ¤æƒ™æƒæƒˆæ‚±æƒ›æ‚·æƒŠæ‚¿æƒƒæƒæƒ€æŒ²æ¥æŽŠæŽ‚æ½æŽ½æŽžæŽ­æŽæŽ—æŽ«æŽŽæ¯æŽ‡æŽæ®æŽ¯æµæŽœæ­æŽ®æ¼æŽ¤æŒ»æŽŸ"], ["d5a1","æ¸æŽ…æŽæŽ‘æŽæ°æ•“æ—æ™¥æ™¡æ™›æ™™æ™œæ™¢æœ˜æ¡¹æ¢‡æ¢æ¢œæ¡­æ¡®æ¢®æ¢«æ¥–æ¡¯æ¢£æ¢¬æ¢©æ¡µæ¡´æ¢²æ¢æ¡·æ¢’æ¡¼æ¡«æ¡²æ¢ªæ¢€æ¡±æ¡¾æ¢›æ¢–æ¢‹æ¢ æ¢‰æ¢¤æ¡¸æ¡»æ¢‘æ¢Œæ¢Šæ¡½æ¬¶æ¬³æ¬·æ¬¸æ®‘æ®æ®æ®Žæ®Œæ°ªæ·€æ¶«æ¶´æ¶³æ¹´æ¶¬æ·©æ·¢æ¶·æ·¶æ·”æ¸€æ·ˆæ· æ·Ÿæ·–æ¶¾æ·¥æ·œæ·æ·›æ·´æ·Šæ¶½æ·­æ·°æ¶ºæ·•æ·‚æ·æ·‰"], ["d640","æ·æ·²æ·“æ·½æ·—æ·æ·£æ¶»çƒºç„烷焗烴焌烰焄烳ç„烼烿焆焓焀烸烶焋焂焎牾牻牼牿çŒçŒ—猇猑猘猊猈狿çŒçŒžçŽˆç¶ç¸çµç„çç½ç‡ç€çºç¼ç¿çŒç‹ç´çˆç•¤ç•£ç—Žç—’ç—"], ["d6a1","痋痌痑ç—çšçš‰ç›“眹眯眭眱眲眴眳眽眥眻眵硈硒硉ç¡ç¡Šç¡Œç ¦ç¡…ç¡ç¥¤ç¥§ç¥©ç¥ªç¥£ç¥«ç¥¡ç¦»ç§ºç§¸ç§¶ç§·çªçª”çªç¬µç­‡ç¬´ç¬¥ç¬°ç¬¢ç¬¤ç¬³ç¬˜ç¬ªç¬ç¬±ç¬«ç¬­ç¬¯ç¬²ç¬¸ç¬šç¬£ç²”粘粖粣紵紽紸紶紺絅紬紩çµçµ‡ç´¾ç´¿çµŠç´»ç´¨ç½£ç¾•羜ç¾ç¾›ç¿Šç¿‹ç¿ç¿ç¿‘翇ç¿ç¿‰è€Ÿ"], ["d740","耞耛è‡èƒèˆè„˜è„¥è„™è„›è„­è„Ÿè„¬è„žè„¡è„•è„§è„脢舑舸舳舺舴舲艴èŽèŽ£èŽ¨èŽèºè³èޤè´èŽèŽèŽ•èŽ™èµèŽ”èŽ©è½èŽƒèŽŒèŽèŽ›èŽªèŽ‹è¾èŽ¥èŽ¯èŽˆèŽ—èŽ°è¿èŽ¦èŽ‡èŽ®è¶èŽšè™™è™–èš¿èš·"], ["d7a1","蛂è›è›…蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜è±è±½è²¥èµ½èµ»èµ¹è¶¼è·‚趹趿è·è»˜è»žè»è»œè»—軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], ["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿éªé „飥馗傛傕傔傞傋傣傃傌傎å‚å¨å‚œå‚’傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈å–å–µå–喣喒喤啽喌喦啿喕喡喎圌堩堷"], ["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜åªåª“åªå¯ªå¯å¯‹å¯”寑寊寎尌尰崷嵃嵫åµåµ‹å´¿å´µåµ‘嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄å¹å½˜å¾¦å¾¥å¾«æƒ‰æ‚¹æƒŒæƒ¢æƒŽæƒ„æ„”"], ["d940","æƒ²æ„Šæ„–æ„…æƒµæ„“æƒ¸æƒ¼æƒ¾æƒæ„ƒæ„˜æ„æ„æƒ¿æ„„æ„‹æ‰ŠæŽ”æŽ±æŽ°æŽæ¥æ¨æ¯æƒæ’æ³æŠæ æ¶æ•æ²æµæ‘¡æŸæŽ¾ææœæ„æ˜æ“æ‚æ‡æŒæ‹æˆæ°æ—æ™æ”²æ•§æ•ªæ•¤æ•œæ•¨æ•¥æ–Œæ–æ–žæ–®æ—æ—’"], ["d9a1","æ™¼æ™¬æ™»æš€æ™±æ™¹æ™ªæ™²æœæ¤Œæ£“æ¤„æ£œæ¤ªæ£¬æ£ªæ£±æ¤æ£–æ£·æ£«æ£¤æ£¶æ¤“æ¤æ£³æ£¡æ¤‡æ£Œæ¤ˆæ¥°æ¢´æ¤‘æ£¯æ£†æ¤”æ£¸æ£æ£½æ£¼æ£¨æ¤‹æ¤Šæ¤—æ£Žæ£ˆæ£æ£žæ£¦æ£´æ£‘æ¤†æ£”æ£©æ¤•æ¤¥æ£‡æ¬¹æ¬»æ¬¿æ¬¼æ®”æ®—æ®™æ®•æ®½æ¯°æ¯²æ¯³æ°°æ·¼æ¹†æ¹‡æ¸Ÿæ¹‰æºˆæ¸¼æ¸½æ¹…æ¹¢æ¸«æ¸¿æ¹æ¹æ¹³æ¸œæ¸³æ¹‹æ¹€æ¹‘渻渃渮湞"], ["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌ç®ç¬ç°ç«ç–"], ["daa1","çšç¡ç­ç±ç¤ç£çç©ç ç²ç“»ç”¯ç•¯ç•¬ç—§ç—šç—¡ç—¦ç—痟痤痗皕皒盚ç†ç‡ç„çç…çŠçŽç‹çŒçŸžçŸ¬ç¡ ç¡¤ç¡¥ç¡œç¡­ç¡±ç¡ªç¡®ç¡°ç¡©ç¡¨ç¡žç¡¢ç¥´ç¥³ç¥²ç¥°ç¨‚稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪çµçµ­çµœçµ«çµ’絔絩絑絟絎缾缿罥"], ["db40","罦羢羠羡翗è‘èè胾胔腃腊腒è…腇脽è…脺臦臮臷臸臹舄舼舽舿艵茻èè¹è£è€è¨è’è§è¤è¼è¶èè†èˆè«è£èŽ¿èèè¥è˜è¿è¡è‹èŽè–èµè‰è‰èèžè‘è†è‚è³"], ["dba1","è•èºè‡è‘èªè“èƒè¬è®è„è»è—è¢è›è›è¾è›˜è›¢è›¦è›“蛣蛚蛪è›è›«è›œè›¬è›©è›—蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲è¤è£‰è¦•覘覗è§è§šè§›è©Žè©è¨¹è©™è©€è©—詘詄詅詒詈詑詊詌è©è±Ÿè²è²€è²ºè²¾è²°è²¹è²µè¶„趀趉跘跓è·è·‡è·–è·œè·è·•跙跈跗跅軯軷軺"], ["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻é„鄀鄇鄅鄃酡酤酟酢酠éˆéˆŠéˆ¥éˆƒéˆšéˆ¦éˆéˆŒéˆ€éˆ’釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻é–é–Œé–隇陾隈"], ["dca1","隉隃隀雂雈雃雱雰é¬é°é®é ‡é¢©é£«é³¦é»¹äºƒäº„亶傽傿僆傮僄僊傴僈僂傰åƒå‚ºå‚±åƒ‹åƒ‰å‚¶å‚¸å‡—剺剸剻剼嗃嗛嗌å—å—‹å—Šå—嗀嗔嗄嗩喿嗒å–å—嗕嗢嗖嗈嗲å—嗙嗂圔塓塨塤å¡å¡å¡‰å¡¯å¡•塎å¡å¡™å¡¥å¡›å ½å¡£å¡±å£¼å«‡å«„嫋媺媸媱媵媰媿嫈媻嫆"], ["dd40","媷嫀嫊媴媶å«åª¹åªå¯–寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰å¹å¹Žå¹Šå¹å¹‹å»…å»Œå»†å»‹å»‡å½€å¾¯å¾­æƒ·æ…‰æ…Šæ„«æ……æ„¶æ„²æ„®æ…†æ„¯æ…æ„©æ…€æˆ é…¨æˆ£æˆ¥æˆ¤æ…æ±æ«ææ’æ‰æ æ¤"], ["dda1","æ³æ‘ƒæŸæ•æ˜æ¹æ·æ¢æ£æŒæ¦æ°æ¨æ‘æµæ¯æŠæšæ‘€æ¥æ§æ‹æ§æ›æ®æ¡æŽæ•¯æ–’æ—“æš†æšŒæš•æšæš‹æšŠæš™æš”æ™¸æœ æ¥¦æ¥Ÿæ¤¸æ¥Žæ¥¢æ¥±æ¤¿æ¥…æ¥ªæ¤¹æ¥‚æ¥—æ¥™æ¥ºæ¥ˆæ¥‰æ¤µæ¥¬æ¤³æ¤½æ¥¥æ£°æ¥¸æ¤´æ¥©æ¥€æ¥¯æ¥„æ¥¶æ¥˜æ¥æ¥´æ¥Œæ¤»æ¥‹æ¤·æ¥œæ¥æ¥‘æ¤²æ¥’æ¤¯æ¥»æ¤¼æ­†æ­…æ­ƒæ­‚æ­ˆæ­æ®›ï¨æ¯»æ¯¼"], ["de40","æ¯¹æ¯·æ¯¸æº›æ»–æ»ˆæºæ»€æºŸæº“æº”æº æº±æº¹æ»†æ»’æº½æ»æºžæ»‰æº·æº°æ»æº¦æ»æº²æº¾æ»ƒæ»œæ»˜æº™æº’æºŽæºæº¤æº¡æº¿æº³æ»æ»Šæº—溮溣煇煔煒煣煠ç…ç…煢煲煸煪煡煂煘煃煋煰煟ç…ç…“"], ["dea1","ç…„ç…ç…šç‰çŠçŠŒçŠ‘çŠçŠŽçŒ¼ç‚猻猺ç€çŠç‰ç‘„瑊瑋瑒瑑瑗瑀ç‘ç‘瑎瑂瑆ç‘瑔瓡瓿瓾瓽ç”畹畷榃痯ç˜ç˜ƒç—·ç—¾ç—¼ç—¹ç—¸ç˜ç—»ç—¶ç—­ç—µç—½çš™çšµç›ç•çŸç ç’ç–çšç©ç§ç”ç™ç­çŸ ç¢‡ç¢šç¢”ç¢ç¢„碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], ["df40","稛ç¨çª£çª¢çªžç««ç­¦ç­¤ç­­ç­´ç­©ç­²ç­¥ç­³ç­±ç­°ç­¡ç­¸ç­¶ç­£ç²²ç²´ç²¯ç¶ˆç¶†ç¶€ç¶çµ¿ç¶…絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], ["dfa1","è…„è…¡èˆè‰‰è‰„艀艂艅蓱è¿è‘–葶葹è’è’葥葑葀蒆葧è°è‘葽葚葙葴葳è‘蔇葞è·èºè´è‘ºè‘ƒè‘¸è²è‘…è©è™è‘‹è¯è‘‚è­è‘Ÿè‘°è¹è‘Žè‘Œè‘’葯蓅蒎è»è‘‡è¶è³è‘¨è‘¾è‘„è«è‘ è‘”è‘®è‘蜋蜄蛷蜌蛺蛖蛵è蛸蜎蜉èœè›¶èœèœ…裖裋è£è£Žè£žè£›è£šè£Œè£è¦…覛觟觥觤"], ["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃èªè©´è©ºè°¼è±‹è±Šè±¥è±¤è±¦è²†è²„貅賌赨赩趑趌趎è¶è¶è¶“è¶”è¶è¶’跰跠跬跱跮è·è·©è·£è·¢è·§è·²è·«è·´è¼†è»¿è¼è¼€è¼…輇輈輂輋é’逿"], ["e0a1","é„é‰é€½é„é„é„鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬é‰é‰ é‰§é‰¯éˆ¶é‰¡é‰°éˆ±é‰”鉣é‰é‰²é‰Žé‰“鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵é³é·é¸é²é é é Žé¢¬é£¶é£¹é¦¯é¦²é¦°é¦µéª­éª«é­›é³ªé³­é³§éº€é»½åƒ¦åƒ”僗僨僳僛僪åƒåƒ¤åƒ“僬僰僯僣僠"], ["e140","凘劀åŠå‹©å‹«åŒ°åŽ¬å˜§å˜•å˜Œå˜’å—¼å˜å˜œå˜å˜“嘂嗺å˜å˜„嗿嗹墉塼å¢å¢˜å¢†å¢å¡¿å¡´å¢‹å¡ºå¢‡å¢‘墎塶墂墈塻墔å¢å£¾å¥«å«œå«®å«¥å«•嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞å«å«™å«¨å«Ÿå­·å¯ "], ["e1a1","寣屣嶂嶀嵽嶆嵺å¶åµ·å¶Šå¶‰å¶ˆåµ¾åµ¼å¶åµ¹åµ¿å¹˜å¹™å¹“å»˜å»‘å»—å»Žå»œå»•å»™å»’å»”å½„å½ƒå½¯å¾¶æ„¬æ„¨æ…æ…žæ…±æ…³æ…’æ…“æ…²æ…¬æ†€æ…´æ…”æ…ºæ…›æ…¥æ„»æ…ªæ…¡æ…–æˆ©æˆ§æˆ«æ«æ‘æ‘›æ‘æ‘´æ‘¶æ‘²æ‘³æ‘½æ‘µæ‘¦æ’¦æ‘Žæ’‚æ‘žæ‘œæ‘‹æ‘“æ‘ æ‘æ‘¿æ¿æ‘¬æ‘«æ‘™æ‘¥æ‘·æ•³æ– æš¡æš æšŸæœ…朄朢榱榶槉"], ["e240","æ¦ æ§Žæ¦–æ¦°æ¦¬æ¦¼æ¦‘æ¦™æ¦Žæ¦§æ¦æ¦©æ¦¾æ¦¯æ¦¿æ§„æ¦½æ¦¤æ§”æ¦¹æ§Šæ¦šæ§æ¦³æ¦“æ¦ªæ¦¡æ¦žæ§™æ¦—æ¦æ§‚æ¦µæ¦¥æ§†æ­Šæ­æ­‹æ®žæ®Ÿæ® æ¯ƒæ¯„毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], ["e2a1","æ¼¶æ½³æ»¹æ»®æ¼­æ½€æ¼°æ¼¼æ¼µæ»«æ¼‡æ¼Žæ½ƒæ¼…æ»½æ»¶æ¼¹æ¼œæ»¼æ¼ºæ¼Ÿæ¼æ¼žæ¼ˆæ¼¡ç†‡ç†ç†‰ç†€ç†…熂ç†ç…»ç††ç†ç†—牄牓犗犕犓çƒçç‘çŒç‘¢ç‘³ç‘±ç‘µç‘²ç‘§ç‘®ç”€ç”‚甃畽ç–瘖瘈瘌瘕瘑瘊瘔皸çžç¼çž…çž‚ç®çž€ç¯ç¾çžƒç¢²ç¢ªç¢´ç¢­ç¢¨ç¡¾ç¢«ç¢žç¢¥ç¢ ç¢¬ç¢¢ç¢¤ç¦˜ç¦Šç¦‹ç¦–禕禔禓"], ["e340","禗禈禒ç¦ç¨«ç©Šç¨°ç¨¯ç¨¨ç¨¦çª¨çª«çª¬ç«®ç®ˆç®œç®Šç®‘ç®ç®–ç®ç®Œç®›ç®Žç®…箘劄箙箤箂粻粿粼粺綧綷緂綣綪ç·ç·€ç·…ç¶ç·Žç·„緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], ["e3a1","耤èèœè†‰è††è†ƒè†‡è†è†Œè†‹èˆ•蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴è“è“蒪蒚蒱è“è’蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶è“蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨è«è€èœ®èœžèœ¡èœ™èœ›èƒèœ¬è蜾è†èœ èœ²èœªèœ­èœ¼èœ’蜺蜱蜵è‚蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], ["e440","裰裬裫è¦è¦¡è¦Ÿè¦žè§©è§«è§¨èª«èª™èª‹èª’èªèª–谽豨豩賕è³è³—趖踉踂跿è¸è·½è¸Šè¸ƒè¸‡è¸†è¸…跾踀踄è¼è¼‘輎è¼é„£é„œé„ é„¢é„Ÿé„鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪éŠ"], ["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩éŠéŠ‹éˆ­éšžéš¡é›¿é˜é½éºé¾éžƒéž€éž‚é»éž„éžé¿éŸŽéŸé –颭颮餂餀餇é¦é¦œé§ƒé¦¹é¦»é¦ºé§‚馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵å™å™Šå™‰å™†å™˜"], ["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫å¢å¢±å¢ å¢£å¢¯å¢¬å¢¥å¢¡å£¿å«¿å«´å«½å«·å«¶å¬ƒå«¸å¬‚嫹å¬å¬‡å¬…å¬å±§å¶™å¶—嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩å¹å¹ å¹œç·³å»›å»žå»¡å½‰å¾²æ†‹æ†ƒæ…¹æ†±æ†°æ†¢æ†‰"], ["e5a1","æ†›æ†“æ†¯æ†­æ†Ÿæ†’æ†ªæ†¡æ†æ…¦æ†³æˆ­æ‘®æ‘°æ’–æ’ æ’…æ’—æ’œæ’æ’‹æ’Šæ’Œæ’£æ’Ÿæ‘¨æ’±æ’˜æ•¶æ•ºæ•¹æ•»æ–²æ–³æšµæš°æš©æš²æš·æšªæš¯æ¨€æ¨†æ¨—æ§¥æ§¸æ¨•æ§±æ§¤æ¨ æ§¿æ§¬æ§¢æ¨›æ¨æ§¾æ¨§æ§²æ§®æ¨”æ§·æ§§æ©€æ¨ˆæ§¦æ§»æ¨æ§¼æ§«æ¨‰æ¨„æ¨˜æ¨¥æ¨æ§¶æ¨¦æ¨‡æ§´æ¨–æ­‘æ®¥æ®£æ®¢æ®¦æ°æ°€æ¯¿æ°‚æ½æ¼¦æ½¾æ¾‡æ¿†æ¾’"], ["e640","æ¾æ¾‰æ¾Œæ½¢æ½æ¾…æ½šæ¾–æ½¶æ½¬æ¾‚æ½•æ½²æ½’æ½æ½—æ¾”æ¾“æ½æ¼€æ½¡æ½«æ½½æ½§æ¾æ½“澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵ç†ç†¥ç†žç†¤ç†¡ç†ªç†œç†§ç†³çŠ˜çŠšç˜ç’çžçŸç çç›ç¡çšç™"], ["e6a1","ç¢ç’‡ç’‰ç’Šç’†ç’瑽璅璈瑼瑹甈甇畾瘥瘞瘙ç˜ç˜œç˜£ç˜šç˜¨ç˜›çšœçšçšžçš›çžçžçž‰çžˆç£ç¢»ç£ç£Œç£‘磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨è¤è§è†£è†Ÿ"], ["e740","膞膕膢膙膗舖è‰è‰“艒è‰è‰Žè‰‘蔤蔻è”蔀蔩蔎蔉è”蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨è”蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], ["e7a1","è–è£è¤è·èŸ¡è³è˜è”è›è’è¡èšè‘èžè­èªèèŽèŸèè¯è¬èºè®èœè¥èè»èµè¢è§è©è¡šè¤…褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬è«è«†èª¸è«“諑諔諕誻諗誾諀諅諘諃誺誽諙谾è±è²è³¥è³Ÿè³™è³¨è³šè³è³§è¶ è¶œè¶¡è¶›è¸ è¸£è¸¥è¸¤è¸®è¸•踛踖踑踙踦踧"], ["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗é³é°é¯é§é«é„¯é„«é„©é„ªé„²é„¦é„®é†…醆醊é†é†‚醄醀é‹é‹ƒé‹„鋀鋙銶é‹é‹±é‹Ÿé‹˜é‹©é‹—é‹é‹Œé‹¯é‹‚鋨鋊鋈鋎鋦é‹é‹•鋉鋠鋞鋧鋑鋓"], ["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂éšéžŠéžŽéžˆéŸéŸé žé é ¦é ©é ¨é  é ›é §é¢²é¤ˆé£ºé¤‘餔餖餗餕駜é§é§é§“駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓é¼é¼å„œå„“儗儚儑凞匴å¡å™°å™ å™®"], ["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓å¬å¬–å¬¨å¬šå¬ å¬žå¯¯å¶¬å¶±å¶©å¶§å¶µå¶°å¶®å¶ªå¶¨å¶²å¶­å¶¯å¶´å¹§å¹¨å¹¦å¹¯å»©å»§å»¦å»¨å»¥å½‹å¾¼æ†æ†¨æ†–æ‡…æ†´æ‡†æ‡æ‡Œæ†º"], ["e9a1","æ†¿æ†¸æ†Œæ“—æ“–æ“æ“æ“‰æ’½æ’‰æ“ƒæ“›æ“³æ“™æ”³æ•¿æ•¼æ–¢æ›ˆæš¾æ›€æ›Šæ›‹æ›æš½æš»æšºæ›Œæœ£æ¨´æ©¦æ©‰æ©§æ¨²æ©¨æ¨¾æ©æ©­æ©¶æ©›æ©‘æ¨¨æ©šæ¨»æ¨¿æ©æ©ªæ©¤æ©æ©æ©”æ©¯æ©©æ© æ¨¼æ©žæ©–æ©•æ©æ©Žæ©†æ­•æ­”æ­–æ®§æ®ªæ®«æ¯ˆæ¯‡æ°„æ°ƒæ°†æ¾­æ¿‹æ¾£æ¿‡æ¾¼æ¿Žæ¿ˆæ½žæ¿„æ¾½æ¾žæ¿Šæ¾¨ç€„æ¾¥æ¾®æ¾ºæ¾¬æ¾ªæ¿æ¾¿æ¾¸"], ["ea40","æ¾¢æ¿‰æ¾«æ¿æ¾¯æ¾²æ¾°ç‡…燂熿熸燖燀ç‡ç‡‹ç‡”燊燇ç‡ç†½ç‡˜ç†¼ç‡†ç‡šç‡›çŠçŠžç©ç¦ç§ç¬ç¥ç«çªç‘¿ç’šç’ ç’”璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚çžçž¡çžœçž›çž¢çž£çž•çž™"], ["eaa1","çž—ç£ç£©ç£¥ç£ªç£žç££ç£›ç£¡ç£¢ç£­ç£Ÿç£ ç¦¤ç©„穈穇窶窸窵窱窷篞篣篧ç¯ç¯•篥篚篨篹篔篪篢篜篫篘篟糒糔糗ç³ç³‘縒縡縗縌縟縠縓縎縜縕縚縢縋ç¸ç¸–ç¸ç¸”縥縤罃罻罼罺羱翯耪耩è¬è†±è†¦è†®è†¹è†µè†«è†°è†¬è†´è†²è†·è†§è‡²è‰•艖艗蕖蕅蕫è•蕓蕡蕘"], ["eb40","蕀蕆蕤è•蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦è•蕔蕥蕬虣虥虤螛èžèž—螓螒螈èžèž–螘è¹èž‡èž£èž…èžèž‘èžèž„螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], ["eba1","諢諲諴諵è«è¬”諤諟諰諈諞諡諨諿諯諻貑貒è²è³µè³®è³±è³°è³³èµ¬èµ®è¶¥è¶§è¸³è¸¾è¸¸è¹€è¹…踶踼踽è¹è¸°è¸¿èº½è¼¶è¼®è¼µè¼²è¼¹è¼·è¼´é¶é¹é»é‚†éƒºé„³é„µé„¶é†“é†é†‘é†é†éŒ§éŒžéŒˆéŒŸéŒ†éŒéºéŒ¸éŒ¼éŒ›éŒ£éŒ’éŒé†éŒ­éŒŽéŒé‹‹éŒé‹ºéŒ¥éŒ“鋹鋷錴錂錤鋿錩錹錵錪錔錌"], ["ec40","錋鋾錉錀鋻錖閼é—閾閹閺閶閿閵閽隩雔霋霒éœéž™éž—鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒é®é­ºé®•"], ["eca1","魽鮈鴥鴗鴠鴞鴔鴩é´é´˜é´¢é´é´™é´Ÿéºˆéº†éº‡éº®éº­é»•黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌åšåš†åš„嚃噾嚂噿åšå£–壔å£å£’å¬­å¬¥å¬²å¬£å¬¬å¬§å¬¦å¬¯å¬®å­»å¯±å¯²å¶·å¹¬å¹ªå¾¾å¾»æ‡ƒæ†µæ†¼æ‡§æ‡ æ‡¥æ‡¤æ‡¨æ‡žæ“¯æ“©æ“£æ“«æ“¤æ“¨æ–æ–€æ–¶æ—šæ›’æªæª–æªæª¥æª‰æªŸæª›æª¡æªžæª‡æª“檎"], ["ed40","æª•æªƒæª¨æª¤æª‘æ©¿æª¦æªšæª…æªŒæª’æ­›æ®­æ°‰æ¿Œæ¾©æ¿´æ¿”æ¿£æ¿œæ¿­æ¿§æ¿¦æ¿žæ¿²æ¿æ¿¢æ¿¨ç‡¡ç‡±ç‡¨ç‡²ç‡¤ç‡°ç‡¢ç³ç®ç¯ç’—璲璫ç’璪璭璱璥璯ç”甑甒ç”疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], ["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀ç«ç°…ç°ç¯²ç°€ç¯¿ç¯»ç°Žç¯´ç°‹ç¯³ç°‚簉簃ç°ç¯¸ç¯½ç°†ç¯°ç¯±ç°ç°Šç³¨ç¸­ç¸¼ç¹‚縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀è–薧薕薠薋薣蕻薤薚薞"], ["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆è–è–™è–è–薢薂薈薅蕹蕶薘è–薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾è¥è¥’褷襂覭覯覮觲觳謞"], ["eea1","謘謖謑謅謋謢è¬è¬’謕謇è¬è¬ˆè¬†è¬œè¬“謚è±è±°è±²è±±è±¯è²•貔賹赯蹎è¹è¹“è¹è¹Œè¹‡è½ƒè½€é‚…é¾é„¸é†šé†¢é†›é†™é†Ÿé†¡é†é† éŽ¡éŽƒéŽ¯é¤é–é‡é¼é˜éœé¶é‰éé‘é é­éŽéŒéªé¹é—é•é’éé±é·é»é¡éžé£é§éŽ€éŽé™é—‡é—€é—‰é—ƒé—…閷隮隰隬霠霟霘éœéœ™éžšéž¡éžœ"], ["ef40","éžžéžéŸ•韔韱é¡é¡„顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽é¬é«¼é­ˆé®šé®¨é®žé®›é®¦é®¡é®¥é®¤é®†é®¢é® é®¯é´³éµéµ§é´¶é´®é´¯é´±é´¸é´°"], ["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉éºéº°é»ˆé»šé»»é»¿é¼¤é¼£é¼¢é½”龠儱儭儮嚘嚜嚗嚚åšåš™å¥°å¬¼å±©å±ªå·€å¹­å¹®æ‡˜æ‡Ÿæ‡­æ‡®æ‡±æ‡ªæ‡°æ‡«æ‡–æ‡©æ“¿æ”„æ“½æ“¸æ”æ”ƒæ“¼æ–”旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌ç€ç€ç€…瀔瀎濿瀀濻瀦濼濷瀊çˆç‡¿ç‡¹çˆƒç‡½ç¶"], ["f040","璸瓀璵ç“璾璶璻瓂甔甓癜癤癙ç™ç™“癗癚皦皽盬矂瞺磿礌礓礔礉ç¤ç¤’礑禭禬穟簜簩簙簠簟簭ç°ç°¦ç°¨ç°¢ç°¥ç°°ç¹œç¹ç¹–繣繘繢繟繑繠繗繓羵羳翷翸èµè‡‘臒"], ["f0a1","è‡è‰Ÿè‰žè–´è—†è—€è—ƒè—‚薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙è èŸ´èŸ¨èŸè¥“襋è¥è¥Œè¥†è¥è¥‘襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], ["f140","蹛蹚蹡è¹è¹©è¹”轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛éŽéŽ‰éŽ§éŽŽéŽªéŽžéŽ¦éŽ•éŽˆéŽ™éŽŸéŽéŽ±éŽ‘éŽ²éŽ¤éŽ¨éŽ´éŽ£éŽ¥é—’é—“é—‘éš³é›—é›šå·‚é›Ÿé›˜é›éœ£éœ¢éœ¥éž¬éž®éž¨éž«éž¤éžª"], ["f1a1","鞢鞥韗韙韖韘韺é¡é¡‘顒颸é¥é¤¼é¤ºé¨é¨‹é¨‰é¨é¨„騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿é¯é®µé®¸é¯“鮶鯄鮹鮽鵜鵓éµéµŠéµ›éµ‹éµ™éµ–鵌鵗鵒鵔鵟鵘鵚麎麌黟é¼é¼€é¼–鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚å£å£›å¤’嬽嬾嬿巃幰"], ["f240","å¾¿æ‡»æ”‡æ”æ”æ”‰æ”Œæ”Žæ–„æ—žæ—æ›žæ«§æ« æ«Œæ«‘æ«™æ«‹æ«Ÿæ«œæ«æ««æ«æ«æ«žæ­ æ®°æ°Œç€™ç€§ç€ ç€–瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱ç¤ç¤›"], ["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾è¸è‡—臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘è¥è¥™è¦ˆè¦·è¦¶è§¶è­è­ˆè­Šè­€è­“譖譔譋譕"], ["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑è½è½è½“辴酀鄿醰醭éžé‡éé‚éšéé¹é¬éŒé™éŽ©é¦éŠé”é®é£é•é„éŽé€é’é§é•½é—šé—›é›¡éœ©éœ«éœ¬éœ¨éœ¦"], ["f3a1","鞳鞷鞶éŸéŸžéŸŸé¡œé¡™é¡é¡—颿颽颻颾饈饇饃馦馧騚騕騥é¨é¨¤é¨›é¨¢é¨ é¨§é¨£é¨žé¨œé¨”髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷é¶é¶Šé¶„鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀é½é½é½–齗齘匷嚲"], ["f440","åšµåš³å££å­…å·†å·‡å»®å»¯å¿€å¿æ‡¹æ”—攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱ç‚瀸瀿瀺瀹ç€ç€»ç€³ç爓爔犨ç½ç¼ç’ºçš«çšªçš¾ç›­çŸŒçŸŽçŸçŸçŸ²ç¤¥ç¤£ç¤§ç¤¨ç¤¤ç¤©"], ["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾çºçº€ç¾ºç¿¿è¹è‡›è‡™èˆ‹è‰¨è‰©è˜¢è—¿è˜è—¾è˜›è˜€è—¶è˜„蘉蘅蘌藽蠙è è ‘蠗蠓蠖襣襦覹觷譠譪è­è­¨è­£è­¥è­§è­­è¶®èº†èºˆèº„轙轖轗轕轘轚é‚é…ƒé…醷醵醲醳é‹é“é»é éé”é¾é•éé¨é™ééµé€é·é‡éŽé–é’éºé‰é¸éŠé¿"], ["f540","é¼éŒé¶é‘é†é—žé— é—Ÿéœ®éœ¯éž¹éž»éŸ½éŸ¾é¡ é¡¢é¡£é¡Ÿé£é£‚é¥é¥Žé¥™é¥Œé¥‹é¥“騲騴騱騬騪騶騩騮騸騭髇髊髆é¬é¬’鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤é¶é¶’鶘é¶é¶›"], ["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞é½é½™é¾‘儺儹劘劗囃嚽嚾孈孇巋å·å»±æ‡½æ”›æ¬‚櫼欃櫸欀çƒç„çŠçˆç‰ç…ç†çˆçˆšçˆ™ç¾ç”—癪çŸç¤­ç¤±ç¤¯ç±”籓糲纊纇纈纋纆çºç½ç¾»è€°è‡è˜˜è˜ªè˜¦è˜Ÿè˜£è˜œè˜™è˜§è˜®è˜¡è˜ è˜©è˜žè˜¥"], ["f640","è ©è è ›è  è ¤è œè «è¡Šè¥­è¥©è¥®è¥«è§ºè­¹è­¸è­…譺譻è´è´”趯躎躌轞轛è½é…†é…„酅醹é¿é»é¶é©é½é¼é°é¹éªé·é¬é‘€é±é—¥é—¤é—£éœµéœºéž¿éŸ¡é¡¤é£‰é£†é£€é¥˜é¥–騹騽驆驄驂é©é¨º"], ["f6a1","騿é«é¬•鬗鬘鬖鬺魒鰫é°é°œé°¬é°£é°¨é°©é°¤é°¡é¶·é¶¶é¶¼é·é·‡é·Šé·é¶¾é·…鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳é·é¶²é¹ºéºœé»«é»®é»­é¼›é¼˜é¼šé¼±é½Žé½¥é½¤é¾’亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉æ°ç•ç–ç—ç’爞爟犩ç¿ç“˜ç“•瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], ["f740","糴糱纑ç½ç¾‡è‡žè‰«è˜´è˜µè˜³è˜¬è˜²è˜¶è ¬è ¨è ¦è ªè ¥è¥±è¦¿è¦¾è§»è­¾è®„讂讆讅譿贕躕躔躚躒èºèº–躗轠轢酇鑌é‘鑊鑋é‘鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌é©é©ˆé©Š"], ["f7a1","驉驒é©é«é¬™é¬«é¬»é­–魕鱆鱈鰿鱄鰹鰳é±é°¼é°·é°´é°²é°½é°¶é·›é·’é·žé·šé·‹é·é·œé·‘鷟鷩鷙鷘鷖鷵鷕é·éº¶é»°é¼µé¼³é¼²é½‚齫龕龢儽劙壨壧奲å­å·˜è ¯å½æˆæˆƒæˆ„æ”©æ”¥æ––æ›«æ¬‘æ¬’æ¬æ¯Šç›çšçˆ¢çŽ‚çŽçŽƒç™°çŸ”ç±§ç±¦çº•è‰¬è˜ºè™€è˜¹è˜¼è˜±è˜»è˜¾è °è ²è ®è ³è¥¶è¥´è¥³è§¾"], ["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕é‘鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘é±é±Šé±é±‹é±•鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂é»é»²é»³é¼†é¼œé¼¸é¼·é¼¶é½ƒé½"], ["f8a1","齱齰齮齯囓å›å­Žå±­æ”­æ›­æ›®æ¬“çŸç¡çç çˆ£ç“›ç“¥çŸ•礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠èºé†¾é†½é‡‚鑫鑨鑩雥é†éƒé‡éŸ‡éŸ¥é©žé«•魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀é¸é¸‰é·¿é·½é¸„麠鼞齆齴齵齶囔攮斸欘欙欗欚ç¢çˆ¦çŠªçŸ˜çŸ™ç¤¹ç±©ç±«ç³¶çºš"], ["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳é‰é¡²é¥Ÿé±¨é±®é±­é¸‹é¸é¸é¸é¸’鸑麡黵鼉齇齸齻齺齹圞ç¦ç±¯è ¼è¶²èº¦é‡ƒé‘´é‘¸é‘¶é‘µé© é±´é±³é±±é±µé¸”鸓黶鼊"], ["f9a1","龤ç¨ç¥ç³·è™ªè ¾è ½è ¿è®žè²œèº©è»‰é‹é¡³é¡´é£Œé¥¡é¦«é©¤é©¦é©§é¬¤é¸•鸗齈戇欞爧虌躨钂钀é’驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺é¸ç©çªéº¤é½¾é½‰é¾˜ç¢éйè£å¢»æ’粧嫺╔╦╗╠╬╣╚╩â•╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║â•╭╮╰╯▓"] ] [ ["0","\u0000",127], ["8ea1","。",62], ["a1a1"," ã€ã€‚,.・:;?ï¼ã‚›ã‚œÂ´ï½€Â¨ï¼¾ï¿£ï¼¿ãƒ½ãƒ¾ã‚ゞ〃ä»ã€…〆〇ー―â€ï¼ï¼¼ï½žâˆ¥ï½œâ€¦â€¥â€˜â€™â€œâ€ï¼ˆï¼‰ã€”〕[]{ï½ã€ˆ",9,"+ï¼Â±Ã—÷ï¼â‰ ï¼œï¼žâ‰¦â‰§âˆžâˆ´â™‚♀°′″℃¥$¢£%#&*@§☆★○â—â—Žâ—‡"], ["a2a1","◆□■△▲▽▼※〒→â†â†‘↓〓"], ["a2ba","∈∋⊆⊇⊂⊃∪∩"], ["a2ca","∧∨¬⇒⇔∀∃"], ["a2dc","∠⊥⌒∂∇≡≒≪≫√∽âˆâˆµâˆ«âˆ¬"], ["a2f2","ʼn♯♭♪†‡¶"], ["a2fe","â—¯"], ["a3b0","ï¼",9], ["a3c1","A",25], ["a3e1","ï½",25], ["a4a1","ã",82], ["a5a1","ã‚¡",85], ["a6a1","Α",16,"Σ",6], ["a6c1","α",16,"σ",6], ["a7a1","Ð",5,"ÐЖ",25], ["a7d1","а",5,"ёж",25], ["a8a1","─│┌â”┘└├┬┤┴┼â”┃â”┓┛┗┣┳┫┻╋┠┯┨┷┿â”┰┥┸╂"], ["ada1","â‘ ",19,"â… ",9], ["adc0","ã‰ãŒ”㌢ã㌘㌧㌃㌶ã‘ã—ãŒãŒ¦ãŒ£ãŒ«ãŠãŒ»ãŽœãŽãŽžãŽŽãŽã„㎡"], ["addf","ã»ã€ã€Ÿâ„–ã℡㊤",4,"㈱㈲㈹ã¾ã½ã¼â‰’≡∫∮∑√⊥∠∟⊿∵∩∪"], ["b0a1","äºœå”–å¨ƒé˜¿å“€æ„›æŒ¨å§¶é€¢è‘µèŒœç©æ‚ªæ¡æ¸¥æ—­è‘¦èŠ¦é¯µæ¢“åœ§æ–¡æ‰±å®›å§è™»é£´çµ¢ç¶¾é®Žæˆ–ç²Ÿè¢·å®‰åºµæŒ‰æš—æ¡ˆé—‡éžæä»¥ä¼Šä½ä¾å‰å›²å¤·å§”å¨å°‰æƒŸæ„慰易椅為ç•異移維緯胃èŽè¡£è¬‚é•éºåŒ»äº•亥域育éƒç£¯ä¸€å£±æº¢é€¸ç¨²èŒ¨èЋ鰝å…å°å’½å“¡å› å§»å¼•飲淫胤蔭"], ["b1a1","院陰隠韻å‹å³å®‡çƒç¾½è¿‚雨å¯éµœçªºä¸‘碓臼渦嘘唄æ¬è”šé°»å§¥åŽ©æµ¦ç“œé–噂云é‹é›²è餌å¡å–¶å¬°å½±æ˜ æ›³æ „永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦è¬è¶Šé–²æ¦ŽåŽ­å††åœ’å °å¥„å®´å»¶æ€¨æŽ©æ´æ²¿æ¼”炎焔煙燕猿ç¸è‰¶è‹‘è–—é é‰›é´›å¡©æ–¼æ±šç”¥å‡¹å¤®å¥¥å¾€å¿œ"], ["b2a1","押旺横欧殴王ç¿è¥–鴬鴎黄岡沖è»å„„å±‹æ†¶è‡†æ¡¶ç‰¡ä¹™ä¿ºå¸æ©æ¸©ç©éŸ³ä¸‹åŒ–仮何伽価佳加å¯å˜‰å¤å«å®¶å¯¡ç§‘暇果架歌河ç«ç‚ç¦ç¦¾ç¨¼ç®‡èŠ±è‹›èŒ„è·è¯è“è¦èª²å˜©è²¨è¿¦éŽéœžèšŠä¿„å³¨æˆ‘ç‰™ç”»è‡¥èŠ½è›¾è³€é›…é¤“é§•ä»‹ä¼šè§£å›žå¡Šå£Šå»»å¿«æ€ªæ‚”æ¢æ‡æˆ’æ‹æ”¹"], ["b3a1","é­æ™¦æ¢°æµ·ç°ç•Œçš†çµµèŠ¥èŸ¹é–‹éšŽè²å‡±åŠ¾å¤–å’³å®³å´–æ…¨æ¦‚æ¶¯ç¢è“‹è¡—該鎧骸浬馨蛙垣柿蛎鈎劃嚇å„廓拡撹格核殻ç²ç¢ºç©«è¦šè§’赫較郭閣隔é©å­¦å²³æ¥½é¡é¡ŽæŽ›ç¬ æ¨«æ©¿æ¢¶é°æ½Ÿå‰²å–æ°æ‹¬æ´»æ¸‡æ»‘è‘›è¤è½„䏔鰹嶿¤›æ¨ºéž„株兜竃蒲釜鎌噛鴨栢茅è±"], ["b4a1","ç²¥åˆˆè‹…ç“¦ä¹¾ä¾ƒå† å¯’åˆŠå‹˜å‹§å·»å–šå ªå§¦å®Œå®˜å¯›å¹²å¹¹æ‚£æ„Ÿæ…£æ†¾æ›æ•¢æŸ‘桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰è‚艦莞観諌貫還鑑間閑関陥韓館舘丸å«å²¸å·ŒçŽ©ç™Œçœ¼å²©ç¿«è´‹é›é ‘顔願ä¼ä¼Žå±å–œå™¨åŸºå¥‡å¬‰å¯„å²å¸Œå¹¾å¿Œæ®æœºæ——既期棋棄"], ["b5a1","機帰毅気汽畿祈季稀紀徽è¦è¨˜è²´èµ·è»Œè¼é£¢é¨Žé¬¼äº€å½å„€å¦“宜戯技擬欺犠疑祇義蟻誼議掬èŠéž å‰åƒå–«æ¡”橘詰砧æµé»å´å®¢è„šè™é€†ä¸˜ä¹…仇休åŠå¸å®®å¼“急救朽求汲泣ç¸çƒç©¶çª®ç¬ˆç´šç³¾çµ¦æ—§ç‰›åŽ»å±…å·¨æ‹’æ‹ æŒ™æ¸ è™šè¨±è·é‹¸æ¼ç¦¦é­šäº¨äº«äº¬"], ["b6a1","供侠僑兇競共凶å”匡å¿å«å–¬å¢ƒå³¡å¼·å½Šæ€¯ææ­æŒŸæ•™æ©‹æ³ç‹‚狭矯胸脅興蕎郷é¡éŸ¿é¥—驚仰å‡å°­æšæ¥­å±€æ›²æ¥µçމæ¡ç²åƒ…勤å‡å·¾éŒ¦æ–¤æ¬£æ¬½ç´ç¦ç¦½ç­‹ç·ŠèйèŒè¡¿è¥Ÿè¬¹è¿‘金åŸéŠ€ä¹å€¶å¥åŒºç‹—玖矩苦躯駆駈駒具愚虞喰空å¶å¯“é‡éš…串櫛釧屑屈"], ["b7a1","掘窟沓é´è½¡çªªç†Šéšˆç²‚æ —ç¹°æ¡‘é¬å‹²å›è–«è¨“群è»éƒ¡å¦è¢ˆç¥ä¿‚傾刑兄啓圭çªåž‹å¥‘å½¢å¾„æµæ…¶æ…§æ†©æŽ²æºæ•¬æ™¯æ¡‚渓畦稽系経継繋罫茎èŠè›è¨ˆè©£è­¦è»½é šé¶èŠ¸è¿Žé¯¨åŠ‡æˆŸæ’ƒæ¿€éš™æ¡å‚‘欠決潔穴çµè¡€è¨£æœˆä»¶å€¹å€¦å¥å…¼åˆ¸å‰£å–§åœå …嫌建憲懸拳æ²"], ["b8a1","検権牽犬献研硯絹県肩見謙賢軒é£éµé™ºé¡•験鹸元原厳幻弦減æºçŽ„ç¾çµƒèˆ·è¨€è«ºé™ä¹Žå€‹å¤å‘¼å›ºå§‘孤己庫弧戸故枯湖ç‹ç³Šè¢´è‚¡èƒ¡è°è™Žèª‡è·¨éˆ·é›‡é¡§é¼“五互ä¼åˆå‘‰å¾å¨¯å¾Œå¾¡æ‚Ÿæ¢§æªŽç‘šç¢èªžèª¤è­·é†ä¹žé¯‰äº¤ä½¼ä¾¯å€™å€–光公功効勾厚å£å‘"], ["b9a1","åŽå–‰å‘垢好孔å­å®å·¥å·§å··å¹¸åºƒåºšåº·å¼˜æ’æ…ŒæŠ—æ‹˜æŽ§æ”»æ˜‚æ™ƒæ›´æ­æ ¡æ¢—構江洪浩港æºç”²çš‡ç¡¬ç¨¿ç³ ç´…紘絞綱耕考肯肱腔è†èˆªè’行衡講貢購郊酵鉱砿鋼閤é™é …香高鴻剛劫å·åˆå£•æ‹·æ¿ è±ªè½Ÿéº¹å…‹åˆ»å‘Šå›½ç©€é…·éµ é»’ç„æ¼‰è…°ç”‘忽惚骨狛込"], ["baa1","此頃今困å¤å¢¾å©šæ¨æ‡‡æ˜æ˜†æ ¹æ¢±æ··ç—•紺艮魂些ä½å‰å”†åµ¯å·¦å·®æŸ»æ²™ç‘³ç ‚è©éŽ–è£Ÿååº§æŒ«å‚µå‚¬å†æœ€å“‰å¡žå¦»å®°å½©æ‰æŽ¡æ ½æ­³æ¸ˆç½é‡‡çŠ€ç •ç ¦ç¥­æ–Žç´°èœè£è¼‰éš›å‰¤åœ¨æç½ªè²¡å†´å‚é˜ªå ºæ¦Šè‚´å’²å´ŽåŸ¼ç¢•é·ºä½œå‰Šå’‹æ¾æ˜¨æœ”柵窄策索錯桜鮭笹匙冊刷"], ["bba1","察拶撮擦札殺薩雑çšé¯–æŒéŒ†é®«çš¿æ™’三傘å‚山惨撒散桟燦çŠç”£ç®—çº‚èš•è®ƒè³›é…¸é¤æ–¬æš«æ®‹ä»•仔伺使刺å¸å²å—£å››å£«å§‹å§‰å§¿å­å±å¸‚å¸«å¿—æ€æŒ‡æ”¯å­œæ–¯æ–½æ—¨æžæ­¢æ­»æ°ç…祉ç§ç³¸ç´™ç´«è‚¢è„‚至視詞詩試誌諮資賜雌飼歯事似ä¾å…å­—å¯ºæ…ˆæŒæ™‚"], ["bca1","次滋治爾璽痔ç£ç¤ºè€Œè€³è‡ªè’”辞æ±é¹¿å¼è­˜é´«ç«ºè»¸å®é›«ä¸ƒå±åŸ·å¤±å«‰å®¤æ‚‰æ¹¿æ¼†ç–¾è³ªå®Ÿè”€ç¯ å²æŸ´èŠå±¡è•Šç¸žèˆŽå†™å°„æ¨èµ¦æ–œç…®ç¤¾ç´—者è¬è»Šé®è›‡é‚ªå€Ÿå‹ºå°ºæ“ç¼çˆµé…Œé‡ˆéŒ«è‹¥å¯‚弱惹主å–守手朱殊狩ç ç¨®è…«è¶£é…’首儒å—呪寿授樹綬需囚åŽå‘¨"], ["bda1","å®—å°±å·žä¿®æ„æ‹¾æ´²ç§€ç§‹çµ‚ç¹ç¿’臭舟è’衆襲è®è¹´è¼¯é€±é…‹é…¬é›†é†œä»€ä½å……åå¾“æˆŽæŸ”æ±æ¸‹ç£ç¸¦é‡éŠƒå”夙宿淑ç¥ç¸®ç²›å¡¾ç†Ÿå‡ºè¡“述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡éµé†‡é †å‡¦åˆæ‰€æš‘曙渚庶緒署書薯藷諸助å™å¥³åºå¾æ•鋤除傷償"], ["bea1","å‹åŒ å‡å¬å“¨å•†å”±å˜—奨妾娼宵将å°å°‘å°šåº„åºŠå» å½°æ‰¿æŠ„æ‹›æŽŒæ·æ˜‡æ˜Œæ˜­æ™¶æ¾æ¢¢æ¨Ÿæ¨µæ²¼æ¶ˆæ¸‰æ¹˜ç„¼ç„¦ç…§ç—‡çœç¡ç¤ç¥¥ç§°ç« ç¬‘粧紹肖è–蒋蕉è¡è£³è¨Ÿè¨¼è©”詳象賞醤鉦é¾é˜éšœéž˜ä¸Šä¸ˆä¸žä¹—å†—å‰°åŸŽå ´å£Œå¬¢å¸¸æƒ…æ“¾æ¡æ–浄状畳穣蒸譲醸錠嘱埴飾"], ["bfa1","æ‹­æ¤æ®–燭織è·è‰²è§¦é£Ÿè•辱尻伸信侵唇娠å¯å¯©å¿ƒæ…ŽæŒ¯æ–°æ™‹æ£®æ¦›æµ¸æ·±ç”³ç–¹çœŸç¥žç§¦ç´³è‡£èŠ¯è–ªè¦ªè¨ºèº«è¾›é€²é‡éœ‡äººä»åˆƒå¡µå£¬å°‹ç”šå°½è…Žè¨Šè¿…陣é­ç¬¥è«é ˆé…¢å›³åލ逗å¹åž‚帥推水炊ç¡ç²‹ç¿ è¡°é‚é…”éŒéŒ˜éšç‘žé«„å´‡åµ©æ•°æž¢è¶¨é››æ®æ‰æ¤™è…頗雀裾"], ["c0a1","æ¾„æ‘ºå¯¸ä¸–ç€¬ç•æ˜¯å‡„åˆ¶å‹¢å§“å¾æ€§æˆæ”¿æ•´æ˜Ÿæ™´æ£²æ –正清牲生盛精è–声製西誠誓請é€é†’é’陿–‰ç¨Žè„†éš»å¸­æƒœæˆšæ–¥æ˜”æžçŸ³ç©ç±ç¸¾è„Šè²¬èµ¤è·¡è¹Ÿç¢©åˆ‡æ‹™æŽ¥æ‘‚折設窃節説雪絶舌è‰ä»™å…ˆåƒå å®£å°‚å°–å·æˆ¦æ‰‡æ’°æ “栴泉浅洗染潜煎煽旋穿箭線"], ["c1a1","繊羨腺舛船薦詮賎践é¸é·éŠ­éŠ‘é–ƒé®®å‰å–„漸然全禅繕膳糎噌塑岨措曾曽楚狙ç–疎礎祖租粗素組蘇訴阻é¡é¼ åƒ§å‰µåŒå¢å€‰å–ªå£®å¥çˆ½å®‹å±¤åŒæƒ£æƒ³æœæŽƒæŒ¿æŽ»æ“æ—©æ›¹å·£æ§æ§½æ¼•燥争痩相窓糟ç·ç¶œè¡è‰è˜è‘¬è’¼è—»è£…èµ°é€é­éŽ—éœœé¨’åƒå¢—憎"], ["c2a1","臓蔵贈造促å´å‰‡å³æ¯æ‰æŸæ¸¬è¶³é€Ÿä¿—属賊æ—ç¶šå’袖其æƒå­˜å­«å°Šææ‘éœä»–多太汰詑唾堕妥惰打æŸèˆµæ¥•陀駄騨体堆対è€å²±å¸¯å¾…怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代å°å¤§ç¬¬é†é¡Œé·¹æ»ç€§å“啄宅托択拓沢濯ç¢è¨—鏿¿è«¾èŒ¸å‡§è›¸åª"], ["c3a1","å©ä½†é”辰奪脱巽竪辿棚谷狸鱈樽誰丹å˜å˜†å¦æ‹…探旦歎淡湛炭短端箪綻耽胆蛋誕é›å›£å£‡å¼¾æ–­æš–æª€æ®µç”·è«‡å€¤çŸ¥åœ°å¼›æ¥æ™ºæ± ç—´ç¨šç½®è‡´èœ˜é…馳築畜竹筑蓄é€ç§©çª’茶嫡ç€ä¸­ä»²å®™å¿ æŠ½æ˜¼æŸ±æ³¨è™«è¡·è¨»é…Žé‹³é§æ¨—瀦猪苧著貯ä¸å…†å‡‹å–‹å¯µ"], ["c4a1","帖帳åºå¼”å¼µå½«å¾´æ‡²æŒ‘æš¢æœæ½®ç‰’町眺è´è„¹è…¸è¶èª¿è«œè¶…跳銚長頂鳥勅æ—直朕沈çè³ƒéŽ®é™³æ´¥å¢œæ¤Žæ§Œè¿½éŽšç—›é€šå¡šæ ‚æŽ´æ§»ä½ƒæ¼¬æŸ˜è¾»è”¦ç¶´é”æ¤¿æ½°åªå£·å¬¬ç´¬çˆªåŠé‡£é¶´äº­ä½Žåœåµå‰ƒè²žå‘ˆå ¤å®šå¸åº•åº­å»·å¼Ÿæ‚ŒæŠµæŒºææ¢¯æ±€ç¢‡ç¦Žç¨‹ç· è‰‡è¨‚諦蹄逓"], ["c5a1","邸鄭釘鼎泥摘擢敵滴的笛é©é‘溺哲徹撤è½è¿­é‰„典填天展店添çºç”œè²¼è»¢é¡›ç‚¹ä¼æ®¿æ¾±ç”°é›»å…Žåå µå¡—å¦¬å± å¾’æ–—æœæ¸¡ç™»èŸè³­é€”都é砥砺努度土奴怒倒党冬å‡åˆ€å”å¡”å¡˜å¥—å®•å³¶å¶‹æ‚¼æŠ•æ­æ±æ¡ƒæ¢¼æ£Ÿç›—淘湯涛ç¯ç‡ˆå½“痘祷等答筒糖統到"], ["c6a1","董蕩藤討謄豆è¸é€ƒé€é™é™¶é ­é¨°é—˜åƒå‹•åŒå ‚導憧撞洞瞳童胴è„é“銅峠鴇匿得徳涜特ç£ç¦¿ç¯¤æ¯’ç‹¬èª­æ ƒæ©¡å‡¸çªæ¤´å±Šé³¶è‹«å¯…酉瀞噸屯惇敦沌豚é頓呑曇éˆå¥ˆé‚£å†…ä¹å‡ªè–™è¬Žç˜æºé‹æ¥¢é¦´ç¸„ç•·å—æ¥ è»Ÿé›£æ±äºŒå°¼å¼è¿©åŒ‚賑肉虹廿日乳入"], ["c7a1","如尿韮任妊å¿èªæ¿¡ç¦°ç¥¢å¯§è‘±çŒ«ç†±å¹´å¿µæ»æ’šç‡ƒç²˜ä¹ƒå»¼ä¹‹åŸœå𢿂©æ¿ƒç´èƒ½è„³è†¿è¾²è¦—èš¤å·´æŠŠæ’­è¦‡æ·æ³¢æ´¾ç¶ç ´å©†ç½µèŠ­é¦¬ä¿³å»ƒæ‹æŽ’æ•—æ¯ç›ƒç‰ŒèƒŒè‚ºè¼©é…å€åŸ¹åª’梅楳煤狽買売賠陪這è¿ç§¤çŸ§è©ä¼¯å‰¥å𿋿Ÿæ³Šç™½ç®”ç²•èˆ¶è–„è¿«æ›æ¼ çˆ†ç¸›èŽ«é§éº¦"], ["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪ä¼ç½°æŠœç­é–¥é³©å™ºå¡™è›¤éš¼ä¼´åˆ¤åŠåå›å¸†æ¬æ–‘æ¿æ°¾æ±Žç‰ˆçНç­ç•”ç¹èˆ¬è—©è²©ç¯„釆煩頒飯挽晩番盤ç£è•ƒè›®åŒªå‘å¦å¦ƒåº‡å½¼æ‚²æ‰‰æ‰¹æŠ«æ–比泌疲皮碑秘緋罷肥被誹費é¿éžé£›æ¨‹ç°¸å‚™å°¾å¾®æž‡æ¯˜çµçœ‰ç¾Ž"], ["c9a1","鼻柊稗匹疋髭彦è†è±è‚˜å¼¼å¿…畢筆逼桧姫媛ç´ç™¾è¬¬ä¿µå½ªæ¨™æ°·æ¼‚瓢票表評豹廟æç—…秒苗錨鋲蒜蛭鰭å“彬斌浜瀕貧賓頻æ•ç“¶ä¸ä»˜åŸ å¤«å©¦å¯Œå†¨å¸ƒåºœæ€–扶敷斧普浮父符è…è†šèŠ™è­œè² è³¦èµ´é˜œé™„ä¾®æ’«æ­¦èˆžè‘¡è•ªéƒ¨å°æ¥“風葺蕗ä¼å‰¯å¾©å¹…æœ"], ["caa1","ç¦è…¹è¤‡è¦†æ·µå¼—払沸ä»ç‰©é®’分å»å™´å¢³æ†¤æ‰®ç„šå¥®ç²‰ç³žç´›é›°æ–‡èžä¸™ä½µå…µå¡€å¹£å¹³å¼ŠæŸ„並蔽閉陛米é åƒ»å£ç™–碧別瞥蔑箆å変片篇編辺返é便勉娩å¼éž­ä¿èˆ—é‹ªåœƒæ•æ­©ç”«è£œè¼”穂募墓慕戊暮æ¯ç°¿è©å€£ä¿¸åŒ…呆報奉å®å³°å³¯å´©åº–æŠ±æ§æ”¾æ–¹æœ‹"], ["cba1","法泡烹砲縫胞芳èŒè“¬èœ‚褒訪豊邦鋒飽鳳鵬ä¹äº¡å‚剖åŠå¦¨å¸½å¿˜å¿™æˆ¿æš´æœ›æŸæ£’冒紡肪膨謀貌貿鉾防å é ¬åŒ—僕åœå¢¨æ’²æœ´ç‰§ç¦ç©†é‡¦å‹ƒæ²¡æ®†å €å¹Œå¥”本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒æ¡äº¦ä¿£åˆæŠ¹æœ«æ²«è¿„侭繭麿万慢満"], ["cca1","æ¼«è”“å‘³æœªé­…å·³ç®•å²¬å¯†èœœæ¹Šè“‘ç¨”è„ˆå¦™ç²æ°‘眠務夢無牟矛霧鵡椋婿娘冥åå‘½æ˜Žç›Ÿè¿·éŠ˜é³´å§ªç‰æ»…å…æ£‰ç¶¿ç·¬é¢éººæ‘¸æ¨¡èŒ‚妄孟毛猛盲網耗蒙儲木黙目æ¢å‹¿é¤…å°¤æˆ»ç±¾è²°å•æ‚¶ç´‹é–€åŒä¹Ÿå†¶å¤œçˆºè€¶é‡Žå¼¥çŸ¢åŽ„å½¹ç´„è–¬è¨³èºé–柳薮鑓愉愈油癒"], ["cda1","諭輸唯佑優勇å‹å®¥å¹½æ‚ æ†‚æ–æœ‰æŸšæ¹§æ¶ŒçŒ¶çŒ·ç”±ç¥è£•誘éŠé‚‘郵雄èžå¤•予余与誉輿é å‚­å¹¼å¦–å®¹åº¸æšæºæ“曜楊様洋溶熔用窯羊耀葉蓉è¦è¬¡è¸Šé¥é™½é¤Šæ…¾æŠ‘欲沃浴翌翼淀羅螺裸æ¥èŽ±é ¼é›·æ´›çµ¡è½é…ªä¹±åµåµæ¬„æ¿«è—蘭覧利åå±¥æŽæ¢¨ç†ç’ƒ"], ["cea1","ç—¢è£è£¡é‡Œé›¢é™¸å¾‹çŽ‡ç«‹è‘ŽæŽ ç•¥åŠ‰æµæºœç‰ç•™ç¡«ç²’隆竜é¾ä¾¶æ…®æ—…è™œäº†äº®åƒšä¸¡å‡Œå¯®æ–™æ¢æ¶¼çŒŸç™‚瞭稜糧良諒é¼é‡é™µé ˜åŠ›ç·‘å€«åŽ˜æž—æ·‹ç‡ç³è‡¨è¼ªéš£é±—éºŸç‘ å¡æ¶™ç´¯é¡žä»¤ä¼¶ä¾‹å†·åŠ±å¶ºæ€œçŽ²ç¤¼è‹“éˆ´éš·é›¶éœŠéº—é½¢æš¦æ­´åˆ—åŠ£çƒˆè£‚å»‰æ‹æ†æ¼£ç…‰ç°¾ç·´è¯"], ["cfa1","蓮連錬呂魯櫓炉賂路露労å©å»Šå¼„朗楼榔浪æ¼ç‰¢ç‹¼ç¯­è€è¾è‹éƒŽå…­éº“禄肋録論倭和話歪賄脇惑枠鷲亙亘é°è©«è—蕨椀湾碗腕"], ["d0a1","弌ä¸ä¸•个丱丶丼丿乂乖乘亂亅豫亊舒å¼äºŽäºžäºŸäº äº¢äº°äº³äº¶ä»Žä»ä»„仆仂仗仞仭仟价伉佚估佛ä½ä½—佇佶侈ä¾ä¾˜ä½»ä½©ä½°ä¾‘佯來侖儘俔俟俎俘俛俑俚ä¿ä¿¤ä¿¥å€šå€¨å€”倪倥倅伜俶倡倩倬俾俯們倆åƒå‡æœƒå•ååˆåšå–å¬å¸å‚€å‚šå‚…傴傲"], ["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉å„儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉å†å†‘冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹å‰å‰„剋剌剞剔剪剴剩剳剿剽åŠåŠ”åŠ’å‰±åŠˆåŠ‘è¾¨"], ["d2a1","辧劬劭劼劵å‹å‹å‹—勞勣勦飭勠勳勵勸勹匆匈甸åŒåŒåŒåŒ•匚匣匯匱匳匸å€å†å…丗å‰å凖åžå©å®å¤˜å»å·åŽ‚åŽ–åŽ åŽ¦åŽ¥åŽ®åŽ°åŽ¶åƒç°’é›™åŸæ›¼ç‡®å®å¨å­åºåå½å‘€å¬å­å¼å®å¶å©å呎å’呵咎呟呱呷呰咒呻咀呶咄å’咆哇咢咸咥咬哄哈咨"], ["d3a1","咫哂咤咾咼哘哥哦å”唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳å•喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎å™ç‡Ÿå˜´å˜¶å˜²å˜¸å™«å™¤å˜¯å™¬å™ªåš†åš€åšŠåš åš”åšåš¥åš®åš¶åš´å›‚åš¼å›å›ƒå›€å›ˆå›Žå›‘囓囗囮囹圀囿圄圉"], ["d4a1","圈國åœåœ“團圖嗇圜圦圷圸åŽåœ»å€åå©åŸ€åžˆå¡å¿åž‰åž“垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙å å¡²å ¡å¡¢å¡‹å¡°æ¯€å¡’堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊å¤å¤›æ¢¦å¤¥å¤¬å¤­å¤²å¤¸å¤¾ç«’奕å¥å¥Žå¥šå¥˜å¥¢å¥ å¥§å¥¬å¥©"], ["d5a1","奸å¦å¦ä½žä¾«å¦£å¦²å§†å§¨å§œå¦å§™å§šå¨¥å¨Ÿå¨‘娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲å«å¬ªå¬¶å¬¾å­ƒå­…孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔å¯å¯¤å¯¦å¯¢å¯žå¯¥å¯«å¯°å¯¶å¯³å°…將專å°å°“尠尢尨尸尹å±å±†å±Žå±“"], ["d6a1","å±å±å­±å±¬å±®ä¹¢å±¶å±¹å²Œå²‘岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢å¶å¶¬å¶®å¶½å¶å¶·å¶¼å·‰å·å·“巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠å»å»‚廈å»å»"], ["d7a1","廖廣å»å»šå»›å»¢å»¡å»¨å»©å»¬å»±å»³å»°å»´å»¸å»¾å¼ƒå¼‰å½å½œå¼‹å¼‘弖弩弭弸å½å½ˆå½Œå½Žå¼¯å½‘å½–å½—å½™å½¡å½­å½³å½·å¾ƒå¾‚å½¿å¾Šå¾ˆå¾‘å¾‡å¾žå¾™å¾˜å¾ å¾¨å¾­å¾¼å¿–å¿»å¿¤å¿¸å¿±å¿æ‚³å¿¿æ€¡æ æ€™æ€æ€©æ€Žæ€±æ€›æ€•æ€«æ€¦æ€æ€ºæšææªæ·æŸæŠæ†ææ£æƒæ¤æ‚æ¬æ«æ™æ‚æ‚æƒ§æ‚ƒæ‚š"], ["d8a1","æ‚„æ‚›æ‚–æ‚—æ‚’æ‚§æ‚‹æƒ¡æ‚¸æƒ æƒ“æ‚´å¿°æ‚½æƒ†æ‚µæƒ˜æ…æ„•æ„†æƒ¶æƒ·æ„€æƒ´æƒºæ„ƒæ„¡æƒ»æƒ±æ„æ„Žæ…‡æ„¾æ„¨æ„§æ…Šæ„¿æ„¼æ„¬æ„´æ„½æ…‚æ…„æ…³æ…·æ…˜æ…™æ…šæ…«æ…´æ…¯æ…¥æ…±æ…Ÿæ…æ…“æ…µæ†™æ†–æ†‡æ†¬æ†”æ†šæ†Šæ†‘æ†«æ†®æ‡Œæ‡Šæ‡‰æ‡·æ‡ˆæ‡ƒæ‡†æ†ºæ‡‹ç½¹æ‡æ‡¦æ‡£æ‡¶æ‡ºæ‡´æ‡¿æ‡½æ‡¼æ‡¾æˆ€æˆˆæˆ‰æˆæˆŒæˆ”戛"], ["d9a1","æˆžæˆ¡æˆªæˆ®æˆ°æˆ²æˆ³æ‰æ‰Žæ‰žæ‰£æ‰›æ‰ æ‰¨æ‰¼æŠ‚æŠ‰æ‰¾æŠ’æŠ“æŠ–æ‹”æŠƒæŠ”æ‹—æ‹‘æŠ»æ‹æ‹¿æ‹†æ“”æ‹ˆæ‹œæ‹Œæ‹Šæ‹‚æ‹‡æŠ›æ‹‰æŒŒæ‹®æ‹±æŒ§æŒ‚æŒˆæ‹¯æ‹µææŒ¾ææœææŽ–æŽŽæŽ€æŽ«æ¶æŽ£æŽæŽ‰æŽŸæŽµæ«æ©æŽ¾æ©æ€æ†æ£æ‰æ’æ¶æ„æ–æ´æ†æ“æ¦æ¶æ”æ—æ¨ææ‘§æ‘¯æ‘¶æ‘Žæ”ªæ’•撓撥撩撈撼"], ["daa1","æ“šæ“’æ“…æ“‡æ’»æ“˜æ“‚æ“±æ“§èˆ‰æ“ æ“¡æŠ¬æ“£æ“¯æ”¬æ“¶æ“´æ“²æ“ºæ”€æ“½æ”˜æ”œæ”…æ”¤æ”£æ”«æ”´æ”µæ”·æ”¶æ”¸ç•‹æ•ˆæ•–æ••æ•æ•˜æ•žæ•æ•²æ•¸æ–‚æ–ƒè®Šæ–›æ–Ÿæ–«æ–·æ—ƒæ—†æ—æ—„æ—Œæ—’æ—›æ—™æ— æ—¡æ—±æ²æ˜Šæ˜ƒæ—»æ³æ˜µæ˜¶æ˜´æ˜œæ™æ™„æ™‰æ™æ™žæ™æ™¤æ™§æ™¨æ™Ÿæ™¢æ™°æšƒæšˆæšŽæš‰æš„æš˜æšæ›æš¹æ›‰æš¾æš¼"], ["dba1","æ›„æš¸æ›–æ›šæ› æ˜¿æ›¦æ›©æ›°æ›µæ›·æœæœ–æœžæœ¦æœ§éœ¸æœ®æœ¿æœ¶ææœ¸æœ·æ†æžæ æ™æ£æ¤æž‰æ°æž©æ¼æªæžŒæž‹æž¦æž¡æž…æž·æŸ¯æž´æŸ¬æž³æŸ©æž¸æŸ¤æŸžæŸæŸ¢æŸ®æž¹æŸŽæŸ†æŸ§æªœæ žæ¡†æ ©æ¡€æ¡æ ²æ¡Žæ¢³æ «æ¡™æ¡£æ¡·æ¡¿æ¢Ÿæ¢æ¢­æ¢”æ¢æ¢›æ¢ƒæª®æ¢¹æ¡´æ¢µæ¢ æ¢ºæ¤æ¢æ¡¾æ¤æ£Šæ¤ˆæ£˜æ¤¢æ¤¦æ£¡æ¤Œæ£"], ["dca1","æ£”æ£§æ£•æ¤¶æ¤’æ¤„æ£—æ££æ¤¥æ£¹æ£ æ£¯æ¤¨æ¤ªæ¤šæ¤£æ¤¡æ£†æ¥¹æ¥·æ¥œæ¥¸æ¥«æ¥”æ¥¾æ¥®æ¤¹æ¥´æ¤½æ¥™æ¤°æ¥¡æ¥žæ¥æ¦æ¥ªæ¦²æ¦®æ§æ¦¿æ§æ§“æ¦¾æ§Žå¯¨æ§Šæ§æ¦»æ§ƒæ¦§æ¨®æ¦‘æ¦ æ¦œæ¦•æ¦´æ§žæ§¨æ¨‚æ¨›æ§¿æ¬Šæ§¹æ§²æ§§æ¨…æ¦±æ¨žæ§­æ¨”æ§«æ¨Šæ¨’æ«æ¨£æ¨“æ©„æ¨Œæ©²æ¨¶æ©¸æ©‡æ©¢æ©™æ©¦æ©ˆæ¨¸æ¨¢æªæªæª æª„檢檣"], ["dda1","æª—è˜—æª»æ«ƒæ«‚æª¸æª³æª¬æ«žæ«‘æ«Ÿæªªæ«šæ«ªæ«»æ¬…è˜–æ«ºæ¬’æ¬–é¬±æ¬Ÿæ¬¸æ¬·ç›œæ¬¹é£®æ­‡æ­ƒæ­‰æ­æ­™æ­”æ­›æ­Ÿæ­¡æ­¸æ­¹æ­¿æ®€æ®„æ®ƒæ®æ®˜æ®•æ®žæ®¤æ®ªæ®«æ®¯æ®²æ®±æ®³æ®·æ®¼æ¯†æ¯‹æ¯“æ¯Ÿæ¯¬æ¯«æ¯³æ¯¯éº¾æ°ˆæ°“æ°”æ°›æ°¤æ°£æ±žæ±•æ±¢æ±ªæ²‚æ²æ²šæ²æ²›æ±¾æ±¨æ±³æ²’æ²æ³„æ³±æ³“æ²½æ³—æ³…æ³æ²®æ²±æ²¾"], ["dea1","æ²ºæ³›æ³¯æ³™æ³ªæ´Ÿè¡æ´¶æ´«æ´½æ´¸æ´™æ´µæ´³æ´’æ´Œæµ£æ¶“æµ¤æµšæµ¹æµ™æ¶Žæ¶•æ¿¤æ¶…æ·¹æ¸•æ¸Šæ¶µæ·‡æ·¦æ¶¸æ·†æ·¬æ·žæ·Œæ·¨æ·’æ·…æ·ºæ·™æ·¤æ·•æ·ªæ·®æ¸­æ¹®æ¸®æ¸™æ¹²æ¹Ÿæ¸¾æ¸£æ¹«æ¸«æ¹¶æ¹æ¸Ÿæ¹ƒæ¸ºæ¹Žæ¸¤æ»¿æ¸æ¸¸æº‚æºªæº˜æ»‰æº·æ»“æº½æº¯æ»„æº²æ»”æ»•æºæº¥æ»‚æºŸæ½æ¼‘çŒæ»¬æ»¸æ»¾æ¼¿æ»²æ¼±æ»¯æ¼²æ»Œ"], ["dfa1","æ¼¾æ¼“æ»·æ¾†æ½ºæ½¸æ¾æ¾€æ½¯æ½›æ¿³æ½­æ¾‚潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑ç€ç€æ¿¾ç€›ç€šæ½´ç€ç€˜ç€Ÿç€°ç€¾ç€²ç‘ç£ç‚™ç‚’炯烱炬炸炳炮烟烋çƒçƒ™ç„‰çƒ½ç„œç„™ç…¥ç…•熈煦煢煌煖煬ç†ç‡»ç†„熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], ["e0a1","燹燿çˆçˆçˆ›çˆ¨çˆ­çˆ¬çˆ°çˆ²çˆ»çˆ¼çˆ¿ç‰€ç‰†ç‰‹ç‰˜ç‰´ç‰¾çŠ‚çŠçŠ‡çŠ’çŠ–çŠ¢çŠ§çŠ¹çŠ²ç‹ƒç‹†ç‹„ç‹Žç‹’ç‹¢ç‹ ç‹¡ç‹¹ç‹·å€çŒ—猊猜猖çŒçŒ´çŒ¯çŒ©çŒ¥çŒ¾çŽç默ç—çªç¨ç°ç¸çµç»çºçˆç޳çŽçŽ»ç€ç¥ç®çžç’¢ç…瑯ç¥ç¸ç²çºç‘•ç¿ç‘Ÿç‘™ç‘瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊ç“ç“”ç±"], ["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎ç”甕甓甞甦甬甼畄ç•畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚ç–疥疣痂疳痃疵疽疸疼疱ç—痊痒痙痣痞痾痿痼ç˜ç—°ç—ºç—²ç—³ç˜‹ç˜ç˜‰ç˜Ÿç˜§ç˜ ç˜¡ç˜¢ç˜¤ç˜´ç˜°ç˜»ç™‡ç™ˆç™†ç™œç™˜ç™¡ç™¢ç™¨ç™©ç™ªç™§ç™¬ç™°"], ["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂ç›ç›–盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸ç‡çšç¨ç«ç›ç¥ç¿ç¾ç¹çžŽçž‹çž‘瞠瞞瞰瞶瞹瞿瞼瞽瞻矇çŸçŸ—矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], ["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊ç¦ç¦§é½‹ç¦ªç¦®ç¦³ç¦¹ç¦ºç§‰ç§•秧秬秡秣稈ç¨ç¨˜ç¨™ç¨ ç¨Ÿç¦€ç¨±ç¨»ç¨¾ç¨·ç©ƒç©—穉穡穢穩é¾ç©°ç©¹ç©½çªˆçª—窕窘窖窩竈窰窶竅竄窿邃竇竊ç«ç«ç«•竓站竚ç«ç«¡ç«¢ç«¦ç«­ç«°ç¬‚ç¬ç¬Šç¬†ç¬³ç¬˜ç¬™ç¬žç¬µç¬¨ç¬¶ç­"], ["e4a1","筺笄ç­ç¬‹ç­Œç­…筵筥筴筧筰筱筬筮ç®ç®˜ç®Ÿç®ç®œç®šç®‹ç®’ç®ç­ç®™ç¯‹ç¯ç¯Œç¯ç®´ç¯†ç¯ç¯©ç°‘簔篦篥籠簀簇簓篳篷簗ç°ç¯¶ç°£ç°§ç°ªç°Ÿç°·ç°«ç°½ç±Œç±ƒç±”ç±ç±€ç±ç±˜ç±Ÿç±¤ç±–籥籬籵粃ç²ç²¤ç²­ç²¢ç²«ç²¡ç²¨ç²³ç²²ç²±ç²®ç²¹ç²½ç³€ç³…糂糘糒糜糢鬻糯糲糴糶糺紆"], ["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮çµçµ£ç¶“綉絛ç¶çµ½ç¶›ç¶ºç¶®ç¶£ç¶µç·‡ç¶½ç¶«ç¸½ç¶¢ç¶¯ç·œç¶¸ç¶Ÿç¶°ç·˜ç·ç·¤ç·žç·»ç·²ç·¡ç¸…縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧ç¹ç¹–繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒çºçº“纔纖纎纛纜缸缺"], ["e6a1","罅罌ç½ç½Žç½ç½‘罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞ç¾ç¾šç¾£ç¾¯ç¾²ç¾¹ç¾®ç¾¶ç¾¸è­±ç¿…翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻èŠè†è’è˜èšèŸè¢è¨è³è²è°è¶è¹è½è¿è‚„肆肅肛肓肚肭å†è‚¬èƒ›èƒ¥èƒ™èƒèƒ„胚胖脉胯胱脛脩脣脯腋"], ["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉è‡è‡‘臙臘臈臚臟臠臧臺臻臾èˆèˆ‚舅與舊èˆèˆèˆ–舩舫舸舳艀艙艘è‰è‰šè‰Ÿè‰¤è‰¢è‰¨è‰ªè‰«èˆ®è‰±è‰·è‰¸è‰¾èŠèŠ’èŠ«èŠŸèŠ»èŠ¬è‹¡è‹£è‹Ÿè‹’è‹´è‹³è‹ºèŽ“èŒƒè‹»è‹¹è‹žèŒ†è‹œèŒ‰è‹™"], ["e8a1","茵茴茖茲茱è€èŒ¹èè…茯茫茗茘莅莚莪莟莢莖茣莎莇莊è¼è޵è³èµèŽ èŽ‰èŽ¨è´è“è«èŽè½èƒè˜è‹èè·è‡è è²èè¢è è޽è¸è”†è»è‘­èªè¼è•šè’„葷葫蒭葮蒂葩葆è¬è‘¯è‘¹èµè“Šè‘¢è’¹è’¿è’Ÿè“™è“蒻蓚è“è“蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], ["e9a1","è•蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾è–藉薺è—è–¹è—è—•è—藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿è™ä¹•虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉èœè›¹èœŠèœ´èœ¿èœ·èœ»èœ¥èœ©èœšè èŸè¸èŒèŽè´è—è¨è®è™"], ["eaa1","è“è£èªè …螢螟螂螯蟋螽蟀èŸé›–螫蟄螳蟇蟆螻蟯蟲蟠è è èŸ¾èŸ¶èŸ·è ŽèŸ’蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫è¢è¡¾è¢žè¡µè¡½è¢µè¡²è¢‚袗袒袮袙袢è¢è¢¤è¢°è¢¿è¢±è£ƒè£„裔裘裙è£è£¹è¤‚裼裴裨裲褄褌褊褓襃褞褥褪褫è¥è¥„褻褶褸襌è¤è¥ è¥ž"], ["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜è§è§§è§´è§¸è¨ƒè¨–è¨è¨Œè¨›è¨è¨¥è¨¶è©è©›è©’詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄è«è«‚諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖è¬è¬—謠謳鞫謦謫謾謨è­è­Œè­è­Žè­‰è­–譛譚譫"], ["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺è±è°¿è±ˆè±Œè±Žè±è±•豢豬豸豺貂貉貅貊è²è²Žè²”豼貘æˆè²­è²ªè²½è²²è²³è²®è²¶è³ˆè³è³¤è³£è³šè³½è³ºè³»è´„è´…è´Šè´‡è´è´è´é½Žè´“è³è´”贖赧赭赱赳è¶è¶™è·‚趾趺è·è·šè·–跌跛跋跪跫跟跣跼踈踉跿è¸è¸žè¸è¸Ÿè¹‚踵踰踴蹊"], ["eda1","蹇蹉蹌è¹è¹ˆè¹™è¹¤è¹ è¸ªè¹£è¹•蹶蹲蹼èºèº‡èº…躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡é€é€žé€–逋逧逶逵逹迸"], ["eea1","ééé‘é’逎é‰é€¾é–é˜éžé¨é¯é¶éš¨é²é‚‚é½é‚邀邊邉é‚邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀é‡é‡‰é‡‹é‡é‡–釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋é‰éŠœéŠ–éŠ“éŠ›é‰šé‹éŠ¹éŠ·é‹©éŒé‹ºé„錮"], ["efa1","錙錢錚錣錺錵錻éœé é¼é®é–鎰鎬鎭鎔鎹é–é—é¨é¥é˜éƒéééˆé¤éšé”é“éƒé‡éé¶é«éµé¡éºé‘鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾é’鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃é—闌闕闔闖關闡闥闢阡阨阮阯陂陌é™é™‹é™·é™œé™ž"], ["f0a1","é™é™Ÿé™¦é™²é™¬éšéš˜éš•隗險隧隱隲隰隴隶隸隹雎雋雉é›è¥é›œéœé›•雹霄霆霈霓霎霑éœéœ–霙霤霪霰霹霽霾é„é†éˆé‚é‰éœé é¤é¦é¨å‹’é«é±é¹éž…é¼éžéºéž†éž‹éžéžéžœéž¨éž¦éž£éž³éž´éŸƒéŸ†éŸˆéŸ‹éŸœéŸ­é½éŸ²ç«ŸéŸ¶éŸµé é Œé ¸é ¤é ¡é ·é ½é¡†é¡é¡‹é¡«é¡¯é¡°"], ["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡é¤é¤žé¤¤é¤ é¤¬é¤®é¤½é¤¾é¥‚饉饅é¥é¥‹é¥‘饒饌饕馗馘馥馭馮馼駟駛é§é§˜é§‘駭駮駱駲駻駸é¨é¨é¨…駢騙騫騷驅驂驀驃騾驕é©é©›é©—驟驢驥驤驩驫驪骭骰骼髀é«é«‘髓體髞髟髢髣髦髯髫髮髴髱髷"], ["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃é­é­é­Žé­‘魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆é¯é¯‘鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒éµé´¿é´¾éµ†éµˆ"], ["f3a1","éµéµžéµ¤éµ‘éµéµ™éµ²é¶‰é¶‡é¶«éµ¯éµºé¶šé¶¤é¶©é¶²é·„é·é¶»é¶¸é¶ºé·†é·é·‚鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽éºéºˆéº‹éºŒéº’麕麑éºéº¥éº©éº¸éºªéº­é¡é»Œé»Žé»é»é»”黜點é»é» é»¥é»¨é»¯é»´é»¶é»·é»¹é»»é»¼é»½é¼‡é¼ˆçš·é¼•鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], ["f4a1","堯槇é™ç‘¤å‡œç†™"], ["f9a1","纊褜éˆéŠˆè“œä¿‰ç‚»æ˜±æ£ˆé‹¹æ›»å½…ä¸¨ä»¡ä»¼ä¼€ä¼ƒä¼¹ä½–ä¾’ä¾Šä¾šä¾”ä¿å€å€¢ä¿¿å€žå†å°å‚傔僴僘兊兤å†å†¾å‡¬åˆ•劜劦勀勛匀匇匤å²åŽ“åŽ²å﨎咜咊咩哿喆å™å¥åž¬åŸˆåŸ‡ï¨ï¨å¢žå¢²å¤‹å¥“奛å¥å¥£å¦¤å¦ºå­–寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹å·å¼¡å¼´å½§å¾·"], ["faa1","å¿žææ‚…æ‚Šæƒžæƒ•æ„ æƒ²æ„‘æ„·æ„°æ†˜æˆ“æŠ¦æµæ‘ æ’æ“Žæ•Žæ˜€æ˜•æ˜»æ˜‰æ˜®æ˜žæ˜¤æ™¥æ™—æ™™ï¨’æ™³æš™æš æš²æš¿æ›ºæœŽï¤©æ¦æž»æ¡’æŸ€æ æ¡„æ£ï¨“æ¥¨ï¨”æ¦˜æ§¢æ¨°æ©«æ©†æ©³æ©¾æ«¢æ«¤æ¯–æ°¿æ±œæ²†æ±¯æ³šæ´„æ¶‡æµ¯æ¶–æ¶¬æ·æ·¸æ·²æ·¼æ¸¹æ¹œæ¸§æ¸¼æº¿æ¾ˆæ¾µæ¿µç€…瀇瀨炅炫ç„焄煜煆煇凞ç‡ç‡¾çб"], ["fba1","犾猤猪ç·ç޽ç‰ç–ç£ç’ç‡çµç¦çªç©ç®ç‘¢ç’‰ç’Ÿç”畯皂皜皞皛皦益ç†åŠ¯ç ¡ç¡Žç¡¤ç¡ºç¤°ï¨˜ï¨™ï¨šç¦”ï¨›ç¦›ç«‘ç«§ï¨œç««ç®žï¨çµˆçµœç¶·ç¶ ç·–繒罇羡羽èŒè¢è¿è‡è¶è‘ˆè’´è•“蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣è»ï¨¤ï¨¥é§éƒžï¨¦é„•鄧釚"], ["fca1","釗釞釭釮釤釥鈆éˆéˆŠéˆºé‰€éˆ¼é‰Žé‰™é‰‘鈹鉧銧鉷鉸鋧鋗鋙é‹ï¨§é‹•鋠鋓錥錡鋻﨨錞鋿éŒéŒ‚é°é—鎤é†éžé¸é±é‘…鑈閒隆﨩éšéš¯éœ³éœ»éƒééé‘é•顗顥飯飼餧館馞驎髙髜魵魲é®é®±é®»é°€éµ°éµ«ï¨­é¸™é»‘"], ["fcf1","â…°",9,"¬¦'""], ["8fa2af","˘ˇ¸˙˯˛˚~΄΅"], ["8fa2c2","¡¦¿"], ["8fa2eb","ºª©®™¤№"], ["8fa6e1","ΆΈΉΊΪ"], ["8fa6e7","ÎŒ"], ["8fa6e9","ΎΫ"], ["8fa6ec","Î"], ["8fa6f1","άέήίϊÎόςÏϋΰώ"], ["8fa7c2","Ђ",10,"ÐŽÐ"], ["8fa7f2","Ñ’",10,"ўџ"], ["8fa9a1","ÆÄ"], ["8fa9a4","Ħ"], ["8fa9a6","IJ"], ["8fa9a8","ÅÄ¿"], ["8fa9ab","ŊØŒ"], ["8fa9af","ŦÞ"], ["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], ["8faaa1","ÃÀÄÂĂÇĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], ["8faaba","ĜĞĢĠĤÃÃŒÃÃŽÇİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑÅŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴßŶŹŽŻ"], ["8faba1","áàäâăǎÄąåãćĉÄçċÄéèëêěėēęǵÄÄŸ"], ["8fabbd","ġĥíìïîÇ"], ["8fabc5","īįĩĵķĺľļńňņñóòöôǒőÅõŕřŗśÅšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], ["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀ä¹ä¹„乇乑乚乜乣乨乩乴乵乹乿äºäº–亗äºäº¯äº¹ä»ƒä»ä»šä»›ä» ä»¡ä»¢ä»¨ä»¯ä»±ä»³ä»µä»½ä»¾ä»¿ä¼€ä¼‚伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾ä¾ä¾‚侄"], ["8fb1a1","侅侉侊侌侎ä¾ä¾’侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀ä¿ä¿…俆俈俉俋俌ä¿ä¿ä¿’俜俠俢俰俲俼俽俿倀å€å€„倇倊倌倎å€å€“倗倘倛倜å€å€žå€¢å€§å€®å€°å€²å€³å€µå€åå‚å…å†åŠåŒåŽå‘å’å“å—å™åŸå å¢å£å¦å§åªå­å°å±å€»å‚傃傄傆傊傎å‚å‚"], ["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎åƒåƒ“僔僘僜åƒåƒŸåƒ¢åƒ¤åƒ¦åƒ¨åƒ©åƒ¯åƒ±åƒ¶åƒºåƒ¾å„ƒå„†å„‡å„ˆå„‹å„Œå„儎僲å„儗儙儛儜å„儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊å…兓兕兗兘兟兤兦兾冃冄冋冎冘å†å†¡å†£å†­å†¸å†ºå†¼å†¾å†¿å‡‚"], ["8fb3a1","凈å‡å‡‘凒凓凕凘凞凢凥凮凲凳凴凷åˆåˆ‚刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌å‹å‹‘勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], ["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾å‚åŒå‹å™å›å¡å£å¥å¬å­å²å¹å¾åŽƒåŽ‡åŽˆåŽŽåŽ“åŽ”åŽ™åŽåŽ¡åŽ¤åŽªåŽ«åŽ¯åŽ²åŽ´åŽµåŽ·åŽ¸åŽºåŽ½å€å…åå’å“å•åšååžå å¦å§åµå‚å“åšå¡å§å¨åªå¯å±å´åµå‘ƒå‘„呇å‘å‘呞呢呤呦呧呩呫呭呮呴呿"], ["8fb5a1","å’咃咅咈咉å’咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊å“哎哠哪哬哯哶哼哾哿唀å”唅唈唉唌å”唎唕唪唫唲唵唶唻唼唽å•啇啉啊å•å•啑啘啚啛啞啠啡啤啦啿å–喂喆喈喎å–喑喒喓喔喗喣喤喭喲喿å—嗃嗆嗉嗋嗌嗎嗑嗒"], ["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊å˜",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀å™å™ƒå™„噆噉噋å™å™å™”噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚åšåšžåšŸåš¦åš§åš¨åš©åš«åš¬åš­åš±åš³åš·åš¾å›…囉囊囋å›å›å›Œå›å›™å›œå›å›Ÿå›¡å›¤",4,"囱囫园"], ["8fb7a1","å›¶å›·åœåœ‚圇圊圌圑圕圚圛åœåœ åœ¢åœ£åœ¤åœ¥åœ©åœªåœ¬åœ®åœ¯åœ³åœ´åœ½åœ¾åœ¿å…å†åŒåå’å¢å¥å§å¨å«å­",4,"å³å´åµå·å¹åºå»å¼å¾åžåžƒåžŒåž”垗垙垚垜åžåžžåžŸåž¡åž•垧垨垩垬垸垽埇埈埌åŸåŸ•åŸåŸžåŸ¤åŸ¦åŸ§åŸ©åŸ­åŸ°åŸµåŸ¶åŸ¸åŸ½åŸ¾åŸ¿å ƒå „堈堉埡"], ["8fb8a1","å Œå å ›å žå Ÿå  å ¦å §å ­å ²å ¹å ¿å¡‰å¡Œå¡å¡å¡å¡•塟塡塤塧塨塸塼塿墀å¢å¢‡å¢ˆå¢‰å¢Šå¢Œå¢å¢å¢å¢”墖å¢å¢ å¢¡å¢¢å¢¦å¢©å¢±å¢²å£„墼壂壈å£å£Žå£å£’壔壖壚å£å£¡å£¢å£©å£³å¤…夆夋夌夒夓夔è™å¤å¤¡å¤£å¤¤å¤¨å¤¯å¤°å¤³å¤µå¤¶å¤¿å¥ƒå¥†å¥’奓奙奛å¥å¥žå¥Ÿå¥¡å¥£å¥«å¥­"], ["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼å§å§ƒå§„姈姊å§å§’å§å§žå§Ÿå§£å§¤å§§å§®å§¯å§±å§²å§´å§·å¨€å¨„娌å¨å¨Žå¨’娓娞娣娤娧娨娪娭娰婄婅婇婈婌å©å©•婞婣婥婧婭婷婺婻婾媋åªåª“媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], ["8fbaa1","嫄嫆嫈å«å«šå«œå« å«¥å«ªå«®å«µå«¶å«½å¬€å¬å¬ˆå¬—嬴嬙嬛å¬å¬¡å¬¥å¬­å¬¸å­å­‹å­Œå­’孖孞孨孮孯孼孽孾孿å®å®„宆宊宎å®å®‘宓宔宖宨宩宬宭宯宱宲宷宺宼寀å¯å¯å¯å¯–",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], ["8fbba1","屭屰屴屵屺屻屼屽岇岈岊å²å²’å²å²Ÿå² å²¢å²£å²¦å²ªå²²å²´å²µå²ºå³‰å³‹å³’å³å³—峮峱峲峴å´å´†å´å´’崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿å¶å¶ƒå¶ˆå¶Šå¶’嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋å·å·Žå·˜å·™å· å·¤"], ["8fbca1","巩巸巹帀帇å¸å¸’帔帕帘帟帠帮帨帲帵帾幋å¹å¹‰å¹‘幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜å¼å¼¡å¼¢å¼£å¼¤å¼¨å¼«å¼¬å¼®å¼°å¼´å¼¶å¼»å¼½å¼¿å½€å½„彅彇å½å½å½”彘彛彠彣彤彧"], ["8fbda1","彯彲彴彵彸彺彽彾徉å¾å¾å¾–徜å¾å¾¢å¾§å¾«å¾¤å¾¬å¾¯å¾°å¾±å¾¸å¿„忇忈忉忋å¿",4,"å¿žå¿¡å¿¢å¿¨å¿©å¿ªå¿¬å¿­å¿®å¿¯å¿²å¿³å¿¶å¿ºå¿¼æ€‡æ€Šæ€æ€“æ€”æ€—æ€˜æ€šæ€Ÿæ€¤æ€­æ€³æ€µæ€æ‡æˆæ‰æŒæ‘æ”æ–æ—ææ¡æ§æ±æ¾æ¿æ‚‚æ‚†æ‚ˆæ‚Šæ‚Žæ‚‘æ‚“æ‚•æ‚˜æ‚æ‚žæ‚¢æ‚¤æ‚¥æ‚¨æ‚°æ‚±æ‚·"], ["8fbea1","æ‚»æ‚¾æƒ‚æƒ„æƒˆæƒ‰æƒŠæƒ‹æƒŽæƒæƒ”æƒ•æƒ™æƒ›æƒæƒžæƒ¢æƒ¥æƒ²æƒµæƒ¸æƒ¼æƒ½æ„‚愇愊愌æ„",4,"æ„–æ„—æ„™æ„œæ„žæ„¢æ„ªæ„«æ„°æ„±æ„µæ„¶æ„·æ„¹æ…æ……æ…†æ…‰æ…žæ… æ…¬æ…²æ…¸æ…»æ…¼æ…¿æ†€æ†æ†ƒæ†„æ†‹æ†æ†’æ†“æ†—æ†˜æ†œæ†æ†Ÿæ† æ†¥æ†¨æ†ªæ†­æ†¸æ†¹æ†¼æ‡€æ‡æ‡‚æ‡Žæ‡æ‡•æ‡œæ‡æ‡žæ‡Ÿæ‡¡æ‡¢æ‡§æ‡©æ‡¥"], ["8fbfa1","æ‡¬æ‡­æ‡¯æˆæˆƒæˆ„æˆ‡æˆ“æˆ•æˆœæˆ æˆ¢æˆ£æˆ§æˆ©æˆ«æˆ¹æˆ½æ‰‚æ‰ƒæ‰„æ‰†æ‰Œæ‰æ‰‘æ‰’æ‰”æ‰–æ‰šæ‰œæ‰¤æ‰­æ‰¯æ‰³æ‰ºæ‰½æŠæŠŽæŠæŠæŠ¦æŠ¨æŠ³æŠ¶æŠ·æŠºæŠ¾æŠ¿æ‹„æ‹Žæ‹•æ‹–æ‹šæ‹ªæ‹²æ‹´æ‹¼æ‹½æŒƒæŒ„æŒŠæŒ‹æŒæŒæŒ“æŒ–æŒ˜æŒ©æŒªæŒ­æŒµæŒ¶æŒ¹æŒ¼ææ‚æƒæ„æ†æŠæ‹æŽæ’æ“æ”æ˜æ›æ¥æ¦æ¬æ­æ±æ´æµ"], ["8fc0a1","æ¸æ¼æ½æ¿æŽ‚æŽ„æŽ‡æŽŠæŽæŽ”æŽ•æŽ™æŽšæŽžæŽ¤æŽ¦æŽ­æŽ®æŽ¯æŽ½ææ…æˆæŽæ‘æ“æ”æ•æœæ æ¥æªæ¬æ²æ³æµæ¸æ¹æ‰æŠææ’æ”æ˜æžæ æ¢æ¤æ¥æ©æªæ¯æ°æµæ½æ¿æ‘‹æ‘æ‘‘æ‘’æ‘“æ‘”æ‘šæ‘›æ‘œæ‘æ‘Ÿæ‘ æ‘¡æ‘£æ‘­æ‘³æ‘´æ‘»æ‘½æ’…æ’‡æ’æ’æ’‘æ’˜æ’™æ’›æ’æ’Ÿæ’¡æ’£æ’¦æ’¨æ’¬æ’³æ’½æ’¾æ’¿"], ["8fc1a1","æ“„æ“‰æ“Šæ“‹æ“Œæ“Žæ“æ“‘æ“•æ“—æ“¤æ“¥æ“©æ“ªæ“­æ“°æ“µæ“·æ“»æ“¿æ”æ”„æ”ˆæ”‰æ”Šæ”æ”“æ””æ”–æ”™æ”›æ”žæ”Ÿæ”¢æ”¦æ”©æ”®æ”±æ”ºæ”¼æ”½æ•ƒæ•‡æ•‰æ•æ•’æ•”æ•Ÿæ• æ•§æ•«æ•ºæ•½æ–æ–…æ–Šæ–’æ–•æ–˜æ–æ– æ–£æ–¦æ–®æ–²æ–³æ–´æ–¿æ—‚æ—ˆæ—‰æ—Žæ—æ—”æ—–æ—˜æ—Ÿæ—°æ—²æ—´æ—µæ—¹æ—¾æ—¿æ˜€æ˜„æ˜ˆæ˜‰æ˜æ˜‘昒昕昖æ˜"], ["8fc2a1","æ˜žæ˜¡æ˜¢æ˜£æ˜¤æ˜¦æ˜©æ˜ªæ˜«æ˜¬æ˜®æ˜°æ˜±æ˜³æ˜¹æ˜·æ™€æ™…æ™†æ™Šæ™Œæ™‘æ™Žæ™—æ™˜æ™™æ™›æ™œæ™ æ™¡æ›»æ™ªæ™«æ™¬æ™¾æ™³æ™µæ™¿æ™·æ™¸æ™¹æ™»æš€æ™¼æš‹æšŒæšæšæš’æš™æššæš›æšœæšŸæš æš¤æš­æš±æš²æšµæš»æš¿æ›€æ›‚æ›ƒæ›ˆæ›Œæ›Žæ›æ›”æ››æ›Ÿæ›¨æ›«æ›¬æ›®æ›ºæœ…æœ‡æœŽæœ“æœ™æœœæœ æœ¢æœ³æœ¾æ…æ‡æˆæŒæ”æ•æ"], ["8fc3a1","æ¦æ¬æ®æ´æ¶æ»æžæž„æžŽæžæž‘æž“æž–æž˜æž™æž›æž°æž±æž²æžµæž»æž¼æž½æŸ¹æŸ€æŸ‚æŸƒæŸ…æŸˆæŸ‰æŸ’æŸ—æŸ™æŸœæŸ¡æŸ¦æŸ°æŸ²æŸ¶æŸ·æ¡’æ ”æ ™æ æ Ÿæ ¨æ §æ ¬æ ­æ ¯æ °æ ±æ ³æ »æ ¿æ¡„桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌æ£"], ["8fc4a1","æ£æ£‘æ£“æ£–æ£™æ£œæ£æ£¥æ£¨æ£ªæ£«æ£¬æ£­æ£°æ£±æ£µæ£¶æ£»æ£¼æ£½æ¤†æ¤‰æ¤Šæ¤æ¤‘æ¤“æ¤–æ¤—æ¤±æ¤³æ¤µæ¤¸æ¤»æ¥‚æ¥…æ¥‰æ¥Žæ¥—æ¥›æ¥£æ¥¤æ¥¥æ¥¦æ¥¨æ¥©æ¥¬æ¥°æ¥±æ¥²æ¥ºæ¥»æ¥¿æ¦€æ¦æ¦’æ¦–æ¦˜æ¦¡æ¦¥æ¦¦æ¦¨æ¦«æ¦­æ¦¯æ¦·æ¦¸æ¦ºæ¦¼æ§…æ§ˆæ§‘æ§–æ§—æ§¢æ§¥æ§®æ§¯æ§±æ§³æ§µæ§¾æ¨€æ¨æ¨ƒæ¨æ¨‘æ¨•æ¨šæ¨æ¨ æ¨¤æ¨¨æ¨°æ¨²"], ["8fc5a1","æ¨´æ¨·æ¨»æ¨¾æ¨¿æ©…æ©†æ©‰æ©Šæ©Žæ©æ©‘æ©’æ©•æ©–æ©›æ©¤æ©§æ©ªæ©±æ©³æ©¾æªæªƒæª†æª‡æª‰æª‹æª‘æª›æªæªžæªŸæª¥æª«æª¯æª°æª±æª´æª½æª¾æª¿æ«†æ«‰æ«ˆæ«Œæ«æ«”æ«•æ«–æ«œæ«æ«¤æ«§æ«¬æ«°æ«±æ«²æ«¼æ«½æ¬‚æ¬ƒæ¬†æ¬‡æ¬‰æ¬æ¬æ¬‘æ¬—æ¬›æ¬žæ¬¤æ¬¨æ¬«æ¬¬æ¬¯æ¬µæ¬¶æ¬»æ¬¿æ­†æ­Šæ­æ­’æ­–æ­˜æ­æ­ æ­§æ­«æ­®æ­°æ­µæ­½"], ["8fc6a1","æ­¾æ®‚æ®…æ®—æ®›æ®Ÿæ® æ®¢æ®£æ®¨æ®©æ®¬æ®­æ®®æ®°æ®¸æ®¹æ®½æ®¾æ¯ƒæ¯„æ¯‰æ¯Œæ¯–æ¯šæ¯¡æ¯£æ¯¦æ¯§æ¯®æ¯±æ¯·æ¯¹æ¯¿æ°‚æ°„æ°…æ°‰æ°æ°Žæ°æ°’æ°™æ°Ÿæ°¦æ°§æ°¨æ°¬æ°®æ°³æ°µæ°¶æ°ºæ°»æ°¿æ±Šæ±‹æ±æ±æ±’æ±”æ±™æ±›æ±œæ±«æ±­æ±¯æ±´æ±¶æ±¸æ±¹æ±»æ²…æ²†æ²‡æ²‰æ²”æ²•æ²—æ²˜æ²œæ²Ÿæ²°æ²²æ²´æ³‚æ³†æ³æ³æ³æ³‘泒泔泖"], ["8fc7a1","æ³šæ³œæ³ æ³§æ³©æ³«æ³¬æ³®æ³²æ³´æ´„æ´‡æ´Šæ´Žæ´æ´‘æ´“æ´šæ´¦æ´§æ´¨æ±§æ´®æ´¯æ´±æ´¹æ´¼æ´¿æµ—æµžæµŸæµ¡æµ¥æµ§æµ¯æµ°æµ¼æ¶‚æ¶‡æ¶‘æ¶’æ¶”æ¶–æ¶—æ¶˜æ¶ªæ¶¬æ¶´æ¶·æ¶¹æ¶½æ¶¿æ·„æ·ˆæ·Šæ·Žæ·æ·–æ·›æ·æ·Ÿæ· æ·¢æ·¥æ·©æ·¯æ·°æ·´æ·¶æ·¼æ¸€æ¸„æ¸žæ¸¢æ¸§æ¸²æ¸¶æ¸¹æ¸»æ¸¼æ¹„æ¹…æ¹ˆæ¹‰æ¹‹æ¹æ¹‘æ¹’æ¹“æ¹”æ¹—æ¹œæ¹æ¹ž"], ["8fc8a1","æ¹¢æ¹£æ¹¨æ¹³æ¹»æ¹½æºæº“æº™æº æº§æº­æº®æº±æº³æº»æº¿æ»€æ»æ»ƒæ»‡æ»ˆæ»Šæ»æ»Žæ»æ»«æ»­æ»®æ»¹æ»»æ»½æ¼„æ¼ˆæ¼Šæ¼Œæ¼æ¼–æ¼˜æ¼šæ¼›æ¼¦æ¼©æ¼ªæ¼¯æ¼°æ¼³æ¼¶æ¼»æ¼¼æ¼­æ½æ½‘æ½’æ½“æ½—æ½™æ½šæ½æ½žæ½¡æ½¢æ½¨æ½¬æ½½æ½¾æ¾ƒæ¾‡æ¾ˆæ¾‹æ¾Œæ¾æ¾æ¾’澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], ["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇ç€ç€—瀠瀣瀯瀴瀷瀹瀼çƒç„çˆç‰çŠç‹ç”ç•ççžçŽç¤ç¥ç¬ç®çµç¶ç¾ç‚炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌ç„焞焠焫焭焯焰焱焸ç…煅煆煇煊煋ç…煒煗煚煜煞煠"], ["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀ç‡ç‡„燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚çˆçˆŸçˆ¤çˆ«çˆ¯çˆ´çˆ¸çˆ¹ç‰ç‰‚牃牅牎ç‰ç‰ç‰“牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉çŠçŠŽçŠ“çŠ›çŠ¨çŠ­çŠ®çŠ±çŠ´çŠ¾ç‹ç‹‡ç‹‰ç‹Œç‹•狖狘狟狥狳狴狺狻"], ["8fcba1","狾猂猄猅猇猋çŒçŒ’猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽çƒççç’ç–ç˜ççžçŸç ç¦ç§ç©ç«ç¬ç®ç¯ç±ç·ç¹ç¼çŽ€çŽçŽƒçŽ…çŽ†çŽŽçŽçŽ“çŽ•çŽ—çŽ˜çŽœçŽžçŽŸçŽ çŽ¢çŽ¥çŽ¦çŽªçŽ«çŽ­çŽµçŽ·çŽ¹çŽ¼çŽ½çŽ¿ç…ç†ç‰ç‹çŒçç’ç“ç–ç™çç¡ç£ç¦ç§ç©ç´çµç·ç¹çºç»ç½"], ["8fcca1","ç¿ç€çç„ç‡çŠç‘çšç›ç¤ç¦ç¨",9,"ç¹ç‘€ç‘ƒç‘„瑆瑇瑋ç‘ç‘‘ç‘’ç‘—ç‘瑢瑦瑧瑨瑫瑭瑮瑱瑲璀ç’璅璆璇璉ç’ç’璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌ç“瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], ["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎ç•畒畗畞畟畡畯畱畹",5,"ç–ç–…ç–疒疓疕疙疜疢疤疴疺疿痀ç—痄痆痌痎ç—痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌ç˜ç˜’瘓瘕瘖瘙瘛瘜ç˜ç˜žç˜£ç˜¥ç˜¦ç˜©ç˜­ç˜²ç˜³ç˜µç˜¸ç˜¹"], ["8fcea1","瘺瘼癊癀ç™ç™ƒç™„癅癉癋癕癙癟癤癥癭癮癯癱癴çšçš…皌çšçš•皛皜çšçšŸçš çš¢",6,"皪皭皽ç›ç›…盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾ç‚ç…ç†çŠççŽçç’ç–ç—çœçžçŸç ç¢"], ["8fcfa1","ç¤ç§çªç¬ç°ç²ç³ç´çºç½çž€çž„瞌çžçž”瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉ç ç Žç ‘ç ç ¡ç ¢ç £ç ­ç ®ç °ç µç ·ç¡ƒç¡„硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊ç¢ç¢”碘碡ç¢ç¢žç¢Ÿç¢¤ç¢¨ç¢¬ç¢­ç¢°ç¢±ç¢²ç¢³"], ["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌ç¤ç¤šç¤œç¤žç¤Ÿç¤ ç¤¥ç¤§ç¤©ç¤­ç¤±ç¤´ç¤µç¤»ç¤½ç¤¿ç¥„祅祆祊祋ç¥ç¥‘祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊ç§ç§”ç§–ç§šç§ç§ž"], ["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜ç©ç©Ÿç© ç©¥ç©§ç©ªç©­ç©µç©¸ç©¾çª€çª‚窅窆窊窋çªçª‘窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], ["8fd2a1","笱笴笽笿筀ç­ç­‡ç­Žç­•筠筤筦筩筪筭筯筲筳筷箄箉箎ç®ç®‘箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾ç°ç°‚簃簄簆簉簋簌簎ç°ç°™ç°›ç° ç°¥ç°¦ç°¨ç°¬ç°±ç°³ç°´ç°¶ç°¹ç°ºç±†ç±Šç±•籑籒籓籙",5], ["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇ç²ç²”粞粠粦粰粶粷粺粻粼粿糄糇糈糉ç³ç³ç³“糔糕糗糙糚ç³ç³¦ç³©ç³«ç³µç´ƒç´‡ç´ˆç´‰ç´ç´‘ç´’ç´“ç´–ç´ç´žç´£ç´¦ç´ªç´­ç´±ç´¼ç´½ç´¾çµ€çµçµ‡çµˆçµçµ‘絓絗絙絚絜çµçµ¥çµ§çµªçµ°çµ¸çµºçµ»çµ¿ç¶ç¶‚綃綅綆綈綋綌ç¶ç¶‘ç¶–ç¶—ç¶"], ["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"ç·Œç·ç·Žç·—緙縀緢緥緦緪緫緭緱緵緶緹緺縈ç¸ç¸‘縕縗縜ç¸ç¸ ç¸§ç¸¨ç¸¬ç¸­ç¸¯ç¸³ç¸¶ç¸¿ç¹„繅繇繎ç¹ç¹’繘繟繡繢繥繫繮繯繳繸繾çºçº†çº‡çºŠçºçº‘纕纘纚çºçºžç¼¼ç¼»ç¼½ç¼¾ç¼¿ç½ƒç½„罇ç½ç½’罓罛罜ç½ç½¡ç½£ç½¤ç½¥ç½¦ç½­"], ["8fd5a1","罱罽罾罿羀羋ç¾ç¾ç¾ç¾‘羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎ç¿ç¿›ç¿Ÿç¿£ç¿¥ç¿¨ç¿¬ç¿®ç¿¯ç¿²ç¿ºç¿½ç¿¾ç¿¿è€‡è€ˆè€Šè€è€Žè€è€‘耓耔耖è€è€žè€Ÿè€ è€¤è€¦è€¬è€®è€°è€´è€µè€·è€¹è€ºè€¼è€¾è€è„è è¤è¦è­è±èµè‚肈肎肜肞肦肧肫肸肹胈èƒèƒèƒ’胔胕胗胘胠胭胮"], ["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷è†è†è†„膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎è‡è‡•臗臛è‡è‡žè‡¡è‡¤è‡«è‡¬è‡°è‡±è‡²è‡µè‡¶è‡¸è‡¹è‡½è‡¿èˆ€èˆƒèˆèˆ“舔舙舚èˆèˆ¡èˆ¢èˆ¨èˆ²èˆ´èˆºè‰ƒè‰„艅艆"], ["8fd7a1","艋艎è‰è‰‘艖艜艠艣艧艭艴艻艽艿芀èŠèŠƒèŠ„èŠ‡èŠ‰èŠŠèŠŽèŠ‘èŠ”èŠ–èŠ˜èŠšèŠ›èŠ èŠ¡èŠ£èŠ¤èŠ§èŠ¨èŠ©èŠªèŠ®èŠ°èŠ²èŠ´èŠ·èŠºèŠ¼èŠ¾èŠ¿è‹†è‹è‹•苚苠苢苤苨苪苭苯苶苷苽苾茀èŒèŒ‡èŒˆèŒŠèŒ‹è”茛èŒèŒžèŒŸèŒ¡èŒ¢èŒ¬èŒ­èŒ®èŒ°èŒ³èŒ·èŒºèŒ¼èŒ½è‚èƒè„è‡èèŽè‘è•è–è—è°è¸"], ["8fd8a1","è½è¿èŽ€èŽ‚èŽ„èŽ†èŽèŽ’èŽ”èŽ•èŽ˜èŽ™èŽ›èŽœèŽèŽ¦èŽ§èŽ©èŽ¬èŽ¾èŽ¿è€è‡è‰èèè‘è”èè“è¨èªè¶è¸è¹è¼èè†èŠèè‘è•è™èŽ­è¯è¹è‘…葇葈葊è‘è‘葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽è’蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌è“è““"], ["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎è”蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆è•",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿è–薅薆薉薋薌è–è–“è–˜è–薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], ["8fdaa1","藿蘀蘄蘅è˜è˜Žè˜è˜‘蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙è™è™ ",4,"虩虬虯虵虶虷虺èšèš‘蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀è›è›ƒè›…蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎èœèœèœ“蜔蜙蜞蜟蜡蜣"], ["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾è€èƒè…èè˜èè¡è¤è¥è¯è±è²è»èžƒ",6,"螋螌èžèž“螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿èŸèŸˆèŸ‰èŸŠèŸŽèŸ•蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿è è ƒè †è ‰è Šè ‹è è ™è ’蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], ["8fdca1","蠺蠼è¡è¡ƒè¡…衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷è¤è¤†è¤è¤Žè¤è¤•褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉è¥è¥’襗襚襛襜襡襢襣襫襮襰襳襵襺"], ["8fdda1","襻襼襽覉è¦è¦è¦”覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇è¨è¨‘訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉è©è©Žè©“詖詗詘詜è©è©¡è©¥è©§è©µè©¶è©·è©¹è©ºè©»è©¾è©¿èª€èªƒèª†èª‹èªèªèª’誖誗誙誟誧誩誮誯誳"], ["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗è«è«Ÿè«¬è«°è«´è«µè«¶è«¼è«¿è¬…謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙è­è­žè­£è­­è­¶è­¸è­¹è­¼è­¾è®è®„讅讋è®è®è®”讕讜讞讟谸谹谽谾豅豇豉豋è±è±‘豓豔豗豘豛è±è±™è±£è±¤è±¦è±¨è±©è±­è±³è±µè±¶è±»è±¾è²†"], ["8fdfa1","貇貋è²è²’貓貙貛貜貤貹貺賅賆賉賋è³è³–賕賙è³è³¡è³¨è³¬è³¯è³°è³²è³µè³·è³¸è³¾è³¿è´è´ƒè´‰è´’贗贛赥赩赬赮赿趂趄趈è¶è¶è¶‘趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽è¸è¸„踅踆踋踑踔踖踠踡踢"], ["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀è¹è¹‹è¹è¹Žè¹è¹”蹛蹜è¹è¹žè¹¡è¹¢è¹©è¹¬è¹­è¹¯è¹°è¹±è¹¹è¹ºè¹»èº‚躃躉èºèº’躕躚躛èºèºžèº¢èº§èº©èº­èº®èº³èºµèººèº»è»€è»è»ƒè»„軇è»è»‘軔軜軨軮軰軱軷軹軺軭輀輂輇輈è¼è¼è¼–輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀è½"], ["8fe1a1","轃轇è½è½‘",4,"轘è½è½žè½¥è¾è¾ è¾¡è¾¤è¾¥è¾¦è¾µè¾¶è¾¸è¾¾è¿€è¿è¿†è¿Šè¿‹è¿è¿è¿’迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿éƒé„éŒé›éé¢é¦é§é¬é°é´é¹é‚…邈邋邌邎é‚邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], ["8fe2a1","郄郅郇郈郕郗郘郙郜éƒéƒŸéƒ¥éƒ’郶郫郯郰郴郾郿鄀鄄鄅鄆鄈é„é„鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈é…酓酗酙酚酛酡酤酧酭酴酹酺酻é†é†ƒé†…醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], ["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀éˆéˆ„鈅鈆鈇鈉鈊鈌éˆéˆ’鈓鈖鈘鈜éˆéˆ£éˆ¤éˆ¥éˆ¦éˆ¨éˆ®éˆ¯éˆ°éˆ³éˆµéˆ¶éˆ¸éˆ¹éˆºéˆ¼éˆ¾é‰€é‰‚鉃鉆鉇鉊é‰é‰Žé‰é‰‘鉘鉙鉜é‰é‰ é‰¡é‰¥é‰§é‰¨é‰©é‰®é‰¯é‰°é‰µ",4,"鉻鉼鉽鉿銈銉銊éŠéŠŽéŠ’éŠ—"], ["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌é‹é‹Žé‹é‹“鋕鋗鋘鋙鋜é‹é‹Ÿé‹ é‹¡é‹£é‹¥é‹§é‹¨é‹¬é‹®é‹°é‹¹é‹»é‹¿éŒ€éŒ‚錈éŒéŒ‘錔錕錜éŒéŒžéŒŸéŒ¡éŒ¤éŒ¥éŒ§éŒ©éŒªéŒ³éŒ´éŒ¶éŒ·é‡éˆé‰éé‘é’é•é—é˜éšéžé¤é¥é§é©éªé­é¯é°é±é³é´é¶"], ["8fe5a1","éºé½é¿éŽ€éŽéŽ‚éŽˆéŽŠéŽ‹éŽéŽéŽ’éŽ•éŽ˜éŽ›éŽžéŽ¡éŽ£éŽ¤éŽ¦éŽ¨éŽ«éŽ´éŽµéŽ¶éŽºéŽ©éé„é…é†é‡é‰",4,"é“é™éœéžéŸé¢é¦é§é¹é·é¸éºé»é½éé‚é„éˆé‰ééŽéé•é–é—éŸé®é¯é±é²é³é´é»é¿é½é‘ƒé‘…鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], ["8fe6a1","镾閄閈閌é–é–Žé–閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋é—闑闒闓闙闚é—闞闟闠闤闦é˜é˜žé˜¢é˜¤é˜¥é˜¦é˜¬é˜±é˜³é˜·é˜¸é˜¹é˜ºé˜¼é˜½é™é™’陔陖陗陘陡陮陴陻陼陾陿éšéš‚隃隄隉隑隖隚éšéšŸéš¤éš¥éš¦éš©éš®éš¯éš³éšºé›Šé›’嶲雘雚é›é›žé›Ÿé›©é›¯é›±é›ºéœ‚"], ["8fe7a1","霃霅霉霚霛éœéœ¡éœ¢éœ£éœ¨éœ±éœ³ééƒéŠéŽéé•é—é˜éšé›é£é§éªé®é³é¶é·é¸é»é½é¿éž€éž‰éž•鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿éŸéŸ„韅韇韉韊韌éŸéŸŽéŸéŸ‘韔韗韘韙éŸéŸžéŸ éŸ›éŸ¡éŸ¤éŸ¯éŸ±éŸ´éŸ·éŸ¸éŸºé ‡é Šé ™é é Žé ”頖頜頞頠頣頦"], ["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀é¥é¥†é¥‡é¥ˆé¥é¥Žé¥”饘饙饛饜饞饟饠馛é¦é¦Ÿé¦¦é¦°é¦±é¦²é¦µ"], ["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌é¨é¨‘騖騞騠騢騣騤騧騭騮騳騵騶騸驇é©é©„驊驋驌驎驑驔驖é©éªªéª¬éª®éª¯éª²éª´éªµéª¶éª¹éª»éª¾éª¿é«é«ƒé«†é«ˆé«Žé«é«’髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], ["8feaa1","鬄鬅鬈鬉鬋鬌é¬é¬Žé¬é¬’鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋é®é®é®é®”鮚é®é®žé®¦é®§é®©é®¬é®°é®±é®²é®·é®¸é®»é®¼é®¾é®¿é¯é¯‡é¯ˆé¯Žé¯é¯—鯘é¯é¯Ÿé¯¥é¯§é¯ªé¯«é¯¯é¯³é¯·é¯¸"], ["8feba1","鯹鯺鯽鯿鰀鰂鰋é°é°‘鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽é±é±ƒé±„鱅鱉鱊鱎é±é±é±“鱔鱖鱘鱛é±é±žé±Ÿé±£é±©é±ªé±œé±«é±¨é±®é±°é±²é±µé±·é±»é³¦é³²é³·é³¹é´‹é´‚鴑鴗鴘鴜é´é´žé´¯é´°é´²é´³é´´é´ºé´¼éµ…鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], ["8feca1","鵼鵾鶃鶄鶆鶊é¶é¶Žé¶’鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎é¸é¸‘鸒鸕鸖鸙鸜é¸é¹ºé¹»é¹¼éº€éº‚麃麄麅麇麎éºéº–麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], ["8feda1","黸黿鼂鼃鼉é¼é¼é¼‘鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿é½é½ƒ",4,"齓齕齖齗齘齚é½é½žé½¨é½©é½­",4,"齳齵齺齽é¾é¾é¾‘龒龔龖龗龞龡龢龣龥"] ] {"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]}[ ["a140","",62], ["a180","î”…",32], ["a240","",62], ["a280","î•¥",32], ["a2ab","î¦",5], ["a2e3","€î­"], ["a2ef","î®î¯"], ["a2fd","î°î±"], ["a340","î–†",62], ["a380","î—…",31," "], ["a440","î—¦",62], ["a480","",32], ["a4f4","î²",10], ["a540","",62], ["a580","îš…",32], ["a5f7","î½",7], ["a640","",62], ["a680","",32], ["a6b9","îž…",7], ["a6d9","îž",6], ["a6ec",""], ["a6f3","îž–"], ["a6f6","îž—",8], ["a740","",62], ["a780","î…",32], ["a7c2","îž ",14], ["a7f2","",12], ["a896","îž¼",10], ["a8bc","ḿ"], ["a8bf","ǹ"], ["a8c1",""], ["a8ea","îŸ",20], ["a958",""], ["a95b",""], ["a95d",""], ["a989","〾⿰",11], ["a997","",12], ["a9f0","î ",14], ["aaa1","",93], ["aba1","îž",93], ["aca1","",93], ["ada1","",93], ["aea1","î…¸",93], ["afa1","",93], ["d7fa","î ",4], ["f8a1","",93], ["f9a1","",93], ["faa1","î‹°",93], ["fba1","îŽ",93], ["fca1","",93], ["fda1","îŠ",93], ["fe50","âºî –⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘ã§ã§Ÿã©³ã§î «î ¬ã­Žã±®ã³ âº§î ±î ²âºªä–䅟⺮䌷⺳⺶⺷䎱䎬⺻ä䓖䙡䙌"], ["fe80","䜣䜩ä¼äžâ»Šä¥‡ä¥ºä¥½ä¦‚䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93], ["8135f437",""] ] [ ["0","\u0000",128], ["a1","。",62], ["8140"," ã€ã€‚,.・:;?ï¼ã‚›ã‚œÂ´ï½€Â¨ï¼¾ï¿£ï¼¿ãƒ½ãƒ¾ã‚ゞ〃ä»ã€…〆〇ー―â€ï¼ï¼¼ï½žâˆ¥ï½œâ€¦â€¥â€˜â€™â€œâ€ï¼ˆï¼‰ã€”〕[]{ï½ã€ˆ",9,"+ï¼Â±Ã—"], ["8180","÷ï¼â‰ ï¼œï¼žâ‰¦â‰§âˆžâˆ´â™‚♀°′″℃¥$¢£%#&*@§☆★○â—◎◇◆□■△▲▽▼※〒→â†â†‘↓〓"], ["81b8","∈∋⊆⊇⊂⊃∪∩"], ["81c8","∧∨¬⇒⇔∀∃"], ["81da","∠⊥⌒∂∇≡≒≪≫√∽âˆâˆµâˆ«âˆ¬"], ["81f0","ʼn♯♭♪†‡¶"], ["81fc","â—¯"], ["824f","ï¼",9], ["8260","A",25], ["8281","ï½",25], ["829f","ã",82], ["8340","ã‚¡",62], ["8380","ム",22], ["839f","Α",16,"Σ",6], ["83bf","α",16,"σ",6], ["8440","Ð",5,"ÐЖ",25], ["8470","а",5,"ёж",7], ["8480","о",17], ["849f","─│┌â”┘└├┬┤┴┼â”┃â”┓┛┗┣┳┫┻╋┠┯┨┷┿â”┰┥┸╂"], ["8740","â‘ ",19,"â… ",9], ["875f","ã‰ãŒ”㌢ã㌘㌧㌃㌶ã‘ã—ãŒãŒ¦ãŒ£ãŒ«ãŠãŒ»ãŽœãŽãŽžãŽŽãŽã„㎡"], ["877e","ã»"], ["8780","ã€ã€Ÿâ„–ã℡㊤",4,"㈱㈲㈹ã¾ã½ã¼â‰’≡∫∮∑√⊥∠∟⊿∵∩∪"], ["889f","äºœå”–å¨ƒé˜¿å“€æ„›æŒ¨å§¶é€¢è‘µèŒœç©æ‚ªæ¡æ¸¥æ—­è‘¦èŠ¦é¯µæ¢“åœ§æ–¡æ‰±å®›å§è™»é£´çµ¢ç¶¾é®Žæˆ–ç²Ÿè¢·å®‰åºµæŒ‰æš—æ¡ˆé—‡éžæä»¥ä¼Šä½ä¾å‰å›²å¤·å§”å¨å°‰æƒŸæ„慰易椅為ç•異移維緯胃èŽè¡£è¬‚é•éºåŒ»äº•亥域育éƒç£¯ä¸€å£±æº¢é€¸ç¨²èŒ¨èЋ鰝å…å°å’½å“¡å› å§»å¼•飲淫胤蔭"], ["8940","院陰隠韻å‹å³å®‡çƒç¾½è¿‚雨å¯éµœçªºä¸‘碓臼渦嘘唄æ¬è”šé°»å§¥åŽ©æµ¦ç“œé–噂云é‹é›²è餌å¡å–¶å¬°å½±æ˜ æ›³æ „永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦è¬è¶Šé–²æ¦Žåޭ円"], ["8980","åœ’å °å¥„å®´å»¶æ€¨æŽ©æ´æ²¿æ¼”炎焔煙燕猿ç¸è‰¶è‹‘è–—é é‰›é´›å¡©æ–¼æ±šç”¥å‡¹å¤®å¥¥å¾€å¿œæŠ¼æ—ºæ¨ªæ¬§æ®´çŽ‹ç¿è¥–鴬鴎黄岡沖è»å„„å±‹æ†¶è‡†æ¡¶ç‰¡ä¹™ä¿ºå¸æ©æ¸©ç©éŸ³ä¸‹åŒ–仮何伽価佳加å¯å˜‰å¤å«å®¶å¯¡ç§‘暇果架歌河ç«ç‚ç¦ç¦¾ç¨¼ç®‡èŠ±è‹›èŒ„è·è¯è“è¦èª²å˜©è²¨è¿¦éŽéœžèšŠä¿„å³¨æˆ‘ç‰™ç”»è‡¥èŠ½è›¾è³€é›…é¤“é§•ä»‹ä¼šè§£å›žå¡Šå£Šå»»å¿«æ€ªæ‚”æ¢æ‡æˆ’æ‹æ”¹"], ["8a40","é­æ™¦æ¢°æµ·ç°ç•Œçš†çµµèŠ¥èŸ¹é–‹éšŽè²å‡±åŠ¾å¤–å’³å®³å´–æ…¨æ¦‚æ¶¯ç¢è“‹è¡—該鎧骸浬馨蛙垣柿蛎鈎劃嚇å„廓拡撹格核殻ç²ç¢ºç©«è¦šè§’赫較郭閣隔é©å­¦å²³æ¥½é¡é¡ŽæŽ›ç¬ æ¨«"], ["8a80","æ©¿æ¢¶é°æ½Ÿå‰²å–æ°æ‹¬æ´»æ¸‡æ»‘è‘›è¤è½„䏔鰹嶿¤›æ¨ºéž„株兜竃蒲釜鎌噛鴨栢茅è±ç²¥åˆˆè‹…ç“¦ä¹¾ä¾ƒå† å¯’åˆŠå‹˜å‹§å·»å–šå ªå§¦å®Œå®˜å¯›å¹²å¹¹æ‚£æ„Ÿæ…£æ†¾æ›æ•¢æŸ‘桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰è‚艦莞観諌貫還鑑間閑関陥韓館舘丸å«å²¸å·ŒçŽ©ç™Œçœ¼å²©ç¿«è´‹é›é ‘顔願ä¼ä¼Žå±å–œå™¨åŸºå¥‡å¬‰å¯„å²å¸Œå¹¾å¿Œæ®æœºæ——既期棋棄"], ["8b40","機帰毅気汽畿祈季稀紀徽è¦è¨˜è²´èµ·è»Œè¼é£¢é¨Žé¬¼äº€å½å„€å¦“宜戯技擬欺犠疑祇義蟻誼議掬èŠéž å‰åƒå–«æ¡”橘詰砧æµé»å´å®¢è„šè™é€†ä¸˜ä¹…仇休åŠå¸å®®å¼“急救"], ["8b80","朽求汲泣ç¸çƒç©¶çª®ç¬ˆç´šç³¾çµ¦æ—§ç‰›åŽ»å±…å·¨æ‹’æ‹ æŒ™æ¸ è™šè¨±è·é‹¸æ¼ç¦¦é­šäº¨äº«äº¬ä¾›ä¾ åƒ‘兇競共凶å”匡å¿å«å–¬å¢ƒå³¡å¼·å½Šæ€¯ææ­æŒŸæ•™æ©‹æ³ç‹‚狭矯胸脅興蕎郷é¡éŸ¿é¥—驚仰å‡å°­æšæ¥­å±€æ›²æ¥µçމæ¡ç²åƒ…勤å‡å·¾éŒ¦æ–¤æ¬£æ¬½ç´ç¦ç¦½ç­‹ç·ŠèйèŒè¡¿è¥Ÿè¬¹è¿‘金åŸéŠ€ä¹å€¶å¥åŒºç‹—玖矩苦躯駆駈駒具愚虞喰空å¶å¯“é‡éš…串櫛釧屑屈"], ["8c40","掘窟沓é´è½¡çªªç†Šéšˆç²‚æ —ç¹°æ¡‘é¬å‹²å›è–«è¨“群è»éƒ¡å¦è¢ˆç¥ä¿‚傾刑兄啓圭çªåž‹å¥‘å½¢å¾„æµæ…¶æ…§æ†©æŽ²æºæ•¬æ™¯æ¡‚渓畦稽系経継繋罫茎èŠè›è¨ˆè©£è­¦è»½é šé¶èŠ¸è¿Žé¯¨"], ["8c80","劇戟撃激隙æ¡å‚‘欠決潔穴çµè¡€è¨£æœˆä»¶å€¹å€¦å¥å…¼åˆ¸å‰£å–§åœå …å«Œå»ºæ†²æ‡¸æ‹³æ²æ¤œæ¨©ç‰½çŠ¬çŒ®ç ”ç¡¯çµ¹çœŒè‚©è¦‹è¬™è³¢è»’é£éµé™ºé¡•験鹸元原厳幻弦減æºçŽ„ç¾çµƒèˆ·è¨€è«ºé™ä¹Žå€‹å¤å‘¼å›ºå§‘孤己庫弧戸故枯湖ç‹ç³Šè¢´è‚¡èƒ¡è°è™Žèª‡è·¨éˆ·é›‡é¡§é¼“五互ä¼åˆå‘‰å¾å¨¯å¾Œå¾¡æ‚Ÿæ¢§æªŽç‘šç¢èªžèª¤è­·é†ä¹žé¯‰äº¤ä½¼ä¾¯å€™å€–光公功効勾厚å£å‘"], ["8d40","åŽå–‰å‘垢好孔å­å®å·¥å·§å··å¹¸åºƒåºšåº·å¼˜æ’æ…ŒæŠ—æ‹˜æŽ§æ”»æ˜‚æ™ƒæ›´æ­æ ¡æ¢—構江洪浩港æºç”²çš‡ç¡¬ç¨¿ç³ ç´…紘絞綱耕考肯肱腔è†èˆªè’行衡講貢購郊酵鉱砿鋼閤é™"], ["8d80","項香高鴻剛劫å·åˆå£•æ‹·æ¿ è±ªè½Ÿéº¹å…‹åˆ»å‘Šå›½ç©€é…·éµ é»’ç„æ¼‰è…°ç”‘忽惚骨狛込此頃今困å¤å¢¾å©šæ¨æ‡‡æ˜æ˜†æ ¹æ¢±æ··ç—•紺艮魂些ä½å‰å”†åµ¯å·¦å·®æŸ»æ²™ç‘³ç ‚è©éŽ–è£Ÿååº§æŒ«å‚µå‚¬å†æœ€å“‰å¡žå¦»å®°å½©æ‰æŽ¡æ ½æ­³æ¸ˆç½é‡‡çŠ€ç •ç ¦ç¥­æ–Žç´°èœè£è¼‰éš›å‰¤åœ¨æç½ªè²¡å†´å‚é˜ªå ºæ¦Šè‚´å’²å´ŽåŸ¼ç¢•é·ºä½œå‰Šå’‹æ¾æ˜¨æœ”柵窄策索錯桜鮭笹匙冊刷"], ["8e40","察拶撮擦札殺薩雑çšé¯–æŒéŒ†é®«çš¿æ™’三傘å‚山惨撒散桟燦çŠç”£ç®—çº‚èš•è®ƒè³›é…¸é¤æ–¬æš«æ®‹ä»•仔伺使刺å¸å²å—£å››å£«å§‹å§‰å§¿å­å±å¸‚å¸«å¿—æ€æŒ‡æ”¯å­œæ–¯æ–½æ—¨æžæ­¢"], ["8e80","æ­»æ°ç…祉ç§ç³¸ç´™ç´«è‚¢è„‚至視詞詩試誌諮資賜雌飼歯事似ä¾å…å­—å¯ºæ…ˆæŒæ™‚次滋治爾璽痔ç£ç¤ºè€Œè€³è‡ªè’”辞æ±é¹¿å¼è­˜é´«ç«ºè»¸å®é›«ä¸ƒå±åŸ·å¤±å«‰å®¤æ‚‰æ¹¿æ¼†ç–¾è³ªå®Ÿè”€ç¯ å²æŸ´èŠå±¡è•Šç¸žèˆŽå†™å°„æ¨èµ¦æ–œç…®ç¤¾ç´—者è¬è»Šé®è›‡é‚ªå€Ÿå‹ºå°ºæ“ç¼çˆµé…Œé‡ˆéŒ«è‹¥å¯‚弱惹主å–守手朱殊狩ç ç¨®è…«è¶£é…’首儒å—呪寿授樹綬需囚åŽå‘¨"], ["8f40","å®—å°±å·žä¿®æ„æ‹¾æ´²ç§€ç§‹çµ‚ç¹ç¿’臭舟è’衆襲è®è¹´è¼¯é€±é…‹é…¬é›†é†œä»€ä½å……åå¾“æˆŽæŸ”æ±æ¸‹ç£ç¸¦é‡éŠƒå”夙宿淑ç¥ç¸®ç²›å¡¾ç†Ÿå‡ºè¡“述俊峻春瞬竣舜駿准循旬楯殉淳"], ["8f80","準潤盾純巡éµé†‡é †å‡¦åˆæ‰€æš‘曙渚庶緒署書薯藷諸助å™å¥³åºå¾æ•鋤除傷償å‹åŒ å‡å¬å“¨å•†å”±å˜—奨妾娼宵将å°å°‘å°šåº„åºŠå» å½°æ‰¿æŠ„æ‹›æŽŒæ·æ˜‡æ˜Œæ˜­æ™¶æ¾æ¢¢æ¨Ÿæ¨µæ²¼æ¶ˆæ¸‰æ¹˜ç„¼ç„¦ç…§ç—‡çœç¡ç¤ç¥¥ç§°ç« ç¬‘粧紹肖è–蒋蕉è¡è£³è¨Ÿè¨¼è©”詳象賞醤鉦é¾é˜éšœéž˜ä¸Šä¸ˆä¸žä¹—å†—å‰°åŸŽå ´å£Œå¬¢å¸¸æƒ…æ“¾æ¡æ–浄状畳穣蒸譲醸錠嘱埴飾"], ["9040","æ‹­æ¤æ®–燭織è·è‰²è§¦é£Ÿè•辱尻伸信侵唇娠å¯å¯©å¿ƒæ…ŽæŒ¯æ–°æ™‹æ£®æ¦›æµ¸æ·±ç”³ç–¹çœŸç¥žç§¦ç´³è‡£èŠ¯è–ªè¦ªè¨ºèº«è¾›é€²é‡éœ‡äººä»åˆƒå¡µå£¬å°‹ç”šå°½è…Žè¨Šè¿…陣é­ç¬¥è«é ˆé…¢å›³åލ"], ["9080","逗å¹åž‚帥推水炊ç¡ç²‹ç¿ è¡°é‚é…”éŒéŒ˜éšç‘žé«„å´‡åµ©æ•°æž¢è¶¨é››æ®æ‰æ¤™è…é —é›€è£¾æ¾„æ‘ºå¯¸ä¸–ç€¬ç•æ˜¯å‡„åˆ¶å‹¢å§“å¾æ€§æˆæ”¿æ•´æ˜Ÿæ™´æ£²æ –正清牲生盛精è–声製西誠誓請é€é†’é’陿–‰ç¨Žè„†éš»å¸­æƒœæˆšæ–¥æ˜”æžçŸ³ç©ç±ç¸¾è„Šè²¬èµ¤è·¡è¹Ÿç¢©åˆ‡æ‹™æŽ¥æ‘‚折設窃節説雪絶舌è‰ä»™å…ˆåƒå å®£å°‚å°–å·æˆ¦æ‰‡æ’°æ “栴泉浅洗染潜煎煽旋穿箭線"], ["9140","繊羨腺舛船薦詮賎践é¸é·éŠ­éŠ‘é–ƒé®®å‰å–„漸然全禅繕膳糎噌塑岨措曾曽楚狙ç–疎礎祖租粗素組蘇訴阻é¡é¼ åƒ§å‰µåŒå¢å€‰å–ªå£®å¥çˆ½å®‹å±¤åŒæƒ£æƒ³æœæŽƒæŒ¿æŽ»"], ["9180","æ“æ—©æ›¹å·£æ§æ§½æ¼•燥争痩相窓糟ç·ç¶œè¡è‰è˜è‘¬è’¼è—»è£…èµ°é€é­éŽ—éœœé¨’åƒå¢—憎臓蔵贈造促å´å‰‡å³æ¯æ‰æŸæ¸¬è¶³é€Ÿä¿—属賊æ—ç¶šå’袖其æƒå­˜å­«å°Šææ‘éœä»–多太汰詑唾堕妥惰打æŸèˆµæ¥•陀駄騨体堆対è€å²±å¸¯å¾…怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代å°å¤§ç¬¬é†é¡Œé·¹æ»ç€§å“啄宅托択拓沢濯ç¢è¨—鏿¿è«¾èŒ¸å‡§è›¸åª"], ["9240","å©ä½†é”辰奪脱巽竪辿棚谷狸鱈樽誰丹å˜å˜†å¦æ‹…探旦歎淡湛炭短端箪綻耽胆蛋誕é›å›£å£‡å¼¾æ–­æš–æª€æ®µç”·è«‡å€¤çŸ¥åœ°å¼›æ¥æ™ºæ± ç—´ç¨šç½®è‡´èœ˜é…馳築畜竹筑蓄"], ["9280","é€ç§©çª’茶嫡ç€ä¸­ä»²å®™å¿ æŠ½æ˜¼æŸ±æ³¨è™«è¡·è¨»é…Žé‹³é§æ¨—瀦猪苧著貯ä¸å…†å‡‹å–‹å¯µå¸–帳åºå¼”å¼µå½«å¾´æ‡²æŒ‘æš¢æœæ½®ç‰’町眺è´è„¹è…¸è¶èª¿è«œè¶…跳銚長頂鳥勅æ—直朕沈çè³ƒéŽ®é™³æ´¥å¢œæ¤Žæ§Œè¿½éŽšç—›é€šå¡šæ ‚æŽ´æ§»ä½ƒæ¼¬æŸ˜è¾»è”¦ç¶´é”æ¤¿æ½°åªå£·å¬¬ç´¬çˆªåŠé‡£é¶´äº­ä½Žåœåµå‰ƒè²žå‘ˆå ¤å®šå¸åº•åº­å»·å¼Ÿæ‚ŒæŠµæŒºææ¢¯æ±€ç¢‡ç¦Žç¨‹ç· è‰‡è¨‚諦蹄逓"], ["9340","邸鄭釘鼎泥摘擢敵滴的笛é©é‘溺哲徹撤è½è¿­é‰„典填天展店添çºç”œè²¼è»¢é¡›ç‚¹ä¼æ®¿æ¾±ç”°é›»å…Žåå µå¡—å¦¬å± å¾’æ–—æœæ¸¡ç™»èŸè³­é€”都é砥砺努度土奴怒倒党冬"], ["9380","å‡åˆ€å”å¡”å¡˜å¥—å®•å³¶å¶‹æ‚¼æŠ•æ­æ±æ¡ƒæ¢¼æ£Ÿç›—淘湯涛ç¯ç‡ˆå½“痘祷等答筒糖統到董蕩藤討謄豆è¸é€ƒé€é™é™¶é ­é¨°é—˜åƒå‹•åŒå ‚導憧撞洞瞳童胴è„é“銅峠鴇匿得徳涜特ç£ç¦¿ç¯¤æ¯’ç‹¬èª­æ ƒæ©¡å‡¸çªæ¤´å±Šé³¶è‹«å¯…酉瀞噸屯惇敦沌豚é頓呑曇éˆå¥ˆé‚£å†…ä¹å‡ªè–™è¬Žç˜æºé‹æ¥¢é¦´ç¸„ç•·å—æ¥ è»Ÿé›£æ±äºŒå°¼å¼è¿©åŒ‚賑肉虹廿日乳入"], ["9440","如尿韮任妊å¿èªæ¿¡ç¦°ç¥¢å¯§è‘±çŒ«ç†±å¹´å¿µæ»æ’šç‡ƒç²˜ä¹ƒå»¼ä¹‹åŸœå𢿂©æ¿ƒç´èƒ½è„³è†¿è¾²è¦—èš¤å·´æŠŠæ’­è¦‡æ·æ³¢æ´¾ç¶ç ´å©†ç½µèŠ­é¦¬ä¿³å»ƒæ‹æŽ’æ•—æ¯ç›ƒç‰ŒèƒŒè‚ºè¼©é…å€åŸ¹åª’梅"], ["9480","楳煤狽買売賠陪這è¿ç§¤çŸ§è©ä¼¯å‰¥å𿋿Ÿæ³Šç™½ç®”ç²•èˆ¶è–„è¿«æ›æ¼ çˆ†ç¸›èŽ«é§éº¦å‡½ç®±ç¡²ç®¸è‚‡ç­ˆæ«¨å¹¡è‚Œç•‘畠八鉢溌発醗髪ä¼ç½°æŠœç­é–¥é³©å™ºå¡™è›¤éš¼ä¼´åˆ¤åŠåå›å¸†æ¬æ–‘æ¿æ°¾æ±Žç‰ˆçНç­ç•”ç¹èˆ¬è—©è²©ç¯„釆煩頒飯挽晩番盤ç£è•ƒè›®åŒªå‘å¦å¦ƒåº‡å½¼æ‚²æ‰‰æ‰¹æŠ«æ–比泌疲皮碑秘緋罷肥被誹費é¿éžé£›æ¨‹ç°¸å‚™å°¾å¾®æž‡æ¯˜çµçœ‰ç¾Ž"], ["9540","鼻柊稗匹疋髭彦è†è±è‚˜å¼¼å¿…畢筆逼桧姫媛ç´ç™¾è¬¬ä¿µå½ªæ¨™æ°·æ¼‚瓢票表評豹廟æç—…秒苗錨鋲蒜蛭鰭å“彬斌浜瀕貧賓頻æ•ç“¶ä¸ä»˜åŸ å¤«å©¦å¯Œå†¨å¸ƒåºœæ€–扶敷"], ["9580","斧普浮父符è…è†šèŠ™è­œè² è³¦èµ´é˜œé™„ä¾®æ’«æ­¦èˆžè‘¡è•ªéƒ¨å°æ¥“風葺蕗ä¼å‰¯å¾©å¹…æœç¦è…¹è¤‡è¦†æ·µå¼—払沸ä»ç‰©é®’分å»å™´å¢³æ†¤æ‰®ç„šå¥®ç²‰ç³žç´›é›°æ–‡èžä¸™ä½µå…µå¡€å¹£å¹³å¼ŠæŸ„並蔽閉陛米é åƒ»å£ç™–碧別瞥蔑箆å変片篇編辺返é便勉娩å¼éž­ä¿èˆ—é‹ªåœƒæ•æ­©ç”«è£œè¼”穂募墓慕戊暮æ¯ç°¿è©å€£ä¿¸åŒ…呆報奉å®å³°å³¯å´©åº–æŠ±æ§æ”¾æ–¹æœ‹"], ["9640","法泡烹砲縫胞芳èŒè“¬èœ‚褒訪豊邦鋒飽鳳鵬ä¹äº¡å‚剖åŠå¦¨å¸½å¿˜å¿™æˆ¿æš´æœ›æŸæ£’冒紡肪膨謀貌貿鉾防å é ¬åŒ—僕åœå¢¨æ’²æœ´ç‰§ç¦ç©†é‡¦å‹ƒæ²¡æ®†å €å¹Œå¥”本翻凡盆"], ["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒æ¡äº¦ä¿£åˆæŠ¹æœ«æ²«è¿„ä¾­ç¹­éº¿ä¸‡æ…¢æº€æ¼«è”“å‘³æœªé­…å·³ç®•å²¬å¯†èœœæ¹Šè“‘ç¨”è„ˆå¦™ç²æ°‘眠務夢無牟矛霧鵡椋婿娘冥åå‘½æ˜Žç›Ÿè¿·éŠ˜é³´å§ªç‰æ»…å…æ£‰ç¶¿ç·¬é¢éººæ‘¸æ¨¡èŒ‚妄孟毛猛盲網耗蒙儲木黙目æ¢å‹¿é¤…å°¤æˆ»ç±¾è²°å•æ‚¶ç´‹é–€åŒä¹Ÿå†¶å¤œçˆºè€¶é‡Žå¼¥çŸ¢åŽ„å½¹ç´„è–¬è¨³èºé–柳薮鑓愉愈油癒"], ["9740","諭輸唯佑優勇å‹å®¥å¹½æ‚ æ†‚æ–æœ‰æŸšæ¹§æ¶ŒçŒ¶çŒ·ç”±ç¥è£•誘éŠé‚‘郵雄èžå¤•予余与誉輿é å‚­å¹¼å¦–å®¹åº¸æšæºæ“曜楊様洋溶熔用窯羊耀葉蓉è¦è¬¡è¸Šé¥é™½é¤Šæ…¾æŠ‘欲"], ["9780","沃浴翌翼淀羅螺裸æ¥èŽ±é ¼é›·æ´›çµ¡è½é…ªä¹±åµåµæ¬„æ¿«è—蘭覧利åå±¥æŽæ¢¨ç†ç’ƒç—¢è£è£¡é‡Œé›¢é™¸å¾‹çŽ‡ç«‹è‘ŽæŽ ç•¥åŠ‰æµæºœç‰ç•™ç¡«ç²’隆竜é¾ä¾¶æ…®æ—…è™œäº†äº®åƒšä¸¡å‡Œå¯®æ–™æ¢æ¶¼çŒŸç™‚瞭稜糧良諒é¼é‡é™µé ˜åŠ›ç·‘å€«åŽ˜æž—æ·‹ç‡ç³è‡¨è¼ªéš£é±—éºŸç‘ å¡æ¶™ç´¯é¡žä»¤ä¼¶ä¾‹å†·åŠ±å¶ºæ€œçŽ²ç¤¼è‹“éˆ´éš·é›¶éœŠéº—é½¢æš¦æ­´åˆ—åŠ£çƒˆè£‚å»‰æ‹æ†æ¼£ç…‰ç°¾ç·´è¯"], ["9840","蓮連錬呂魯櫓炉賂路露労å©å»Šå¼„朗楼榔浪æ¼ç‰¢ç‹¼ç¯­è€è¾è‹éƒŽå…­éº“禄肋録論倭和話歪賄脇惑枠鷲亙亘é°è©«è—蕨椀湾碗腕"], ["989f","弌ä¸ä¸•个丱丶丼丿乂乖乘亂亅豫亊舒å¼äºŽäºžäºŸäº äº¢äº°äº³äº¶ä»Žä»ä»„仆仂仗仞仭仟价伉佚估佛ä½ä½—佇佶侈ä¾ä¾˜ä½»ä½©ä½°ä¾‘佯來侖儘俔俟俎俘俛俑俚ä¿ä¿¤ä¿¥å€šå€¨å€”倪倥倅伜俶倡倩倬俾俯們倆åƒå‡æœƒå•ååˆåšå–å¬å¸å‚€å‚šå‚…傴傲"], ["9940","僉僊傳僂僖僞僥僭僣僮價僵儉å„儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉å†å†‘冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], ["9980","凰凵凾刄刋刔刎刧刪刮刳刹å‰å‰„剋剌剞剔剪剴剩剳剿剽åŠåŠ”åŠ’å‰±åŠˆåŠ‘è¾¨è¾§åŠ¬åŠ­åŠ¼åŠµå‹å‹å‹—勞勣勦飭勠勳勵勸勹匆匈甸åŒåŒåŒåŒ•匚匣匯匱匳匸å€å†å…丗å‰å凖åžå©å®å¤˜å»å·åŽ‚åŽ–åŽ åŽ¦åŽ¥åŽ®åŽ°åŽ¶åƒç°’é›™åŸæ›¼ç‡®å®å¨å­åºåå½å‘€å¬å­å¼å®å¶å©å呎å’呵咎呟呱呷呰咒呻咀呶咄å’咆哇咢咸咥咬哄哈咨"], ["9a40","咫哂咤咾咼哘哥哦å”唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳å•喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎å™ç‡Ÿå˜´å˜¶å˜²å˜¸"], ["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔åšåš¥åš®åš¶åš´å›‚åš¼å›å›ƒå›€å›ˆå›Žå›‘囓囗囮囹圀囿圄圉圈國åœåœ“團圖嗇圜圦圷圸åŽåœ»å€åå©åŸ€åžˆå¡å¿åž‰åž“垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙å å¡²å ¡å¡¢å¡‹å¡°æ¯€å¡’堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊å¤å¤›æ¢¦å¤¥å¤¬å¤­å¤²å¤¸å¤¾ç«’奕å¥å¥Žå¥šå¥˜å¥¢å¥ å¥§å¥¬å¥©"], ["9b40","奸å¦å¦ä½žä¾«å¦£å¦²å§†å§¨å§œå¦å§™å§šå¨¥å¨Ÿå¨‘娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲å«å¬ªå¬¶å¬¾å­ƒå­…孀孑孕孚孛孥孩孰孳孵學斈孺宀"], ["9b80","它宦宸寃寇寉寔å¯å¯¤å¯¦å¯¢å¯žå¯¥å¯«å¯°å¯¶å¯³å°…將專å°å°“尠尢尨尸尹å±å±†å±Žå±“å±å±å­±å±¬å±®ä¹¢å±¶å±¹å²Œå²‘岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢å¶å¶¬å¶®å¶½å¶å¶·å¶¼å·‰å·å·“巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠å»å»‚廈å»å»"], ["9c40","廖廣å»å»šå»›å»¢å»¡å»¨å»©å»¬å»±å»³å»°å»´å»¸å»¾å¼ƒå¼‰å½å½œå¼‹å¼‘弖弩弭弸å½å½ˆå½Œå½Žå¼¯å½‘å½–å½—å½™å½¡å½­å½³å½·å¾ƒå¾‚å½¿å¾Šå¾ˆå¾‘å¾‡å¾žå¾™å¾˜å¾ å¾¨å¾­å¾¼å¿–å¿»å¿¤å¿¸å¿±å¿æ‚³å¿¿æ€¡æ "], ["9c80","æ€™æ€æ€©æ€Žæ€±æ€›æ€•æ€«æ€¦æ€æ€ºæšææªæ·æŸæŠæ†ææ£æƒæ¤æ‚æ¬æ«æ™æ‚æ‚æƒ§æ‚ƒæ‚šæ‚„æ‚›æ‚–æ‚—æ‚’æ‚§æ‚‹æƒ¡æ‚¸æƒ æƒ“æ‚´å¿°æ‚½æƒ†æ‚µæƒ˜æ…æ„•æ„†æƒ¶æƒ·æ„€æƒ´æƒºæ„ƒæ„¡æƒ»æƒ±æ„æ„Žæ…‡æ„¾æ„¨æ„§æ…Šæ„¿æ„¼æ„¬æ„´æ„½æ…‚æ…„æ…³æ…·æ…˜æ…™æ…šæ…«æ…´æ…¯æ…¥æ…±æ…Ÿæ…æ…“æ…µæ†™æ†–æ†‡æ†¬æ†”æ†šæ†Šæ†‘æ†«æ†®æ‡Œæ‡Šæ‡‰æ‡·æ‡ˆæ‡ƒæ‡†æ†ºæ‡‹ç½¹æ‡æ‡¦æ‡£æ‡¶æ‡ºæ‡´æ‡¿æ‡½æ‡¼æ‡¾æˆ€æˆˆæˆ‰æˆæˆŒæˆ”戛"], ["9d40","æˆžæˆ¡æˆªæˆ®æˆ°æˆ²æˆ³æ‰æ‰Žæ‰žæ‰£æ‰›æ‰ æ‰¨æ‰¼æŠ‚æŠ‰æ‰¾æŠ’æŠ“æŠ–æ‹”æŠƒæŠ”æ‹—æ‹‘æŠ»æ‹æ‹¿æ‹†æ“”æ‹ˆæ‹œæ‹Œæ‹Šæ‹‚æ‹‡æŠ›æ‹‰æŒŒæ‹®æ‹±æŒ§æŒ‚æŒˆæ‹¯æ‹µææŒ¾ææœææŽ–æŽŽæŽ€æŽ«æ¶æŽ£æŽæŽ‰æŽŸæŽµæ«"], ["9d80","æ©æŽ¾æ©æ€æ†æ£æ‰æ’æ¶æ„æ–æ´æ†æ“æ¦æ¶æ”æ—æ¨ææ‘§æ‘¯æ‘¶æ‘Žæ”ªæ’•æ’“æ’¥æ’©æ’ˆæ’¼æ“šæ“’æ“…æ“‡æ’»æ“˜æ“‚æ“±æ“§èˆ‰æ“ æ“¡æŠ¬æ“£æ“¯æ”¬æ“¶æ“´æ“²æ“ºæ”€æ“½æ”˜æ”œæ”…æ”¤æ”£æ”«æ”´æ”µæ”·æ”¶æ”¸ç•‹æ•ˆæ•–æ••æ•æ•˜æ•žæ•æ•²æ•¸æ–‚æ–ƒè®Šæ–›æ–Ÿæ–«æ–·æ—ƒæ—†æ—æ—„æ—Œæ—’æ—›æ—™æ— æ—¡æ—±æ²æ˜Šæ˜ƒæ—»æ³æ˜µæ˜¶æ˜´æ˜œæ™æ™„æ™‰æ™æ™žæ™æ™¤æ™§æ™¨æ™Ÿæ™¢æ™°æšƒæšˆæšŽæš‰æš„æš˜æšæ›æš¹æ›‰æš¾æš¼"], ["9e40","æ›„æš¸æ›–æ›šæ› æ˜¿æ›¦æ›©æ›°æ›µæ›·æœæœ–æœžæœ¦æœ§éœ¸æœ®æœ¿æœ¶ææœ¸æœ·æ†æžæ æ™æ£æ¤æž‰æ°æž©æ¼æªæžŒæž‹æž¦æž¡æž…æž·æŸ¯æž´æŸ¬æž³æŸ©æž¸æŸ¤æŸžæŸæŸ¢æŸ®æž¹æŸŽæŸ†æŸ§æªœæ žæ¡†æ ©æ¡€æ¡æ ²æ¡Ž"], ["9e80","æ¢³æ «æ¡™æ¡£æ¡·æ¡¿æ¢Ÿæ¢æ¢­æ¢”æ¢æ¢›æ¢ƒæª®æ¢¹æ¡´æ¢µæ¢ æ¢ºæ¤æ¢æ¡¾æ¤æ£Šæ¤ˆæ£˜æ¤¢æ¤¦æ£¡æ¤Œæ£æ£”æ£§æ£•æ¤¶æ¤’æ¤„æ£—æ££æ¤¥æ£¹æ£ æ£¯æ¤¨æ¤ªæ¤šæ¤£æ¤¡æ£†æ¥¹æ¥·æ¥œæ¥¸æ¥«æ¥”æ¥¾æ¥®æ¤¹æ¥´æ¤½æ¥™æ¤°æ¥¡æ¥žæ¥æ¦æ¥ªæ¦²æ¦®æ§æ¦¿æ§æ§“æ¦¾æ§Žå¯¨æ§Šæ§æ¦»æ§ƒæ¦§æ¨®æ¦‘æ¦ æ¦œæ¦•æ¦´æ§žæ§¨æ¨‚æ¨›æ§¿æ¬Šæ§¹æ§²æ§§æ¨…æ¦±æ¨žæ§­æ¨”æ§«æ¨Šæ¨’æ«æ¨£æ¨“æ©„æ¨Œæ©²æ¨¶æ©¸æ©‡æ©¢æ©™æ©¦æ©ˆæ¨¸æ¨¢æªæªæª æª„檢檣"], ["9f40","æª—è˜—æª»æ«ƒæ«‚æª¸æª³æª¬æ«žæ«‘æ«Ÿæªªæ«šæ«ªæ«»æ¬…è˜–æ«ºæ¬’æ¬–é¬±æ¬Ÿæ¬¸æ¬·ç›œæ¬¹é£®æ­‡æ­ƒæ­‰æ­æ­™æ­”æ­›æ­Ÿæ­¡æ­¸æ­¹æ­¿æ®€æ®„æ®ƒæ®æ®˜æ®•殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], ["9f80","éº¾æ°ˆæ°“æ°”æ°›æ°¤æ°£æ±žæ±•æ±¢æ±ªæ²‚æ²æ²šæ²æ²›æ±¾æ±¨æ±³æ²’æ²æ³„æ³±æ³“æ²½æ³—æ³…æ³æ²®æ²±æ²¾æ²ºæ³›æ³¯æ³™æ³ªæ´Ÿè¡æ´¶æ´«æ´½æ´¸æ´™æ´µæ´³æ´’æ´Œæµ£æ¶“æµ¤æµšæµ¹æµ™æ¶Žæ¶•æ¿¤æ¶…æ·¹æ¸•æ¸Šæ¶µæ·‡æ·¦æ¶¸æ·†æ·¬æ·žæ·Œæ·¨æ·’æ·…æ·ºæ·™æ·¤æ·•æ·ªæ·®æ¸­æ¹®æ¸®æ¸™æ¹²æ¹Ÿæ¸¾æ¸£æ¹«æ¸«æ¹¶æ¹æ¸Ÿæ¹ƒæ¸ºæ¹Žæ¸¤æ»¿æ¸æ¸¸æº‚æºªæº˜æ»‰æº·æ»“æº½æº¯æ»„æº²æ»”æ»•æºæº¥æ»‚æºŸæ½æ¼‘çŒæ»¬æ»¸æ»¾æ¼¿æ»²æ¼±æ»¯æ¼²æ»Œ"], ["e040","æ¼¾æ¼“æ»·æ¾†æ½ºæ½¸æ¾æ¾€æ½¯æ½›æ¿³æ½­æ¾‚潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑ç€ç€æ¿¾ç€›ç€šæ½´ç€ç€˜ç€Ÿç€°ç€¾ç€²ç‘ç£ç‚™ç‚’炯烱炬炸炳炮烟烋çƒ"], ["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬ç†ç‡»ç†„熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿çˆçˆçˆ›çˆ¨çˆ­çˆ¬çˆ°çˆ²çˆ»çˆ¼çˆ¿ç‰€ç‰†ç‰‹ç‰˜ç‰´ç‰¾çŠ‚çŠçŠ‡çŠ’çŠ–çŠ¢çŠ§çŠ¹çŠ²ç‹ƒç‹†ç‹„ç‹Žç‹’ç‹¢ç‹ ç‹¡ç‹¹ç‹·å€çŒ—猊猜猖çŒçŒ´çŒ¯çŒ©çŒ¥çŒ¾çŽç默ç—çªç¨ç°ç¸çµç»çºçˆç޳çŽçŽ»ç€ç¥ç®çžç’¢ç…瑯ç¥ç¸ç²çºç‘•ç¿ç‘Ÿç‘™ç‘瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊ç“ç“”ç±"], ["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎ç”甕甓甞甦甬甼畄ç•畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚ç–疥疣痂疳痃疵疽疸疼疱ç—痊痒痙痣痞痾痿"], ["e180","ç—¼ç˜ç—°ç—ºç—²ç—³ç˜‹ç˜ç˜‰ç˜Ÿç˜§ç˜ ç˜¡ç˜¢ç˜¤ç˜´ç˜°ç˜»ç™‡ç™ˆç™†ç™œç™˜ç™¡ç™¢ç™¨ç™©ç™ªç™§ç™¬ç™°ç™²ç™¶ç™¸ç™¼çš€çšƒçšˆçš‹çšŽçš–皓皙皚皰皴皸皹皺盂ç›ç›–盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸ç‡çšç¨ç«ç›ç¥ç¿ç¾ç¹çžŽçž‹çž‘瞠瞞瞰瞶瞹瞿瞼瞽瞻矇çŸçŸ—矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], ["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊ç¦ç¦§é½‹ç¦ªç¦®ç¦³ç¦¹ç¦ºç§‰ç§•秧秬秡秣稈ç¨ç¨˜ç¨™ç¨ ç¨Ÿç¦€ç¨±ç¨»ç¨¾ç¨·ç©ƒç©—穉穡穢穩é¾ç©°ç©¹ç©½çªˆçª—窕窘窖窩竈窰"], ["e280","窶竅竄窿邃竇竊ç«ç«ç«•竓站竚ç«ç«¡ç«¢ç«¦ç«­ç«°ç¬‚ç¬ç¬Šç¬†ç¬³ç¬˜ç¬™ç¬žç¬µç¬¨ç¬¶ç­ç­ºç¬„ç­ç¬‹ç­Œç­…筵筥筴筧筰筱筬筮ç®ç®˜ç®Ÿç®ç®œç®šç®‹ç®’ç®ç­ç®™ç¯‹ç¯ç¯Œç¯ç®´ç¯†ç¯ç¯©ç°‘簔篦篥籠簀簇簓篳篷簗ç°ç¯¶ç°£ç°§ç°ªç°Ÿç°·ç°«ç°½ç±Œç±ƒç±”ç±ç±€ç±ç±˜ç±Ÿç±¤ç±–籥籬籵粃ç²ç²¤ç²­ç²¢ç²«ç²¡ç²¨ç²³ç²²ç²±ç²®ç²¹ç²½ç³€ç³…糂糘糒糜糢鬻糯糲糴糶糺紆"], ["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮çµçµ£ç¶“綉絛ç¶çµ½ç¶›ç¶ºç¶®ç¶£ç¶µç·‡ç¶½ç¶«ç¸½ç¶¢ç¶¯ç·œç¶¸ç¶Ÿç¶°ç·˜ç·ç·¤ç·žç·»ç·²ç·¡ç¸…縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], ["e380","縲縺繧ç¹ç¹–繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒çºçº“纔纖纎纛纜缸缺罅罌ç½ç½Žç½ç½‘罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞ç¾ç¾šç¾£ç¾¯ç¾²ç¾¹ç¾®ç¾¶ç¾¸è­±ç¿…翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻èŠè†è’è˜èšèŸè¢è¨è³è²è°è¶è¹è½è¿è‚„肆肅肛肓肚肭å†è‚¬èƒ›èƒ¥èƒ™èƒèƒ„胚胖脉胯胱脛脩脣脯腋"], ["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉è‡è‡‘臙臘臈臚臟臠臧臺臻臾èˆèˆ‚舅與舊èˆèˆèˆ–舩舫舸舳艀艙艘è‰è‰šè‰Ÿè‰¤"], ["e480","艢艨艪艫舮艱艷艸艾èŠèŠ’èŠ«èŠŸèŠ»èŠ¬è‹¡è‹£è‹Ÿè‹’è‹´è‹³è‹ºèŽ“èŒƒè‹»è‹¹è‹žèŒ†è‹œèŒ‰è‹™èŒµèŒ´èŒ–èŒ²èŒ±è€èŒ¹èè…茯茫茗茘莅莚莪莟莢莖茣莎莇莊è¼è޵è³èµèŽ èŽ‰èŽ¨è´è“è«èŽè½èƒè˜è‹èè·è‡è è²èè¢è è޽è¸è”†è»è‘­èªè¼è•šè’„葷葫蒭葮蒂葩葆è¬è‘¯è‘¹èµè“Šè‘¢è’¹è’¿è’Ÿè“™è“蒻蓚è“è“蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], ["e540","è•蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾è–藉薺è—è–¹è—è—•è—藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿è™ä¹•虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], ["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉èœè›¹èœŠèœ´èœ¿èœ·èœ»èœ¥èœ©èœšè èŸè¸èŒèŽè´è—è¨è®è™è“è£èªè …螢螟螂螯蟋螽蟀èŸé›–螫蟄螳蟇蟆螻蟯蟲蟠è è èŸ¾èŸ¶èŸ·è ŽèŸ’蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫è¢è¡¾è¢žè¡µè¡½è¢µè¡²è¢‚袗袒袮袙袢è¢è¢¤è¢°è¢¿è¢±è£ƒè£„裔裘裙è£è£¹è¤‚裼裴裨裲褄褌褊褓襃褞褥褪褫è¥è¥„褻褶褸襌è¤è¥ è¥ž"], ["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜è§è§§è§´è§¸è¨ƒè¨–è¨è¨Œè¨›è¨è¨¥è¨¶è©è©›è©’詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄è«è«‚諚諫諳諧"], ["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖è¬è¬—謠謳鞫謦謫謾謨è­è­Œè­è­Žè­‰è­–譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺è±è°¿è±ˆè±Œè±Žè±è±•豢豬豸豺貂貉貅貊è²è²Žè²”豼貘æˆè²­è²ªè²½è²²è²³è²®è²¶è³ˆè³è³¤è³£è³šè³½è³ºè³»è´„è´…è´Šè´‡è´è´è´é½Žè´“è³è´”贖赧赭赱赳è¶è¶™è·‚趾趺è·è·šè·–跌跛跋跪跫跟跣跼踈踉跿è¸è¸žè¸è¸Ÿè¹‚踵踰踴蹊"], ["e740","蹇蹉蹌è¹è¹ˆè¹™è¹¤è¹ è¸ªè¹£è¹•蹶蹲蹼èºèº‡èº…躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], ["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡é€é€žé€–逋逧逶逵逹迸ééé‘é’逎é‰é€¾é–é˜éžé¨é¯é¶éš¨é²é‚‚é½é‚邀邊邉é‚邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀é‡é‡‰é‡‹é‡é‡–釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋é‰éŠœéŠ–éŠ“éŠ›é‰šé‹éŠ¹éŠ·é‹©éŒé‹ºé„錮"], ["e840","錙錢錚錣錺錵錻éœé é¼é®é–鎰鎬鎭鎔鎹é–é—é¨é¥é˜éƒéééˆé¤éšé”é“éƒé‡éé¶é«éµé¡éºé‘鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾é’鑿閂閇閊閔閖閘閙"], ["e880","閠閨閧閭閼閻閹閾闊濶闃é—闌闕闔闖關闡闥闢阡阨阮阯陂陌é™é™‹é™·é™œé™žé™é™Ÿé™¦é™²é™¬éšéš˜éš•隗險隧隱隲隰隴隶隸隹雎雋雉é›è¥é›œéœé›•雹霄霆霈霓霎霑éœéœ–霙霤霪霰霹霽霾é„é†éˆé‚é‰éœé é¤é¦é¨å‹’é«é±é¹éž…é¼éžéºéž†éž‹éžéžéžœéž¨éž¦éž£éž³éž´éŸƒéŸ†éŸˆéŸ‹éŸœéŸ­é½éŸ²ç«ŸéŸ¶éŸµé é Œé ¸é ¤é ¡é ·é ½é¡†é¡é¡‹é¡«é¡¯é¡°"], ["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡é¤é¤žé¤¤é¤ é¤¬é¤®é¤½é¤¾é¥‚饉饅é¥é¥‹é¥‘饒饌饕馗馘馥馭馮馼駟駛é§é§˜é§‘駭駮駱駲駻駸é¨é¨é¨…駢騙騫騷驅驂驀驃"], ["e980","騾驕é©é©›é©—驟驢驥驤驩驫驪骭骰骼髀é«é«‘髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃é­é­é­Žé­‘魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆é¯é¯‘鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒éµé´¿é´¾éµ†éµˆ"], ["ea40","éµéµžéµ¤éµ‘éµéµ™éµ²é¶‰é¶‡é¶«éµ¯éµºé¶šé¶¤é¶©é¶²é·„é·é¶»é¶¸é¶ºé·†é·é·‚鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽éºéºˆéº‹éºŒéº’麕麑éºéº¥éº©éº¸éºªéº­é¡é»Œé»Žé»é»é»”黜點é»é» é»¥é»¨é»¯"], ["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇é™ç‘¤å‡œç†™"], ["ed40","纊褜éˆéŠˆè“œä¿‰ç‚»æ˜±æ£ˆé‹¹æ›»å½…ä¸¨ä»¡ä»¼ä¼€ä¼ƒä¼¹ä½–ä¾’ä¾Šä¾šä¾”ä¿å€å€¢ä¿¿å€žå†å°å‚傔僴僘兊兤å†å†¾å‡¬åˆ•劜劦勀勛匀匇匤å²åŽ“åŽ²å﨎咜咊咩哿喆å™å¥åž¬åŸˆåŸ‡ï¨"], ["ed80","ï¨å¢žå¢²å¤‹å¥“奛å¥å¥£å¦¤å¦ºå­–寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹å·å¼¡å¼´å½§å¾·å¿žææ‚…æ‚Šæƒžæƒ•æ„ æƒ²æ„‘æ„·æ„°æ†˜æˆ“æŠ¦æµæ‘ æ’æ“Žæ•Žæ˜€æ˜•æ˜»æ˜‰æ˜®æ˜žæ˜¤æ™¥æ™—æ™™ï¨’æ™³æš™æš æš²æš¿æ›ºæœŽï¤©æ¦æž»æ¡’æŸ€æ æ¡„æ£ï¨“æ¥¨ï¨”æ¦˜æ§¢æ¨°æ©«æ©†æ©³æ©¾æ«¢æ«¤æ¯–æ°¿æ±œæ²†æ±¯æ³šæ´„æ¶‡æµ¯æ¶–æ¶¬æ·æ·¸æ·²æ·¼æ¸¹æ¹œæ¸§æ¸¼æº¿æ¾ˆæ¾µæ¿µç€…瀇瀨炅炫ç„焄煜煆煇凞ç‡ç‡¾çб"], ["ee40","犾猤猪ç·ç޽ç‰ç–ç£ç’ç‡çµç¦çªç©ç®ç‘¢ç’‰ç’Ÿç”畯皂皜皞皛皦益ç†åŠ¯ç ¡ç¡Žç¡¤ç¡ºç¤°ï¨˜ï¨™ï¨šç¦”ï¨›ç¦›ç«‘ç«§ï¨œç««ç®žï¨çµˆçµœç¶·ç¶ ç·–繒罇羡羽èŒè¢è¿è‡è¶è‘ˆè’´è•“è•™"], ["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣è»ï¨¤ï¨¥é§éƒžï¨¦é„•鄧釚釗釞釭釮釤釥鈆éˆéˆŠéˆºé‰€éˆ¼é‰Žé‰™é‰‘鈹鉧銧鉷鉸鋧鋗鋙é‹ï¨§é‹•鋠鋓錥錡鋻﨨錞鋿éŒéŒ‚é°é—鎤é†éžé¸é±é‘…鑈閒隆﨩éšéš¯éœ³éœ»éƒééé‘é•顗顥飯飼餧館馞驎髙髜魵魲é®é®±é®»é°€éµ°éµ«ï¨­é¸™é»‘"], ["eeef","â…°",9,"¬¦'""], ["f040","",62], ["f080","",124], ["f140","",62], ["f180","",124], ["f240","î…¸",62], ["f280","",124], ["f340","",62], ["f380","",124], ["f440","î‹°",62], ["f480","",124], ["f540","",62], ["f580","î«",124], ["f640","",62], ["f680","î’§",124], ["f740","",62], ["f780","î•£",124], ["f840","î— ",62], ["f880","",124], ["f940","îšœ"], ["fa40","â…°",9,"â… ",9,"¬¦'"㈱№℡∵纊褜éˆéŠˆè“œä¿‰ç‚»æ˜±æ£ˆé‹¹æ›»å½…ä¸¨ä»¡ä»¼ä¼€ä¼ƒä¼¹ä½–ä¾’ä¾Šä¾šä¾”ä¿å€å€¢ä¿¿å€žå†å°å‚傔僴僘兊"], ["fa80","å…¤å†å†¾å‡¬åˆ•劜劦勀勛匀匇匤å²åŽ“åŽ²å﨎咜咊咩哿喆å™å¥åž¬åŸˆåŸ‡ï¨ï¨å¢žå¢²å¤‹å¥“奛å¥å¥£å¦¤å¦ºå­–寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹å·å¼¡å¼´å½§å¾·å¿žææ‚…æ‚Šæƒžæƒ•æ„ æƒ²æ„‘æ„·æ„°æ†˜æˆ“æŠ¦æµæ‘ æ’æ“Žæ•Žæ˜€æ˜•æ˜»æ˜‰æ˜®æ˜žæ˜¤æ™¥æ™—æ™™ï¨’æ™³æš™æš æš²æš¿æ›ºæœŽï¤©æ¦æž»æ¡’æŸ€æ æ¡„æ£ï¨“楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], ["fb40","æ¶–æ¶¬æ·æ·¸æ·²æ·¼æ¸¹æ¹œæ¸§æ¸¼æº¿æ¾ˆæ¾µæ¿µç€…瀇瀨炅炫ç„焄煜煆煇凞ç‡ç‡¾çŠ±çŠ¾çŒ¤ï¨–ç·ç޽ç‰ç–ç£ç’ç‡çµç¦çªç©ç®ç‘¢ç’‰ç’Ÿç”畯皂皜皞皛皦益ç†åŠ¯ç ¡ç¡Žç¡¤ç¡ºç¤°ï¨˜ï¨™"], ["fb80","祥禔福禛竑竧靖竫箞ï¨çµˆçµœç¶·ç¶ ç·–繒罇羡羽èŒè¢è¿è‡è¶è‘ˆè’´è•“蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣è»ï¨¤ï¨¥é§éƒžï¨¦é„•鄧釚釗釞釭釮釤釥鈆éˆéˆŠéˆºé‰€éˆ¼é‰Žé‰™é‰‘鈹鉧銧鉷鉸鋧鋗鋙é‹ï¨§é‹•鋠鋓錥錡鋻﨨錞鋿éŒéŒ‚é°é—鎤é†éžé¸é±é‘…鑈閒隆﨩éšéš¯éœ³éœ»éƒééé‘é•顗顥飯飼餧館馞驎髙"], ["fc40","髜魵魲é®é®±é®»é°€éµ°éµ«ï¨­é¸™é»‘"] ] "use strict"; var Buffer = require("safer-buffer").Buffer; // Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js // == UTF16-BE codec. ========================================================== exports.utf16be = Utf16BECodec; function Utf16BECodec() { } Utf16BECodec.prototype.encoder = Utf16BEEncoder; Utf16BECodec.prototype.decoder = Utf16BEDecoder; Utf16BECodec.prototype.bomAware = true; // -- Encoding function Utf16BEEncoder() { } Utf16BEEncoder.prototype.write = function(str) { var buf = Buffer.from(str, 'ucs2'); for (var i = 0; i < buf.length; i += 2) { var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; } return buf; } Utf16BEEncoder.prototype.end = function() { } // -- Decoding function Utf16BEDecoder() { this.overflowByte = -1; } Utf16BEDecoder.prototype.write = function(buf) { if (buf.length == 0) return ''; var buf2 = Buffer.alloc(buf.length + 1), i = 0, j = 0; if (this.overflowByte !== -1) { buf2[0] = buf[0]; buf2[1] = this.overflowByte; i = 1; j = 2; } for (; i < buf.length-1; i += 2, j+= 2) { buf2[j] = buf[i+1]; buf2[j+1] = buf[i]; } this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; return buf2.slice(0, j).toString('ucs2'); } Utf16BEDecoder.prototype.end = function() { this.overflowByte = -1; } // == UTF-16 codec ============================================================= // Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. // Defaults to UTF-16LE, as it's prevalent and default in Node. // http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le // Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); // Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). exports.utf16 = Utf16Codec; function Utf16Codec(codecOptions, iconv) { this.iconv = iconv; } Utf16Codec.prototype.encoder = Utf16Encoder; Utf16Codec.prototype.decoder = Utf16Decoder; // -- Encoding (pass-through) function Utf16Encoder(options, codec) { options = options || {}; if (options.addBOM === undefined) options.addBOM = true; this.encoder = codec.iconv.getEncoder('utf-16le', options); } Utf16Encoder.prototype.write = function(str) { return this.encoder.write(str); } Utf16Encoder.prototype.end = function() { return this.encoder.end(); } // -- Decoding function Utf16Decoder(options, codec) { this.decoder = null; this.initialBufs = []; this.initialBufsLen = 0; this.options = options || {}; this.iconv = codec.iconv; } Utf16Decoder.prototype.write = function(buf) { if (!this.decoder) { // Codec is not chosen yet. Accumulate initial bytes. this.initialBufs.push(buf); this.initialBufsLen += buf.length; if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below) return ''; // We have enough bytes -> detect endianness. var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var resStr = ''; for (var i = 0; i < this.initialBufs.length; i++) resStr += this.decoder.write(this.initialBufs[i]); this.initialBufs.length = this.initialBufsLen = 0; return resStr; } return this.decoder.write(buf); } Utf16Decoder.prototype.end = function() { if (!this.decoder) { var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var resStr = ''; for (var i = 0; i < this.initialBufs.length; i++) resStr += this.decoder.write(this.initialBufs[i]); var trail = this.decoder.end(); if (trail) resStr += trail; this.initialBufs.length = this.initialBufsLen = 0; return resStr; } return this.decoder.end(); } function detectEncoding(bufs, defaultEncoding) { var b = []; var charsProcessed = 0; var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE. outer_loop: for (var i = 0; i < bufs.length; i++) { var buf = bufs[i]; for (var j = 0; j < buf.length; j++) { b.push(buf[j]); if (b.length === 2) { if (charsProcessed === 0) { // Check BOM first. if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le'; if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be'; } if (b[0] === 0 && b[1] !== 0) asciiCharsBE++; if (b[0] !== 0 && b[1] === 0) asciiCharsLE++; b.length = 0; charsProcessed++; if (charsProcessed >= 100) { break outer_loop; } } } } // Make decisions. // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. // So, we count ASCII as if it was LE or BE, and decide from that. if (asciiCharsBE > asciiCharsLE) return 'utf-16be'; if (asciiCharsBE < asciiCharsLE) return 'utf-16le'; // Couldn't decide (likely all zeros or not enough data). return defaultEncoding || 'utf-16le'; } 'use strict'; var Buffer = require('safer-buffer').Buffer; // == UTF32-LE/BE codec. ========================================================== exports._utf32 = Utf32Codec; function Utf32Codec(codecOptions, iconv) { this.iconv = iconv; this.bomAware = true; this.isLE = codecOptions.isLE; } exports.utf32le = { type: '_utf32', isLE: true }; exports.utf32be = { type: '_utf32', isLE: false }; // Aliases exports.ucs4le = 'utf32le'; exports.ucs4be = 'utf32be'; Utf32Codec.prototype.encoder = Utf32Encoder; Utf32Codec.prototype.decoder = Utf32Decoder; // -- Encoding function Utf32Encoder(options, codec) { this.isLE = codec.isLE; this.highSurrogate = 0; } Utf32Encoder.prototype.write = function(str) { var src = Buffer.from(str, 'ucs2'); var dst = Buffer.alloc(src.length * 2); var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; var offset = 0; for (var i = 0; i < src.length; i += 2) { var code = src.readUInt16LE(i); var isHighSurrogate = (0xD800 <= code && code < 0xDC00); var isLowSurrogate = (0xDC00 <= code && code < 0xE000); if (this.highSurrogate) { if (isHighSurrogate || !isLowSurrogate) { // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character // (technically wrong, but expected by some applications, like Windows file names). write32.call(dst, this.highSurrogate, offset); offset += 4; } else { // Create 32-bit value from high and low surrogates; var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000; write32.call(dst, codepoint, offset); offset += 4; this.highSurrogate = 0; continue; } } if (isHighSurrogate) this.highSurrogate = code; else { // Even if the current character is a low surrogate, with no previous high surrogate, we'll // encode it as a semi-invalid stand-alone character for the same reasons expressed above for // unpaired high surrogates. write32.call(dst, code, offset); offset += 4; this.highSurrogate = 0; } } if (offset < dst.length) dst = dst.slice(0, offset); return dst; }; Utf32Encoder.prototype.end = function() { // Treat any leftover high surrogate as a semi-valid independent character. if (!this.highSurrogate) return; var buf = Buffer.alloc(4); if (this.isLE) buf.writeUInt32LE(this.highSurrogate, 0); else buf.writeUInt32BE(this.highSurrogate, 0); this.highSurrogate = 0; return buf; }; // -- Decoding function Utf32Decoder(options, codec) { this.isLE = codec.isLE; this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0); this.overflow = []; } Utf32Decoder.prototype.write = function(src) { if (src.length === 0) return ''; var i = 0; var codepoint = 0; var dst = Buffer.alloc(src.length + 4); var offset = 0; var isLE = this.isLE; var overflow = this.overflow; var badChar = this.badChar; if (overflow.length > 0) { for (; i < src.length && overflow.length < 4; i++) overflow.push(src[i]); if (overflow.length === 4) { // NOTE: codepoint is a signed int32 and can be negative. // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer). if (isLE) { codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24); } else { codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24); } overflow.length = 0; offset = _writeCodepoint(dst, offset, codepoint, badChar); } } // Main loop. Should be as optimized as possible. for (; i < src.length - 3; i += 4) { // NOTE: codepoint is a signed int32 and can be negative. if (isLE) { codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24); } else { codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24); } offset = _writeCodepoint(dst, offset, codepoint, badChar); } // Keep overflowing bytes. for (; i < src.length; i++) { overflow.push(src[i]); } return dst.slice(0, offset).toString('ucs2'); }; function _writeCodepoint(dst, offset, codepoint, badChar) { // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations. if (codepoint < 0 || codepoint > 0x10FFFF) { // Not a valid Unicode codepoint codepoint = badChar; } // Ephemeral Planes: Write high surrogate. if (codepoint >= 0x10000) { codepoint -= 0x10000; var high = 0xD800 | (codepoint >> 10); dst[offset++] = high & 0xff; dst[offset++] = high >> 8; // Low surrogate is written below. var codepoint = 0xDC00 | (codepoint & 0x3FF); } // Write BMP char or low surrogate. dst[offset++] = codepoint & 0xff; dst[offset++] = codepoint >> 8; return offset; }; Utf32Decoder.prototype.end = function() { this.overflow.length = 0; }; // == UTF-32 Auto codec ============================================================= // Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic. // Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32 // Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'}); // Encoder prepends BOM (which can be overridden with (addBOM: false}). exports.utf32 = Utf32AutoCodec; exports.ucs4 = 'utf32'; function Utf32AutoCodec(options, iconv) { this.iconv = iconv; } Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; // -- Encoding function Utf32AutoEncoder(options, codec) { options = options || {}; if (options.addBOM === undefined) options.addBOM = true; this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options); } Utf32AutoEncoder.prototype.write = function(str) { return this.encoder.write(str); }; Utf32AutoEncoder.prototype.end = function() { return this.encoder.end(); }; // -- Decoding function Utf32AutoDecoder(options, codec) { this.decoder = null; this.initialBufs = []; this.initialBufsLen = 0; this.options = options || {}; this.iconv = codec.iconv; } Utf32AutoDecoder.prototype.write = function(buf) { if (!this.decoder) { // Codec is not chosen yet. Accumulate initial bytes. this.initialBufs.push(buf); this.initialBufsLen += buf.length; if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below) return ''; // We have enough bytes -> detect endianness. var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var resStr = ''; for (var i = 0; i < this.initialBufs.length; i++) resStr += this.decoder.write(this.initialBufs[i]); this.initialBufs.length = this.initialBufsLen = 0; return resStr; } return this.decoder.write(buf); }; Utf32AutoDecoder.prototype.end = function() { if (!this.decoder) { var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var resStr = ''; for (var i = 0; i < this.initialBufs.length; i++) resStr += this.decoder.write(this.initialBufs[i]); var trail = this.decoder.end(); if (trail) resStr += trail; this.initialBufs.length = this.initialBufsLen = 0; return resStr; } return this.decoder.end(); }; function detectEncoding(bufs, defaultEncoding) { var b = []; var charsProcessed = 0; var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE. var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE. outer_loop: for (var i = 0; i < bufs.length; i++) { var buf = bufs[i]; for (var j = 0; j < buf.length; j++) { b.push(buf[j]); if (b.length === 4) { if (charsProcessed === 0) { // Check BOM first. if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) { return 'utf-32le'; } if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) { return 'utf-32be'; } } if (b[0] !== 0 || b[1] > 0x10) invalidBE++; if (b[3] !== 0 || b[2] > 0x10) invalidLE++; if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++; if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++; b.length = 0; charsProcessed++; if (charsProcessed >= 100) { break outer_loop; } } } } // Make decisions. if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be'; if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le'; // Couldn't decide (likely all zeros or not enough data). return defaultEncoding || 'utf-32le'; } "use strict"; var Buffer = require("safer-buffer").Buffer; // UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 // See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 exports.utf7 = Utf7Codec; exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 function Utf7Codec(codecOptions, iconv) { this.iconv = iconv; }; Utf7Codec.prototype.encoder = Utf7Encoder; Utf7Codec.prototype.decoder = Utf7Decoder; Utf7Codec.prototype.bomAware = true; // -- Encoding var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; function Utf7Encoder(options, codec) { this.iconv = codec.iconv; } Utf7Encoder.prototype.write = function(str) { // Naive implementation. // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". return Buffer.from(str.replace(nonDirectChars, function(chunk) { return "+" + (chunk === '+' ? '' : this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + "-"; }.bind(this))); } Utf7Encoder.prototype.end = function() { } // -- Decoding function Utf7Decoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = ''; } var base64Regex = /[A-Za-z0-9\/+]/; var base64Chars = []; for (var i = 0; i < 256; i++) base64Chars[i] = base64Regex.test(String.fromCharCode(i)); var plusChar = '+'.charCodeAt(0), minusChar = '-'.charCodeAt(0), andChar = '&'.charCodeAt(0); Utf7Decoder.prototype.write = function(buf) { var res = "", lastI = 0, inBase64 = this.inBase64, base64Accum = this.base64Accum; // The decoder is more involved as we must handle chunks in stream. for (var i = 0; i < buf.length; i++) { if (!inBase64) { // We're in direct mode. // Write direct chars until '+' if (buf[i] == plusChar) { res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. lastI = i+1; inBase64 = true; } } else { // We decode base64. if (!base64Chars[buf[i]]) { // Base64 ended. if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" res += "+"; } else { var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii"); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } if (buf[i] != minusChar) // Minus is absorbed after base64. i--; lastI = i+1; inBase64 = false; base64Accum = ''; } } } if (!inBase64) { res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. } else { var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii"); var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. b64str = b64str.slice(0, canBeDecoded); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } this.inBase64 = inBase64; this.base64Accum = base64Accum; return res; } Utf7Decoder.prototype.end = function() { var res = ""; if (this.inBase64 && this.base64Accum.length > 0) res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); this.inBase64 = false; this.base64Accum = ''; return res; } // UTF-7-IMAP codec. // RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) // Differences: // * Base64 part is started by "&" instead of "+" // * Direct characters are 0x20-0x7E, except "&" (0x26) // * In Base64, "," is used instead of "/" // * Base64 must not be used to represent direct characters. // * No implicit shift back from Base64 (should always end with '-') // * String must end in non-shifted position. // * "-&" while in base64 is not allowed. exports.utf7imap = Utf7IMAPCodec; function Utf7IMAPCodec(codecOptions, iconv) { this.iconv = iconv; }; Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; Utf7IMAPCodec.prototype.bomAware = true; // -- Encoding function Utf7IMAPEncoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = Buffer.alloc(6); this.base64AccumIdx = 0; } Utf7IMAPEncoder.prototype.write = function(str) { var inBase64 = this.inBase64, base64Accum = this.base64Accum, base64AccumIdx = this.base64AccumIdx, buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; for (var i = 0; i < str.length; i++) { var uChar = str.charCodeAt(i); if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. if (inBase64) { if (base64AccumIdx > 0) { bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); base64AccumIdx = 0; } buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. inBase64 = false; } if (!inBase64) { buf[bufIdx++] = uChar; // Write direct character if (uChar === andChar) // Ampersand -> '&-' buf[bufIdx++] = minusChar; } } else { // Non-direct character if (!inBase64) { buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. inBase64 = true; } if (inBase64) { base64Accum[base64AccumIdx++] = uChar >> 8; base64Accum[base64AccumIdx++] = uChar & 0xFF; if (base64AccumIdx == base64Accum.length) { bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); base64AccumIdx = 0; } } } } this.inBase64 = inBase64; this.base64AccumIdx = base64AccumIdx; return buf.slice(0, bufIdx); } Utf7IMAPEncoder.prototype.end = function() { var buf = Buffer.alloc(10), bufIdx = 0; if (this.inBase64) { if (this.base64AccumIdx > 0) { bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); this.base64AccumIdx = 0; } buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. this.inBase64 = false; } return buf.slice(0, bufIdx); } // -- Decoding function Utf7IMAPDecoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = ''; } var base64IMAPChars = base64Chars.slice(); base64IMAPChars[','.charCodeAt(0)] = true; Utf7IMAPDecoder.prototype.write = function(buf) { var res = "", lastI = 0, inBase64 = this.inBase64, base64Accum = this.base64Accum; // The decoder is more involved as we must handle chunks in stream. // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). for (var i = 0; i < buf.length; i++) { if (!inBase64) { // We're in direct mode. // Write direct chars until '&' if (buf[i] == andChar) { res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. lastI = i+1; inBase64 = true; } } else { // We decode base64. if (!base64IMAPChars[buf[i]]) { // Base64 ended. if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" res += "&"; } else { var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/'); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } if (buf[i] != minusChar) // Minus may be absorbed after base64. i--; lastI = i+1; inBase64 = false; base64Accum = ''; } } } if (!inBase64) { res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. } else { var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/'); var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. b64str = b64str.slice(0, canBeDecoded); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } this.inBase64 = inBase64; this.base64Accum = base64Accum; return res; } Utf7IMAPDecoder.prototype.end = function() { var res = ""; if (this.inBase64 && this.base64Accum.length > 0) res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); this.inBase64 = false; this.base64Accum = ''; return res; } "use strict"; var BOMChar = '\uFEFF'; exports.PrependBOM = PrependBOMWrapper function PrependBOMWrapper(encoder, options) { this.encoder = encoder; this.addBOM = true; } PrependBOMWrapper.prototype.write = function(str) { if (this.addBOM) { str = BOMChar + str; this.addBOM = false; } return this.encoder.write(str); } PrependBOMWrapper.prototype.end = function() { return this.encoder.end(); } //------------------------------------------------------------------------------ exports.StripBOM = StripBOMWrapper; function StripBOMWrapper(decoder, options) { this.decoder = decoder; this.pass = false; this.options = options || {}; } StripBOMWrapper.prototype.write = function(buf) { var res = this.decoder.write(buf); if (this.pass || !res) return res; if (res[0] === BOMChar) { res = res.slice(1); if (typeof this.options.stripBOM === 'function') this.options.stripBOM(); } this.pass = true; return res; } StripBOMWrapper.prototype.end = function() { return this.decoder.end(); } "use strict"; var Buffer = require("safer-buffer").Buffer; var bomHandling = require("./bom-handling"), iconv = module.exports; // All codecs and aliases are kept here, keyed by encoding name/alias. // They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. iconv.encodings = null; // Characters emitted in case of error. iconv.defaultCharUnicode = '�'; iconv.defaultCharSingleByte = '?'; // Public API. iconv.encode = function encode(str, encoding, options) { str = "" + (str || ""); // Ensure string. var encoder = iconv.getEncoder(encoding, options); var res = encoder.write(str); var trail = encoder.end(); return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; } iconv.decode = function decode(buf, encoding, options) { if (typeof buf === 'string') { if (!iconv.skipDecodeWarning) { console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); iconv.skipDecodeWarning = true; } buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. } var decoder = iconv.getDecoder(encoding, options); var res = decoder.write(buf); var trail = decoder.end(); return trail ? (res + trail) : res; } iconv.encodingExists = function encodingExists(enc) { try { iconv.getCodec(enc); return true; } catch (e) { return false; } } // Legacy aliases to convert functions iconv.toEncoding = iconv.encode; iconv.fromEncoding = iconv.decode; // Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. iconv._codecDataCache = {}; iconv.getCodec = function getCodec(encoding) { if (!iconv.encodings) iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. var enc = iconv._canonicalizeEncoding(encoding); // Traverse iconv.encodings to find actual codec. var codecOptions = {}; while (true) { var codec = iconv._codecDataCache[enc]; if (codec) return codec; var codecDef = iconv.encodings[enc]; switch (typeof codecDef) { case "string": // Direct alias to other encoding. enc = codecDef; break; case "object": // Alias with options. Can be layered. for (var key in codecDef) codecOptions[key] = codecDef[key]; if (!codecOptions.encodingName) codecOptions.encodingName = enc; enc = codecDef.type; break; case "function": // Codec itself. if (!codecOptions.encodingName) codecOptions.encodingName = enc; // The codec function must load all tables and return object with .encoder and .decoder methods. // It'll be called only once (for each different options object). codec = new codecDef(codecOptions, iconv); iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. return codec; default: throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); } } } iconv._canonicalizeEncoding = function(encoding) { // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); } iconv.getEncoder = function getEncoder(encoding, options) { var codec = iconv.getCodec(encoding), encoder = new codec.encoder(options, codec); if (codec.bomAware && options && options.addBOM) encoder = new bomHandling.PrependBOM(encoder, options); return encoder; } iconv.getDecoder = function getDecoder(encoding, options) { var codec = iconv.getCodec(encoding), decoder = new codec.decoder(options, codec); if (codec.bomAware && !(options && options.stripBOM === false)) decoder = new bomHandling.StripBOM(decoder, options); return decoder; } // Streaming API // NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add // up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default. // If you would like to enable it explicitly, please add the following code to your app: // > iconv.enableStreamingAPI(require('stream')); iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) { if (iconv.supportsStreams) return; // Dependency-inject stream module to create IconvLite stream classes. var streams = require("./streams")(stream_module); // Not public API yet, but expose the stream classes. iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; // Streaming API. iconv.encodeStream = function encodeStream(encoding, options) { return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); } iconv.decodeStream = function decodeStream(encoding, options) { return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); } iconv.supportsStreams = true; } // Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments). var stream_module; try { stream_module = require("stream"); } catch (e) {} if (stream_module && stream_module.Transform) { iconv.enableStreamingAPI(stream_module); } else { // In rare cases where 'stream' module is not available by default, throw a helpful exception. iconv.encodeStream = iconv.decodeStream = function() { throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it."); }; } if ("Ä€" != "\u0100") { console.error("iconv-lite warning: js files use non-utf8 encoding. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); } "use strict"; var Buffer = require("safer-buffer").Buffer; // NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), // we opt to dependency-inject it instead of creating a hard dependency. module.exports = function(stream_module) { var Transform = stream_module.Transform; // == Encoder stream ======================================================= function IconvLiteEncoderStream(conv, options) { this.conv = conv; options = options || {}; options.decodeStrings = false; // We accept only strings, so we don't need to decode them. Transform.call(this, options); } IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { constructor: { value: IconvLiteEncoderStream } }); IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { if (typeof chunk != 'string') return done(new Error("Iconv encoding stream needs strings as its input.")); try { var res = this.conv.write(chunk); if (res && res.length) this.push(res); done(); } catch (e) { done(e); } } IconvLiteEncoderStream.prototype._flush = function(done) { try { var res = this.conv.end(); if (res && res.length) this.push(res); done(); } catch (e) { done(e); } } IconvLiteEncoderStream.prototype.collect = function(cb) { var chunks = []; this.on('error', cb); this.on('data', function(chunk) { chunks.push(chunk); }); this.on('end', function() { cb(null, Buffer.concat(chunks)); }); return this; } // == Decoder stream ======================================================= function IconvLiteDecoderStream(conv, options) { this.conv = conv; options = options || {}; options.encoding = this.encoding = 'utf8'; // We output strings. Transform.call(this, options); } IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { constructor: { value: IconvLiteDecoderStream } }); IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) return done(new Error("Iconv decoding stream needs buffers as its input.")); try { var res = this.conv.write(chunk); if (res && res.length) this.push(res, this.encoding); done(); } catch (e) { done(e); } } IconvLiteDecoderStream.prototype._flush = function(done) { try { var res = this.conv.end(); if (res && res.length) this.push(res, this.encoding); done(); } catch (e) { done(e); } } IconvLiteDecoderStream.prototype.collect = function(cb) { var res = ''; this.on('error', cb); this.on('data', function(chunk) { res += chunk; }); this.on('end', function() { cb(null, res); }); return this; } return { IconvLiteEncoderStream: IconvLiteEncoderStream, IconvLiteDecoderStream: IconvLiteDecoderStream, }; }; { "name": "iconv-lite", "description": "Convert character encodings in pure javascript.", "version": "0.6.3", "license": "MIT", "keywords": [ "iconv", "convert", "charset", "icu" ], "author": "Alexander Shtuchkin ", "main": "./lib/index.js", "typings": "./lib/index.d.ts", "homepage": "https://github.com/ashtuchkin/iconv-lite", "bugs": "https://github.com/ashtuchkin/iconv-lite/issues", "repository": { "type": "git", "url": "git://github.com/ashtuchkin/iconv-lite.git" }, "engines": { "node": ">=0.10.0" }, "scripts": { "coverage": "c8 _mocha --grep .", "test": "mocha --reporter spec --grep ." }, "browser": { "stream": false }, "devDependencies": { "async": "^3.2.0", "c8": "^7.2.0", "errto": "^0.2.1", "iconv": "^2.3.5", "mocha": "^3.5.3", "request": "^2.88.2", "semver": "^6.3.0", "unorm": "^1.6.0" }, "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } } The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 'use strict' const fs = require('fs') const path = require('path') const EE = require('events').EventEmitter const Minimatch = require('minimatch').Minimatch class Walker extends EE { constructor (opts) { opts = opts || {} super(opts) // set to true if this.path is a symlink, whether follow is true or not this.isSymbolicLink = opts.isSymbolicLink this.path = opts.path || process.cwd() this.basename = path.basename(this.path) this.ignoreFiles = opts.ignoreFiles || ['.ignore'] this.ignoreRules = {} this.parent = opts.parent || null this.includeEmpty = !!opts.includeEmpty this.root = this.parent ? this.parent.root : this.path this.follow = !!opts.follow this.result = this.parent ? this.parent.result : new Set() this.entries = null this.sawError = false this.exact = opts.exact } sort (a, b) { return a.localeCompare(b, 'en') } emit (ev, data) { let ret = false if (!(this.sawError && ev === 'error')) { if (ev === 'error') { this.sawError = true } else if (ev === 'done' && !this.parent) { data = Array.from(data) .map(e => /^@/.test(e) ? `./${e}` : e).sort(this.sort) this.result = data } if (ev === 'error' && this.parent) { ret = this.parent.emit('error', data) } else { ret = super.emit(ev, data) } } return ret } start () { fs.readdir(this.path, (er, entries) => er ? this.emit('error', er) : this.onReaddir(entries)) return this } isIgnoreFile (e) { return e !== '.' && e !== '..' && this.ignoreFiles.indexOf(e) !== -1 } onReaddir (entries) { this.entries = entries if (entries.length === 0) { if (this.includeEmpty) { this.result.add(this.path.slice(this.root.length + 1)) } this.emit('done', this.result) } else { const hasIg = this.entries.some(e => this.isIgnoreFile(e)) if (hasIg) { this.addIgnoreFiles() } else { this.filterEntries() } } } addIgnoreFiles () { const newIg = this.entries .filter(e => this.isIgnoreFile(e)) let igCount = newIg.length const then = () => { if (--igCount === 0) { this.filterEntries() } } newIg.forEach(e => this.addIgnoreFile(e, then)) } addIgnoreFile (file, then) { const ig = path.resolve(this.path, file) fs.readFile(ig, 'utf8', (er, data) => er ? this.emit('error', er) : this.onReadIgnoreFile(file, data, then)) } onReadIgnoreFile (file, data, then) { const mmopt = { matchBase: true, dot: true, flipNegate: true, nocase: true, } const rules = data.split(/\r?\n/) .filter(line => !/^#|^$/.test(line.trim())) .map(rule => { return new Minimatch(rule.trim(), mmopt) }) this.ignoreRules[file] = rules then() } filterEntries () { // at this point we either have ignore rules, or just inheriting // this exclusion is at the point where we know the list of // entries in the dir, but don't know what they are. since // some of them *might* be directories, we have to run the // match in dir-mode as well, so that we'll pick up partials // of files that will be included later. Anything included // at this point will be checked again later once we know // what it is. const filtered = this.entries.map(entry => { // at this point, we don't know if it's a dir or not. const passFile = this.filterEntry(entry) const passDir = this.filterEntry(entry, true) return (passFile || passDir) ? [entry, passFile, passDir] : false }).filter(e => e) // now we stat them all // if it's a dir, and passes as a dir, then recurse // if it's not a dir, but passes as a file, add to set let entryCount = filtered.length if (entryCount === 0) { this.emit('done', this.result) } else { const then = () => { if (--entryCount === 0) { this.emit('done', this.result) } } filtered.forEach(filt => { const entry = filt[0] const file = filt[1] const dir = filt[2] this.stat({ entry, file, dir }, then) }) } } onstat ({ st, entry, file, dir, isSymbolicLink }, then) { const abs = this.path + '/' + entry if (!st.isDirectory()) { if (file) { this.result.add(abs.slice(this.root.length + 1)) } then() } else { // is a directory if (dir) { this.walker(entry, { isSymbolicLink, exact: file || this.filterEntry(entry + '/') }, then) } else { then() } } } stat ({ entry, file, dir }, then) { const abs = this.path + '/' + entry fs.lstat(abs, (lstatErr, lstatResult) => { if (lstatErr) { this.emit('error', lstatErr) } else { const isSymbolicLink = lstatResult.isSymbolicLink() if (this.follow && isSymbolicLink) { fs.stat(abs, (statErr, statResult) => { if (statErr) { this.emit('error', statErr) } else { this.onstat({ st: statResult, entry, file, dir, isSymbolicLink }, then) } }) } else { this.onstat({ st: lstatResult, entry, file, dir, isSymbolicLink }, then) } } }) } walkerOpt (entry, opts) { return { path: this.path + '/' + entry, parent: this, ignoreFiles: this.ignoreFiles, follow: this.follow, includeEmpty: this.includeEmpty, ...opts, } } walker (entry, opts, then) { new Walker(this.walkerOpt(entry, opts)).on('done', then).start() } filterEntry (entry, partial, entryBasename) { let included = true // this = /a/b/c // entry = d // parent /a/b sees c/d if (this.parent && this.parent.filterEntry) { const parentEntry = this.basename + '/' + entry const parentBasename = entryBasename || entry included = this.parent.filterEntry(parentEntry, partial, parentBasename) if (!included && !this.exact) { return false } } this.ignoreFiles.forEach(f => { if (this.ignoreRules[f]) { this.ignoreRules[f].forEach(rule => { // negation means inclusion // so if it's negated, and already included, no need to check // likewise if it's neither negated nor included if (rule.negate !== included) { const isRelativeRule = entryBasename && rule.globParts.some(part => part.length <= (part.slice(-1)[0] ? 1 : 2) ) // first, match against /foo/bar // then, against foo/bar // then, in the case of partials, match with a / // then, if also the rule is relative, match against basename const match = rule.match('/' + entry) || rule.match(entry) || !!partial && ( rule.match('/' + entry + '/') || rule.match(entry + '/') || rule.negate && ( rule.match('/' + entry, true) || rule.match(entry, true)) || isRelativeRule && ( rule.match('/' + entryBasename + '/') || rule.match(entryBasename + '/') || rule.negate && ( rule.match('/' + entryBasename, true) || rule.match(entryBasename, true)))) if (match) { included = rule.negate } } }) } }) return included } } class WalkerSync extends Walker { start () { this.onReaddir(fs.readdirSync(this.path)) return this } addIgnoreFile (file, then) { const ig = path.resolve(this.path, file) this.onReadIgnoreFile(file, fs.readFileSync(ig, 'utf8'), then) } stat ({ entry, file, dir }, then) { const abs = this.path + '/' + entry let st = fs.lstatSync(abs) const isSymbolicLink = st.isSymbolicLink() if (this.follow && isSymbolicLink) { st = fs.statSync(abs) } // console.error('STAT SYNC', {st, entry, file, dir, isSymbolicLink, then}) this.onstat({ st, entry, file, dir, isSymbolicLink }, then) } walker (entry, opts, then) { new WalkerSync(this.walkerOpt(entry, opts)).start() then() } } const walk = (opts, callback) => { const p = new Promise((resolve, reject) => { new Walker(opts).on('done', resolve).on('error', reject).start() }) return callback ? p.then(res => callback(null, res), callback) : p } const walkSync = opts => new WalkerSync(opts).start().result module.exports = walk walk.sync = walkSync walk.Walker = Walker walk.WalkerSync = WalkerSync { "name": "ignore-walk", "version": "7.0.0", "description": "Nested/recursive `.gitignore`/`.npmignore` parsing and filtering.", "main": "lib/index.js", "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "mutate-fs": "^2.1.1", "tap": "^16.0.1" }, "scripts": { "test": "tap", "posttest": "npm run lint", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "test:windows-coverage": "npm pkg set tap.statements=99 --json && npm pkg set tap.branches=98 --json && npm pkg set tap.lines=99 --json", "snap": "tap", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "keywords": [ "ignorefile", "ignore", "file", ".gitignore", ".npmignore", "glob" ], "author": "GitHub Inc.", "license": "ISC", "repository": { "type": "git", "url": "git+https://github.com/npm/ignore-walk.git" }, "files": [ "bin/", "lib/" ], "dependencies": { "minimatch": "^9.0.0" }, "tap": { "test-env": "LC_ALL=sk", "before": "test/00-setup.js", "after": "test/zz-cleanup.js", "timeout": 600, "jobs": 1, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "content": "scripts/template-oss", "publish": "true" } } /** * @preserve * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) * * @author Jens Taylor * @see http://github.com/homebrewing/brauhaus-diff * @author Gary Court * @see http://github.com/garycourt/murmurhash-js * @author Austin Appleby * @see http://sites.google.com/site/murmurhash/ */ (function(){ var cache; // Call this function without `new` to use the cached object (good for // single-threaded environments), or with `new` to create a new object. // // @param {string} key A UTF-16 or ASCII string // @param {number} seed An optional positive integer // @return {object} A MurmurHash3 object for incremental hashing function MurmurHash3(key, seed) { var m = this instanceof MurmurHash3 ? this : cache; m.reset(seed) if (typeof key === 'string' && key.length > 0) { m.hash(key); } if (m !== this) { return m; } }; // Incrementally add a string to this hash // // @param {string} key A UTF-16 or ASCII string // @return {object} this MurmurHash3.prototype.hash = function(key) { var h1, k1, i, top, len; len = key.length; this.len += len; k1 = this.k1; i = 0; switch (this.rem) { case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; case 3: k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; } this.rem = (len + this.rem) & 3; // & 3 is same as % 4 len -= this.rem; if (len > 0) { h1 = this.h1; while (1) { k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; if (i >= len) { break; } k1 = ((key.charCodeAt(i++) & 0xffff)) ^ ((key.charCodeAt(i++) & 0xffff) << 8) ^ ((key.charCodeAt(i++) & 0xffff) << 16); top = key.charCodeAt(i++); k1 ^= ((top & 0xff) << 24) ^ ((top & 0xff00) >> 8); } k1 = 0; switch (this.rem) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xffff); } this.h1 = h1; } this.k1 = k1; return this; }; // Get the result of this hash // // @return {number} The 32-bit hash MurmurHash3.prototype.result = function() { var k1, h1; k1 = this.k1; h1 = this.h1; if (k1 > 0) { k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; h1 ^= k1; } h1 ^= this.len; h1 ^= h1 >>> 16; h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; h1 ^= h1 >>> 13; h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; h1 ^= h1 >>> 16; return h1 >>> 0; }; // Reset the hash object for reuse // // @param {number} seed An optional positive integer MurmurHash3.prototype.reset = function(seed) { this.h1 = typeof seed === 'number' ? seed : 0; this.rem = this.k1 = this.len = 0; return this; }; // A cached object to use. This can be safely used if you're in a single- // threaded environment, otherwise you need to create new hashes to use. cache = new MurmurHash3(); if (typeof(module) != 'undefined') { module.exports = MurmurHash3; } else { this.MurmurHash3 = MurmurHash3; } }()); /** * @preserve * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) * * @author Jens Taylor * @see http://github.com/homebrewing/brauhaus-diff * @author Gary Court * @see http://github.com/garycourt/murmurhash-js * @author Austin Appleby * @see http://sites.google.com/site/murmurhash/ */ !function(){function t(h,r){var s=this instanceof t?this:e;return s.reset(r),"string"==typeof h&&h.length>0&&s.hash(h),s!==this?s:void 0}var e;t.prototype.hash=function(t){var e,h,r,s,i;switch(i=t.length,this.len+=i,h=this.k1,r=0,this.rem){case 0:h^=i>r?65535&t.charCodeAt(r++):0;case 1:h^=i>r?(65535&t.charCodeAt(r++))<<8:0;case 2:h^=i>r?(65535&t.charCodeAt(r++))<<16:0;case 3:h^=i>r?(255&t.charCodeAt(r))<<24:0,h^=i>r?(65280&t.charCodeAt(r++))>>8:0}if(this.rem=3&i+this.rem,i-=this.rem,i>0){for(e=this.h1;;){if(h=4294967295&11601*h+3432906752*(65535&h),h=h<<15|h>>>17,h=4294967295&13715*h+461832192*(65535&h),e^=h,e=e<<13|e>>>19,e=4294967295&5*e+3864292196,r>=i)break;h=65535&t.charCodeAt(r++)^(65535&t.charCodeAt(r++))<<8^(65535&t.charCodeAt(r++))<<16,s=t.charCodeAt(r++),h^=(255&s)<<24^(65280&s)>>8}switch(h=0,this.rem){case 3:h^=(65535&t.charCodeAt(r+2))<<16;case 2:h^=(65535&t.charCodeAt(r+1))<<8;case 1:h^=65535&t.charCodeAt(r)}this.h1=e}return this.k1=h,this},t.prototype.result=function(){var t,e;return t=this.k1,e=this.h1,t>0&&(t=4294967295&11601*t+3432906752*(65535&t),t=t<<15|t>>>17,t=4294967295&13715*t+461832192*(65535&t),e^=t),e^=this.len,e^=e>>>16,e=4294967295&51819*e+2246770688*(65535&e),e^=e>>>13,e=4294967295&44597*e+3266445312*(65535&e),e^=e>>>16,e>>>0},t.prototype.reset=function(t){return this.h1="number"==typeof t?t:0,this.rem=this.k1=this.len=0,this},e=new t,"undefined"!=typeof module?module.exports=t:this.MurmurHash3=t}();{ "name": "imurmurhash", "version": "0.1.4", "description": "An incremental implementation of MurmurHash3", "homepage": "https://github.com/jensyt/imurmurhash-js", "main": "imurmurhash.js", "files": [ "imurmurhash.js", "imurmurhash.min.js", "package.json", "README.md" ], "repository": { "type": "git", "url": "https://github.com/jensyt/imurmurhash-js" }, "bugs": { "url": "https://github.com/jensyt/imurmurhash-js/issues" }, "keywords": [ "murmur", "murmurhash", "murmurhash3", "hash", "incremental" ], "author": { "name": "Jens Taylor", "email": "jensyt@gmail.com", "url": "https://github.com/homebrewing" }, "license": "MIT", "dependencies": { }, "devDependencies": { }, "engines": { "node": ">=0.8.19" } } The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const { hasOwnProperty } = Object.prototype const encode = (obj, opt = {}) => { if (typeof opt === 'string') { opt = { section: opt } } opt.align = opt.align === true opt.newline = opt.newline === true opt.sort = opt.sort === true opt.whitespace = opt.whitespace === true || opt.align === true // The `typeof` check is required because accessing the `process` directly fails on browsers. /* istanbul ignore next */ opt.platform = opt.platform || (typeof process !== 'undefined' && process.platform) opt.bracketedArray = opt.bracketedArray !== false /* istanbul ignore next */ const eol = opt.platform === 'win32' ? '\r\n' : '\n' const separator = opt.whitespace ? ' = ' : '=' const children = [] const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj) let padToChars = 0 // If aligning on the separator, then padToChars is determined as follows: // 1. Get the keys // 2. Exclude keys pointing to objects unless the value is null or an array // 3. Add `[]` to array keys // 4. Ensure non empty set of keys // 5. Reduce the set to the longest `safe` key // 6. Get the `safe` length if (opt.align) { padToChars = safe( ( keys .filter(k => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== 'object') .map(k => Array.isArray(obj[k]) ? `${k}[]` : k) ) .concat(['']) .reduce((a, b) => safe(a).length >= safe(b).length ? a : b) ).length } let out = '' const arraySuffix = opt.bracketedArray ? '[]' : '' for (const k of keys) { const val = obj[k] if (val && Array.isArray(val)) { for (const item of val) { out += safe(`${k}${arraySuffix}`).padEnd(padToChars, ' ') + separator + safe(item) + eol } } else if (val && typeof val === 'object') { children.push(k) } else { out += safe(k).padEnd(padToChars, ' ') + separator + safe(val) + eol } } if (opt.section && out.length) { out = '[' + safe(opt.section) + ']' + (opt.newline ? eol + eol : eol) + out } for (const k of children) { const nk = splitSections(k, '.').join('\\.') const section = (opt.section ? opt.section + '.' : '') + nk const child = encode(obj[k], { ...opt, section, }) if (out.length && child.length) { out += eol } out += child } return out } function splitSections (str, separator) { var lastMatchIndex = 0 var lastSeparatorIndex = 0 var nextIndex = 0 var sections = [] do { nextIndex = str.indexOf(separator, lastMatchIndex) if (nextIndex !== -1) { lastMatchIndex = nextIndex + separator.length if (nextIndex > 0 && str[nextIndex - 1] === '\\') { continue } sections.push(str.slice(lastSeparatorIndex, nextIndex)) lastSeparatorIndex = nextIndex + separator.length } } while (nextIndex !== -1) sections.push(str.slice(lastSeparatorIndex)) return sections } const decode = (str, opt = {}) => { opt.bracketedArray = opt.bracketedArray !== false const out = Object.create(null) let p = out let section = null // section |key = value const re = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i const lines = str.split(/[\r\n]+/g) const duplicates = {} for (const line of lines) { if (!line || line.match(/^\s*[;#]/) || line.match(/^\s*$/)) { continue } const match = line.match(re) if (!match) { continue } if (match[1] !== undefined) { section = unsafe(match[1]) if (section === '__proto__') { // not allowed // keep parsing the section, but don't attach it. p = Object.create(null) continue } p = out[section] = out[section] || Object.create(null) continue } const keyRaw = unsafe(match[2]) let isArray if (opt.bracketedArray) { isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]' } else { duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1 isArray = duplicates[keyRaw] > 1 } const key = isArray && keyRaw.endsWith('[]') ? keyRaw.slice(0, -2) : keyRaw if (key === '__proto__') { continue } const valueRaw = match[3] ? unsafe(match[4]) : true const value = valueRaw === 'true' || valueRaw === 'false' || valueRaw === 'null' ? JSON.parse(valueRaw) : valueRaw // Convert keys with '[]' suffix to an array if (isArray) { if (!hasOwnProperty.call(p, key)) { p[key] = [] } else if (!Array.isArray(p[key])) { p[key] = [p[key]] } } // safeguard against resetting a previously defined // array by accidentally forgetting the brackets if (Array.isArray(p[key])) { p[key].push(value) } else { p[key] = value } } // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} // use a filter to return the keys that have to be deleted. const remove = [] for (const k of Object.keys(out)) { if (!hasOwnProperty.call(out, k) || typeof out[k] !== 'object' || Array.isArray(out[k])) { continue } // see if the parent section is also an object. // if so, add it to that, and mark this one for deletion const parts = splitSections(k, '.') p = out const l = parts.pop() const nl = l.replace(/\\\./g, '.') for (const part of parts) { if (part === '__proto__') { continue } if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') { p[part] = Object.create(null) } p = p[part] } if (p === out && nl === l) { continue } p[nl] = out[k] remove.push(k) } for (const del of remove) { delete out[del] } return out } const isQuoted = val => { return (val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'")) } const safe = val => { if ( typeof val !== 'string' || val.match(/[=\r\n]/) || val.match(/^\[/) || (val.length > 1 && isQuoted(val)) || val !== val.trim() ) { return JSON.stringify(val) } return val.split(';').join('\\;').split('#').join('\\#') } const unsafe = val => { val = (val || '').trim() if (isQuoted(val)) { // remove the single quotes before calling JSON.parse if (val.charAt(0) === "'") { val = val.slice(1, -1) } try { val = JSON.parse(val) } catch { // ignore errors } } else { // walk the val to find the first not-escaped ; character let esc = false let unesc = '' for (let i = 0, l = val.length; i < l; i++) { const c = val.charAt(i) if (esc) { if ('\\;#'.indexOf(c) !== -1) { unesc += c } else { unesc += '\\' + c } esc = false } else if (';#'.indexOf(c) !== -1) { break } else if (c === '\\') { esc = true } else { unesc += c } } if (esc) { unesc += '\\' } return unesc.trim() } return val } module.exports = { parse: decode, decode, stringify: encode, encode, safe, unsafe, } { "author": "GitHub Inc.", "name": "ini", "description": "An ini encoder/decoder for node", "version": "5.0.0", "repository": { "type": "git", "url": "git+https://github.com/npm/ini.git" }, "main": "lib/ini.js", "scripts": { "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "test": "tap", "snap": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.0.1" }, "license": "ISC", "files": [ "bin/", "lib/" ], "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": "true" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* globals config, dirname, package, basename, yes, prompt */ const fs = require('fs/promises') const path = require('path') const validateLicense = require('validate-npm-package-license') const validateName = require('validate-npm-package-name') const npa = require('npm-package-arg') const semver = require('semver') // more popular packages should go here, maybe? const isTestPkg = (p) => !!p.match(/^(expresso|mocha|tap|coffee-script|coco|streamline)$/) const invalid = (msg) => Object.assign(new Error(msg), { notValid: true }) const readDeps = (test, excluded) => async () => { const dirs = await fs.readdir('node_modules').catch(() => null) if (!dirs) { return } const deps = {} for (const dir of dirs) { if (dir.match(/^\./) || test !== isTestPkg(dir) || excluded[dir]) { continue } const dp = path.join(dirname, 'node_modules', dir, 'package.json') const p = await fs.readFile(dp, 'utf8').then((d) => JSON.parse(d)).catch(() => null) if (!p || !p.version || p?._requiredBy?.some((r) => r === '#USER')) { continue } deps[dir] = config.get('save-exact') ? p.version : config.get('save-prefix') + p.version } return deps } const getConfig = (key) => { // dots take precedence over dashes const def = config?.defaults?.[`init.${key}`] const val = config.get(`init.${key}`) return (val !== def && val) ? val : config.get(`init-${key.replace(/\./g, '-')}`) } const getName = () => { const rawName = package.name || basename let name = rawName .replace(/^node-|[.-]js$/g, '') .replace(/\s+/g, ' ') .replace(/ /g, '-') .toLowerCase() let spec try { spec = npa(name) } catch { spec = {} } let scope = config.get('scope') if (scope) { if (scope.charAt(0) !== '@') { scope = '@' + scope } if (spec.scope) { name = scope + '/' + spec.name.split('/')[1] } else { name = scope + '/' + name } } return name } const name = getName() exports.name = yes ? name : prompt('package name', name, (data) => { const its = validateName(data) if (its.validForNewPackages) { return data } const errors = (its.errors || []).concat(its.warnings || []) return invalid(`Sorry, ${errors.join(' and ')}.`) }) const version = package.version || getConfig('version') || '1.0.0' exports.version = yes ? version : prompt('version', version, (v) => { if (semver.valid(v)) { return v } return invalid(`Invalid version: "${v}"`) }) if (!package.description) { exports.description = yes ? '' : prompt('description') } if (!package.main) { exports.main = async () => { const files = await fs.readdir(dirname) .then(list => list.filter((f) => f.match(/\.js$/))) .catch(() => []) let index if (files.includes('index.js')) { index = 'index.js' } else if (files.includes('main.js')) { index = 'main.js' } else if (files.includes(basename + '.js')) { index = basename + '.js' } else { index = files[0] || 'index.js' } return yes ? index : prompt('entry point', index) } } if (!package.bin) { exports.bin = async () => { try { const d = await fs.readdir(path.resolve(dirname, 'bin')) // just take the first js file we find there, or nada let r = d.find(f => f.match(/\.js$/)) if (r) { r = `bin/${r}` } return r } catch { // no bins } } } exports.directories = async () => { const dirs = await fs.readdir(dirname) const res = dirs.reduce((acc, d) => { if (/^examples?$/.test(d)) { acc.example = d } else if (/^tests?$/.test(d)) { acc.test = d } else if (/^docs?$/.test(d)) { acc.doc = d } else if (d === 'man') { acc.man = d } else if (d === 'lib') { acc.lib = d } return acc }, {}) return Object.keys(res).length === 0 ? undefined : res } if (!package.dependencies) { exports.dependencies = readDeps(false, package.devDependencies || {}) } if (!package.devDependencies) { exports.devDependencies = readDeps(true, package.dependencies || {}) } // MUST have a test script! if (!package.scripts) { const scripts = package.scripts || {} const notest = 'echo "Error: no test specified" && exit 1' exports.scripts = async () => { const d = await fs.readdir(path.join(dirname, 'node_modules')).catch(() => []) // check to see what framework is in use, if any let command if (!scripts.test || scripts.test === notest) { const commands = { tap: 'tap test/*.js', expresso: 'expresso test', mocha: 'mocha', } for (const [k, v] of Object.entries(commands)) { if (d.includes(k)) { command = v } } } const promptArgs = ['test command', (t) => t || notest] if (command) { promptArgs.splice(1, 0, command) } scripts.test = yes ? command || notest : prompt(...promptArgs) return scripts } } if (!package.repository) { exports.repository = async () => { const gitConfigPath = path.resolve(dirname, '.git', 'config') const gconf = await fs.readFile(gitConfigPath, 'utf8').catch(() => '') const lines = gconf.split(/\r?\n/) let url const i = lines.indexOf('[remote "origin"]') if (i !== -1) { url = lines[i + 1] if (!url.match(/^\s*url =/)) { url = lines[i + 2] } if (!url.match(/^\s*url =/)) { url = null } else { url = url.replace(/^\s*url = /, '') } } if (url && url.match(/^git@github.com:/)) { url = url.replace(/^git@github.com:/, 'https://github.com/') } return yes ? url || '' : prompt('git repository', url || undefined) } } if (!package.keywords) { exports.keywords = yes ? '' : prompt('keywords', (data) => { if (!data) { return } if (Array.isArray(data)) { data = data.join(' ') } if (typeof data !== 'string') { return data } return data.split(/[\s,]+/) }) } if (!package.author) { const authorName = getConfig('author.name') exports.author = authorName ? { name: authorName, email: getConfig('author.email'), url: getConfig('author.url'), } : yes ? '' : prompt('author') } const license = package.license || getConfig('license') || 'ISC' exports.license = yes ? license : prompt('license', license, (data) => { const its = validateLicense(data) if (its.validForNewPackages) { return data } const errors = (its.errors || []).concat(its.warnings || []) return invalid(`Sorry, ${errors.join(' and ')}.`) }) const type = package.type || getConfig('type') || 'commonjs' exports.type = yes ? type : prompt('type', type, (data) => { return data }) const promzard = require('promzard') const path = require('path') const semver = require('semver') const { read } = require('read') const util = require('util') const PackageJson = require('@npmcli/package-json') const def = require.resolve('./default-input.js') const extras = [ 'bundleDependencies', 'gypfile', 'serverjs', 'scriptpath', 'readme', 'bin', 'githead', 'fillTypes', 'normalizeData', ] const isYes = (c) => !!(c.get('yes') || c.get('y') || c.get('force') || c.get('f')) const getConfig = (c) => { // accept either a plain-jane object, or a config object with a "get" method. if (typeof c.get !== 'function') { const data = c return { get: (k) => data[k], toJSON: () => data, } } return c } // Coverage disabled because this is just walking back the fixPeople // normalization from the normalizeData step and we don't need to re-test all // of those paths. /* istanbul ignore next */ const stringifyPerson = (p) => { const { name, url, web, email, mail } = p const u = url || web const e = email || mail return `${name}${e ? ` <${e}>` : ''}${u ? ` (${u})` : ''}` } async function init (dir, // TODO test for non-default definitions /* istanbul ignore next */ input = def, c = {}) { const config = getConfig(c) const yes = isYes(config) const packageFile = path.resolve(dir, 'package.json') // read what's already there to inform our prompts const pkg = await PackageJson.load(dir, { create: true }) await pkg.normalize() if (!semver.valid(pkg.content.version)) { delete pkg.content.version } // make sure that the input is valid. if not, use the default const pzData = await promzard(path.resolve(input), { yes, config, filename: packageFile, dirname: dir, basename: path.basename(dir), package: pkg.content, }, { backupFile: def }) for (const [k, v] of Object.entries(pzData)) { if (v != null) { pkg.content[k] = v } } await pkg.normalize({ steps: extras }) // turn the objects back into somewhat more humane strings. // "normalizeData" does this and there isn't a way to choose which of those steps happen if (pkg.content.author) { pkg.content.author = stringifyPerson(pkg.content.author) } // no need for the readme now. delete pkg.content.readme delete pkg.content.readmeFilename // really don't want to have this lying around in the file delete pkg.content._id // ditto delete pkg.content.gitHead // if the repo is empty, remove it. if (!pkg.content.repository) { delete pkg.content.repository } // readJson filters out empty descriptions, but init-package-json // traditionally leaves them alone if (!pkg.content.description) { pkg.content.description = pzData.description } // optionalDependencies don't need to be repeated in two places if (pkg.content.dependencies) { if (pkg.content.optionalDependencies) { for (const name of Object.keys(pkg.content.optionalDependencies)) { delete pkg.content.dependencies[name] } } if (Object.keys(pkg.content.dependencies).length === 0) { delete pkg.content.dependencies } } const stringified = JSON.stringify(pkg.content, null, 2) + '\n' const msg = util.format('%s:\n\n%s\n', packageFile, stringified) if (yes) { await pkg.save() if (!config.get('silent')) { // eslint-disable-next-line no-console console.log(`Wrote to ${msg}`) } return pkg.content } // eslint-disable-next-line no-console console.log(`About to write to ${msg}`) const ok = await read({ prompt: 'Is this OK? ', default: 'yes' }) if (!ok || !ok.toLowerCase().startsWith('y')) { // eslint-disable-next-line no-console console.log('Aborted.') return } await pkg.save({ sort: true }) return pkg.content } module.exports = init module.exports.yes = isYes { "name": "init-package-json", "version": "8.0.0", "main": "lib/init-package-json.js", "scripts": { "test": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/init-package-json.git" }, "author": "GitHub Inc.", "license": "ISC", "description": "A node module to get your node module started", "dependencies": { "@npmcli/package-json": "^6.1.0", "npm-package-arg": "^12.0.0", "promzard": "^2.0.0", "read": "^4.0.0", "semver": "^7.3.5", "validate-npm-package-license": "^3.0.4", "validate-npm-package-name": "^6.0.0" }, "devDependencies": { "@npmcli/config": "^9.0.0", "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.4", "tap": "^16.0.1" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "tap": { "test-ignore": "fixtures/", "nyc-arg": [ "--exclude", "tap-snapshots/**" ], "timeout": 300 }, "keywords": [ "init", "package.json", "package", "helper", "wizard", "wizerd", "prompt", "start" ], "files": [ "bin/", "lib/" ], "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.4", "publish": true } } Copyright (C) 2011 by Beau Gunderson 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. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AddressError = void 0; class AddressError extends Error { constructor(message, parseMessage) { super(message); this.name = 'AddressError'; if (parseMessage !== null) { this.parseMessage = parseMessage; } } } exports.AddressError = AddressError; //# sourceMappingURL=address-error.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCorrect = exports.isInSubnet = void 0; function isInSubnet(address) { if (this.subnetMask < address.subnetMask) { return false; } if (this.mask(address.subnetMask) === address.mask()) { return true; } return false; } exports.isInSubnet = isInSubnet; function isCorrect(defaultBits) { return function () { if (this.addressMinusSuffix !== this.correctForm()) { return false; } if (this.subnetMask === defaultBits && !this.parsedSubnet) { return true; } return this.parsedSubnet === String(this.subnetMask); }; } exports.isCorrect = isCorrect; //# sourceMappingURL=common.js.map"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; const ipv4_1 = require("./ipv4"); Object.defineProperty(exports, "Address4", { enumerable: true, get: function () { return ipv4_1.Address4; } }); const ipv6_1 = require("./ipv6"); Object.defineProperty(exports, "Address6", { enumerable: true, get: function () { return ipv6_1.Address6; } }); const address_error_1 = require("./address-error"); Object.defineProperty(exports, "AddressError", { enumerable: true, get: function () { return address_error_1.AddressError; } }); const helpers = __importStar(require("./v6/helpers")); exports.v6 = { helpers }; //# sourceMappingURL=ip-address.js.map"use strict"; /* eslint-disable no-param-reassign */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Address4 = void 0; const common = __importStar(require("./common")); const constants = __importStar(require("./v4/constants")); const address_error_1 = require("./address-error"); const jsbn_1 = require("jsbn"); const sprintf_js_1 = require("sprintf-js"); /** * Represents an IPv4 address * @class Address4 * @param {string} address - An IPv4 address string */ class Address4 { constructor(address) { this.groups = constants.GROUPS; this.parsedAddress = []; this.parsedSubnet = ''; this.subnet = '/32'; this.subnetMask = 32; this.v4 = true; /** * Returns true if the address is correct, false otherwise * @memberof Address4 * @instance * @returns {Boolean} */ this.isCorrect = common.isCorrect(constants.BITS); /** * Returns true if the given address is in the subnet of the current address * @memberof Address4 * @instance * @returns {boolean} */ this.isInSubnet = common.isInSubnet; this.address = address; const subnet = constants.RE_SUBNET_STRING.exec(address); if (subnet) { this.parsedSubnet = subnet[0].replace('/', ''); this.subnetMask = parseInt(this.parsedSubnet, 10); this.subnet = `/${this.subnetMask}`; if (this.subnetMask < 0 || this.subnetMask > constants.BITS) { throw new address_error_1.AddressError('Invalid subnet mask.'); } address = address.replace(constants.RE_SUBNET_STRING, ''); } this.addressMinusSuffix = address; this.parsedAddress = this.parse(address); } static isValid(address) { try { // eslint-disable-next-line no-new new Address4(address); return true; } catch (e) { return false; } } /* * Parses a v4 address */ parse(address) { const groups = address.split('.'); if (!address.match(constants.RE_ADDRESS)) { throw new address_error_1.AddressError('Invalid IPv4 address.'); } return groups; } /** * Returns the correct form of an address * @memberof Address4 * @instance * @returns {String} */ correctForm() { return this.parsedAddress.map((part) => parseInt(part, 10)).join('.'); } /** * Converts a hex string to an IPv4 address object * @memberof Address4 * @static * @param {string} hex - a hex string to convert * @returns {Address4} */ static fromHex(hex) { const padded = hex.replace(/:/g, '').padStart(8, '0'); const groups = []; let i; for (i = 0; i < 8; i += 2) { const h = padded.slice(i, i + 2); groups.push(parseInt(h, 16)); } return new Address4(groups.join('.')); } /** * Converts an integer into a IPv4 address object * @memberof Address4 * @static * @param {integer} integer - a number to convert * @returns {Address4} */ static fromInteger(integer) { return Address4.fromHex(integer.toString(16)); } /** * Return an address from in-addr.arpa form * @memberof Address4 * @static * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address * @returns {Adress4} * @example * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.) * address.correctForm(); // '192.0.2.42' */ static fromArpa(arpaFormAddress) { // remove ending ".in-addr.arpa." or just "." const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, ''); const address = leader.split('.').reverse().join('.'); return new Address4(address); } /** * Converts an IPv4 address object to a hex string * @memberof Address4 * @instance * @returns {String} */ toHex() { return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)('%02x', parseInt(part, 10))).join(':'); } /** * Converts an IPv4 address object to an array of bytes * @memberof Address4 * @instance * @returns {Array} */ toArray() { return this.parsedAddress.map((part) => parseInt(part, 10)); } /** * Converts an IPv4 address object to an IPv6 address group * @memberof Address4 * @instance * @returns {String} */ toGroup6() { const output = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { const hex = (0, sprintf_js_1.sprintf)('%02x%02x', parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10)); output.push((0, sprintf_js_1.sprintf)('%x', parseInt(hex, 16))); } return output.join(':'); } /** * Returns the address as a BigInteger * @memberof Address4 * @instance * @returns {BigInteger} */ bigInteger() { return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%02x', parseInt(n, 10))).join(''), 16); } /** * Helper function getting start address. * @memberof Address4 * @instance * @returns {BigInteger} */ _startAddress() { return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants.BITS - this.subnetMask), 2); } /** * The first address in the range given by this address' subnet. * Often referred to as the Network Address. * @memberof Address4 * @instance * @returns {Address4} */ startAddress() { return Address4.fromBigInteger(this._startAddress()); } /** * The first host address in the range given by this address's subnet ie * the first address after the Network Address * @memberof Address4 * @instance * @returns {Address4} */ startAddressExclusive() { const adjust = new jsbn_1.BigInteger('1'); return Address4.fromBigInteger(this._startAddress().add(adjust)); } /** * Helper function getting end address. * @memberof Address4 * @instance * @returns {BigInteger} */ _endAddress() { return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants.BITS - this.subnetMask), 2); } /** * The last address in the range given by this address' subnet * Often referred to as the Broadcast * @memberof Address4 * @instance * @returns {Address4} */ endAddress() { return Address4.fromBigInteger(this._endAddress()); } /** * The last host address in the range given by this address's subnet ie * the last address prior to the Broadcast Address * @memberof Address4 * @instance * @returns {Address4} */ endAddressExclusive() { const adjust = new jsbn_1.BigInteger('1'); return Address4.fromBigInteger(this._endAddress().subtract(adjust)); } /** * Converts a BigInteger to a v4 address object * @memberof Address4 * @static * @param {BigInteger} bigInteger - a BigInteger to convert * @returns {Address4} */ static fromBigInteger(bigInteger) { return Address4.fromInteger(parseInt(bigInteger.toString(), 10)); } /** * Returns the first n bits of the address, defaulting to the * subnet mask * @memberof Address4 * @instance * @returns {String} */ mask(mask) { if (mask === undefined) { mask = this.subnetMask; } return this.getBitsBase2(0, mask); } /** * Returns the bits in the given range as a base-2 string * @memberof Address4 * @instance * @returns {string} */ getBitsBase2(start, end) { return this.binaryZeroPad().slice(start, end); } /** * Return the reversed ip6.arpa form of the address * @memberof Address4 * @param {Object} options * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix * @instance * @returns {String} */ reverseForm(options) { if (!options) { options = {}; } const reversed = this.correctForm().split('.').reverse().join('.'); if (options.omitSuffix) { return reversed; } return (0, sprintf_js_1.sprintf)('%s.in-addr.arpa.', reversed); } /** * Returns true if the given address is a multicast address * @memberof Address4 * @instance * @returns {boolean} */ isMulticast() { return this.isInSubnet(new Address4('224.0.0.0/4')); } /** * Returns a zero-padded base-2 string representation of the address * @memberof Address4 * @instance * @returns {string} */ binaryZeroPad() { return this.bigInteger().toString(2).padStart(constants.BITS, '0'); } /** * Groups an IPv4 address for inclusion at the end of an IPv6 address * @returns {String} */ groupForV6() { const segments = this.parsedAddress; return this.address.replace(constants.RE_ADDRESS, (0, sprintf_js_1.sprintf)('%s.%s', segments.slice(0, 2).join('.'), segments.slice(2, 4).join('.'))); } } exports.Address4 = Address4; //# sourceMappingURL=ipv4.js.map"use strict"; /* eslint-disable prefer-destructuring */ /* eslint-disable no-param-reassign */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Address6 = void 0; const common = __importStar(require("./common")); const constants4 = __importStar(require("./v4/constants")); const constants6 = __importStar(require("./v6/constants")); const helpers = __importStar(require("./v6/helpers")); const ipv4_1 = require("./ipv4"); const regular_expressions_1 = require("./v6/regular-expressions"); const address_error_1 = require("./address-error"); const jsbn_1 = require("jsbn"); const sprintf_js_1 = require("sprintf-js"); function assert(condition) { if (!condition) { throw new Error('Assertion failed.'); } } function addCommas(number) { const r = /(\d+)(\d{3})/; while (r.test(number)) { number = number.replace(r, '$1,$2'); } return number; } function spanLeadingZeroes4(n) { n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2'); n = n.replace(/^(0{1,})(0)$/, '$1$2'); return n; } /* * A helper function to compact an array */ function compact(address, slice) { const s1 = []; const s2 = []; let i; for (i = 0; i < address.length; i++) { if (i < slice[0]) { s1.push(address[i]); } else if (i > slice[1]) { s2.push(address[i]); } } return s1.concat(['compact']).concat(s2); } function paddedHex(octet) { return (0, sprintf_js_1.sprintf)('%04x', parseInt(octet, 16)); } function unsignByte(b) { // eslint-disable-next-line no-bitwise return b & 0xff; } /** * Represents an IPv6 address * @class Address6 * @param {string} address - An IPv6 address string * @param {number} [groups=8] - How many octets to parse * @example * var address = new Address6('2001::/32'); */ class Address6 { constructor(address, optionalGroups) { this.addressMinusSuffix = ''; this.parsedSubnet = ''; this.subnet = '/128'; this.subnetMask = 128; this.v4 = false; this.zone = ''; // #region Attributes /** * Returns true if the given address is in the subnet of the current address * @memberof Address6 * @instance * @returns {boolean} */ this.isInSubnet = common.isInSubnet; /** * Returns true if the address is correct, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ this.isCorrect = common.isCorrect(constants6.BITS); if (optionalGroups === undefined) { this.groups = constants6.GROUPS; } else { this.groups = optionalGroups; } this.address = address; const subnet = constants6.RE_SUBNET_STRING.exec(address); if (subnet) { this.parsedSubnet = subnet[0].replace('/', ''); this.subnetMask = parseInt(this.parsedSubnet, 10); this.subnet = `/${this.subnetMask}`; if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) { throw new address_error_1.AddressError('Invalid subnet mask.'); } address = address.replace(constants6.RE_SUBNET_STRING, ''); } else if (/\//.test(address)) { throw new address_error_1.AddressError('Invalid subnet mask.'); } const zone = constants6.RE_ZONE_STRING.exec(address); if (zone) { this.zone = zone[0]; address = address.replace(constants6.RE_ZONE_STRING, ''); } this.addressMinusSuffix = address; this.parsedAddress = this.parse(this.addressMinusSuffix); } static isValid(address) { try { // eslint-disable-next-line no-new new Address6(address); return true; } catch (e) { return false; } } /** * Convert a BigInteger to a v6 address object * @memberof Address6 * @static * @param {BigInteger} bigInteger - a BigInteger to convert * @returns {Address6} * @example * var bigInteger = new BigInteger('1000000000000'); * var address = Address6.fromBigInteger(bigInteger); * address.correctForm(); // '::e8:d4a5:1000' */ static fromBigInteger(bigInteger) { const hex = bigInteger.toString(16).padStart(32, '0'); const groups = []; let i; for (i = 0; i < constants6.GROUPS; i++) { groups.push(hex.slice(i * 4, (i + 1) * 4)); } return new Address6(groups.join(':')); } /** * Convert a URL (with optional port number) to an address object * @memberof Address6 * @static * @param {string} url - a URL with optional port number * @example * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); * addressAndPort.address.correctForm(); // 'ffff::' * addressAndPort.port; // 8080 */ static fromURL(url) { let host; let port = null; let result; // If we have brackets parse them and find a port if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) { result = constants6.RE_URL_WITH_PORT.exec(url); if (result === null) { return { error: 'failed to parse address with port', address: null, port: null, }; } host = result[1]; port = result[2]; // If there's a URL extract the address } else if (url.indexOf('/') !== -1) { // Remove the protocol prefix url = url.replace(/^[a-z0-9]+:\/\//, ''); // Parse the address result = constants6.RE_URL.exec(url); if (result === null) { return { error: 'failed to parse address from URL', address: null, port: null, }; } host = result[1]; // Otherwise just assign the URL to the host and let the library parse it } else { host = url; } // If there's a port convert it to an integer if (port) { port = parseInt(port, 10); // squelch out of range ports if (port < 0 || port > 65536) { port = null; } } else { // Standardize `undefined` to `null` port = null; } return { address: new Address6(host), port, }; } /** * Create an IPv6-mapped address given an IPv4 address * @memberof Address6 * @static * @param {string} address - An IPv4 address string * @returns {Address6} * @example * var address = Address6.fromAddress4('192.168.0.1'); * address.correctForm(); // '::ffff:c0a8:1' * address.to4in6(); // '::ffff:192.168.0.1' */ static fromAddress4(address) { const address4 = new ipv4_1.Address4(address); const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); return new Address6(`::ffff:${address4.correctForm()}/${mask6}`); } /** * Return an address from ip6.arpa form * @memberof Address6 * @static * @param {string} arpaFormAddress - an 'ip6.arpa' form address * @returns {Adress6} * @example * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' */ static fromArpa(arpaFormAddress) { // remove ending ".ip6.arpa." or just "." let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, ''); const semicolonAmount = 7; // correct ip6.arpa form with ending removed will be 63 characters if (address.length !== 63) { throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); } const parts = address.split('.').reverse(); for (let i = semicolonAmount; i > 0; i--) { const insertIndex = i * 4; parts.splice(insertIndex, 0, ':'); } address = parts.join(''); return new Address6(address); } /** * Return the Microsoft UNC transcription of the address * @memberof Address6 * @instance * @returns {String} the Microsoft UNC transcription of the address */ microsoftTranscription() { return (0, sprintf_js_1.sprintf)('%s.ipv6-literal.net', this.correctForm().replace(/:/g, '-')); } /** * Return the first n bits of the address, defaulting to the subnet mask * @memberof Address6 * @instance * @param {number} [mask=subnet] - the number of bits to mask * @returns {String} the first n bits of the address as a string */ mask(mask = this.subnetMask) { return this.getBitsBase2(0, mask); } /** * Return the number of possible subnets of a given size in the address * @memberof Address6 * @instance * @param {number} [size=128] - the subnet size * @returns {String} */ // TODO: probably useful to have a numeric version of this too possibleSubnets(subnetSize = 128) { const availableBits = constants6.BITS - this.subnetMask; const subnetBits = Math.abs(subnetSize - constants6.BITS); const subnetPowers = availableBits - subnetBits; if (subnetPowers < 0) { return '0'; } return addCommas(new jsbn_1.BigInteger('2', 10).pow(subnetPowers).toString(10)); } /** * Helper function getting start address. * @memberof Address6 * @instance * @returns {BigInteger} */ _startAddress() { return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants6.BITS - this.subnetMask), 2); } /** * The first address in the range given by this address' subnet * Often referred to as the Network Address. * @memberof Address6 * @instance * @returns {Address6} */ startAddress() { return Address6.fromBigInteger(this._startAddress()); } /** * The first host address in the range given by this address's subnet ie * the first address after the Network Address * @memberof Address6 * @instance * @returns {Address6} */ startAddressExclusive() { const adjust = new jsbn_1.BigInteger('1'); return Address6.fromBigInteger(this._startAddress().add(adjust)); } /** * Helper function getting end address. * @memberof Address6 * @instance * @returns {BigInteger} */ _endAddress() { return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants6.BITS - this.subnetMask), 2); } /** * The last address in the range given by this address' subnet * Often referred to as the Broadcast * @memberof Address6 * @instance * @returns {Address6} */ endAddress() { return Address6.fromBigInteger(this._endAddress()); } /** * The last host address in the range given by this address's subnet ie * the last address prior to the Broadcast Address * @memberof Address6 * @instance * @returns {Address6} */ endAddressExclusive() { const adjust = new jsbn_1.BigInteger('1'); return Address6.fromBigInteger(this._endAddress().subtract(adjust)); } /** * Return the scope of the address * @memberof Address6 * @instance * @returns {String} */ getScope() { let scope = constants6.SCOPES[this.getBits(12, 16).intValue()]; if (this.getType() === 'Global unicast' && scope !== 'Link local') { scope = 'Global'; } return scope || 'Unknown'; } /** * Return the type of the address * @memberof Address6 * @instance * @returns {String} */ getType() { for (const subnet of Object.keys(constants6.TYPES)) { if (this.isInSubnet(new Address6(subnet))) { return constants6.TYPES[subnet]; } } return 'Global unicast'; } /** * Return the bits in the given range as a BigInteger * @memberof Address6 * @instance * @returns {BigInteger} */ getBits(start, end) { return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2); } /** * Return the bits in the given range as a base-2 string * @memberof Address6 * @instance * @returns {String} */ getBitsBase2(start, end) { return this.binaryZeroPad().slice(start, end); } /** * Return the bits in the given range as a base-16 string * @memberof Address6 * @instance * @returns {String} */ getBitsBase16(start, end) { const length = end - start; if (length % 4 !== 0) { throw new Error('Length of bits to retrieve must be divisible by four'); } return this.getBits(start, end) .toString(16) .padStart(length / 4, '0'); } /** * Return the bits that are set past the subnet mask length * @memberof Address6 * @instance * @returns {String} */ getBitsPastSubnet() { return this.getBitsBase2(this.subnetMask, constants6.BITS); } /** * Return the reversed ip6.arpa form of the address * @memberof Address6 * @param {Object} options * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix * @instance * @returns {String} */ reverseForm(options) { if (!options) { options = {}; } const characters = Math.floor(this.subnetMask / 4); const reversed = this.canonicalForm() .replace(/:/g, '') .split('') .slice(0, characters) .reverse() .join('.'); if (characters > 0) { if (options.omitSuffix) { return reversed; } return (0, sprintf_js_1.sprintf)('%s.ip6.arpa.', reversed); } if (options.omitSuffix) { return ''; } return 'ip6.arpa.'; } /** * Return the correct form of the address * @memberof Address6 * @instance * @returns {String} */ correctForm() { let i; let groups = []; let zeroCounter = 0; const zeroes = []; for (i = 0; i < this.parsedAddress.length; i++) { const value = parseInt(this.parsedAddress[i], 16); if (value === 0) { zeroCounter++; } if (value !== 0 && zeroCounter > 0) { if (zeroCounter > 1) { zeroes.push([i - zeroCounter, i - 1]); } zeroCounter = 0; } } // Do we end with a string of zeroes? if (zeroCounter > 1) { zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); } const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); if (zeroes.length > 0) { const index = zeroLengths.indexOf(Math.max(...zeroLengths)); groups = compact(this.parsedAddress, zeroes[index]); } else { groups = this.parsedAddress; } for (i = 0; i < groups.length; i++) { if (groups[i] !== 'compact') { groups[i] = parseInt(groups[i], 16).toString(16); } } let correct = groups.join(':'); correct = correct.replace(/^compact$/, '::'); correct = correct.replace(/^compact|compact$/, ':'); correct = correct.replace(/compact/, ''); return correct; } /** * Return a zero-padded base-2 string representation of the address * @memberof Address6 * @instance * @returns {String} * @example * var address = new Address6('2001:4860:4001:803::1011'); * address.binaryZeroPad(); * // '0010000000000001010010000110000001000000000000010000100000000011 * // 0000000000000000000000000000000000000000000000000001000000010001' */ binaryZeroPad() { return this.bigInteger().toString(2).padStart(constants6.BITS, '0'); } // TODO: Improve the semantics of this helper function parse4in6(address) { const groups = address.split(':'); const lastGroup = groups.slice(-1)[0]; const address4 = lastGroup.match(constants4.RE_ADDRESS); if (address4) { this.parsedAddress4 = address4[0]; this.address4 = new ipv4_1.Address4(this.parsedAddress4); for (let i = 0; i < this.address4.groups; i++) { if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) { throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.'))); } } this.v4 = true; groups[groups.length - 1] = this.address4.toGroup6(); address = groups.join(':'); } return address; } // TODO: Make private? parse(address) { address = this.parse4in6(address); const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); if (badCharacters) { throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Bad character%s detected in address: %s', badCharacters.length > 1 ? 's' : '', badCharacters.join('')), address.replace(constants6.RE_BAD_CHARACTERS, '$1')); } const badAddress = address.match(constants6.RE_BAD_ADDRESS); if (badAddress) { throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Address failed regex: %s', badAddress.join('')), address.replace(constants6.RE_BAD_ADDRESS, '$1')); } let groups = []; const halves = address.split('::'); if (halves.length === 2) { let first = halves[0].split(':'); let last = halves[1].split(':'); if (first.length === 1 && first[0] === '') { first = []; } if (last.length === 1 && last[0] === '') { last = []; } const remaining = this.groups - (first.length + last.length); if (!remaining) { throw new address_error_1.AddressError('Error parsing groups'); } this.elidedGroups = remaining; this.elisionBegin = first.length; this.elisionEnd = first.length + this.elidedGroups; groups = groups.concat(first); for (let i = 0; i < remaining; i++) { groups.push('0'); } groups = groups.concat(last); } else if (halves.length === 1) { groups = address.split(':'); this.elidedGroups = 0; } else { throw new address_error_1.AddressError('Too many :: groups found'); } groups = groups.map((group) => (0, sprintf_js_1.sprintf)('%x', parseInt(group, 16))); if (groups.length !== this.groups) { throw new address_error_1.AddressError('Incorrect number of groups found'); } return groups; } /** * Return the canonical form of the address * @memberof Address6 * @instance * @returns {String} */ canonicalForm() { return this.parsedAddress.map(paddedHex).join(':'); } /** * Return the decimal form of the address * @memberof Address6 * @instance * @returns {String} */ decimal() { return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%05d', parseInt(n, 16))).join(':'); } /** * Return the address as a BigInteger * @memberof Address6 * @instance * @returns {BigInteger} */ bigInteger() { return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(''), 16); } /** * Return the last two groups of this address as an IPv4 address string * @memberof Address6 * @instance * @returns {Address4} * @example * var address = new Address6('2001:4860:4001::1825:bf11'); * address.to4().correctForm(); // '24.37.191.17' */ to4() { const binary = this.binaryZeroPad().split(''); return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(''), 2).toString(16)); } /** * Return the v4-in-v6 form of the address * @memberof Address6 * @instance * @returns {String} */ to4in6() { const address4 = this.to4(); const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6); const correct = address6.correctForm(); let infix = ''; if (!/:$/.test(correct)) { infix = ':'; } return correct + infix + address4.address; } /** * Return an object containing the Teredo properties of the address * @memberof Address6 * @instance * @returns {Object} */ inspectTeredo() { /* - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32). - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that is used. - Bits 64 to 79 can be used to define some flags. Currently only the higher order bit is used; it is set to 1 if the Teredo client is located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista and Windows Server 2008 implementations, more bits are used. In those implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA", where "C" remains the "Cone" flag. The "R" bit is reserved for future use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit is Individual/Group flag (set to 0). The A bits are set to a 12-bit randomly generated number chosen by the Teredo client to introduce additional protection for the Teredo node against IPv6-based scanning attacks. - Bits 80 to 95 contains the obfuscated UDP port number. This is the port number that is mapped by the NAT to the Teredo client with all bits inverted. - Bits 96 to 127 contains the obfuscated IPv4 address. This is the public IPv4 address of the NAT with all bits inverted. */ const prefix = this.getBitsBase16(0, 32); const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger('ffff', 16)).toString(); const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger('ffffffff', 16)).toString(16)); const flags = this.getBits(64, 80); const flagsBase2 = this.getBitsBase2(64, 80); const coneNat = flags.testBit(15); const reserved = flags.testBit(14); const groupIndividual = flags.testBit(8); const universalLocal = flags.testBit(9); const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10); return { prefix: (0, sprintf_js_1.sprintf)('%s:%s', prefix.slice(0, 4), prefix.slice(4, 8)), server4: server4.address, client4: client4.address, flags: flagsBase2, coneNat, microsoft: { reserved, universalLocal, groupIndividual, nonce, }, udpPort, }; } /** * Return an object containing the 6to4 properties of the address * @memberof Address6 * @instance * @returns {Object} */ inspect6to4() { /* - Bits 0 to 15 are set to the 6to4 prefix (2002::/16). - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used. */ const prefix = this.getBitsBase16(0, 16); const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); return { prefix: (0, sprintf_js_1.sprintf)('%s', prefix.slice(0, 4)), gateway: gateway.address, }; } /** * Return a v6 6to4 address from a v6 v4inv6 address * @memberof Address6 * @instance * @returns {Address6} */ to6to4() { if (!this.is4()) { return null; } const addr6to4 = [ '2002', this.getBitsBase16(96, 112), this.getBitsBase16(112, 128), '', '/16', ].join(':'); return new Address6(addr6to4); } /** * Return a byte array * @memberof Address6 * @instance * @returns {Array} */ toByteArray() { const byteArray = this.bigInteger().toByteArray(); // work around issue where `toByteArray` returns a leading 0 element if (byteArray.length === 17 && byteArray[0] === 0) { return byteArray.slice(1); } return byteArray; } /** * Return an unsigned byte array * @memberof Address6 * @instance * @returns {Array} */ toUnsignedByteArray() { return this.toByteArray().map(unsignByte); } /** * Convert a byte array to an Address6 object * @memberof Address6 * @static * @returns {Address6} */ static fromByteArray(bytes) { return this.fromUnsignedByteArray(bytes.map(unsignByte)); } /** * Convert an unsigned byte array to an Address6 object * @memberof Address6 * @static * @returns {Address6} */ static fromUnsignedByteArray(bytes) { const BYTE_MAX = new jsbn_1.BigInteger('256', 10); let result = new jsbn_1.BigInteger('0', 10); let multiplier = new jsbn_1.BigInteger('1', 10); for (let i = bytes.length - 1; i >= 0; i--) { result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10))); multiplier = multiplier.multiply(BYTE_MAX); } return Address6.fromBigInteger(result); } /** * Returns true if the address is in the canonical form, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isCanonical() { return this.addressMinusSuffix === this.canonicalForm(); } /** * Returns true if the address is a link local address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isLinkLocal() { // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10' if (this.getBitsBase2(0, 64) === '1111111010000000000000000000000000000000000000000000000000000000') { return true; } return false; } /** * Returns true if the address is a multicast address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isMulticast() { return this.getType() === 'Multicast'; } /** * Returns true if the address is a v4-in-v6 address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ is4() { return this.v4; } /** * Returns true if the address is a Teredo address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isTeredo() { return this.isInSubnet(new Address6('2001::/32')); } /** * Returns true if the address is a 6to4 address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ is6to4() { return this.isInSubnet(new Address6('2002::/16')); } /** * Returns true if the address is a loopback address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isLoopback() { return this.getType() === 'Loopback'; } // #endregion // #region HTML /** * @returns {String} the address in link form with a default port of 80 */ href(optionalPort) { if (optionalPort === undefined) { optionalPort = ''; } else { optionalPort = (0, sprintf_js_1.sprintf)(':%s', optionalPort); } return (0, sprintf_js_1.sprintf)('http://[%s]%s/', this.correctForm(), optionalPort); } /** * @returns {String} a link suitable for conveying the address via a URL hash */ link(options) { if (!options) { options = {}; } if (options.className === undefined) { options.className = ''; } if (options.prefix === undefined) { options.prefix = '/#address='; } if (options.v4 === undefined) { options.v4 = false; } let formFunction = this.correctForm; if (options.v4) { formFunction = this.to4in6; } if (options.className) { return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this), options.className); } return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this)); } /** * Groups an address * @returns {String} */ group() { if (this.elidedGroups === 0) { // The simple case return helpers.simpleGroup(this.address).join(':'); } assert(typeof this.elidedGroups === 'number'); assert(typeof this.elisionBegin === 'number'); // The elided case const output = []; const [left, right] = this.address.split('::'); if (left.length) { output.push(...helpers.simpleGroup(left)); } else { output.push(''); } const classes = ['hover-group']; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push((0, sprintf_js_1.sprintf)('group-%d', i)); } output.push((0, sprintf_js_1.sprintf)('', classes.join(' '))); if (right.length) { output.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { output.push(''); } if (this.is4()) { assert(this.address4 instanceof ipv4_1.Address4); output.pop(); output.push(this.address4.groupForV6()); } return output.join(':'); } // #endregion // #region Regular expressions /** * Generate a regular expression string that can be used to find or validate * all variations of this address * @memberof Address6 * @instance * @param {boolean} substringSearch * @returns {string} */ regularExpressionString(substringSearch = false) { let output = []; // TODO: revisit why this is necessary const address6 = new Address6(this.correctForm()); if (address6.elidedGroups === 0) { // The simple case output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { // A completely elided address output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { // A partially elided address const halves = address6.address.split('::'); if (halves[0].length) { output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':'))); } assert(typeof address6.elidedGroups === 'number'); output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':'))); } output = [output.join(':')]; } if (!substringSearch) { output = [ '(?=^|', regular_expressions_1.ADDRESS_BOUNDARY, '|[^\\w\\:])(', ...output, ')(?=[^\\w\\:]|', regular_expressions_1.ADDRESS_BOUNDARY, '|$)', ]; } return output.join(''); } /** * Generate a regular expression that can be used to find or validate all * variations of this address. * @memberof Address6 * @instance * @param {boolean} substringSearch * @returns {RegExp} */ regularExpression(substringSearch = false) { return new RegExp(this.regularExpressionString(substringSearch), 'i'); } } exports.Address6 = Address6; //# sourceMappingURL=ipv6.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0; exports.BITS = 32; exports.GROUPS = 4; exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g; exports.RE_SUBNET_STRING = /\/\d{1,2}$/; //# sourceMappingURL=constants.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0; exports.BITS = 128; exports.GROUPS = 8; /** * Represents IPv6 address scopes * @memberof Address6 * @static */ exports.SCOPES = { 0: 'Reserved', 1: 'Interface local', 2: 'Link local', 4: 'Admin local', 5: 'Site local', 8: 'Organization local', 14: 'Global', 15: 'Reserved', }; /** * Represents IPv6 address types * @memberof Address6 * @static */ exports.TYPES = { 'ff01::1/128': 'Multicast (All nodes on this interface)', 'ff01::2/128': 'Multicast (All routers on this interface)', 'ff02::1/128': 'Multicast (All nodes on this link)', 'ff02::2/128': 'Multicast (All routers on this link)', 'ff05::2/128': 'Multicast (All routers in this site)', 'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)', 'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)', 'ff02::9/128': 'Multicast (RIP routers)', 'ff02::a/128': 'Multicast (EIGRP routers)', 'ff02::d/128': 'Multicast (PIM routers)', 'ff02::16/128': 'Multicast (MLDv2 reports)', 'ff01::fb/128': 'Multicast (mDNSv6)', 'ff02::fb/128': 'Multicast (mDNSv6)', 'ff05::fb/128': 'Multicast (mDNSv6)', 'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)', 'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)', 'ff02::1:3/128': 'Multicast (All DHCP servers on this link)', 'ff05::1:3/128': 'Multicast (All DHCP servers in this site)', '::/128': 'Unspecified', '::1/128': 'Loopback', 'ff00::/8': 'Multicast', 'fe80::/10': 'Link-local unicast', }; /** * A regular expression that matches bad characters in an IPv6 address * @memberof Address6 * @static */ exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; /** * A regular expression that matches an incorrect IPv6 address * @memberof Address6 * @static */ exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; /** * A regular expression that matches an IPv6 subnet * @memberof Address6 * @static */ exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; /** * A regular expression that matches an IPv6 zone * @memberof Address6 * @static */ exports.RE_ZONE_STRING = /%.*$/; exports.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/); exports.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/); //# sourceMappingURL=constants.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.simpleGroup = exports.spanLeadingZeroes = exports.spanAll = exports.spanAllZeroes = void 0; const sprintf_js_1 = require("sprintf-js"); /** * @returns {String} the string with all zeroes contained in a */ function spanAllZeroes(s) { return s.replace(/(0+)/g, '$1'); } exports.spanAllZeroes = spanAllZeroes; /** * @returns {String} the string with each character contained in a */ function spanAll(s, offset = 0) { const letters = s.split(''); return letters .map((n, i) => (0, sprintf_js_1.sprintf)('%s', n, i + offset, spanAllZeroes(n)) // XXX Use #base-2 .value-0 instead? ) .join(''); } exports.spanAll = spanAll; function spanLeadingZeroesSimple(group) { return group.replace(/^(0+)/, '$1'); } /** * @returns {String} the string with leading zeroes contained in a */ function spanLeadingZeroes(address) { const groups = address.split(':'); return groups.map((g) => spanLeadingZeroesSimple(g)).join(':'); } exports.spanLeadingZeroes = spanLeadingZeroes; /** * Groups an address * @returns {String} a grouped address */ function simpleGroup(addressString, offset = 0) { const groups = addressString.split(':'); return groups.map((g, i) => { if (/group-v4/.test(g)) { return g; } return (0, sprintf_js_1.sprintf)('%s', i + offset, spanLeadingZeroesSimple(g)); }); } exports.simpleGroup = simpleGroup; //# sourceMappingURL=helpers.js.map"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.possibleElisions = exports.simpleRegularExpression = exports.ADDRESS_BOUNDARY = exports.padGroup = exports.groupPossibilities = void 0; const v6 = __importStar(require("./constants")); const sprintf_js_1 = require("sprintf-js"); function groupPossibilities(possibilities) { return (0, sprintf_js_1.sprintf)('(%s)', possibilities.join('|')); } exports.groupPossibilities = groupPossibilities; function padGroup(group) { if (group.length < 4) { return (0, sprintf_js_1.sprintf)('0{0,%d}%s', 4 - group.length, group); } return group; } exports.padGroup = padGroup; exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]'; function simpleRegularExpression(groups) { const zeroIndexes = []; groups.forEach((group, i) => { const groupInteger = parseInt(group, 16); if (groupInteger === 0) { zeroIndexes.push(i); } }); // You can technically elide a single 0, this creates the regular expressions // to match that eventuality const possibilities = zeroIndexes.map((zeroIndex) => groups .map((group, i) => { if (i === zeroIndex) { const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : ''; return groupPossibilities([padGroup(group), elision]); } return padGroup(group); }) .join(':')); // The simplest case possibilities.push(groups.map(padGroup).join(':')); return groupPossibilities(possibilities); } exports.simpleRegularExpression = simpleRegularExpression; function possibleElisions(elidedGroups, moreLeft, moreRight) { const left = moreLeft ? '' : ':'; const right = moreRight ? '' : ':'; const possibilities = []; // 1. elision of everything (::) if (!moreLeft && !moreRight) { possibilities.push('::'); } // 2. complete elision of the middle if (moreLeft && moreRight) { possibilities.push(''); } if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) { // 3. complete elision of one side possibilities.push(':'); } // 4. elision from the left side possibilities.push((0, sprintf_js_1.sprintf)('%s(:0{1,4}){1,%d}', left, elidedGroups - 1)); // 5. elision from the right side possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){1,%d}%s', elidedGroups - 1, right)); // 6. no elision possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}0{1,4}', elidedGroups - 1)); // 7. elision (including sloppy elision) from the middle for (let groups = 1; groups < elidedGroups - 1; groups++) { for (let position = 1; position < elidedGroups - groups; position++) { possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}', position, elidedGroups - position - groups - 1)); } } return groupPossibilities(possibilities); } exports.possibleElisions = possibleElisions; //# sourceMappingURL=regular-expressions.js.map{ "name": "ip-address", "description": "A library for parsing IPv4 and IPv6 IP addresses in node and the browser.", "keywords": [ "ipv6", "ipv4", "browser", "validation" ], "version": "9.0.5", "author": "Beau Gunderson (https://beaugunderson.com/)", "license": "MIT", "main": "dist/ip-address.js", "types": "dist/ip-address.d.ts", "scripts": { "docs": "documentation build --github --output docs --format html ./ip-address.js", "build": "rm -rf dist; mkdir dist; tsc", "prepack": "npm run build", "release": "release-it", "test-ci": "nyc mocha", "test": "mocha", "watch": "mocha --watch" }, "nyc": { "extension": [ ".ts" ], "exclude": [ "**/*.d.ts", ".eslintrc.js", "coverage/", "dist/", "test/", "tmp/" ], "reporter": [ "html", "lcov", "text" ], "all": true }, "engines": { "node": ">= 12" }, "files": [ "src", "dist" ], "repository": { "type": "git", "url": "git://github.com/beaugunderson/ip-address.git" }, "dependencies": { "jsbn": "1.1.0", "sprintf-js": "^1.1.3" }, "devDependencies": { "@types/chai": "^4.2.18", "@types/jsbn": "^1.2.31", "@types/mocha": "^10.0.1", "@types/sprintf-js": "^1.1.2", "@typescript-eslint/eslint-plugin": "^6.7.2", "@typescript-eslint/parser": "^6.7.2", "browserify": "^17.0.0", "chai": "^4.3.4", "codecov": "^3.8.2", "documentation": "^14.0.2", "eslint": "^8.50.0", "eslint-config-airbnb": "^19.0.4", "eslint-config-prettier": "^9.0.0", "eslint-plugin-filenames": "^1.3.2", "eslint-plugin-import": "^2.23.4", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-prettier": "^5.0.0", "eslint-plugin-react": "^7.24.0", "eslint-plugin-react-hooks": "^4.2.0", "eslint-plugin-sort-imports-es6-autofix": "^0.6.0", "mocha": "^10.2.0", "nyc": "^15.1.0", "prettier": "^3.0.3", "release-it": "^16.2.0", "source-map-support": "^0.5.19", "ts-node": "^10.0.0", "typescript": "^5.2.2" } } const word = '[a-fA-F\\d:]'; const boundry = options => options && options.includeBoundaries ? `(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))` : ''; const v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}'; const v6segment = '[a-fA-F\\d]{1,4}'; const v6 = ` (?: (?:${v6segment}:){7}(?:${v6segment}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8 (?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4 (?:${v6segment}:){5}(?::${v4}|(?::${v6segment}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4 (?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${v4}|(?::${v6segment}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4 (?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${v4}|(?::${v6segment}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4 (?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${v4}|(?::${v6segment}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4 (?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4 (?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4 )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1 `.replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim(); // Pre-compile only the exact regexes because adding a global flag make regexes stateful const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`); const v4exact = new RegExp(`^${v4}$`); const v6exact = new RegExp(`^${v6}$`); const ipRegex = options => options && options.exact ? v46Exact : new RegExp(`(?:${boundry(options)}${v4}${boundry(options)})|(?:${boundry(options)}${v6}${boundry(options)})`, 'g'); ipRegex.v4 = options => options && options.exact ? v4exact : new RegExp(`${boundry(options)}${v4}${boundry(options)}`, 'g'); ipRegex.v6 = options => options && options.exact ? v6exact : new RegExp(`${boundry(options)}${v6}${boundry(options)}`, 'g'); export default ipRegex; MIT License Copyright (c) Sindre Sorhus (https://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. { "name": "ip-regex", "version": "5.0.0", "description": "Regular expression for matching IP addresses (IPv4 & IPv6)", "license": "MIT", "repository": "sindresorhus/ip-regex", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "ip", "ipv6", "ipv4", "regex", "regexp", "re", "match", "test", "find", "text", "pattern", "internet", "protocol", "address", "validate" ], "devDependencies": { "ava": "^3.15.0", "tsd": "^0.19.1", "xo": "^0.47.0" } } import { v4 as v4$1, v6 as v6$1 } from "cidr-regex"; const re4 = v4$1({ exact: true }); const re6 = v6$1({ exact: true }); const isCidr = (str) => re4.test(str) ? 4 : re6.test(str) ? 6 : 0; const v4 = isCidr.v4 = (str) => re4.test(str); const v6 = isCidr.v6 = (str) => re6.test(str); export { isCidr as default, v4, v6 }; { "name": "is-cidr", "version": "5.1.0", "description": "Check if a string is an IP address in CIDR notation", "author": "silverwind ", "contributors": [ "Felipe Apostol (http://flipjs.io/)" ], "repository": "silverwind/is-cidr", "license": "BSD-2-Clause", "type": "module", "sideEffects": false, "main": "./dist/index.js", "exports": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist" ], "engines": { "node": ">=14" }, "dependencies": { "cidr-regex": "^4.1.1" }, "devDependencies": { "@types/node": "20.12.12", "eslint": "8.57.0", "eslint-config-silverwind": "85.1.4", "eslint-config-silverwind-typescript": "3.2.7", "typescript": "5.4.5", "typescript-config-silverwind": "4.3.2", "updates": "16.1.1", "versions": "12.0.2", "vite": "5.2.11", "vite-config-silverwind": "1.1.2", "vite-plugin-dts": "3.9.1", "vitest": "1.6.0", "vitest-config-silverwind": "9.0.6" } } /* eslint-disable yoda */ 'use strict'; const isFullwidthCodePoint = codePoint => { if (Number.isNaN(codePoint)) { return false; } // Code points are derived from: // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt if ( codePoint >= 0x1100 && ( codePoint <= 0x115F || // Hangul Jamo codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET // CJK Radicals Supplement .. Enclosed CJK Letters and Months (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A (0x3250 <= codePoint && codePoint <= 0x4DBF) || // CJK Unified Ideographs .. Yi Radicals (0x4E00 <= codePoint && codePoint <= 0xA4C6) || // Hangul Jamo Extended-A (0xA960 <= codePoint && codePoint <= 0xA97C) || // Hangul Syllables (0xAC00 <= codePoint && codePoint <= 0xD7A3) || // CJK Compatibility Ideographs (0xF900 <= codePoint && codePoint <= 0xFAFF) || // Vertical Forms (0xFE10 <= codePoint && codePoint <= 0xFE19) || // CJK Compatibility Forms .. Small Form Variants (0xFE30 <= codePoint && codePoint <= 0xFE6B) || // Halfwidth and Fullwidth Forms (0xFF01 <= codePoint && codePoint <= 0xFF60) || (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || // Kana Supplement (0x1B000 <= codePoint && codePoint <= 0x1B001) || // Enclosed Ideographic Supplement (0x1F200 <= codePoint && codePoint <= 0x1F251) || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane (0x20000 <= codePoint && codePoint <= 0x3FFFD) ) ) { return true; } return false; }; module.exports = isFullwidthCodePoint; module.exports.default = isFullwidthCodePoint; MIT License Copyright (c) Sindre Sorhus (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. { "name": "is-fullwidth-code-point", "version": "3.0.0", "description": "Check if the character represented by a given Unicode code point is fullwidth", "license": "MIT", "repository": "sindresorhus/is-fullwidth-code-point", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava && tsd-check" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "fullwidth", "full-width", "full", "width", "unicode", "character", "string", "codepoint", "code", "point", "is", "detect", "check" ], "devDependencies": { "ava": "^1.3.1", "tsd-check": "^0.5.0", "xo": "^0.24.0" } } The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. var fs = require('fs') var core if (process.platform === 'win32' || global.TESTING_WINDOWS) { core = require('./windows.js') } else { core = require('./mode.js') } module.exports = isexe isexe.sync = sync function isexe (path, options, cb) { if (typeof options === 'function') { cb = options options = {} } if (!cb) { if (typeof Promise !== 'function') { throw new TypeError('callback not provided') } return new Promise(function (resolve, reject) { isexe(path, options || {}, function (er, is) { if (er) { reject(er) } else { resolve(is) } }) }) } core(path, options || {}, function (er, is) { // ignore EACCES because that just means we aren't allowed to run it if (er) { if (er.code === 'EACCES' || options && options.ignoreErrors) { er = null is = false } } cb(er, is) }) } function sync (path, options) { // my kingdom for a filtered catch try { return core.sync(path, options || {}) } catch (er) { if (options && options.ignoreErrors || er.code === 'EACCES') { return false } else { throw er } } } module.exports = isexe isexe.sync = sync var fs = require('fs') function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, options)) }) } function sync (path, options) { return checkStat(fs.statSync(path), options) } function checkStat (stat, options) { return stat.isFile() && checkMode(stat, options) } function checkMode (stat, options) { var mod = stat.mode var uid = stat.uid var gid = stat.gid var myUid = options.uid !== undefined ? options.uid : process.getuid && process.getuid() var myGid = options.gid !== undefined ? options.gid : process.getgid && process.getgid() var u = parseInt('100', 8) var g = parseInt('010', 8) var o = parseInt('001', 8) var ug = u | g var ret = (mod & o) || (mod & g) && gid === myGid || (mod & u) && uid === myUid || (mod & ug) && myUid === 0 return ret } { "name": "isexe", "version": "2.0.0", "description": "Minimal module to check if a file is executable.", "main": "index.js", "directories": { "test": "test" }, "devDependencies": { "mkdirp": "^0.5.1", "rimraf": "^2.5.0", "tap": "^10.3.0" }, "scripts": { "test": "tap test/*.js --100", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --all; git push origin --tags" }, "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "license": "ISC", "repository": { "type": "git", "url": "git+https://github.com/isaacs/isexe.git" }, "keywords": [], "bugs": { "url": "https://github.com/isaacs/isexe/issues" }, "homepage": "https://github.com/isaacs/isexe#readme" } var t = require('tap') var fs = require('fs') var path = require('path') var fixture = path.resolve(__dirname, 'fixtures') var meow = fixture + '/meow.cat' var mine = fixture + '/mine.cat' var ours = fixture + '/ours.cat' var fail = fixture + '/fail.false' var noent = fixture + '/enoent.exe' var mkdirp = require('mkdirp') var rimraf = require('rimraf') var isWindows = process.platform === 'win32' var hasAccess = typeof fs.access === 'function' var winSkip = isWindows && 'windows' var accessSkip = !hasAccess && 'no fs.access function' var hasPromise = typeof Promise === 'function' var promiseSkip = !hasPromise && 'no global Promise' function reset () { delete require.cache[require.resolve('../')] return require('../') } t.test('setup fixtures', function (t) { rimraf.sync(fixture) mkdirp.sync(fixture) fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n') fs.chmodSync(meow, parseInt('0755', 8)) fs.writeFileSync(fail, '#!/usr/bin/env false\n') fs.chmodSync(fail, parseInt('0644', 8)) fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n') fs.chmodSync(mine, parseInt('0744', 8)) fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n') fs.chmodSync(ours, parseInt('0754', 8)) t.end() }) t.test('promise', { skip: promiseSkip }, function (t) { var isexe = reset() t.test('meow async', function (t) { isexe(meow).then(function (is) { t.ok(is) t.end() }) }) t.test('fail async', function (t) { isexe(fail).then(function (is) { t.notOk(is) t.end() }) }) t.test('noent async', function (t) { isexe(noent).catch(function (er) { t.ok(er) t.end() }) }) t.test('noent ignore async', function (t) { isexe(noent, { ignoreErrors: true }).then(function (is) { t.notOk(is) t.end() }) }) t.end() }) t.test('no promise', function (t) { global.Promise = null var isexe = reset() t.throws('try to meow a promise', function () { isexe(meow) }) t.end() }) t.test('access', { skip: accessSkip || winSkip }, function (t) { runTest(t) }) t.test('mode', { skip: winSkip }, function (t) { delete fs.access delete fs.accessSync var isexe = reset() t.ok(isexe.sync(ours, { uid: 0, gid: 0 })) t.ok(isexe.sync(mine, { uid: 0, gid: 0 })) runTest(t) }) t.test('windows', function (t) { global.TESTING_WINDOWS = true var pathExt = '.EXE;.CAT;.CMD;.COM' t.test('pathExt option', function (t) { runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' }) }) t.test('pathExt env', function (t) { process.env.PATHEXT = pathExt runTest(t) }) t.test('no pathExt', function (t) { // with a pathExt of '', any filename is fine. // so the "fail" one would still pass. runTest(t, { pathExt: '', skipFail: true }) }) t.test('pathext with empty entry', function (t) { // with a pathExt of '', any filename is fine. // so the "fail" one would still pass. runTest(t, { pathExt: ';' + pathExt, skipFail: true }) }) t.end() }) t.test('cleanup', function (t) { rimraf.sync(fixture) t.end() }) function runTest (t, options) { var isexe = reset() var optionsIgnore = Object.create(options || {}) optionsIgnore.ignoreErrors = true if (!options || !options.skipFail) { t.notOk(isexe.sync(fail, options)) } t.notOk(isexe.sync(noent, optionsIgnore)) if (!options) { t.ok(isexe.sync(meow)) } else { t.ok(isexe.sync(meow, options)) } t.ok(isexe.sync(mine, options)) t.ok(isexe.sync(ours, options)) t.throws(function () { isexe.sync(noent, options) }) t.test('meow async', function (t) { if (!options) { isexe(meow, function (er, is) { if (er) { throw er } t.ok(is) t.end() }) } else { isexe(meow, options, function (er, is) { if (er) { throw er } t.ok(is) t.end() }) } }) t.test('mine async', function (t) { isexe(mine, options, function (er, is) { if (er) { throw er } t.ok(is) t.end() }) }) t.test('ours async', function (t) { isexe(ours, options, function (er, is) { if (er) { throw er } t.ok(is) t.end() }) }) if (!options || !options.skipFail) { t.test('fail async', function (t) { isexe(fail, options, function (er, is) { if (er) { throw er } t.notOk(is) t.end() }) }) } t.test('noent async', function (t) { isexe(noent, options, function (er, is) { t.ok(er) t.notOk(is) t.end() }) }) t.test('noent ignore async', function (t) { isexe(noent, optionsIgnore, function (er, is) { if (er) { throw er } t.notOk(is) t.end() }) }) t.test('directory is not executable', function (t) { isexe(__dirname, options, function (er, is) { if (er) { throw er } t.notOk(is) t.end() }) }) t.end() } module.exports = isexe isexe.sync = sync var fs = require('fs') function checkPathExt (path, options) { var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT if (!pathext) { return true } pathext = pathext.split(';') if (pathext.indexOf('') !== -1) { return true } for (var i = 0; i < pathext.length; i++) { var p = pathext[i].toLowerCase() if (p && path.substr(-p.length).toLowerCase() === p) { return true } } return false } function checkStat (stat, path, options) { if (!stat.isSymbolicLink() && !stat.isFile()) { return false } return checkPathExt(path, options) } function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, path, options)) }) } function sync (path, options) { return checkStat(fs.statSync(path), path, options) } # Blue Oak Model License Version 1.0.0 ## Purpose This license gives everyone as much permission to work with this software as possible, while protecting contributors from liability. ## Acceptance In order to receive this license, you must agree to its rules. The rules of this license are both obligations under that agreement and conditions to your license. You must not do anything with this software that triggers a rule that you cannot or will not follow. ## Copyright Each contributor licenses you to do everything with this software that would otherwise infringe that contributor's copyright in it. ## Notices You must ensure that everyone who gets a copy of any part of this software from you, with or without changes, also gets the text of this license or a link to . ## Excuse If anyone notifies you in writing that you have not complied with [Notices](#notices), you can keep your license by taking all practical steps to comply within 30 days after the notice. If you do not do so, your license ends immediately. ## Patent Each contributor licenses you to do everything with this software that would otherwise infringe any patent claims they can license or become able to license. ## Reliability No contributor can revoke this license. ## No Liability **_As far as the law allows, this software comes as is, without any warranty or condition, and no contributor will be liable to anyone for any damages related to this software or this license, under any kind of legal claim._** "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.jack = exports.Jack = exports.isConfigOption = exports.isConfigType = void 0; const node_util_1 = require("node:util"); const parse_args_js_1 = require("./parse-args.js"); // it's a tiny API, just cast it inline, it's fine //@ts-ignore const cliui_1 = __importDefault(require("@isaacs/cliui")); const node_path_1 = require("node:path"); const width = Math.min((process && process.stdout && process.stdout.columns) || 80, 80); // indentation spaces from heading level const indent = (n) => (n - 1) * 2; const toEnvKey = (pref, key) => { return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')] .join(' ') .trim() .toUpperCase() .replace(/ /g, '_'); }; const toEnvVal = (value, delim = '\n') => { const str = typeof value === 'string' ? value : typeof value === 'boolean' ? value ? '1' : '0' : typeof value === 'number' ? String(value) : Array.isArray(value) ? value.map((v) => toEnvVal(v)).join(delim) : /* c8 ignore start */ undefined; if (typeof str !== 'string') { throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`); } /* c8 ignore stop */ return str; }; const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ? env ? env.split(delim).map(v => fromEnvVal(v, type, false)) : [] : type === 'string' ? env : type === 'boolean' ? env === '1' : +env.trim()); const isConfigType = (t) => typeof t === 'string' && (t === 'string' || t === 'number' || t === 'boolean'); exports.isConfigType = isConfigType; const undefOrType = (v, t) => v === undefined || typeof v === t; const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t)); const isValidOption = (v, vo) => Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v); // print the value type, for error message reporting const valueType = (v) => typeof v === 'string' ? 'string' : typeof v === 'boolean' ? 'boolean' : typeof v === 'number' ? 'number' : Array.isArray(v) ? joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]' : `${v.type}${v.multiple ? '[]' : ''}`; const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ? types[0] : `(${types.join('|')})`; const isValidValue = (v, type, multi) => { if (multi) { if (!Array.isArray(v)) return false; return !v.some((v) => !isValidValue(v, type, false)); } if (Array.isArray(v)) return false; return typeof v === type; }; const isConfigOption = (o, type, multi) => !!o && typeof o === 'object' && (0, exports.isConfigType)(o.type) && o.type === type && undefOrType(o.short, 'string') && undefOrType(o.description, 'string') && undefOrType(o.hint, 'string') && undefOrType(o.validate, 'function') && (o.type === 'boolean' ? o.validOptions === undefined : undefOrTypeArray(o.validOptions, o.type)) && (o.default === undefined || isValidValue(o.default, type, multi)) && !!o.multiple === multi; exports.isConfigOption = isConfigOption; function num(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'number', false)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'number', }, }); } if (!undefOrTypeArray(validOptions, 'number')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'number[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'number', multiple: false, }; } function numList(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'number', true)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'number[]', }, }); } if (!undefOrTypeArray(validOptions, 'number')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'number[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'number', multiple: true, }; } function opt(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'string', false)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'string', }, }); } if (!undefOrTypeArray(validOptions, 'string')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'string[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'string', multiple: false, }; } function optList(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'string', true)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'string[]', }, }); } if (!undefOrTypeArray(validOptions, 'string')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'string[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'string', multiple: true, }; } function flag(o = {}) { const { hint, default: def, validate: val, ...rest } = o; delete rest.validOptions; if (def !== undefined && !isValidValue(def, 'boolean', false)) { throw new TypeError('invalid default value'); } const validate = val ? val : undefined; if (hint !== undefined) { throw new TypeError('cannot provide hint for flag'); } return { ...rest, default: def, validate, type: 'boolean', multiple: false, }; } function flagList(o = {}) { const { hint, default: def, validate: val, ...rest } = o; delete rest.validOptions; if (def !== undefined && !isValidValue(def, 'boolean', true)) { throw new TypeError('invalid default value'); } const validate = val ? val : undefined; if (hint !== undefined) { throw new TypeError('cannot provide hint for flag list'); } return { ...rest, default: def, validate, type: 'boolean', multiple: true, }; } const toParseArgsOptionsConfig = (options) => { const c = {}; for (const longOption in options) { const config = options[longOption]; /* c8 ignore start */ if (!config) { throw new Error('config must be an object: ' + longOption); } /* c8 ignore start */ if ((0, exports.isConfigOption)(config, 'number', true)) { c[longOption] = { type: 'string', multiple: true, default: config.default?.map(c => String(c)), }; } else if ((0, exports.isConfigOption)(config, 'number', false)) { c[longOption] = { type: 'string', multiple: false, default: config.default === undefined ? undefined : String(config.default), }; } else { const conf = config; c[longOption] = { type: conf.type, multiple: !!conf.multiple, default: conf.default, }; } const clo = c[longOption]; if (typeof config.short === 'string') { clo.short = config.short; } if (config.type === 'boolean' && !longOption.startsWith('no-') && !options[`no-${longOption}`]) { c[`no-${longOption}`] = { type: 'boolean', multiple: config.multiple, }; } } return c; }; const isHeading = (r) => r.type === 'heading'; const isDescription = (r) => r.type === 'description'; /** * Class returned by the {@link jack} function and all configuration * definition methods. This is what gets chained together. */ class Jack { #configSet; #shorts; #options; #fields = []; #env; #envPrefix; #allowPositionals; #usage; #usageMarkdown; constructor(options = {}) { this.#options = options; this.#allowPositionals = options.allowPositionals !== false; this.#env = this.#options.env === undefined ? process.env : this.#options.env; this.#envPrefix = options.envPrefix; // We need to fib a little, because it's always the same object, but it // starts out as having an empty config set. Then each method that adds // fields returns `this as Jack` this.#configSet = Object.create(null); this.#shorts = Object.create(null); } /** * Set the default value (which will still be overridden by env or cli) * as if from a parsed config file. The optional `source` param, if * provided, will be included in error messages if a value is invalid or * unknown. */ setConfigValues(values, source = '') { try { this.validate(values); } catch (er) { const e = er; if (source && e && typeof e === 'object') { if (e.cause && typeof e.cause === 'object') { Object.assign(e.cause, { path: source }); } else { e.cause = { path: source }; } } throw e; } for (const [field, value] of Object.entries(values)) { const my = this.#configSet[field]; // already validated, just for TS's benefit /* c8 ignore start */ if (!my) { throw new Error('unexpected field in config set: ' + field, { cause: { found: field }, }); } /* c8 ignore stop */ my.default = value; } return this; } /** * Parse a string of arguments, and return the resulting * `{ values, positionals }` object. * * If an {@link JackOptions#envPrefix} is set, then it will read default * values from the environment, and write the resulting values back * to the environment as well. * * Environment values always take precedence over any other value, except * an explicit CLI setting. */ parse(args = process.argv) { this.loadEnvDefaults(); const p = this.parseRaw(args); this.applyDefaults(p); this.writeEnv(p); return p; } loadEnvDefaults() { if (this.#envPrefix) { for (const [field, my] of Object.entries(this.#configSet)) { const ek = toEnvKey(this.#envPrefix, field); const env = this.#env[ek]; if (env !== undefined) { my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim); } } } } applyDefaults(p) { for (const [field, c] of Object.entries(this.#configSet)) { if (c.default !== undefined && !(field in p.values)) { //@ts-ignore p.values[field] = c.default; } } } /** * Only parse the command line arguments passed in. * Does not strip off the `node script.js` bits, so it must be just the * arguments you wish to have parsed. * Does not read from or write to the environment, or set defaults. */ parseRaw(args) { if (args === process.argv) { args = args.slice(process._eval !== undefined ? 1 : 2); } const options = toParseArgsOptionsConfig(this.#configSet); const result = (0, parse_args_js_1.parseArgs)({ args, options, // always strict, but using our own logic strict: false, allowPositionals: this.#allowPositionals, tokens: true, }); const p = { values: {}, positionals: [], }; for (const token of result.tokens) { if (token.kind === 'positional') { p.positionals.push(token.value); if (this.#options.stopAtPositional || this.#options.stopAtPositionalTest?.(token.value)) { p.positionals.push(...args.slice(token.index + 1)); break; } } else if (token.kind === 'option') { let value = undefined; if (token.name.startsWith('no-')) { const my = this.#configSet[token.name]; const pname = token.name.substring('no-'.length); const pos = this.#configSet[pname]; if (pos && pos.type === 'boolean' && (!my || (my.type === 'boolean' && !!my.multiple === !!pos.multiple))) { value = false; token.name = pname; } } const my = this.#configSet[token.name]; if (!my) { throw new Error(`Unknown option '${token.rawName}'. ` + `To specify a positional argument starting with a '-', ` + `place it at the end of the command after '--', as in ` + `'-- ${token.rawName}'`, { cause: { found: token.rawName + (token.value ? `=${token.value}` : ''), }, }); } if (value === undefined) { if (token.value === undefined) { if (my.type !== 'boolean') { throw new Error(`No value provided for ${token.rawName}, expected ${my.type}`, { cause: { name: token.rawName, wanted: valueType(my), }, }); } value = true; } else { if (my.type === 'boolean') { throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { found: token } }); } if (my.type === 'string') { value = token.value; } else { value = +token.value; if (value !== value) { throw new Error(`Invalid value '${token.value}' provided for ` + `'${token.rawName}' option, expected number`, { cause: { name: token.rawName, found: token.value, wanted: 'number', }, }); } } } } if (my.multiple) { const pv = p.values; const tn = pv[token.name] ?? []; pv[token.name] = tn; tn.push(value); } else { const pv = p.values; pv[token.name] = value; } } } for (const [field, value] of Object.entries(p.values)) { const valid = this.#configSet[field]?.validate; const validOptions = this.#configSet[field]?.validOptions; let cause; if (validOptions && !isValidOption(value, validOptions)) { cause = { name: field, found: value, validOptions: validOptions }; } if (valid && !valid(value)) { cause = cause || { name: field, found: value }; } if (cause) { throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause }); } } return p; } /** * do not set fields as 'no-foo' if 'foo' exists and both are bools * just set foo. */ #noNoFields(f, val, s = f) { if (!f.startsWith('no-') || typeof val !== 'boolean') return; const yes = f.substring('no-'.length); // recurse so we get the core config key we care about. this.#noNoFields(yes, val, s); if (this.#configSet[yes]?.type === 'boolean') { throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { found: s, wanted: yes } }); } } /** * Validate that any arbitrary object is a valid configuration `values` * object. Useful when loading config files or other sources. */ validate(o) { if (!o || typeof o !== 'object') { throw new Error('Invalid config: not an object', { cause: { found: o }, }); } const opts = o; for (const field in o) { const value = opts[field]; /* c8 ignore next - for TS */ if (value === undefined) continue; this.#noNoFields(field, value); const config = this.#configSet[field]; if (!config) { throw new Error(`Unknown config option: ${field}`, { cause: { found: field }, }); } if (!isValidValue(value, config.type, !!config.multiple)) { throw new Error(`Invalid value ${valueType(value)} for ${field}, expected ${valueType(config)}`, { cause: { name: field, found: value, wanted: valueType(config), }, }); } let cause; if (config.validOptions && !isValidOption(value, config.validOptions)) { cause = { name: field, found: value, validOptions: config.validOptions, }; } if (config.validate && !config.validate(value)) { cause = cause || { name: field, found: value }; } if (cause) { throw new Error(`Invalid config value for ${field}: ${value}`, { cause, }); } } } writeEnv(p) { if (!this.#env || !this.#envPrefix) return; for (const [field, value] of Object.entries(p.values)) { const my = this.#configSet[field]; this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(value, my?.delim); } } /** * Add a heading to the usage output banner */ heading(text, level, { pre = false } = {}) { if (level === undefined) { level = this.#fields.some(r => isHeading(r)) ? 2 : 1; } this.#fields.push({ type: 'heading', text, level, pre }); return this; } /** * Add a long-form description to the usage output at this position. */ description(text, { pre } = {}) { this.#fields.push({ type: 'description', text, pre }); return this; } /** * Add one or more number fields. */ num(fields) { return this.#addFields(fields, num); } /** * Add one or more multiple number fields. */ numList(fields) { return this.#addFields(fields, numList); } /** * Add one or more string option fields. */ opt(fields) { return this.#addFields(fields, opt); } /** * Add one or more multiple string option fields. */ optList(fields) { return this.#addFields(fields, optList); } /** * Add one or more flag fields. */ flag(fields) { return this.#addFields(fields, flag); } /** * Add one or more multiple flag fields. */ flagList(fields) { return this.#addFields(fields, flagList); } /** * Generic field definition method. Similar to flag/flagList/number/etc, * but you must specify the `type` (and optionally `multiple` and `delim`) * fields on each one, or Jack won't know how to define them. */ addFields(fields) { const next = this; for (const [name, field] of Object.entries(fields)) { this.#validateName(name, field); next.#fields.push({ type: 'config', name, value: field, }); } Object.assign(next.#configSet, fields); return next; } #addFields(fields, fn) { const next = this; Object.assign(next.#configSet, Object.fromEntries(Object.entries(fields).map(([name, field]) => { this.#validateName(name, field); const option = fn(field); next.#fields.push({ type: 'config', name, value: option, }); return [name, option]; }))); return next; } #validateName(name, field) { if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) { throw new TypeError(`Invalid option name: ${name}, ` + `must be '-' delimited ASCII alphanumeric`); } if (this.#configSet[name]) { throw new TypeError(`Cannot redefine option ${field}`); } if (this.#shorts[name]) { throw new TypeError(`Cannot redefine option ${name}, already ` + `in use for ${this.#shorts[name]}`); } if (field.short) { if (!/^[a-zA-Z0-9]$/.test(field.short)) { throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + 'must be 1 ASCII alphanumeric character'); } if (this.#shorts[field.short]) { throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + `already in use for ${this.#shorts[field.short]}`); } this.#shorts[field.short] = name; this.#shorts[name] = name; } } /** * Return the usage banner for the given configuration */ usage() { if (this.#usage) return this.#usage; let headingLevel = 1; const ui = (0, cliui_1.default)({ width }); const first = this.#fields[0]; let start = first?.type === 'heading' ? 1 : 0; if (first?.type === 'heading') { ui.div({ padding: [0, 0, 0, 0], text: normalize(first.text), }); } ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' }); if (this.#options.usage) { ui.div({ text: this.#options.usage, padding: [0, 0, 0, 2], }); } else { const cmd = (0, node_path_1.basename)(String(process.argv[1])); const shortFlags = []; const shorts = []; const flags = []; const opts = []; for (const [field, config] of Object.entries(this.#configSet)) { if (config.short) { if (config.type === 'boolean') shortFlags.push(config.short); else shorts.push([config.short, config.hint || field]); } else { if (config.type === 'boolean') flags.push(field); else opts.push([field, config.hint || field]); } } const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const lf = flags.map(k => ` --${k}`).join(''); const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); ui.div({ text: usage, padding: [0, 0, 0, 2], }); } ui.div({ padding: [0, 0, 0, 0], text: '' }); const maybeDesc = this.#fields[start]; if (maybeDesc && isDescription(maybeDesc)) { const print = normalize(maybeDesc.text, maybeDesc.pre); start++; ui.div({ padding: [0, 0, 0, 0], text: print }); ui.div({ padding: [0, 0, 0, 0], text: '' }); } const { rows, maxWidth } = this.#usageRows(start); // every heading/description after the first gets indented by 2 // extra spaces. for (const row of rows) { if (row.left) { // If the row is too long, don't wrap it // Bump the right-hand side down a line to make room const configIndent = indent(Math.max(headingLevel, 2)); if (row.left.length > maxWidth - 3) { ui.div({ text: row.left, padding: [0, 0, 0, configIndent] }); ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] }); } else { ui.div({ text: row.left, padding: [0, 1, 0, configIndent], width: maxWidth, }, { padding: [0, 0, 0, 0], text: row.text }); } if (row.skipLine) { ui.div({ padding: [0, 0, 0, 0], text: '' }); } } else { if (isHeading(row)) { const { level } = row; headingLevel = level; // only h1 and h2 have bottom padding // h3-h6 do not const b = level <= 2 ? 1 : 0; ui.div({ ...row, padding: [0, 0, b, indent(level)] }); } else { ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] }); } } } return (this.#usage = ui.toString()); } /** * Return the usage banner markdown for the given configuration */ usageMarkdown() { if (this.#usageMarkdown) return this.#usageMarkdown; const out = []; let headingLevel = 1; const first = this.#fields[0]; let start = first?.type === 'heading' ? 1 : 0; if (first?.type === 'heading') { out.push(`# ${normalizeOneLine(first.text)}`); } out.push('Usage:'); if (this.#options.usage) { out.push(normalizeMarkdown(this.#options.usage, true)); } else { const cmd = (0, node_path_1.basename)(String(process.argv[1])); const shortFlags = []; const shorts = []; const flags = []; const opts = []; for (const [field, config] of Object.entries(this.#configSet)) { if (config.short) { if (config.type === 'boolean') shortFlags.push(config.short); else shorts.push([config.short, config.hint || field]); } else { if (config.type === 'boolean') flags.push(field); else opts.push([field, config.hint || field]); } } const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const lf = flags.map(k => ` --${k}`).join(''); const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); out.push(normalizeMarkdown(usage, true)); } const maybeDesc = this.#fields[start]; if (maybeDesc && isDescription(maybeDesc)) { out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre)); start++; } const { rows } = this.#usageRows(start); // heading level in markdown is number of # ahead of text for (const row of rows) { if (row.left) { out.push('#'.repeat(headingLevel + 1) + ' ' + normalizeOneLine(row.left, true)); if (row.text) out.push(normalizeMarkdown(row.text)); } else if (isHeading(row)) { const { level } = row; headingLevel = level; out.push(`${'#'.repeat(headingLevel)} ${normalizeOneLine(row.text, row.pre)}`); } else { out.push(normalizeMarkdown(row.text, !!row.pre)); } } return (this.#usageMarkdown = out.join('\n\n') + '\n'); } #usageRows(start) { // turn each config type into a row, and figure out the width of the // left hand indentation for the option descriptions. let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3))); let maxWidth = 8; let prev = undefined; const rows = []; for (const field of this.#fields.slice(start)) { if (field.type !== 'config') { if (prev?.type === 'config') prev.skipLine = true; prev = undefined; field.text = normalize(field.text, !!field.pre); rows.push(field); continue; } const { value } = field; const desc = value.description || ''; const mult = value.multiple ? 'Can be set multiple times' : ''; const opts = value.validOptions?.length ? `Valid options:${value.validOptions.map(v => ` ${JSON.stringify(v)}`)}` : ''; const dmDelim = desc.includes('\n') ? '\n\n' : '\n'; const extra = [opts, mult].join(dmDelim).trim(); const text = (normalize(desc) + dmDelim + extra).trim(); const hint = value.hint || (value.type === 'number' ? 'n' : value.type === 'string' ? field.name : undefined); const short = !value.short ? '' : value.type === 'boolean' ? `-${value.short} ` : `-${value.short}<${hint}> `; const left = value.type === 'boolean' ? `${short}--${field.name}` : `${short}--${field.name}=<${hint}>`; const row = { text, left, type: 'config' }; if (text.length > width - maxMax) { row.skipLine = true; } if (prev && left.length > maxMax) prev.skipLine = true; prev = row; const len = left.length + 4; if (len > maxWidth && len < maxMax) { maxWidth = len; } rows.push(row); } return { rows, maxWidth }; } /** * Return the configuration options as a plain object */ toJSON() { return Object.fromEntries(Object.entries(this.#configSet).map(([field, def]) => [ field, { type: def.type, ...(def.multiple ? { multiple: true } : {}), ...(def.delim ? { delim: def.delim } : {}), ...(def.short ? { short: def.short } : {}), ...(def.description ? { description: normalize(def.description) } : {}), ...(def.validate ? { validate: def.validate } : {}), ...(def.validOptions ? { validOptions: def.validOptions } : {}), ...(def.default !== undefined ? { default: def.default } : {}), ...(def.hint ? { hint: def.hint } : {}), }, ])); } /** * Custom printer for `util.inspect` */ [node_util_1.inspect.custom](_, options) { return `Jack ${(0, node_util_1.inspect)(this.toJSON(), options)}`; } } exports.Jack = Jack; // Unwrap and un-indent, so we can wrap description // strings however makes them look nice in the code. const normalize = (s, pre = false) => { if (pre) // prepend a ZWSP to each line so cliui doesn't strip it. return s .split('\n') .map(l => `\u200b${l}`) .join('\n'); return s .split(/^\s*```\s*$/gm) .map((s, i) => { if (i % 2 === 1) { if (!s.trim()) { return `\`\`\`\n\`\`\`\n`; } // outdent the ``` blocks, but preserve whitespace otherwise. const split = s.split('\n'); // throw out the \n at the start and end split.pop(); split.shift(); const si = split.reduce((shortest, l) => { /* c8 ignore next */ const ind = l.match(/^\s*/)?.[0] ?? ''; if (ind.length) return Math.min(ind.length, shortest); else return shortest; }, Infinity); /* c8 ignore next */ const i = isFinite(si) ? si : 0; return ('\n```\n' + split.map(s => `\u200b${s.substring(i)}`).join('\n') + '\n```\n'); } return (s // remove single line breaks, except for lists .replace(/([^\n])\n[ \t]*([^\n])/g, (_, $1, $2) => !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\n${$2}`) // normalize mid-line whitespace .replace(/([^\n])[ \t]+([^\n])/g, '$1 $2') // two line breaks are enough .replace(/\n{3,}/g, '\n\n') // remove any spaces at the start of a line .replace(/\n[ \t]+/g, '\n') .trim()); }) .join('\n'); }; // normalize for markdown printing, remove leading spaces on lines const normalizeMarkdown = (s, pre = false) => { const n = normalize(s, pre).replace(/\\/g, '\\\\'); return pre ? `\`\`\`\n${n.replace(/\u200b/g, '')}\n\`\`\`` : n.replace(/\n +/g, '\n').trim(); }; const normalizeOneLine = (s, pre = false) => { const n = normalize(s, pre) .replace(/[\s\u200b]+/g, ' ') .trim(); return pre ? `\`${n}\`` : n; }; /** * Main entry point. Create and return a {@link Jack} object. */ const jack = (options = {}) => new Jack(options); exports.jack = jack; //# sourceMappingURL=index.js.map{ "type": "commonjs" } "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseArgs = void 0; const util = __importStar(require("util")); const pv = (typeof process === 'object' && !!process && typeof process.version === 'string') ? process.version : 'v0.0.0'; const pvs = pv .replace(/^v/, '') .split('.') .map(s => parseInt(s, 10)); /* c8 ignore start */ const [major = 0, minor = 0] = pvs; /* c8 ignore stop */ let { parseArgs: pa } = util; /* c8 ignore start */ if (!pa || major < 16 || (major === 18 && minor < 11) || (major === 16 && minor < 19)) { /* c8 ignore stop */ pa = require('@pkgjs/parseargs').parseArgs; } exports.parseArgs = pa; //# sourceMappingURL=parse-args-cjs.cjs.mapimport { inspect } from 'node:util'; import { parseArgs } from './parse-args.js'; // it's a tiny API, just cast it inline, it's fine //@ts-ignore import cliui from '@isaacs/cliui'; import { basename } from 'node:path'; const width = Math.min((process && process.stdout && process.stdout.columns) || 80, 80); // indentation spaces from heading level const indent = (n) => (n - 1) * 2; const toEnvKey = (pref, key) => { return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')] .join(' ') .trim() .toUpperCase() .replace(/ /g, '_'); }; const toEnvVal = (value, delim = '\n') => { const str = typeof value === 'string' ? value : typeof value === 'boolean' ? value ? '1' : '0' : typeof value === 'number' ? String(value) : Array.isArray(value) ? value.map((v) => toEnvVal(v)).join(delim) : /* c8 ignore start */ undefined; if (typeof str !== 'string') { throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`); } /* c8 ignore stop */ return str; }; const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ? env ? env.split(delim).map(v => fromEnvVal(v, type, false)) : [] : type === 'string' ? env : type === 'boolean' ? env === '1' : +env.trim()); export const isConfigType = (t) => typeof t === 'string' && (t === 'string' || t === 'number' || t === 'boolean'); const undefOrType = (v, t) => v === undefined || typeof v === t; const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t)); const isValidOption = (v, vo) => Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v); // print the value type, for error message reporting const valueType = (v) => typeof v === 'string' ? 'string' : typeof v === 'boolean' ? 'boolean' : typeof v === 'number' ? 'number' : Array.isArray(v) ? joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]' : `${v.type}${v.multiple ? '[]' : ''}`; const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ? types[0] : `(${types.join('|')})`; const isValidValue = (v, type, multi) => { if (multi) { if (!Array.isArray(v)) return false; return !v.some((v) => !isValidValue(v, type, false)); } if (Array.isArray(v)) return false; return typeof v === type; }; export const isConfigOption = (o, type, multi) => !!o && typeof o === 'object' && isConfigType(o.type) && o.type === type && undefOrType(o.short, 'string') && undefOrType(o.description, 'string') && undefOrType(o.hint, 'string') && undefOrType(o.validate, 'function') && (o.type === 'boolean' ? o.validOptions === undefined : undefOrTypeArray(o.validOptions, o.type)) && (o.default === undefined || isValidValue(o.default, type, multi)) && !!o.multiple === multi; function num(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'number', false)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'number', }, }); } if (!undefOrTypeArray(validOptions, 'number')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'number[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'number', multiple: false, }; } function numList(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'number', true)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'number[]', }, }); } if (!undefOrTypeArray(validOptions, 'number')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'number[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'number', multiple: true, }; } function opt(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'string', false)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'string', }, }); } if (!undefOrTypeArray(validOptions, 'string')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'string[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'string', multiple: false, }; } function optList(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'string', true)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'string[]', }, }); } if (!undefOrTypeArray(validOptions, 'string')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'string[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'string', multiple: true, }; } function flag(o = {}) { const { hint, default: def, validate: val, ...rest } = o; delete rest.validOptions; if (def !== undefined && !isValidValue(def, 'boolean', false)) { throw new TypeError('invalid default value'); } const validate = val ? val : undefined; if (hint !== undefined) { throw new TypeError('cannot provide hint for flag'); } return { ...rest, default: def, validate, type: 'boolean', multiple: false, }; } function flagList(o = {}) { const { hint, default: def, validate: val, ...rest } = o; delete rest.validOptions; if (def !== undefined && !isValidValue(def, 'boolean', true)) { throw new TypeError('invalid default value'); } const validate = val ? val : undefined; if (hint !== undefined) { throw new TypeError('cannot provide hint for flag list'); } return { ...rest, default: def, validate, type: 'boolean', multiple: true, }; } const toParseArgsOptionsConfig = (options) => { const c = {}; for (const longOption in options) { const config = options[longOption]; /* c8 ignore start */ if (!config) { throw new Error('config must be an object: ' + longOption); } /* c8 ignore start */ if (isConfigOption(config, 'number', true)) { c[longOption] = { type: 'string', multiple: true, default: config.default?.map(c => String(c)), }; } else if (isConfigOption(config, 'number', false)) { c[longOption] = { type: 'string', multiple: false, default: config.default === undefined ? undefined : String(config.default), }; } else { const conf = config; c[longOption] = { type: conf.type, multiple: !!conf.multiple, default: conf.default, }; } const clo = c[longOption]; if (typeof config.short === 'string') { clo.short = config.short; } if (config.type === 'boolean' && !longOption.startsWith('no-') && !options[`no-${longOption}`]) { c[`no-${longOption}`] = { type: 'boolean', multiple: config.multiple, }; } } return c; }; const isHeading = (r) => r.type === 'heading'; const isDescription = (r) => r.type === 'description'; /** * Class returned by the {@link jack} function and all configuration * definition methods. This is what gets chained together. */ export class Jack { #configSet; #shorts; #options; #fields = []; #env; #envPrefix; #allowPositionals; #usage; #usageMarkdown; constructor(options = {}) { this.#options = options; this.#allowPositionals = options.allowPositionals !== false; this.#env = this.#options.env === undefined ? process.env : this.#options.env; this.#envPrefix = options.envPrefix; // We need to fib a little, because it's always the same object, but it // starts out as having an empty config set. Then each method that adds // fields returns `this as Jack` this.#configSet = Object.create(null); this.#shorts = Object.create(null); } /** * Set the default value (which will still be overridden by env or cli) * as if from a parsed config file. The optional `source` param, if * provided, will be included in error messages if a value is invalid or * unknown. */ setConfigValues(values, source = '') { try { this.validate(values); } catch (er) { const e = er; if (source && e && typeof e === 'object') { if (e.cause && typeof e.cause === 'object') { Object.assign(e.cause, { path: source }); } else { e.cause = { path: source }; } } throw e; } for (const [field, value] of Object.entries(values)) { const my = this.#configSet[field]; // already validated, just for TS's benefit /* c8 ignore start */ if (!my) { throw new Error('unexpected field in config set: ' + field, { cause: { found: field }, }); } /* c8 ignore stop */ my.default = value; } return this; } /** * Parse a string of arguments, and return the resulting * `{ values, positionals }` object. * * If an {@link JackOptions#envPrefix} is set, then it will read default * values from the environment, and write the resulting values back * to the environment as well. * * Environment values always take precedence over any other value, except * an explicit CLI setting. */ parse(args = process.argv) { this.loadEnvDefaults(); const p = this.parseRaw(args); this.applyDefaults(p); this.writeEnv(p); return p; } loadEnvDefaults() { if (this.#envPrefix) { for (const [field, my] of Object.entries(this.#configSet)) { const ek = toEnvKey(this.#envPrefix, field); const env = this.#env[ek]; if (env !== undefined) { my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim); } } } } applyDefaults(p) { for (const [field, c] of Object.entries(this.#configSet)) { if (c.default !== undefined && !(field in p.values)) { //@ts-ignore p.values[field] = c.default; } } } /** * Only parse the command line arguments passed in. * Does not strip off the `node script.js` bits, so it must be just the * arguments you wish to have parsed. * Does not read from or write to the environment, or set defaults. */ parseRaw(args) { if (args === process.argv) { args = args.slice(process._eval !== undefined ? 1 : 2); } const options = toParseArgsOptionsConfig(this.#configSet); const result = parseArgs({ args, options, // always strict, but using our own logic strict: false, allowPositionals: this.#allowPositionals, tokens: true, }); const p = { values: {}, positionals: [], }; for (const token of result.tokens) { if (token.kind === 'positional') { p.positionals.push(token.value); if (this.#options.stopAtPositional || this.#options.stopAtPositionalTest?.(token.value)) { p.positionals.push(...args.slice(token.index + 1)); break; } } else if (token.kind === 'option') { let value = undefined; if (token.name.startsWith('no-')) { const my = this.#configSet[token.name]; const pname = token.name.substring('no-'.length); const pos = this.#configSet[pname]; if (pos && pos.type === 'boolean' && (!my || (my.type === 'boolean' && !!my.multiple === !!pos.multiple))) { value = false; token.name = pname; } } const my = this.#configSet[token.name]; if (!my) { throw new Error(`Unknown option '${token.rawName}'. ` + `To specify a positional argument starting with a '-', ` + `place it at the end of the command after '--', as in ` + `'-- ${token.rawName}'`, { cause: { found: token.rawName + (token.value ? `=${token.value}` : ''), }, }); } if (value === undefined) { if (token.value === undefined) { if (my.type !== 'boolean') { throw new Error(`No value provided for ${token.rawName}, expected ${my.type}`, { cause: { name: token.rawName, wanted: valueType(my), }, }); } value = true; } else { if (my.type === 'boolean') { throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { found: token } }); } if (my.type === 'string') { value = token.value; } else { value = +token.value; if (value !== value) { throw new Error(`Invalid value '${token.value}' provided for ` + `'${token.rawName}' option, expected number`, { cause: { name: token.rawName, found: token.value, wanted: 'number', }, }); } } } } if (my.multiple) { const pv = p.values; const tn = pv[token.name] ?? []; pv[token.name] = tn; tn.push(value); } else { const pv = p.values; pv[token.name] = value; } } } for (const [field, value] of Object.entries(p.values)) { const valid = this.#configSet[field]?.validate; const validOptions = this.#configSet[field]?.validOptions; let cause; if (validOptions && !isValidOption(value, validOptions)) { cause = { name: field, found: value, validOptions: validOptions }; } if (valid && !valid(value)) { cause = cause || { name: field, found: value }; } if (cause) { throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause }); } } return p; } /** * do not set fields as 'no-foo' if 'foo' exists and both are bools * just set foo. */ #noNoFields(f, val, s = f) { if (!f.startsWith('no-') || typeof val !== 'boolean') return; const yes = f.substring('no-'.length); // recurse so we get the core config key we care about. this.#noNoFields(yes, val, s); if (this.#configSet[yes]?.type === 'boolean') { throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { found: s, wanted: yes } }); } } /** * Validate that any arbitrary object is a valid configuration `values` * object. Useful when loading config files or other sources. */ validate(o) { if (!o || typeof o !== 'object') { throw new Error('Invalid config: not an object', { cause: { found: o }, }); } const opts = o; for (const field in o) { const value = opts[field]; /* c8 ignore next - for TS */ if (value === undefined) continue; this.#noNoFields(field, value); const config = this.#configSet[field]; if (!config) { throw new Error(`Unknown config option: ${field}`, { cause: { found: field }, }); } if (!isValidValue(value, config.type, !!config.multiple)) { throw new Error(`Invalid value ${valueType(value)} for ${field}, expected ${valueType(config)}`, { cause: { name: field, found: value, wanted: valueType(config), }, }); } let cause; if (config.validOptions && !isValidOption(value, config.validOptions)) { cause = { name: field, found: value, validOptions: config.validOptions, }; } if (config.validate && !config.validate(value)) { cause = cause || { name: field, found: value }; } if (cause) { throw new Error(`Invalid config value for ${field}: ${value}`, { cause, }); } } } writeEnv(p) { if (!this.#env || !this.#envPrefix) return; for (const [field, value] of Object.entries(p.values)) { const my = this.#configSet[field]; this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(value, my?.delim); } } /** * Add a heading to the usage output banner */ heading(text, level, { pre = false } = {}) { if (level === undefined) { level = this.#fields.some(r => isHeading(r)) ? 2 : 1; } this.#fields.push({ type: 'heading', text, level, pre }); return this; } /** * Add a long-form description to the usage output at this position. */ description(text, { pre } = {}) { this.#fields.push({ type: 'description', text, pre }); return this; } /** * Add one or more number fields. */ num(fields) { return this.#addFields(fields, num); } /** * Add one or more multiple number fields. */ numList(fields) { return this.#addFields(fields, numList); } /** * Add one or more string option fields. */ opt(fields) { return this.#addFields(fields, opt); } /** * Add one or more multiple string option fields. */ optList(fields) { return this.#addFields(fields, optList); } /** * Add one or more flag fields. */ flag(fields) { return this.#addFields(fields, flag); } /** * Add one or more multiple flag fields. */ flagList(fields) { return this.#addFields(fields, flagList); } /** * Generic field definition method. Similar to flag/flagList/number/etc, * but you must specify the `type` (and optionally `multiple` and `delim`) * fields on each one, or Jack won't know how to define them. */ addFields(fields) { const next = this; for (const [name, field] of Object.entries(fields)) { this.#validateName(name, field); next.#fields.push({ type: 'config', name, value: field, }); } Object.assign(next.#configSet, fields); return next; } #addFields(fields, fn) { const next = this; Object.assign(next.#configSet, Object.fromEntries(Object.entries(fields).map(([name, field]) => { this.#validateName(name, field); const option = fn(field); next.#fields.push({ type: 'config', name, value: option, }); return [name, option]; }))); return next; } #validateName(name, field) { if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) { throw new TypeError(`Invalid option name: ${name}, ` + `must be '-' delimited ASCII alphanumeric`); } if (this.#configSet[name]) { throw new TypeError(`Cannot redefine option ${field}`); } if (this.#shorts[name]) { throw new TypeError(`Cannot redefine option ${name}, already ` + `in use for ${this.#shorts[name]}`); } if (field.short) { if (!/^[a-zA-Z0-9]$/.test(field.short)) { throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + 'must be 1 ASCII alphanumeric character'); } if (this.#shorts[field.short]) { throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + `already in use for ${this.#shorts[field.short]}`); } this.#shorts[field.short] = name; this.#shorts[name] = name; } } /** * Return the usage banner for the given configuration */ usage() { if (this.#usage) return this.#usage; let headingLevel = 1; const ui = cliui({ width }); const first = this.#fields[0]; let start = first?.type === 'heading' ? 1 : 0; if (first?.type === 'heading') { ui.div({ padding: [0, 0, 0, 0], text: normalize(first.text), }); } ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' }); if (this.#options.usage) { ui.div({ text: this.#options.usage, padding: [0, 0, 0, 2], }); } else { const cmd = basename(String(process.argv[1])); const shortFlags = []; const shorts = []; const flags = []; const opts = []; for (const [field, config] of Object.entries(this.#configSet)) { if (config.short) { if (config.type === 'boolean') shortFlags.push(config.short); else shorts.push([config.short, config.hint || field]); } else { if (config.type === 'boolean') flags.push(field); else opts.push([field, config.hint || field]); } } const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const lf = flags.map(k => ` --${k}`).join(''); const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); ui.div({ text: usage, padding: [0, 0, 0, 2], }); } ui.div({ padding: [0, 0, 0, 0], text: '' }); const maybeDesc = this.#fields[start]; if (maybeDesc && isDescription(maybeDesc)) { const print = normalize(maybeDesc.text, maybeDesc.pre); start++; ui.div({ padding: [0, 0, 0, 0], text: print }); ui.div({ padding: [0, 0, 0, 0], text: '' }); } const { rows, maxWidth } = this.#usageRows(start); // every heading/description after the first gets indented by 2 // extra spaces. for (const row of rows) { if (row.left) { // If the row is too long, don't wrap it // Bump the right-hand side down a line to make room const configIndent = indent(Math.max(headingLevel, 2)); if (row.left.length > maxWidth - 3) { ui.div({ text: row.left, padding: [0, 0, 0, configIndent] }); ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] }); } else { ui.div({ text: row.left, padding: [0, 1, 0, configIndent], width: maxWidth, }, { padding: [0, 0, 0, 0], text: row.text }); } if (row.skipLine) { ui.div({ padding: [0, 0, 0, 0], text: '' }); } } else { if (isHeading(row)) { const { level } = row; headingLevel = level; // only h1 and h2 have bottom padding // h3-h6 do not const b = level <= 2 ? 1 : 0; ui.div({ ...row, padding: [0, 0, b, indent(level)] }); } else { ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] }); } } } return (this.#usage = ui.toString()); } /** * Return the usage banner markdown for the given configuration */ usageMarkdown() { if (this.#usageMarkdown) return this.#usageMarkdown; const out = []; let headingLevel = 1; const first = this.#fields[0]; let start = first?.type === 'heading' ? 1 : 0; if (first?.type === 'heading') { out.push(`# ${normalizeOneLine(first.text)}`); } out.push('Usage:'); if (this.#options.usage) { out.push(normalizeMarkdown(this.#options.usage, true)); } else { const cmd = basename(String(process.argv[1])); const shortFlags = []; const shorts = []; const flags = []; const opts = []; for (const [field, config] of Object.entries(this.#configSet)) { if (config.short) { if (config.type === 'boolean') shortFlags.push(config.short); else shorts.push([config.short, config.hint || field]); } else { if (config.type === 'boolean') flags.push(field); else opts.push([field, config.hint || field]); } } const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const lf = flags.map(k => ` --${k}`).join(''); const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); out.push(normalizeMarkdown(usage, true)); } const maybeDesc = this.#fields[start]; if (maybeDesc && isDescription(maybeDesc)) { out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre)); start++; } const { rows } = this.#usageRows(start); // heading level in markdown is number of # ahead of text for (const row of rows) { if (row.left) { out.push('#'.repeat(headingLevel + 1) + ' ' + normalizeOneLine(row.left, true)); if (row.text) out.push(normalizeMarkdown(row.text)); } else if (isHeading(row)) { const { level } = row; headingLevel = level; out.push(`${'#'.repeat(headingLevel)} ${normalizeOneLine(row.text, row.pre)}`); } else { out.push(normalizeMarkdown(row.text, !!row.pre)); } } return (this.#usageMarkdown = out.join('\n\n') + '\n'); } #usageRows(start) { // turn each config type into a row, and figure out the width of the // left hand indentation for the option descriptions. let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3))); let maxWidth = 8; let prev = undefined; const rows = []; for (const field of this.#fields.slice(start)) { if (field.type !== 'config') { if (prev?.type === 'config') prev.skipLine = true; prev = undefined; field.text = normalize(field.text, !!field.pre); rows.push(field); continue; } const { value } = field; const desc = value.description || ''; const mult = value.multiple ? 'Can be set multiple times' : ''; const opts = value.validOptions?.length ? `Valid options:${value.validOptions.map(v => ` ${JSON.stringify(v)}`)}` : ''; const dmDelim = desc.includes('\n') ? '\n\n' : '\n'; const extra = [opts, mult].join(dmDelim).trim(); const text = (normalize(desc) + dmDelim + extra).trim(); const hint = value.hint || (value.type === 'number' ? 'n' : value.type === 'string' ? field.name : undefined); const short = !value.short ? '' : value.type === 'boolean' ? `-${value.short} ` : `-${value.short}<${hint}> `; const left = value.type === 'boolean' ? `${short}--${field.name}` : `${short}--${field.name}=<${hint}>`; const row = { text, left, type: 'config' }; if (text.length > width - maxMax) { row.skipLine = true; } if (prev && left.length > maxMax) prev.skipLine = true; prev = row; const len = left.length + 4; if (len > maxWidth && len < maxMax) { maxWidth = len; } rows.push(row); } return { rows, maxWidth }; } /** * Return the configuration options as a plain object */ toJSON() { return Object.fromEntries(Object.entries(this.#configSet).map(([field, def]) => [ field, { type: def.type, ...(def.multiple ? { multiple: true } : {}), ...(def.delim ? { delim: def.delim } : {}), ...(def.short ? { short: def.short } : {}), ...(def.description ? { description: normalize(def.description) } : {}), ...(def.validate ? { validate: def.validate } : {}), ...(def.validOptions ? { validOptions: def.validOptions } : {}), ...(def.default !== undefined ? { default: def.default } : {}), ...(def.hint ? { hint: def.hint } : {}), }, ])); } /** * Custom printer for `util.inspect` */ [inspect.custom](_, options) { return `Jack ${inspect(this.toJSON(), options)}`; } } // Unwrap and un-indent, so we can wrap description // strings however makes them look nice in the code. const normalize = (s, pre = false) => { if (pre) // prepend a ZWSP to each line so cliui doesn't strip it. return s .split('\n') .map(l => `\u200b${l}`) .join('\n'); return s .split(/^\s*```\s*$/gm) .map((s, i) => { if (i % 2 === 1) { if (!s.trim()) { return `\`\`\`\n\`\`\`\n`; } // outdent the ``` blocks, but preserve whitespace otherwise. const split = s.split('\n'); // throw out the \n at the start and end split.pop(); split.shift(); const si = split.reduce((shortest, l) => { /* c8 ignore next */ const ind = l.match(/^\s*/)?.[0] ?? ''; if (ind.length) return Math.min(ind.length, shortest); else return shortest; }, Infinity); /* c8 ignore next */ const i = isFinite(si) ? si : 0; return ('\n```\n' + split.map(s => `\u200b${s.substring(i)}`).join('\n') + '\n```\n'); } return (s // remove single line breaks, except for lists .replace(/([^\n])\n[ \t]*([^\n])/g, (_, $1, $2) => !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\n${$2}`) // normalize mid-line whitespace .replace(/([^\n])[ \t]+([^\n])/g, '$1 $2') // two line breaks are enough .replace(/\n{3,}/g, '\n\n') // remove any spaces at the start of a line .replace(/\n[ \t]+/g, '\n') .trim()); }) .join('\n'); }; // normalize for markdown printing, remove leading spaces on lines const normalizeMarkdown = (s, pre = false) => { const n = normalize(s, pre).replace(/\\/g, '\\\\'); return pre ? `\`\`\`\n${n.replace(/\u200b/g, '')}\n\`\`\`` : n.replace(/\n +/g, '\n').trim(); }; const normalizeOneLine = (s, pre = false) => { const n = normalize(s, pre) .replace(/[\s\u200b]+/g, ' ') .trim(); return pre ? `\`${n}\`` : n; }; /** * Main entry point. Create and return a {@link Jack} object. */ export const jack = (options = {}) => new Jack(options); //# sourceMappingURL=index.js.map{ "type": "module" } import * as util from 'util'; const pv = (typeof process === 'object' && !!process && typeof process.version === 'string') ? process.version : 'v0.0.0'; const pvs = pv .replace(/^v/, '') .split('.') .map(s => parseInt(s, 10)); /* c8 ignore start */ const [major = 0, minor = 0] = pvs; /* c8 ignore stop */ let { parseArgs: pa, } = util; /* c8 ignore start - version specific */ if (!pa || major < 16 || (major === 18 && minor < 11) || (major === 16 && minor < 19)) { // Ignore because we will clobber it for commonjs //@ts-ignore pa = (await import('@pkgjs/parseargs')).parseArgs; } /* c8 ignore stop */ export const parseArgs = pa; //# sourceMappingURL=parse-args.js.map{ "name": "jackspeak", "publishConfig": { "tag": "v3-legacy" }, "version": "3.4.3", "description": "A very strict and proper argument parser.", "tshy": { "main": true, "exports": { "./package.json": "./package.json", ".": "./src/index.js" } }, "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", "type": "module", "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "files": [ "dist" ], "scripts": { "build-examples": "for i in examples/*.js ; do node $i -h > ${i/.js/.txt}; done", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "prepare": "tshy", "pretest": "npm run prepare", "presnap": "npm run prepare", "test": "tap", "snap": "tap", "format": "prettier --write . --log-level warn", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "license": "BlueOak-1.0.0", "prettier": { "experimentalTernaries": true, "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "devDependencies": { "@types/node": "^20.7.0", "@types/pkgjs__parseargs": "^0.10.1", "prettier": "^3.2.5", "tap": "^18.8.0", "tshy": "^1.14.0", "typedoc": "^0.25.1", "typescript": "^5.2.2" }, "dependencies": { "@isaacs/cliui": "^8.0.2" }, "funding": { "url": "https://github.com/sponsors/isaacs" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/jackspeak.git" }, "keywords": [ "argument", "parser", "args", "option", "flag", "cli", "command", "line", "parse", "parsing" ], "author": "Isaac Z. Schlueter ", "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } } Licensing --------- This software is covered under the following copyright: /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * 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" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ Address all questions regarding this license to: Tom Wu tjw@cs.Stanford.EDU (function () { var BigInteger = jsbn.BigInteger; var a = new BigInteger('91823918239182398123'); console.log(a.bitLength()); }()); (function(){ // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } var inBrowser = typeof navigator !== "undefined"; if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); } else this[this.t-1] |= x<= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1< 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this[i]&((1<>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // Version 1.2: square() API, isProbablePrime fix // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1< 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this^2 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // JSBN-specific extension BigInteger.prototype.square = bnSquare; // Expose the Barrett function BigInteger.prototype.Barrett = Barrett // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) // Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new Date().getTime()); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; if(typeof window !== "undefined" && window.crypto) { if (window.crypto.getRandomValues) { // Use webcrypto if available var ua = new Uint8Array(32); window.crypto.getRandomValues(ua); for(t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; } else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { // Extract entropy (256 bits) from NS4 RNG if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } } while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes; // prng4.js - uses Arcfour as a PRNG function Arcfour() { this.i = 0; this.j = 0; this.S = new Array(); } // Initialize arcfour context from key, an array of ints, each from [0..255] function ARC4init(key) { var i, j, t; for(i = 0; i < 256; ++i) this.S[i] = i; j = 0; for(i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.length]) & 255; t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; } function ARC4next() { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; } Arcfour.prototype.init = ARC4init; Arcfour.prototype.next = ARC4next; // Plug in your RNG constructor here function prng_newstate() { return new Arcfour(); } // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() var rng_psize = 256; if (typeof exports !== 'undefined') { exports = module.exports = { default: BigInteger, BigInteger: BigInteger, SecureRandom: SecureRandom, }; } else { this.jsbn = { BigInteger: BigInteger, SecureRandom: SecureRandom }; } }).call(this); { "name": "jsbn", "version": "1.1.0", "description": "The jsbn library is a fast, portable implementation of large-number math in pure JavaScript, enabling public-key crypto and other applications on desktop and mobile browsers.", "main": "index.js", "scripts": { "test": "mocha test.js" }, "repository": { "type": "git", "url": "https://github.com/andyperlitch/jsbn.git" }, "keywords": [ "biginteger", "bignumber", "big", "integer" ], "author": "Tom Wu", "license": "MIT" } import {BigInteger} from '../'; console.log(typeof BigInteger) Copyright 2017 Kat Marchán Copyright npm, Inc. 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 library is a fork of 'better-json-errors' by Kat Marchán, extended and distributed under the terms of the MIT license above. 'use strict' const INDENT = Symbol.for('indent') const NEWLINE = Symbol.for('newline') const DEFAULT_NEWLINE = '\n' const DEFAULT_INDENT = ' ' const BOM = /^\uFEFF/ // only respect indentation if we got a line break, otherwise squash it // things other than objects and arrays aren't indented, so ignore those // Important: in both of these regexps, the $1 capture group is the newline // or undefined, and the $2 capture group is the indent, or undefined. const FORMAT = /^\s*[{[]((?:\r?\n)+)([\s\t]*)/ const EMPTY = /^(?:\{\}|\[\])((?:\r?\n)+)?$/ // Node 20 puts single quotes around the token and a comma after it const UNEXPECTED_TOKEN = /^Unexpected token '?(.)'?(,)? /i const hexify = (char) => { const h = char.charCodeAt(0).toString(16).toUpperCase() return `0x${h.length % 2 ? '0' : ''}${h}` } // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. const stripBOM = (txt) => String(txt).replace(BOM, '') const makeParsedError = (msg, parsing, position = 0) => ({ message: `${msg} while parsing ${parsing}`, position, }) const parseError = (e, txt, context = 20) => { let msg = e.message if (!txt) { return makeParsedError(msg, 'empty string') } const badTokenMatch = msg.match(UNEXPECTED_TOKEN) const badIndexMatch = msg.match(/ position\s+(\d+)/i) if (badTokenMatch) { msg = msg.replace( UNEXPECTED_TOKEN, `Unexpected token ${JSON.stringify(badTokenMatch[1])} (${hexify(badTokenMatch[1])})$2 ` ) } let errIdx if (badIndexMatch) { errIdx = +badIndexMatch[1] } else /* istanbul ignore next - doesnt happen in Node 22 */ if ( msg.match(/^Unexpected end of JSON.*/i) ) { errIdx = txt.length - 1 } if (errIdx == null) { return makeParsedError(msg, `'${txt.slice(0, context * 2)}'`) } const start = errIdx <= context ? 0 : errIdx - context const end = errIdx + context >= txt.length ? txt.length : errIdx + context const slice = `${start ? '...' : ''}${txt.slice(start, end)}${end === txt.length ? '' : '...'}` return makeParsedError( msg, `${txt === slice ? '' : 'near '}${JSON.stringify(slice)}`, errIdx ) } class JSONParseError extends SyntaxError { constructor (er, txt, context, caller) { const metadata = parseError(er, txt, context) super(metadata.message) Object.assign(this, metadata) this.code = 'EJSONPARSE' this.systemError = er Error.captureStackTrace(this, caller || this.constructor) } get name () { return this.constructor.name } set name (n) {} get [Symbol.toStringTag] () { return this.constructor.name } } const parseJson = (txt, reviver) => { const result = JSON.parse(txt, reviver) if (result && typeof result === 'object') { // get the indentation so that we can save it back nicely // if the file starts with {" then we have an indent of '', ie, none // otherwise, pick the indentation of the next line after the first \n If the // pattern doesn't match, then it means no indentation. JSON.stringify ignores // symbols, so this is reasonably safe. if the string is '{}' or '[]', then // use the default 2-space indent. const match = txt.match(EMPTY) || txt.match(FORMAT) || [null, '', ''] result[NEWLINE] = match[1] ?? DEFAULT_NEWLINE result[INDENT] = match[2] ?? DEFAULT_INDENT } return result } const parseJsonError = (raw, reviver, context) => { const txt = stripBOM(raw) try { return parseJson(txt, reviver) } catch (e) { if (typeof raw !== 'string' && !Buffer.isBuffer(raw)) { const msg = Array.isArray(raw) && raw.length === 0 ? 'an empty array' : String(raw) throw Object.assign( new TypeError(`Cannot parse ${msg}`), { code: 'EJSONPARSE', systemError: e } ) } throw new JSONParseError(e, txt, context, parseJsonError) } } module.exports = parseJsonError parseJsonError.JSONParseError = JSONParseError parseJsonError.noExceptions = (raw, reviver) => { try { return parseJson(stripBOM(raw), reviver) } catch { // no exceptions } } { "name": "json-parse-even-better-errors", "version": "4.0.0", "description": "JSON.parse with context information on error", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "scripts": { "test": "tap", "snap": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "repository": { "type": "git", "url": "git+https://github.com/npm/json-parse-even-better-errors.git" }, "keywords": [ "JSON", "parser" ], "author": "GitHub Inc.", "license": "MIT", "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.3", "tap": "^16.3.0" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.3", "publish": true } } The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const isObj = val => !!val && !Array.isArray(val) && typeof val === 'object' const compare = (ak, bk, prefKeys) => prefKeys.includes(ak) && !prefKeys.includes(bk) ? -1 : prefKeys.includes(bk) && !prefKeys.includes(ak) ? 1 : prefKeys.includes(ak) && prefKeys.includes(bk) ? prefKeys.indexOf(ak) - prefKeys.indexOf(bk) : ak.localeCompare(bk, 'en') const sort = (replacer, seen) => (key, val) => { const prefKeys = Array.isArray(replacer) ? replacer : [] if (typeof replacer === 'function') val = replacer(key, val) if (!isObj(val)) return val if (seen.has(val)) return seen.get(val) const ret = Object.entries(val).sort( ([ak, av], [bk, bv]) => isObj(av) === isObj(bv) ? compare(ak, bk, prefKeys) : isObj(av) ? 1 : -1 ).reduce((set, [k, v]) => { set[k] = v return set }, {}) seen.set(val, ret) return ret } module.exports = (obj, replacer, space = 2) => JSON.stringify(obj, sort(replacer, new Map()), space) + (space ? '\n' : '') { "name": "json-stringify-nice", "version": "1.1.4", "description": "Stringify an object sorting scalars before objects, and defaulting to 2-space indent", "author": "Isaac Z. Schlueter (https://izs.me)", "license": "ISC", "scripts": { "test": "tap", "posttest": "npm run lint", "snap": "tap", "postsnap": "npm run lintfix", "eslint": "eslint", "lint": "npm run eslint -- index.js test/**/*.js", "lintfix": "npm run lint -- --fix", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --follow-tags" }, "tap": { "test-env": [ "LC_ALL=sk" ], "check-coverage": true }, "devDependencies": { "eslint": "^7.25.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^5.1.0", "eslint-plugin-standard": "^5.0.0", "tap": "^15.0.6" }, "funding": { "url": "https://github.com/sponsors/isaacs" }, "repository": "https://github.com/isaacs/json-stringify-nice", "files": [ "index.js" ] } The MIT License Copyright (c) 2012 Tim Caswell 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. var fs = require('fs'), Parser = require('./jsonparse'); var json = fs.readFileSync("samplejson/basic.json"); while (true) { var start = Date.now(); for (var i = 0; i < 1000; i++) { JSON.parse(json); } var first = Date.now() - start; start = Date.now(); var p = new Parser(); for (var i = 0; i < 1000; i++) { p.write(json); } var second = Date.now() - start; console.log("JSON.parse took %s", first); console.log("streaming parser took %s", second); console.log("streaming is %s times slower", second / first); } var Parser = require('../jsonparse'); var Http = require('http'); require('./colors'); var p = new Parser(); var cred = require('./credentials'); var client = Http.createClient(80, "stream.twitter.com"); var request = client.request("GET", "/1/statuses/sample.json", { "Host": "stream.twitter.com", "Authorization": (new Buffer(cred.username + ":" + cred.password)).toString("base64") }); request.on('response', function (response) { console.log(response.statusCode); console.dir(response.headers); response.on('data', function (chunk) { p.write(chunk); }); response.on('end', function () { console.log("END"); }); }); request.end(); var text = "", name = ""; p.onValue = function (value) { if (this.stack.length === 1 && this.key === 'text') { text = value; } if (this.stack.length === 2 && this.key === 'name' && this.stack[1].key === 'user') { name = value; } if (this.stack.length === 0) { console.log(text.blue + " - " + name.yellow); text = name = ""; } }; /*global Buffer*/ // Named constants with unique integer values var C = {}; // Tokens var LEFT_BRACE = C.LEFT_BRACE = 0x1; var RIGHT_BRACE = C.RIGHT_BRACE = 0x2; var LEFT_BRACKET = C.LEFT_BRACKET = 0x3; var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4; var COLON = C.COLON = 0x5; var COMMA = C.COMMA = 0x6; var TRUE = C.TRUE = 0x7; var FALSE = C.FALSE = 0x8; var NULL = C.NULL = 0x9; var STRING = C.STRING = 0xa; var NUMBER = C.NUMBER = 0xb; // Tokenizer States var START = C.START = 0x11; var STOP = C.STOP = 0x12; var TRUE1 = C.TRUE1 = 0x21; var TRUE2 = C.TRUE2 = 0x22; var TRUE3 = C.TRUE3 = 0x23; var FALSE1 = C.FALSE1 = 0x31; var FALSE2 = C.FALSE2 = 0x32; var FALSE3 = C.FALSE3 = 0x33; var FALSE4 = C.FALSE4 = 0x34; var NULL1 = C.NULL1 = 0x41; var NULL2 = C.NULL2 = 0x42; var NULL3 = C.NULL3 = 0x43; var NUMBER1 = C.NUMBER1 = 0x51; var NUMBER3 = C.NUMBER3 = 0x53; var STRING1 = C.STRING1 = 0x61; var STRING2 = C.STRING2 = 0x62; var STRING3 = C.STRING3 = 0x63; var STRING4 = C.STRING4 = 0x64; var STRING5 = C.STRING5 = 0x65; var STRING6 = C.STRING6 = 0x66; // Parser States var VALUE = C.VALUE = 0x71; var KEY = C.KEY = 0x72; // Parser Modes var OBJECT = C.OBJECT = 0x81; var ARRAY = C.ARRAY = 0x82; // Character constants var BACK_SLASH = "\\".charCodeAt(0); var FORWARD_SLASH = "\/".charCodeAt(0); var BACKSPACE = "\b".charCodeAt(0); var FORM_FEED = "\f".charCodeAt(0); var NEWLINE = "\n".charCodeAt(0); var CARRIAGE_RETURN = "\r".charCodeAt(0); var TAB = "\t".charCodeAt(0); var STRING_BUFFER_SIZE = 64 * 1024; function Parser() { this.tState = START; this.value = undefined; this.string = undefined; // string data this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE); this.stringBufferOffset = 0; this.unicode = undefined; // unicode escapes this.highSurrogate = undefined; this.key = undefined; this.mode = undefined; this.stack = []; this.state = VALUE; this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached // Stream offset this.offset = -1; } // Slow code to string converter (only used when throwing syntax errors) Parser.toknam = function (code) { var keys = Object.keys(C); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (C[key] === code) { return key; } } return code && ("0x" + code.toString(16)); }; var proto = Parser.prototype; proto.onError = function (err) { throw err; }; proto.charError = function (buffer, i) { this.tState = STOP; this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState))); }; proto.appendStringChar = function (char) { if (this.stringBufferOffset >= STRING_BUFFER_SIZE) { this.string += this.stringBuffer.toString('utf8'); this.stringBufferOffset = 0; } this.stringBuffer[this.stringBufferOffset++] = char; }; proto.appendStringBuf = function (buf, start, end) { var size = buf.length; if (typeof start === 'number') { if (typeof end === 'number') { if (end < 0) { // adding a negative end decreeses the size size = buf.length - start + end; } else { size = end - start; } } else { size = buf.length - start; } } if (size < 0) { size = 0; } if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) { this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); this.stringBufferOffset = 0; } buf.copy(this.stringBuffer, this.stringBufferOffset, start, end); this.stringBufferOffset += size; }; proto.write = function (buffer) { if (typeof buffer === "string") buffer = new Buffer(buffer); var n; for (var i = 0, l = buffer.length; i < l; i++) { if (this.tState === START){ n = buffer[i]; this.offset++; if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // { }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // } }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [ }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ] }else if(n === 0x3a){ this.onToken(COLON, ":"); // : }else if(n === 0x2c){ this.onToken(COMMA, ","); // , }else if(n === 0x74){ this.tState = TRUE1; // t }else if(n === 0x66){ this.tState = FALSE1; // f }else if(n === 0x6e){ this.tState = NULL1; // n }else if(n === 0x22){ // " this.string = ""; this.stringBufferOffset = 0; this.tState = STRING1; }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // - }else{ if (n >= 0x30 && n < 0x40) { // 1-9 this.string = String.fromCharCode(n); this.tState = NUMBER3; } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) { // whitespace } else { return this.charError(buffer, i); } } }else if (this.tState === STRING1){ // After open quote n = buffer[i]; // get current byte from buffer // check for carry over of a multi byte char split between data chunks // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration if (this.bytes_remaining > 0) { for (var j = 0; j < this.bytes_remaining; j++) { this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j]; } this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]); this.bytes_in_sequence = this.bytes_remaining = 0; i = i + j - 1; } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time if (n <= 193 || n > 244) { return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState))); } if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split for (var k = 0; k <= (buffer.length - 1 - i); k++) { this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk } this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length; i = buffer.length - 1; } else { this.appendStringBuf(buffer, i, i + this.bytes_in_sequence); i = i + this.bytes_in_sequence - 1; } } else if (n === 0x22) { this.tState = START; this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); this.stringBufferOffset = 0; this.onToken(STRING, this.string); this.offset += Buffer.byteLength(this.string, 'utf8') + 1; this.string = undefined; } else if (n === 0x5c) { this.tState = STRING2; } else if (n >= 0x20) { this.appendStringChar(n); } else { return this.charError(buffer, i); } }else if (this.tState === STRING2){ // After backslash n = buffer[i]; if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1; }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1; }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1; }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1; }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1; }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1; }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1; }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1; }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3; }else{ return this.charError(buffer, i); } }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes n = buffer[i]; // 0-9 A-F a-f if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) { this.unicode += String.fromCharCode(n); if (this.tState++ === STRING6) { var intVal = parseInt(this.unicode, 16); this.unicode = undefined; if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal))); this.highSurrogate = undefined; } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate this.highSurrogate = intVal; } else { if (this.highSurrogate !== undefined) { this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))); this.highSurrogate = undefined; } this.appendStringBuf(new Buffer(String.fromCharCode(intVal))); } this.tState = STRING1; } } else { return this.charError(buffer, i); } } else if (this.tState === NUMBER1 || this.tState === NUMBER3) { n = buffer[i]; switch (n) { case 0x30: // 0 case 0x31: // 1 case 0x32: // 2 case 0x33: // 3 case 0x34: // 4 case 0x35: // 5 case 0x36: // 6 case 0x37: // 7 case 0x38: // 8 case 0x39: // 9 case 0x2e: // . case 0x65: // e case 0x45: // E case 0x2b: // + case 0x2d: // - this.string += String.fromCharCode(n); this.tState = NUMBER3; break; default: this.tState = START; var result = Number(this.string); if (isNaN(result)){ return this.charError(buffer, i); } if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) { // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number this.onToken(STRING, this.string); } else { this.onToken(NUMBER, result); } this.offset += this.string.length - 1; this.string = undefined; i--; break; } }else if (this.tState === TRUE1){ // r if (buffer[i] === 0x72) { this.tState = TRUE2; } else { return this.charError(buffer, i); } }else if (this.tState === TRUE2){ // u if (buffer[i] === 0x75) { this.tState = TRUE3; } else { return this.charError(buffer, i); } }else if (this.tState === TRUE3){ // e if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; } else { return this.charError(buffer, i); } }else if (this.tState === FALSE1){ // a if (buffer[i] === 0x61) { this.tState = FALSE2; } else { return this.charError(buffer, i); } }else if (this.tState === FALSE2){ // l if (buffer[i] === 0x6c) { this.tState = FALSE3; } else { return this.charError(buffer, i); } }else if (this.tState === FALSE3){ // s if (buffer[i] === 0x73) { this.tState = FALSE4; } else { return this.charError(buffer, i); } }else if (this.tState === FALSE4){ // e if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; } else { return this.charError(buffer, i); } }else if (this.tState === NULL1){ // u if (buffer[i] === 0x75) { this.tState = NULL2; } else { return this.charError(buffer, i); } }else if (this.tState === NULL2){ // l if (buffer[i] === 0x6c) { this.tState = NULL3; } else { return this.charError(buffer, i); } }else if (this.tState === NULL3){ // l if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; } else { return this.charError(buffer, i); } } } }; proto.onToken = function (token, value) { // Override this to get events }; proto.parseError = function (token, value) { this.tState = STOP; this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state))); }; proto.push = function () { this.stack.push({value: this.value, key: this.key, mode: this.mode}); }; proto.pop = function () { var value = this.value; var parent = this.stack.pop(); this.value = parent.value; this.key = parent.key; this.mode = parent.mode; this.emit(value); if (!this.mode) { this.state = VALUE; } }; proto.emit = function (value) { if (this.mode) { this.state = COMMA; } this.onValue(value); }; proto.onValue = function (value) { // Override me }; proto.onToken = function (token, value) { if(this.state === VALUE){ if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){ if (this.value) { this.value[this.key] = value; } this.emit(value); }else if(token === LEFT_BRACE){ this.push(); if (this.value) { this.value = this.value[this.key] = {}; } else { this.value = {}; } this.key = undefined; this.state = KEY; this.mode = OBJECT; }else if(token === LEFT_BRACKET){ this.push(); if (this.value) { this.value = this.value[this.key] = []; } else { this.value = []; } this.key = 0; this.mode = ARRAY; this.state = VALUE; }else if(token === RIGHT_BRACE){ if (this.mode === OBJECT) { this.pop(); } else { return this.parseError(token, value); } }else if(token === RIGHT_BRACKET){ if (this.mode === ARRAY) { this.pop(); } else { return this.parseError(token, value); } }else{ return this.parseError(token, value); } }else if(this.state === KEY){ if (token === STRING) { this.key = value; this.state = COLON; } else if (token === RIGHT_BRACE) { this.pop(); } else { return this.parseError(token, value); } }else if(this.state === COLON){ if (token === COLON) { this.state = VALUE; } else { return this.parseError(token, value); } }else if(this.state === COMMA){ if (token === COMMA) { if (this.mode === ARRAY) { this.key++; this.state = VALUE; } else if (this.mode === OBJECT) { this.state = KEY; } } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) { this.pop(); } else { return this.parseError(token, value); } }else{ return this.parseError(token, value); } }; Parser.C = C; module.exports = Parser; { "name": "jsonparse", "description": "This is a pure-js JSON streaming parser for node.js", "tags": ["json", "stream"], "version": "1.3.1", "author": "Tim Caswell ", "repository": { "type": "git", "url": "http://github.com/creationix/jsonparse.git" }, "devDependencies": { "tape": "~0.1.1", "tap": "~0.3.3" }, "scripts": { "test": "tap test/*.js" }, "bugs": "http://github.com/creationix/jsonparse/issues", "engines": ["node >= 0.2.0"], "license": "MIT", "main": "jsonparse.js" } [ { }, { "image": [ {"shape": "rect", "fill": "#333", "stroke": "#999", "x": 0.5e+1, "y": 0.5, "z": 0.8e-0, "w": 0.5e5, "u": 2E10, "foo": 2E+1, "bar": 2E-0, "width": 47, "height": 47} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,47.5],[47.5,47.5],[47.5,0.5]]} ], "solid": { "1": [2,4], "2": [1], "3": [2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,0.5],[47.5,47.5],[0.5,47.5]]} ], "solid": { "1": [2], "2": [3], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [7], "9": [6,8] }, "corners": {"1": false,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[0.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [9], "9": [6,8] }, "corners": {"1": true,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,47.5],[0.5,23.5],[24.5,23.5],[24.5,0.5],[47.5,0.5],[47.5,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [6,2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [9], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,0.5],[23.5,0.5],[23.5,24.5],[47.5,24.5],[47.5,47.5],[0.5,47.5]]} ], "jumpable": 3, "solid": { "1": [4,2], "2": [], "3": [2,6], "4": [7], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "circle", "fill": "#ff0", "stroke": "#ff8", "cx": 24, "cy": 24, "r": 18} ], "item": true }, { "image": [ {"shape": "polygon", "fill": "#842", "stroke": "#f84", "points": [[4.5,0.5],[14.5,0.5],[14.5,17.5],[34,17.5],[33.5,0.5],[43.5,0.5],[43.5,47.5],[33.5,47.5],[33.5,30.5],[14.5,30.5],[14.5,47.5],[4.5,47.5]]} ], "jumpable": 3 }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,0.5],[24,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": false,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "rect", "fill": "#114acb", "x": 0.5, "y": 0.5, "width": 47, "height": 47}, {"shape": "polygon", "fill": "rgba(255,255,255,0.30)", "points": [[0.5,0.5],[47.5,0.5],[40,8],[8,8],[8,40],[0.5,47.5]]}, {"shape": "polygon", "fill": "rgba(0,0,0,0.30)", "points": [[47.5,0.5],[48,48],[0.5,47.5],[8,40],[40,40],[40,8]]}, {"shape": "polygon", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "points": [[24,9],[35,20],[26,29],[26,33],[22,33],[22,27],[29,20],[24,15],[16,23],[13,20]]}, {"shape": "rect", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "x": 22, "y":35, "width": 4, "height": 4} ] } ] [ { }, { "image": [ {"shape": "rect", "fill": "#333", "stroke": "#999", "x": 0.5, "y": 0.5, "width": 47, "height": 47} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,47.5],[47.5,47.5],[47.5,0.5]]} ], "solid": { "1": [2,4], "2": [1], "3": [2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,0.5],[47.5,47.5],[0.5,47.5]]} ], "solid": { "1": [2], "2": [3], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [7], "9": [6,8] }, "corners": {"1": false,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[0.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [9], "9": [6,8] }, "corners": {"1": true,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,47.5],[0.5,23.5],[24.5,23.5],[24.5,0.5],[47.5,0.5],[47.5,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [6,2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [9], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,0.5],[23.5,0.5],[23.5,24.5],[47.5,24.5],[47.5,47.5],[0.5,47.5]]} ], "jumpable": 3, "solid": { "1": [4,2], "2": [], "3": [2,6], "4": [7], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "circle", "fill": "#ff0", "stroke": "#ff8", "cx": 24, "cy": 24, "r": 18} ], "item": true }, { "image": [ {"shape": "polygon", "fill": "#842", "stroke": "#f84", "points": [[4.5,0.5],[14.5,0.5],[14.5,17.5],[34,17.5],[33.5,0.5],[43.5,0.5],[43.5,47.5],[33.5,47.5],[33.5,30.5],[14.5,30.5],[14.5,47.5],[4.5,47.5]]} ], "jumpable": 3 }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,0.5],[24,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": false,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "rect", "fill": "#114acb", "x": 0.5, "y": 0.5, "width": 47, "height": 47}, {"shape": "polygon", "fill": "rgba(255,255,255,0.30)", "points": [[0.5,0.5],[47.5,0.5],[40,8],[8,8],[8,40],[0.5,47.5]]}, {"shape": "polygon", "fill": "rgba(0,0,0,0.30)", "points": [[47.5,0.5],[48,48],[0.5,47.5],[8,40],[40,40],[40,8]]}, {"shape": "polygon", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "points": [[24,9],[35,20],[26,29],[26,33],[22,33],[22,27],[29,20],[24,15],[16,23],[13,20]]}, {"shape": "rect", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "x": 22, "y":35, "width": 4, "height": 4} ], "item": true }, { "image": [ {"shape": "circle", "fill": "#80f", "stroke": "#88f", "cx": 24, "cy": 24, "r": 18} ], "item": true }, { "image": [ {"shape": "circle", "fill": "#4f4", "stroke": "#8f8", "cx": 24, "cy": 24, "r": 18} ], "item": true } ] var stream = require('stream'); var JsonParse = require('../jsonparse'); var test = require('tape'); test('can handle large tokens without running out of memory', function (t) { var parser = new JsonParse(); var chunkSize = 1024; var chunks = 1024 * 200; // 200mb var quote = Buffer.from ? Buffer.from('"') : new Buffer('"'); t.plan(1); parser.onToken = function (type, value) { t.equal(value.length, chunkSize * chunks, 'token should be size of input json'); t.end(); }; parser.write(quote); for (var i = 0; i < chunks; ++i) { var buf = Buffer.alloc ? Buffer.alloc(chunkSize) : new Buffer(chunkSize); buf.fill('a'); parser.write(buf); } parser.write(quote); }); var test = require('tape'); var Parser = require('../'); test('2 byte utf8 \'De\' character: д', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, 'д'); }; var de_buffer = new Buffer([0xd0, 0xb4]); p.write('"'); p.write(de_buffer); p.write('"'); }); test('3 byte utf8 \'Han\' character: 我', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '我'); }; var han_buffer = new Buffer([0xe6, 0x88, 0x91]); p.write('"'); p.write(han_buffer); p.write('"'); }); test('4 byte utf8 character (unicode scalar U+2070E): 𠜎', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '𠜎'); }; var Ux2070E_buffer = new Buffer([0xf0, 0xa0, 0x9c, 0x8e]); p.write('"'); p.write(Ux2070E_buffer); p.write('"'); }); test('3 byte utf8 \'Han\' character chunked inbetween 2nd and 3rd byte: 我', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '我'); }; var han_buffer_first = new Buffer([0xe6, 0x88]); var han_buffer_second = new Buffer([0x91]); p.write('"'); p.write(han_buffer_first); p.write(han_buffer_second); p.write('"'); }); test('4 byte utf8 character (unicode scalar U+2070E) chunked inbetween 2nd and 3rd byte: 𠜎', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '𠜎'); }; var Ux2070E_buffer_first = new Buffer([0xf0, 0xa0]); var Ux2070E_buffer_second = new Buffer([0x9c, 0x8e]); p.write('"'); p.write(Ux2070E_buffer_first); p.write(Ux2070E_buffer_second); p.write('"'); }); test('1-4 byte utf8 character string chunked inbetween random bytes: Aж文𠜱B', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, 'Aж文𠜱B'); }; var eclectic_buffer = new Buffer([0x41, // A 0xd0, 0xb6, // ж 0xe6, 0x96, 0x87, // 文 0xf0, 0xa0, 0x9c, 0xb1, // 𠜱 0x42]); // B var rand_chunk = Math.floor(Math.random() * (eclectic_buffer.length)); var first_buffer = eclectic_buffer.slice(0, rand_chunk); var second_buffer = eclectic_buffer.slice(rand_chunk); //console.log('eclectic_buffer: ' + eclectic_buffer) //console.log('sliced from 0 to ' + rand_chunk); //console.log(first_buffer); //console.log('then sliced from ' + rand_chunk + ' to the end'); //console.log(second_buffer); console.log('chunked after offset ' + rand_chunk); p.write('"'); p.write(first_buffer); p.write(second_buffer); p.write('"'); });var test = require('tape'); var Parser = require('../'); var input = '{\n "string": "value",\n "number": 3,\n "object"'; var input2 = ': {\n "key": "vд"\n },\n "array": [\n -1,\n 12\n ]\n '; var input3 = '"null": null, "true": true, "false": false, "frac": 3.14 }'; var offsets = [ [ 0, Parser.C.LEFT_BRACE ], [ 4, Parser.C.STRING ], [ 12, Parser.C.COLON ], [ 14, Parser.C.STRING ], [ 21, Parser.C.COMMA ], [ 25, Parser.C.STRING ], [ 33, Parser.C.COLON ], [ 35, Parser.C.NUMBER ], [ 36, Parser.C.COMMA ], [ 40, Parser.C.STRING ], [ 48, Parser.C.COLON ], [ 50, Parser.C.LEFT_BRACE ], [ 54, Parser.C.STRING ], [ 59, Parser.C.COLON ], [ 61, Parser.C.STRING ], [ 69, Parser.C.RIGHT_BRACE ], [ 70, Parser.C.COMMA ], [ 74, Parser.C.STRING ], [ 81, Parser.C.COLON ], [ 83, Parser.C.LEFT_BRACKET ], [ 87, Parser.C.NUMBER ], [ 89, Parser.C.COMMA ], [ 93, Parser.C.NUMBER ], [ 98, Parser.C.RIGHT_BRACKET ], [ 102, Parser.C.STRING ], [ 108, Parser.C.COLON ], [ 110, Parser.C.NULL ], [ 114, Parser.C.COMMA ], [ 116, Parser.C.STRING ], [ 122, Parser.C.COLON ], [ 124, Parser.C.TRUE ], [ 128, Parser.C.COMMA ], [ 130, Parser.C.STRING ], [ 137, Parser.C.COLON ], [ 139, Parser.C.FALSE ], [ 144, Parser.C.COMMA ], [ 146, Parser.C.STRING ], [ 152, Parser.C.COLON ], [ 154, Parser.C.NUMBER ], [ 159, Parser.C.RIGHT_BRACE ] ]; test('offset', function(t) { t.plan(offsets.length * 2 + 1); var p = new Parser(); var i = 0; p.onToken = function (token) { t.equal(p.offset, offsets[i][0]); t.equal(token, offsets[i][1]); i++; }; p.write(input); p.write(input2); p.write(input3); t.equal(i, offsets.length); }); var test = require('tape'); var Parser = require('../'); var expected = [ [ [], '' ], [ [], 'Hello' ], [ [], 'This"is' ], [ [], '\r\n\f\t\\/"' ], [ [], 'Λάμβδα' ], [ [], '\\' ], [ [], '/' ], [ [], '"' ], [ [ 0 ], 0 ], [ [ 1 ], 1 ], [ [ 2 ], -1 ], [ [], [ 0, 1, -1 ] ], [ [ 0 ], 1 ], [ [ 1 ], 1.1 ], [ [ 2 ], -1.1 ], [ [ 3 ], -1 ], [ [], [ 1, 1.1, -1.1, -1 ] ], [ [ 0 ], -1 ], [ [], [ -1 ] ], [ [ 0 ], -0.1 ], [ [], [ -0.1 ] ], [ [ 0 ], 6.02e+23 ], [ [], [ 6.02e+23 ] ], [ [ 0 ], '7161093205057351174' ], [ [], [ '7161093205057351174'] ] ]; test('primitives', function (t) { t.plan(25); var p = new Parser(); p.onValue = function (value) { var keys = this.stack .slice(1) .map(function (item) { return item.key }) .concat(this.key !== undefined ? this.key : []) ; t.deepEqual( [ keys, value ], expected.shift() ); }; p.write('"""Hello""This\\"is""\\r\\n\\f\\t\\\\\\/\\""'); p.write('"\\u039b\\u03ac\\u03bc\\u03b2\\u03b4\\u03b1"'); p.write('"\\\\"'); p.write('"\\/"'); p.write('"\\""'); p.write('[0,1,-1]'); p.write('[1.0,1.1,-1.1,-1.0][-1][-0.1]'); p.write('[6.02e23]'); p.write('[7161093205057351174]'); }); var test = require('tape'); var Parser = require('../'); test('parse surrogate pair', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '😋'); }; p.write('"\\uD83D\\uDE0B"'); }); test('parse chunked surrogate pair', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '😋'); }; p.write('"\\uD83D'); p.write('\\uDE0B"'); }); var test = require('tape'); var Parser = require('../'); test('unvalid', function (t) { var count = 0; var p = new Parser(); p.onError = function (value) { count++; t.equal(1, count); t.end(); }; p.write('{"test": eer['); }); var test = require('tape'); var Parser = require('../'); test('3 bytes of utf8', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '├──'); }; p.write('"├──"'); }); test('utf8 snowman', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '☃'); }; p.write('"☃"'); }); test('utf8 with regular ascii', function (t) { t.plan(4); var p = new Parser(); var expected = [ "snow: ☃!", "xyz", "¡que!" ]; expected.push(expected.slice()); p.onValue = function (value) { t.deepEqual(value, expected.shift()); }; p.write('["snow: ☃!","xyz","¡que!"]'); }); The MIT License (MIT) Copyright (c) 2016 angus croll 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. module.exports = { diffApply: diffApply, jsonPatchPathConverter: jsonPatchPathConverter, }; /* const obj1 = {a: 3, b: 5}; diffApply(obj1, [ { "op": "remove", "path": ['b'] }, { "op": "replace", "path": ['a'], "value": 4 }, { "op": "add", "path": ['c'], "value": 5 } ] ); obj1; // {a: 4, c: 5} // using converter to apply jsPatch standard paths // see http://jsonpatch.com import {diff, jsonPatchPathConverter} from 'just-diff' const obj2 = {a: 3, b: 5}; diffApply(obj2, [ { "op": "remove", "path": '/b' }, { "op": "replace", "path": '/a', "value": 4 } { "op": "add", "path": '/c', "value": 5 } ], jsonPatchPathConverter); obj2; // {a: 4, c: 5} // arrays const obj3 = {a: 4, b: [1, 2, 3]}; diffApply(obj3, [ { "op": "replace", "path": ['a'], "value": 3 } { "op": "replace", "path": ['b', 2], "value": 4 } { "op": "add", "path": ['b', 3], "value": 9 } ]); obj3; // {a: 3, b: [1, 2, 4, 9]} // nested paths const obj4 = {a: 4, b: {c: 3}}; diffApply(obj4, [ { "op": "replace", "path": ['a'], "value": 5 } { "op": "remove", "path": ['b', 'c']} { "op": "add", "path": ['b', 'd'], "value": 4 } ]); obj4; // {a: 5, b: {d: 4}} */ var REMOVE = 'remove'; var REPLACE = 'replace'; var ADD = 'add'; var MOVE = 'move'; function diffApply(obj, diff, pathConverter) { if (!obj || typeof obj != 'object') { throw new Error('base object must be an object or an array'); } if (!Array.isArray(diff)) { throw new Error('diff must be an array'); } var diffLength = diff.length; for (var i = 0; i < diffLength; i++) { var thisDiff = diff[i]; var subObject = obj; var thisOp = thisDiff.op; var thisPath = transformPath(pathConverter, thisDiff.path); var thisFromPath = thisDiff.from && transformPath(pathConverter, thisDiff.from); var toPath, toPathCopy, lastToProp, subToObject, valueToMove; if (thisFromPath) { // MOVE only, "fromPath" is effectively path and "path" is toPath toPath = thisPath; thisPath = thisFromPath; toPathCopy = toPath.slice(); lastToProp = toPathCopy.pop(); prototypeCheck(lastToProp); if (lastToProp == null) { return false; } var thisToProp; while (((thisToProp = toPathCopy.shift())) != null) { prototypeCheck(thisToProp); if (!(thisToProp in subToObject)) { subToObject[thisToProp] = {}; } subToObject = subToObject[thisToProp]; } } var pathCopy = thisPath.slice(); var lastProp = pathCopy.pop(); prototypeCheck(lastProp); if (lastProp == null) { return false; } var thisProp; while (((thisProp = pathCopy.shift())) != null) { prototypeCheck(thisProp); if (!(thisProp in subObject)) { subObject[thisProp] = {}; } subObject = subObject[thisProp]; } if (thisOp === REMOVE || thisOp === REPLACE || thisOp === MOVE) { var path = thisOp === MOVE ? thisDiff.from : thisDiff.path; if (!subObject.hasOwnProperty(lastProp)) { throw new Error(['expected to find property', path, 'in object', obj].join(' ')); } } if (thisOp === REMOVE || thisOp === MOVE) { if (thisOp === MOVE) { valueToMove = subObject[lastProp]; } Array.isArray(subObject) ? subObject.splice(lastProp, 1) : delete subObject[lastProp]; } if (thisOp === REPLACE || thisOp === ADD) { subObject[lastProp] = thisDiff.value; } if (thisOp === MOVE) { subObject[lastToProp] = valueToMove; } } return subObject; } function transformPath(pathConverter, thisPath) { if(pathConverter) { thisPath = pathConverter(thisPath); if(!Array.isArray(thisPath)) { throw new Error([ 'pathConverter must return an array, returned:', thisPath, ].join(' ')); } } else { if(!Array.isArray(thisPath)) { throw new Error([ 'diff path', thisPath, 'must be an array, consider supplying a path converter'] .join(' ')); } } return thisPath; } function jsonPatchPathConverter(stringPath) { return stringPath.split('/').slice(1); } function prototypeCheck(prop) { // coercion is intentional to catch prop values like `['__proto__']` if (prop == '__proto__' || prop == 'constructor' || prop == 'prototype') { throw new Error('setting of prototype values not supported'); } } /* const obj1 = {a: 3, b: 5}; diffApply(obj1, [ { "op": "remove", "path": ['b'] }, { "op": "replace", "path": ['a'], "value": 4 }, { "op": "add", "path": ['c'], "value": 5 } ] ); obj1; // {a: 4, c: 5} // using converter to apply jsPatch standard paths // see http://jsonpatch.com import {diff, jsonPatchPathConverter} from 'just-diff' const obj2 = {a: 3, b: 5}; diffApply(obj2, [ { "op": "remove", "path": '/b' }, { "op": "replace", "path": '/a', "value": 4 } { "op": "add", "path": '/c', "value": 5 } ], jsonPatchPathConverter); obj2; // {a: 4, c: 5} // arrays const obj3 = {a: 4, b: [1, 2, 3]}; diffApply(obj3, [ { "op": "replace", "path": ['a'], "value": 3 } { "op": "replace", "path": ['b', 2], "value": 4 } { "op": "add", "path": ['b', 3], "value": 9 } ]); obj3; // {a: 3, b: [1, 2, 4, 9]} // nested paths const obj4 = {a: 4, b: {c: 3}}; diffApply(obj4, [ { "op": "replace", "path": ['a'], "value": 5 } { "op": "remove", "path": ['b', 'c']} { "op": "add", "path": ['b', 'd'], "value": 4 } ]); obj4; // {a: 5, b: {d: 4}} */ var REMOVE = 'remove'; var REPLACE = 'replace'; var ADD = 'add'; var MOVE = 'move'; function diffApply(obj, diff, pathConverter) { if (!obj || typeof obj != 'object') { throw new Error('base object must be an object or an array'); } if (!Array.isArray(diff)) { throw new Error('diff must be an array'); } var diffLength = diff.length; for (var i = 0; i < diffLength; i++) { var thisDiff = diff[i]; var subObject = obj; var thisOp = thisDiff.op; var thisPath = transformPath(pathConverter, thisDiff.path); var thisFromPath = thisDiff.from && transformPath(pathConverter, thisDiff.from); var toPath, toPathCopy, lastToProp, subToObject, valueToMove; if (thisFromPath) { // MOVE only, "fromPath" is effectively path and "path" is toPath toPath = thisPath; thisPath = thisFromPath; toPathCopy = toPath.slice(); lastToProp = toPathCopy.pop(); prototypeCheck(lastToProp); if (lastToProp == null) { return false; } var thisToProp; while (((thisToProp = toPathCopy.shift())) != null) { prototypeCheck(thisToProp); if (!(thisToProp in subToObject)) { subToObject[thisToProp] = {}; } subToObject = subToObject[thisToProp]; } } var pathCopy = thisPath.slice(); var lastProp = pathCopy.pop(); prototypeCheck(lastProp); if (lastProp == null) { return false; } var thisProp; while (((thisProp = pathCopy.shift())) != null) { prototypeCheck(thisProp); if (!(thisProp in subObject)) { subObject[thisProp] = {}; } subObject = subObject[thisProp]; } if (thisOp === REMOVE || thisOp === REPLACE || thisOp === MOVE) { var path = thisOp === MOVE ? thisDiff.from : thisDiff.path; if (!subObject.hasOwnProperty(lastProp)) { throw new Error(['expected to find property', path, 'in object', obj].join(' ')); } } if (thisOp === REMOVE || thisOp === MOVE) { if (thisOp === MOVE) { valueToMove = subObject[lastProp]; } Array.isArray(subObject) ? subObject.splice(lastProp, 1) : delete subObject[lastProp]; } if (thisOp === REPLACE || thisOp === ADD) { subObject[lastProp] = thisDiff.value; } if (thisOp === MOVE) { subObject[lastToProp] = valueToMove; } } return subObject; } function transformPath(pathConverter, thisPath) { if(pathConverter) { thisPath = pathConverter(thisPath); if(!Array.isArray(thisPath)) { throw new Error([ 'pathConverter must return an array, returned:', thisPath, ].join(' ')); } } else { if(!Array.isArray(thisPath)) { throw new Error([ 'diff path', thisPath, 'must be an array, consider supplying a path converter'] .join(' ')); } } return thisPath; } function jsonPatchPathConverter(stringPath) { return stringPath.split('/').slice(1); } function prototypeCheck(prop) { // coercion is intentional to catch prop values like `['__proto__']` if (prop == '__proto__' || prop == 'constructor' || prop == 'prototype') { throw new Error('setting of prototype values not supported'); } } export {diffApply, jsonPatchPathConverter}; { "name": "just-diff-apply", "version": "5.5.0", "description": "Apply a diff to an object. Optionally supports jsonPatch protocol", "type": "module", "exports": { ".": { "types": "./index.d.ts", "require": "./index.cjs", "import": "./index.mjs" }, "./package.json": "./package.json" }, "main": "index.cjs", "types": "index.d.ts", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "rollup -c" }, "repository": "https://github.com/angus-c/just", "keywords": [ "object", "diff", "apply", "jsonPatch", "no-dependencies", "just" ], "author": "Angus Croll", "license": "MIT", "bugs": { "url": "https://github.com/angus-c/just/issues" } }const createRollupConfig = require('../../config/createRollupConfig'); module.exports = createRollupConfig(__dirname); The MIT License (MIT) Copyright (c) 2016 angus croll 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. module.exports = { diff: diff, jsonPatchPathConverter: jsonPatchPathConverter, }; /* const obj1 = {a: 4, b: 5}; const obj2 = {a: 3, b: 5}; const obj3 = {a: 4, c: 5}; diff(obj1, obj2); [ { "op": "replace", "path": ['a'], "value": 3 } ] diff(obj2, obj3); [ { "op": "remove", "path": ['b'] }, { "op": "replace", "path": ['a'], "value": 4 } { "op": "add", "path": ['c'], "value": 5 } ] // using converter to generate jsPatch standard paths // see http://jsonpatch.com import {diff, jsonPatchPathConverter} from 'just-diff' diff(obj1, obj2, jsonPatchPathConverter); [ { "op": "replace", "path": '/a', "value": 3 } ] diff(obj2, obj3, jsonPatchPathConverter); [ { "op": "remove", "path": '/b' }, { "op": "replace", "path": '/a', "value": 4 } { "op": "add", "path": '/c', "value": 5 } ] // arrays const obj4 = {a: 4, b: [1, 2, 3]}; const obj5 = {a: 3, b: [1, 2, 4]}; const obj6 = {a: 3, b: [1, 2, 4, 5]}; diff(obj4, obj5); [ { "op": "replace", "path": ['a'], "value": 3 } { "op": "replace", "path": ['b', 2], "value": 4 } ] diff(obj5, obj6); [ { "op": "add", "path": ['b', 3], "value": 5 } ] // nested paths const obj7 = {a: 4, b: {c: 3}}; const obj8 = {a: 4, b: {c: 4}}; const obj9 = {a: 5, b: {d: 4}}; diff(obj7, obj8); [ { "op": "replace", "path": ['b', 'c'], "value": 4 } ] diff(obj8, obj9); [ { "op": "replace", "path": ['a'], "value": 5 } { "op": "remove", "path": ['b', 'c']} { "op": "add", "path": ['b', 'd'], "value": 4 } ] */ function diff(obj1, obj2, pathConverter) { if (!obj1 || typeof obj1 != 'object' || !obj2 || typeof obj2 != 'object') { throw new Error('both arguments must be objects or arrays'); } pathConverter || (pathConverter = function(arr) { return arr; }); function getDiff({obj1, obj2, basePath, basePathForRemoves, diffs}) { var obj1Keys = Object.keys(obj1); var obj1KeysLength = obj1Keys.length; var obj2Keys = Object.keys(obj2); var obj2KeysLength = obj2Keys.length; var path; var lengthDelta = obj1.length - obj2.length; if (trimFromRight(obj1, obj2)) { for (var i = 0; i < obj1KeysLength; i++) { var key = Array.isArray(obj1) ? Number(obj1Keys[i]) : obj1Keys[i]; if (!(key in obj2)) { path = basePathForRemoves.concat(key); diffs.remove.push({ op: 'remove', path: pathConverter(path), }); } } for (var i = 0; i < obj2KeysLength; i++) { var key = Array.isArray(obj2) ? Number(obj2Keys[i]) : obj2Keys[i]; pushReplaces({ key, obj1, obj2, path: basePath.concat(key), pathForRemoves: basePath.concat(key), diffs, }); } } else { // trim from left, objects are both arrays for (var i = 0; i < lengthDelta; i++) { path = basePathForRemoves.concat(i); diffs.remove.push({ op: 'remove', path: pathConverter(path), }); } // now make a copy of obj1 with excess elements left trimmed and see if there any replaces var obj1Trimmed = obj1.slice(lengthDelta);; for (var i = 0; i < obj2KeysLength; i++) { pushReplaces({ key: i, obj1: obj1Trimmed, obj2, path: basePath.concat(i), // since list of removes are reversed before presenting result, // we need to ignore existing parent removes when doing nested removes pathForRemoves: basePath.concat(i + lengthDelta), diffs, }); } } } var diffs = {remove: [], replace: [], add: []}; getDiff({ obj1, obj2, basePath: [], basePathForRemoves: [], diffs, }); // reverse removes since we want to maintain indexes return diffs.remove .reverse() .concat(diffs.replace) .concat(diffs.add); function pushReplaces({key, obj1, obj2, path, pathForRemoves, diffs}) { var obj1AtKey = obj1[key]; var obj2AtKey = obj2[key]; if(!(key in obj1) && (key in obj2)) { var obj2Value = obj2AtKey; diffs.add.push({ op: 'add', path: pathConverter(path), value: obj2Value, }); } else if(obj1AtKey !== obj2AtKey) { if(Object(obj1AtKey) !== obj1AtKey || Object(obj2AtKey) !== obj2AtKey || differentTypes(obj1AtKey, obj2AtKey) ) { pushReplace(path, diffs, obj2AtKey); } else { if(!Object.keys(obj1AtKey).length && !Object.keys(obj2AtKey).length && String(obj1AtKey) != String(obj2AtKey)) { pushReplace(path, diffs, obj2AtKey); } else { getDiff({ obj1: obj1[key], obj2: obj2[key], basePath: path, basePathForRemoves: pathForRemoves, diffs}); } } } } function pushReplace(path, diffs, newValue) { diffs.replace.push({ op: 'replace', path: pathConverter(path), value: newValue, }); } } function jsonPatchPathConverter(arrayPath) { return [''].concat(arrayPath).join('/'); } function differentTypes(a, b) { return Object.prototype.toString.call(a) != Object.prototype.toString.call(b); } function trimFromRight(obj1, obj2) { var lengthDelta = obj1.length - obj2.length; if (Array.isArray(obj1) && Array.isArray(obj2) && lengthDelta > 0) { var leftMatches = 0; var rightMatches = 0; for (var i = 0; i < obj2.length; i++) { if (String(obj1[i]) === String(obj2[i])) { leftMatches++; } else { break; } } for (var j = obj2.length; j > 0; j--) { if (String(obj1[j + lengthDelta]) === String(obj2[j])) { rightMatches++; } else { break; } } // bias to trim right becase it requires less index shifting return leftMatches >= rightMatches; } return true; } /* const obj1 = {a: 4, b: 5}; const obj2 = {a: 3, b: 5}; const obj3 = {a: 4, c: 5}; diff(obj1, obj2); [ { "op": "replace", "path": ['a'], "value": 3 } ] diff(obj2, obj3); [ { "op": "remove", "path": ['b'] }, { "op": "replace", "path": ['a'], "value": 4 } { "op": "add", "path": ['c'], "value": 5 } ] // using converter to generate jsPatch standard paths // see http://jsonpatch.com import {diff, jsonPatchPathConverter} from 'just-diff' diff(obj1, obj2, jsonPatchPathConverter); [ { "op": "replace", "path": '/a', "value": 3 } ] diff(obj2, obj3, jsonPatchPathConverter); [ { "op": "remove", "path": '/b' }, { "op": "replace", "path": '/a', "value": 4 } { "op": "add", "path": '/c', "value": 5 } ] // arrays const obj4 = {a: 4, b: [1, 2, 3]}; const obj5 = {a: 3, b: [1, 2, 4]}; const obj6 = {a: 3, b: [1, 2, 4, 5]}; diff(obj4, obj5); [ { "op": "replace", "path": ['a'], "value": 3 } { "op": "replace", "path": ['b', 2], "value": 4 } ] diff(obj5, obj6); [ { "op": "add", "path": ['b', 3], "value": 5 } ] // nested paths const obj7 = {a: 4, b: {c: 3}}; const obj8 = {a: 4, b: {c: 4}}; const obj9 = {a: 5, b: {d: 4}}; diff(obj7, obj8); [ { "op": "replace", "path": ['b', 'c'], "value": 4 } ] diff(obj8, obj9); [ { "op": "replace", "path": ['a'], "value": 5 } { "op": "remove", "path": ['b', 'c']} { "op": "add", "path": ['b', 'd'], "value": 4 } ] */ function diff(obj1, obj2, pathConverter) { if (!obj1 || typeof obj1 != 'object' || !obj2 || typeof obj2 != 'object') { throw new Error('both arguments must be objects or arrays'); } pathConverter || (pathConverter = function(arr) { return arr; }); function getDiff({obj1, obj2, basePath, basePathForRemoves, diffs}) { var obj1Keys = Object.keys(obj1); var obj1KeysLength = obj1Keys.length; var obj2Keys = Object.keys(obj2); var obj2KeysLength = obj2Keys.length; var path; var lengthDelta = obj1.length - obj2.length; if (trimFromRight(obj1, obj2)) { for (var i = 0; i < obj1KeysLength; i++) { var key = Array.isArray(obj1) ? Number(obj1Keys[i]) : obj1Keys[i]; if (!(key in obj2)) { path = basePathForRemoves.concat(key); diffs.remove.push({ op: 'remove', path: pathConverter(path), }); } } for (var i = 0; i < obj2KeysLength; i++) { var key = Array.isArray(obj2) ? Number(obj2Keys[i]) : obj2Keys[i]; pushReplaces({ key, obj1, obj2, path: basePath.concat(key), pathForRemoves: basePath.concat(key), diffs, }); } } else { // trim from left, objects are both arrays for (var i = 0; i < lengthDelta; i++) { path = basePathForRemoves.concat(i); diffs.remove.push({ op: 'remove', path: pathConverter(path), }); } // now make a copy of obj1 with excess elements left trimmed and see if there any replaces var obj1Trimmed = obj1.slice(lengthDelta);; for (var i = 0; i < obj2KeysLength; i++) { pushReplaces({ key: i, obj1: obj1Trimmed, obj2, path: basePath.concat(i), // since list of removes are reversed before presenting result, // we need to ignore existing parent removes when doing nested removes pathForRemoves: basePath.concat(i + lengthDelta), diffs, }); } } } var diffs = {remove: [], replace: [], add: []}; getDiff({ obj1, obj2, basePath: [], basePathForRemoves: [], diffs, }); // reverse removes since we want to maintain indexes return diffs.remove .reverse() .concat(diffs.replace) .concat(diffs.add); function pushReplaces({key, obj1, obj2, path, pathForRemoves, diffs}) { var obj1AtKey = obj1[key]; var obj2AtKey = obj2[key]; if(!(key in obj1) && (key in obj2)) { var obj2Value = obj2AtKey; diffs.add.push({ op: 'add', path: pathConverter(path), value: obj2Value, }); } else if(obj1AtKey !== obj2AtKey) { if(Object(obj1AtKey) !== obj1AtKey || Object(obj2AtKey) !== obj2AtKey || differentTypes(obj1AtKey, obj2AtKey) ) { pushReplace(path, diffs, obj2AtKey); } else { if(!Object.keys(obj1AtKey).length && !Object.keys(obj2AtKey).length && String(obj1AtKey) != String(obj2AtKey)) { pushReplace(path, diffs, obj2AtKey); } else { getDiff({ obj1: obj1[key], obj2: obj2[key], basePath: path, basePathForRemoves: pathForRemoves, diffs}); } } } } function pushReplace(path, diffs, newValue) { diffs.replace.push({ op: 'replace', path: pathConverter(path), value: newValue, }); } } function jsonPatchPathConverter(arrayPath) { return [''].concat(arrayPath).join('/'); } function differentTypes(a, b) { return Object.prototype.toString.call(a) != Object.prototype.toString.call(b); } function trimFromRight(obj1, obj2) { var lengthDelta = obj1.length - obj2.length; if (Array.isArray(obj1) && Array.isArray(obj2) && lengthDelta > 0) { var leftMatches = 0; var rightMatches = 0; for (var i = 0; i < obj2.length; i++) { if (String(obj1[i]) === String(obj2[i])) { leftMatches++; } else { break; } } for (var j = obj2.length; j > 0; j--) { if (String(obj1[j + lengthDelta]) === String(obj2[j])) { rightMatches++; } else { break; } } // bias to trim right becase it requires less index shifting return leftMatches >= rightMatches; } return true; } export {diff, jsonPatchPathConverter}; { "name": "just-diff", "version": "6.0.2", "description": "Return an object representing the diffs between two objects. Supports jsonPatch protocol", "type": "module", "exports": { ".": { "types": "./index.d.ts", "require": "./index.cjs", "import": "./index.mjs" }, "./package.json": "./package.json" }, "main": "index.cjs", "types": "index.d.ts", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "rollup -c" }, "repository": "https://github.com/angus-c/just", "keywords": [ "object", "diff", "jsonPatch", "no-dependencies", "just" ], "author": "Angus Croll", "license": "MIT", "bugs": { "url": "https://github.com/angus-c/just/issues" } }const createRollupConfig = require('../../config/createRollupConfig'); module.exports = createRollupConfig(__dirname); Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmaccess [![npm version](https://img.shields.io/npm/v/libnpmaccess.svg)](https://npm.im/libnpmaccess) [![license](https://img.shields.io/npm/l/libnpmaccess.svg)](https://npm.im/libnpmaccess) [![CI - libnpmaccess](https://github.com/npm/cli/actions/workflows/ci-libnpmaccess.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmaccess.yml) [`libnpmaccess`](https://github.com/npm/libnpmaccess) is a Node.js library that provides programmatic access to the guts of the npm CLI's `npm access` command. This includes managing account mfa settings, listing packages and permissions, looking at package collaborators, and defining package permissions for users, orgs, and teams. ## Example ```javascript const access = require('libnpmaccess') const opts = { '//registry.npmjs.org/:_authToken: 'npm_token } // List all packages @zkat has access to on the npm registry. console.log(Object.keys(await access.getPackages('zkat', opts))) ``` ### API #### `opts` for all `libnpmaccess` commands `libnpmaccess` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch). All options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options) for options that can be passed in. #### `spec` parameter for all `libnpmaccess` commands `spec` must be an [`npm-package-arg`](https://npm.im/npm-package-arg)-compatible registry spec. #### `access.getCollaborators(spec, opts) -> Promise` Gets collaborators for a given package #### `access.getPackages(user|scope|team, opts) -> Promise` Gets all packages for a given user, scope, or team. Teams should be in the format `scope:team` or `@scope:team` Users and scopes can be in the format `@scope` or `scope` #### `access.getVisibility(spec, opts) -> Promise` Gets the visibility of a given package #### `access.removePermissions(team, spec, opts) -> Promise` Removes the access for a given team to a package. Teams should be in the format `scope:team` or `@scope:team` #### `access.setAccess(package, access, opts) -> Promise` Sets access level for package described by `spec`. The npm registry accepts the following `access` levels: `public`: package is public `private`: package is private The npm registry also only allows scoped packages to have their access level set. #### access.setMfa(spec, level, opts) -> Promise` Sets the publishing mfa requirements for a given package. Level must be one of the following `none`: mfa is not required to publish this package. `publish`: mfa is required to publish this package, automation tokens cannot be used to publish. `automation`: mfa is required to publish this package, automation tokens may also be used for publishing from continuous integration workflows. #### access.setPermissions(team, spec, permssions, opts) -> Promise` Sets permissions levels for a given team to a package. Teams should be in the format `scope:team` or `@scope:team` The npm registry accepts the following `permissions`: `read-only`: Read only permissions `read-write`: Read and write (aka publish) permissions 'use strict' const npa = require('npm-package-arg') const npmFetch = require('npm-registry-fetch') const npar = (spec) => { spec = npa(spec) if (!spec.registry) { throw new Error('must use package name only') } return spec } const parseTeam = (scopeTeam) => { let slice = 0 if (scopeTeam.startsWith('@')) { slice = 1 } const [scope, team] = scopeTeam.slice(slice).split(':').map(encodeURIComponent) return { scope, team } } const getPackages = async (scopeTeam, opts) => { const { scope, team } = parseTeam(scopeTeam) let uri if (team) { uri = `/-/team/${scope}/${team}/package` } else { uri = `/-/org/${scope}/package` } try { return await npmFetch.json(uri, opts) } catch (err) { if (err.code === 'E404') { uri = `/-/user/${scope}/package` return npmFetch.json(uri, opts) } throw err } } const getCollaborators = async (pkg, opts) => { const spec = npar(pkg) const uri = `/-/package/${spec.escapedName}/collaborators` return npmFetch.json(uri, opts) } const getVisibility = async (pkg, opts) => { const spec = npar(pkg) const uri = `/-/package/${spec.escapedName}/visibility` return npmFetch.json(uri, opts) } const setAccess = async (pkg, access, opts) => { const spec = npar(pkg) const uri = `/-/package/${spec.escapedName}/access` await npmFetch(uri, { ...opts, method: 'POST', body: { access }, spec, ignoreBody: true, }) return true } const setMfa = async (pkg, level, opts) => { const spec = npar(pkg) const body = {} switch (level) { case 'none': body.publish_requires_tfa = false break case 'publish': // tfa is required, automation tokens can not override tfa body.publish_requires_tfa = true body.automation_token_overrides_tfa = false break case 'automation': // tfa is required, automation tokens can override tfa body.publish_requires_tfa = true body.automation_token_overrides_tfa = true break default: throw new Error(`Invalid mfa setting ${level}`) } const uri = `/-/package/${spec.escapedName}/access` await npmFetch(uri, { ...opts, method: 'POST', body, spec, ignoreBody: true, }) return true } const setPermissions = async (scopeTeam, pkg, permissions, opts) => { const spec = npar(pkg) const { scope, team } = parseTeam(scopeTeam) if (!scope || !team) { throw new Error('team must be in format `scope:team`') } const uri = `/-/team/${scope}/${team}/package` await npmFetch(uri, { ...opts, method: 'PUT', body: { package: spec.name, permissions }, scope, spec, ignoreBody: true, }) return true } const removePermissions = async (scopeTeam, pkg, opts) => { const spec = npar(pkg) const { scope, team } = parseTeam(scopeTeam) const uri = `/-/team/${scope}/${team}/package` await npmFetch(uri, { ...opts, method: 'DELETE', body: { package: spec.name }, scope, spec, ignoreBody: true, }) return true } module.exports = { getCollaborators, getPackages, getVisibility, removePermissions, setAccess, setMfa, setPermissions, } { "name": "libnpmaccess", "version": "10.0.0", "description": "programmatic library for `npm access` commands", "author": "GitHub Inc.", "license": "ISC", "main": "lib/index.js", "scripts": { "lint": "npm run eslint", "test": "tap", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "snap": "tap", "posttest": "npm run lint", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", "@npmcli/template-oss": "4.23.6", "tap": "^16.3.8" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmaccess" }, "bugs": "https://github.com/npm/libnpmaccess/issues", "homepage": "https://npmjs.com/package/libnpmaccess", "dependencies": { "npm-package-arg": "^12.0.0", "npm-registry-fetch": "^18.0.1" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "files": [ "bin/", "lib/" ], "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } The ISC License Copyright (c) GitHub Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmdiff [![npm version](https://img.shields.io/npm/v/libnpmdiff.svg)](https://npm.im/libnpmdiff) [![license](https://img.shields.io/npm/l/libnpmdiff.svg)](https://npm.im/libnpmdiff) [![CI - libnpmdiff](https://github.com/npm/cli/actions/workflows/ci-libnpmdiff.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmdiff.yml) The registry diff lib. ## Table of Contents * [Example](#example) * [Install](#install) * [Contributing](#contributing) * [API](#api) * [LICENSE](#license) ## Example ```js const libdiff = require('libnpmdiff') const patch = await libdiff([ 'abbrev@1.1.0', 'abbrev@1.1.1' ]) console.log( patch ) ``` Returns: ```patch diff --git a/package.json b/package.json index v1.1.0..v1.1.1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "abbrev", - "version": "1.1.0", + "version": "1.1.1", "description": "Like ruby's abbrev module, but in js", "author": "Isaac Z. Schlueter ", "main": "abbrev.js", ``` ## Install `$ npm install libnpmdiff` ### Contributing The npm team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](https://github.com/npm/cli/blob/latest/CONTRIBUTING.md) outlines the process for community interaction and contribution. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow the [npm Code of Conduct](https://docs.npmjs.com/policies/conduct), and just generally be excellent to each other. Please refer to the [Changelog](CHANGELOG.md) for project history details, too. Happy hacking! ### API #### `> libnpmdif([ a, b ], [opts]) -> Promise` Fetches the registry tarballs and compare files between a spec `a` and spec `b`. **npm** spec types are usually described in `@` form but multiple other types are alsos supported, for more info on valid specs take a look at [`npm-package-arg`](https://github.com/npm/npm-package-arg). **Options**: - `color `: Should add ANSI colors to string output? Defaults to `false`. - `tagVersionPrefix `: What prefix should be used to define version numbers. Defaults to `v` - `diffUnified `: How many lines of code to print before/after each diff. Defaults to `3`. - `diffFiles >`: If set only prints patches for the files listed in this array (also accepts globs). Defaults to `undefined`. - `diffIgnoreAllSpace `: Whether or not should ignore changes in whitespace (very useful to avoid indentation changes extra diff lines). Defaults to `false`. - `diffNameOnly `: Prints only file names and no patch diffs. Defaults to `false`. - `diffNoPrefix `: If true then skips printing any prefixes in filenames. Defaults to `false`. - `diffSrcPrefix `: Prefix to be used in the filenames from `a`. Defaults to `a/`. - `diffDstPrefix `: Prefix to be used in the filenames from `b`. Defaults to `b/`. - `diffText `: Should treat all files as text and try to print diff for binary files. Defaults to `false`. - ...`cache`, `registry`, `where` and other common options accepted by [pacote](https://github.com/npm/pacote#options) Returns a `Promise` that fullfils with a `String` containing the resulting patch diffs. Throws an error if either `a` or `b` are missing or if trying to diff more than two specs. ## LICENSE [ISC](./LICENSE) const jsDiff = require('diff') const shouldPrintPatch = require('./should-print-patch.js') const colors = { // red removed: { open: '\x1B[31m', close: '\x1B[39m' }, // green added: { open: '\x1B[32m', close: '\x1B[39m' }, // blue header: { open: '\x1B[34m', close: '\x1B[39m' }, // cyan section: { open: '\x1B[36m', close: '\x1B[39m' }, } const color = (colorStr, colorId) => { const { open, close } = colors[colorId] // avoid highlighting the "\n" (would highlight till the end of the line) return colorStr.replace(/[^\n\r]+/g, open + '$&' + close) } const formatDiff = async ({ files, opts = {}, refs, versions }) => { let res = '' const srcPrefix = opts.diffNoPrefix ? '' : opts.diffSrcPrefix || 'a/' const dstPrefix = opts.diffNoPrefix ? '' : opts.diffDstPrefix || 'b/' for (const filename of files.values()) { const names = { a: `${srcPrefix}${filename}`, b: `${dstPrefix}${filename}`, } let fileMode = '' const filenames = { a: refs.get(`a/${filename}`), b: refs.get(`b/${filename}`), } const contents = { a: filenames.a && filenames.a.content, b: filenames.b && filenames.b.content, } const modes = { a: filenames.a && filenames.a.mode, b: filenames.b && filenames.b.mode, } if (contents.a === contents.b && modes.a === modes.b) { continue } if (opts.diffNameOnly) { res += `${filename}\n` continue } let patch = '' let headerLength = 0 const header = str => { headerLength++ patch += `${str}\n` } // manually build a git diff-compatible header header(`diff --git ${names.a} ${names.b}`) if (modes.a === modes.b) { fileMode = filenames.a.mode } else { if (modes.a && !modes.b) { header(`deleted file mode ${modes.a}`) } else if (!modes.a && modes.b) { header(`new file mode ${modes.b}`) } else { header(`old mode ${modes.a}`) header(`new mode ${modes.b}`) } } /* eslint-disable-next-line max-len */ header(`index ${opts.tagVersionPrefix || 'v'}${versions.a}..${opts.tagVersionPrefix || 'v'}${versions.b} ${fileMode}`) if (await shouldPrintPatch(filename)) { patch += jsDiff.createTwoFilesPatch( names.a, names.b, contents.a || '', contents.b || '', '', '', { context: opts.diffUnified === 0 ? 0 : opts.diffUnified || 3, ignoreWhitespace: opts.diffIgnoreAllSpace, } ).replace( '===================================================================\n', '' ).replace(/\t\n/g, '\n') // strip trailing tabs headerLength += 2 } else { header(`--- ${names.a}`) header(`+++ ${names.b}`) } if (opts.color) { // this RegExp will include all the `\n` chars into the lines, easier to join const lines = patch.split(/^/m) res += color(lines.slice(0, headerLength).join(''), 'header') res += lines.slice(headerLength).join('') .replace(/^-.*/gm, color('$&', 'removed')) .replace(/^\+.*/gm, color('$&', 'added')) .replace(/^@@.+@@/gm, color('$&', 'section')) } else { res += patch } } return res.trim() } module.exports = formatDiff const pacote = require('pacote') const formatDiff = require('./format-diff.js') const getTarball = require('./tarball.js') const untar = require('./untar.js') // TODO: we test this condition in the diff command // so this error probably doesnt need to be here. Or // if it does we should figure out a standard code // so we can catch it in the cli and display it consistently const argsError = () => Object.assign( new TypeError('libnpmdiff needs two arguments to compare'), { code: 'EDIFFARGS' } ) const diff = async (specs, opts = {}) => { if (specs.length !== 2) { throw argsError() } const [ aManifest, bManifest, ] = await Promise.all(specs.map(spec => pacote.manifest(spec, opts))) const versions = { a: aManifest.version, b: bManifest.version, } // fetches tarball using pacote const [a, b] = await Promise.all([ getTarball(aManifest, opts), getTarball(bManifest, opts), ]) // read all files // populates `files` and `refs` const { files, refs, } = await untar([ { prefix: 'a/', item: a, }, { prefix: 'b/', item: b, }, ], opts) return formatDiff({ files, opts, refs, versions, }) } module.exports = diff const { basename, extname } = require('node:path') // we should try to print patches as long as the // extension is not identified as binary files const shouldPrintPatch = async (path, opts = {}) => { if (opts.diffText) { return true } const { default: binaryExtensions } = await import('binary-extensions') const filename = basename(path) const extension = ( filename.startsWith('.') ? filename : extname(filename) ).slice(1) return !binaryExtensions.includes(extension) } module.exports = shouldPrintPatch const { relative } = require('node:path') const Arborist = require('@npmcli/arborist') const npa = require('npm-package-arg') const pkgContents = require('@npmcli/installed-package-contents') const pacote = require('pacote') const { tarCreateOptions } = pacote.DirFetcher const tar = require('tar') // returns a simplified tarball when reading files from node_modules folder, // thus avoiding running the prepare scripts and the extra logic from packlist const nodeModulesTarball = (manifest) => pkgContents({ path: manifest._resolved, depth: 1 }) .then(files => files.map(file => relative(manifest._resolved, file)) ) .then(files => tar.c(tarCreateOptions(manifest), files).concat() ) const tarball = (manifest, opts) => { const resolved = manifest._resolved const where = opts.where || process.cwd() const fromNodeModules = npa(resolved).type === 'directory' && /node_modules[\\/](@[^\\/]+\/)?[^\\/]+[\\/]?$/.test(relative(where, resolved)) if (fromNodeModules) { return nodeModulesTarball(manifest, opts) } return pacote.tarball(manifest._resolved, { ...opts, Arborist, }) } module.exports = tarball const tar = require('tar') const { minimatch } = require('minimatch') const normalizeMatch = str => str .replace(/\\+/g, '/') .replace(/^\.\/|^\./, '') // files and refs are mutating params // filterFiles, item, prefix and opts are read-only options const untar = ({ files, refs }, { filterFiles, item, prefix }) => { tar.list({ filter: (path, entry) => { const fileMatch = () => (!filterFiles.length || filterFiles.some(f => { const pattern = normalizeMatch(f) return minimatch( normalizeMatch(path), `{package/,}${pattern}`, { matchBase: pattern.startsWith('*') } ) })) // expands usage of simple path filters, e.g: lib or src/ const folderMatch = () => filterFiles.some(f => normalizeMatch(path).startsWith(normalizeMatch(f)) || normalizeMatch(path).startsWith(`package/${normalizeMatch(f)}`)) if ( entry.type === 'File' && (fileMatch() || folderMatch()) ) { const key = path.replace(/^[^/]+\/?/, '') files.add(key) // should skip reading file when using --name-only option let content try { entry.setEncoding('utf8') content = entry.concat() } catch (e) { /* istanbul ignore next */ throw Object.assign( new Error('failed to read files'), { code: 'EDIFFUNTAR' } ) } refs.set(`${prefix}${key}`, { content, mode: `100${entry.mode.toString(8)}`, }) return true } }, }) .on('error', /* istanbul ignore next */ e => { throw e }) .end(item) } const readTarballs = async (tarballs, opts = {}) => { const files = new Set() const refs = new Map() const arr = [].concat(tarballs) const filterFiles = opts.diffFiles || [] for (const i of arr) { untar({ files, refs, }, { item: i.item, prefix: i.prefix, filterFiles, }) } // await to read all content from included files const allRefs = [...refs.values()] const contents = await Promise.all(allRefs.map(async ref => ref.content)) contents.forEach((content, index) => { allRefs[index].content = content }) return { files, refs, } } module.exports = readTarballs { "name": "libnpmdiff", "version": "8.0.0", "description": "The registry diff", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmdiff" }, "main": "lib/index.js", "files": [ "bin/", "lib/" ], "engines": { "node": "^20.17.0 || >=22.9.0" }, "keywords": [ "npm", "npmcli", "libnpm", "cli", "diff" ], "author": "GitHub Inc.", "contributors": [ { "name": "Ruy Adorno", "url": "https://ruyadorno.com", "twitter": "ruyadorno" } ], "license": "ISC", "scripts": { "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "test": "tap", "posttest": "npm run lint", "snap": "tap", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/template-oss": "4.23.6", "tap": "^16.3.8" }, "dependencies": { "@npmcli/arborist": "^9.0.0", "@npmcli/installed-package-contents": "^3.0.0", "binary-extensions": "^3.0.0", "diff": "^7.0.0", "minimatch": "^9.0.4", "npm-package-arg": "^12.0.0", "pacote": "^21.0.0", "tar": "^6.2.1" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } The ISC License Copyright (c) GitHub Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmexec [![npm version](https://img.shields.io/npm/v/libnpmexec.svg)](https://npm.im/libnpmexec) [![license](https://img.shields.io/npm/l/libnpmexec.svg)](https://npm.im/libnpmexec) [![CI - libnpmexec](https://github.com/npm/cli/actions/workflows/ci-libnpmexec.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmexec.yml) The `npm exec` (`npx`) Programmatic API ## Install `npm install libnpmexec` ## Usage: ```js const libexec = require('libnpmexec') await libexec({ args: ['yosay', 'Bom dia!'], cache: '~/.npm/_cacache', npxCache: '~/.npm/_npx', yes: true, }) ``` ## API: ### `libexec(opts)` - `opts`: - `args`: List of pkgs to execute **Array**, defaults to `[]` - `call`: An alternative command to run when using `packages` option **String**, defaults to empty string. - `cache`: The path location to where the npm cache folder is placed **String** - `npxCache`: The path location to where the npx cache folder is placed **String** - `chalk`: Chalk instance to use for colors? **Required** - `localBin`: Location to the `node_modules/.bin` folder of the local project to start scanning for bin files **String**, defaults to `./node_modules/.bin`. **libexec** will walk up the directory structure looking for `node_modules/.bin` folders in parent folders that might satisfy the current `arg` and will use that bin if found. - `locationMsg`: Overrides "at location" message when entering interactive mode **String** - `globalBin`: Location to the global space bin folder, same as: `$(npm bin -g)` **String**, defaults to empty string. - `packages`: A list of packages to be used (possibly fetch from the registry) **Array**, defaults to `[]` - `path`: Location to where to read local project info (`package.json`) **String**, defaults to `.` - `runPath`: Location to where to execute the script **String**, defaults to `.` - `scriptShell`: Default shell to be used **String**, defaults to `sh` on POSIX systems, `process.env.ComSpec` OR `cmd` on Windows - `yes`: Should skip download confirmation prompt when fetching missing packages from the registry? **Boolean** - `registry`, `cache`, and more options that are forwarded to [@npmcli/arborist](https://github.com/npm/arborist/) and [pacote](https://github.com/npm/pacote/#options) **Object** ## LICENSE [ISC](./LICENSE) const { resolve } = require('node:path') const { stat } = require('node:fs/promises') const { walkUp } = require('walk-up-path') const fileExists = async (file) => { try { const res = await stat(file) return res.isFile() } catch { return false } } const localFileExists = async (dir, binName, root) => { for (const path of walkUp(dir)) { const binDir = resolve(path, 'node_modules', '.bin') if (await fileExists(resolve(binDir, binName))) { return binDir } if (path.toLowerCase() === resolve(root).toLowerCase()) { return false } } return false } module.exports = { fileExists, localFileExists, } const getBinFromManifest = (mani) => { // if we have a bin matching (unscoped portion of) packagename, use that // otherwise if there's 1 bin or all bin value is the same (alias), use // that, otherwise fail const bin = mani.bin || {} if (new Set(Object.values(bin)).size === 1) { return Object.keys(bin)[0] } // XXX probably a util to parse this better? const name = mani.name.replace(/^@[^/]+\//, '') if (bin[name]) { return name } // XXX need better error message throw Object.assign(new Error('could not determine executable to run'), { pkgid: mani._id, }) } module.exports = getBinFromManifest 'use strict' const { mkdir } = require('node:fs/promises') const Arborist = require('@npmcli/arborist') const ciInfo = require('ci-info') const crypto = require('node:crypto') const { log, input } = require('proc-log') const npa = require('npm-package-arg') const pacote = require('pacote') const { read } = require('read') const semver = require('semver') const { fileExists, localFileExists } = require('./file-exists.js') const getBinFromManifest = require('./get-bin-from-manifest.js') const noTTY = require('./no-tty.js') const runScript = require('./run-script.js') const isWindows = require('./is-windows.js') const { dirname, resolve } = require('node:path') const binPaths = [] // when checking the local tree we look up manifests, cache those results by // spec.raw so we don't have to fetch again when we check npxCache const manifests = new Map() const getManifest = async (spec, flatOptions) => { if (!manifests.has(spec.raw)) { const manifest = await pacote.manifest(spec, { ...flatOptions, preferOnline: true, Arborist }) manifests.set(spec.raw, manifest) } return manifests.get(spec.raw) } // Returns the required manifest if the spec is missing from the tree // Returns the found node if it is in the tree const missingFromTree = async ({ spec, tree, flatOptions, isNpxTree, shallow }) => { // If asking for a spec by name only (spec.raw === spec.name): // - In local or global mode go with anything in the tree that matches // - If looking in the npx cache check if a newer version is available const npxByNameOnly = isNpxTree && spec.name === spec.raw if (spec.registry && spec.type !== 'tag' && !npxByNameOnly) { // registry spec that is not a specific tag. const nodesBySpec = tree.inventory.query('packageName', spec.name) for (const node of nodesBySpec) { // continue if node is not a top level node if (shallow && node.depth) { continue } if (spec.rawSpec === '*') { return { node } } // package requested by specific version if (spec.type === 'version' && (node.pkgid === spec.raw)) { return { node } } // package requested by version range, only remaining registry type if (semver.satisfies(node.package.version, spec.rawSpec)) { return { node } } } const manifest = await getManifest(spec, flatOptions) return { manifest } } else { // non-registry spec, or a specific tag, or name only in npx tree. Look up // manifest and check resolved to see if it's in the tree. const manifest = await getManifest(spec, flatOptions) if (spec.type === 'directory') { return { manifest } } const nodesByManifest = tree.inventory.query('packageName', manifest.name) for (const node of nodesByManifest) { if (node.package.resolved === manifest._resolved) { // we have a package by the same name and the same resolved destination, nothing to add. return { node } } } return { manifest } } } // see if the package.json at `path` has an entry that matches `cmd` const hasPkgBin = (path, cmd, flatOptions) => pacote.manifest(path, flatOptions) .then(manifest => manifest?.bin?.[cmd]).catch(() => null) const exec = async (opts) => { const { args = [], call = '', localBin = resolve('./node_modules/.bin'), locationMsg = undefined, globalBin = '', globalPath, // dereference values because we manipulate it later packages: [...packages] = [], path = '.', runPath = '.', scriptShell = isWindows ? process.env.ComSpec || 'cmd' : 'sh', ...flatOptions } = opts let pkgPaths = opts.pkgPath if (typeof pkgPaths === 'string') { pkgPaths = [pkgPaths] } if (!pkgPaths) { pkgPaths = ['.'] } let yes = opts.yes const run = () => runScript({ args, call, flatOptions, locationMsg, path, binPaths, runPath, scriptShell, }) // interactive mode if (!call && !args.length && !packages.length) { return run() } // Look in the local tree too pkgPaths.push(path) let needPackageCommandSwap = (args.length > 0) && (packages.length === 0) // If they asked for a command w/o specifying a package, see if there is a // bin that directly matches that name: // - in any local packages (pkgPaths can have workspaces in them or just the root) // - in the local tree (path) // - globally if (needPackageCommandSwap) { // Local packages and local tree for (const p of pkgPaths) { if (await hasPkgBin(p, args[0], flatOptions)) { // we have to install the local package into the npx cache so that its // bin links get set up flatOptions.installLinks = false // args[0] will exist when the package is installed packages.push(p) yes = true needPackageCommandSwap = false break } } if (needPackageCommandSwap) { // no bin entry in local packages or in tree, now we look for binPaths const dir = dirname(dirname(localBin)) const localBinPath = await localFileExists(dir, args[0], '/') if (localBinPath) { binPaths.push(localBinPath) return await run() } else if (globalPath && await fileExists(`${globalBin}/${args[0]}`)) { binPaths.push(globalBin) return await run() } // We swap out args[0] with the bin from the manifest later packages.push(args[0]) } } // Resolve any directory specs so that the npx directory is unique to the // resolved directory, not the potentially relative one (i.e. "npx .") for (const i in packages) { const pkg = packages[i] const spec = npa(pkg) if (spec.type === 'directory') { packages[i] = spec.fetchSpec } } const localArb = new Arborist({ ...flatOptions, path }) const localTree = await localArb.loadActual() // Find anything that isn't installed locally const needInstall = [] let commandManifest await Promise.all(packages.map(async (pkg, i) => { const spec = npa(pkg, path) const { manifest, node } = await missingFromTree({ spec, tree: localTree, flatOptions }) if (manifest) { // Package does not exist in the local tree needInstall.push({ spec, manifest }) if (i === 0) { commandManifest = manifest } } else if (i === 0) { // The node.package has enough to look up the bin commandManifest = node.package } })) if (needPackageCommandSwap) { const spec = npa(args[0]) if (spec.type === 'directory') { yes = true } args[0] = getBinFromManifest(commandManifest) if (needInstall.length > 0 && globalPath) { // See if the package is installed globally. If it is, run the translated bin const globalArb = new Arborist({ ...flatOptions, path: globalPath, global: true }) const globalTree = await globalArb.loadActual().catch(() => { log.verbose(`Could not read global path ${globalPath}, ignoring`) return null }) if (globalTree) { const { manifest: globalManifest } = await missingFromTree({ spec, tree: globalTree, flatOptions, shallow: true }) if (!globalManifest && await fileExists(`${globalBin}/${args[0]}`)) { binPaths.push(globalBin) return await run() } } } } const add = [] if (needInstall.length > 0) { // Install things to the npx cache, if needed const { npxCache } = flatOptions if (!npxCache) { throw new Error('Must provide a valid npxCache path') } const hash = crypto.createHash('sha512') .update(packages.map(p => { // Keeps the npx directory unique to the resolved directory, not the // potentially relative one (i.e. "npx .") const spec = npa(p) if (spec.type === 'directory') { return spec.fetchSpec } return p }).sort((a, b) => a.localeCompare(b, 'en')).join('\n')) .digest('hex') .slice(0, 16) const installDir = resolve(npxCache, hash) await mkdir(installDir, { recursive: true }) const npxArb = new Arborist({ ...flatOptions, path: installDir, }) const npxTree = await npxArb.loadActual() await Promise.all(needInstall.map(async ({ spec }) => { const { manifest } = await missingFromTree({ spec, tree: npxTree, flatOptions, isNpxTree: true, }) if (manifest) { // Manifest is not in npxCache, we need to install it there if (!spec.registry) { add.push(manifest._from) } else { add.push(manifest._id) } } })) if (add.length) { if (!yes) { const addList = add.map(a => `${a.replace(/@$/, '')}`) // set -n to always say no if (yes === false) { // Error message lists missing package(s) when process is canceled /* eslint-disable-next-line max-len */ throw new Error(`npx canceled due to missing packages and no YES option: ${JSON.stringify(addList)}`) } if (noTTY() || ciInfo.isCI) { /* eslint-disable-next-line max-len */ log.warn('exec', `The following package${add.length === 1 ? ' was' : 's were'} not found and will be installed: ${addList.join(', ')}`) } else { const confirm = await input.read(() => read({ /* eslint-disable-next-line max-len */ prompt: `Need to install the following packages:\n${addList.join('\n')}\nOk to proceed? `, default: 'y', })) if (confirm.trim().toLowerCase().charAt(0) !== 'y') { throw new Error('canceled') } } } await npxArb.reify({ ...flatOptions, add, }) } binPaths.push(resolve(installDir, 'node_modules/.bin')) } return await run() } module.exports = exec module.exports = process.platform === 'win32' module.exports = () => !process.stdin.isTTY const ciInfo = require('ci-info') const runScript = require('@npmcli/run-script') const readPackageJson = require('read-package-json-fast') const { log, output } = require('proc-log') const noTTY = require('./no-tty.js') const run = async ({ args, call, flatOptions, locationMsg, path, binPaths, runPath, scriptShell, }) => { // turn list of args into command string const script = call || args.shift() || scriptShell // do the fakey runScript dance // still should work if no package.json in cwd const realPkg = await readPackageJson(`${path}/package.json`).catch(() => ({})) const pkg = { ...realPkg, scripts: { ...(realPkg.scripts || {}), npx: script, }, } if (script === scriptShell) { if (!noTTY()) { if (ciInfo.isCI) { return log.warn('exec', 'Interactive mode disabled in CI environment') } const { chalk } = flatOptions output.standard(`${ chalk.reset('\nEntering npm script environment') }${ chalk.reset(locationMsg || ` at location:\n${chalk.dim(runPath)}`) }${ chalk.bold('\nType \'exit\' or ^D when finished\n') }`) } } return runScript({ ...flatOptions, pkg, // we always run in cwd, not --prefix path: runPath, binPaths, event: 'npx', args, stdio: 'inherit', scriptShell, }) } module.exports = run { "name": "libnpmexec", "version": "10.0.0", "files": [ "bin/", "lib/" ], "main": "lib/index.js", "engines": { "node": "^20.17.0 || >=22.9.0" }, "description": "npm exec (npx) programmatic API", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmexec" }, "keywords": [ "npm", "npmcli", "libnpm", "cli", "workspaces", "libnpmexec" ], "author": "GitHub Inc.", "contributors": [ { "name": "Ruy Adorno", "url": "https://ruyadorno.com", "twitter": "ruyadorno" } ], "license": "ISC", "scripts": { "lint": "npm run eslint", "posttest": "npm run lint", "test": "tap", "snap": "tap", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "files": "test/*.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-registry": "^1.0.0", "@npmcli/template-oss": "4.23.6", "bin-links": "^5.0.0", "chalk": "^5.2.0", "just-extend": "^6.2.0", "just-safe-set": "^4.2.1", "tap": "^16.3.8" }, "dependencies": { "@npmcli/arborist": "^9.0.0", "@npmcli/run-script": "^9.0.1", "ci-info": "^4.0.0", "npm-package-arg": "^12.0.0", "pacote": "^21.0.0", "proc-log": "^5.0.0", "read": "^4.0.0", "read-package-json-fast": "^4.0.0", "semver": "^7.3.7", "walk-up-path": "^4.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" } } The ISC License Copyright (c) npm Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmfund [![npm version](https://img.shields.io/npm/v/libnpmfund.svg)](https://npm.im/libnpmfund) [![license](https://img.shields.io/npm/l/libnpmfund.svg)](https://npm.im/libnpmfund) [![CI - libnpmfund](https://github.com/npm/cli/actions/workflows/ci-libnpmfund.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmfund.yml) [`libnpmfund`](https://github.com/npm/libnpmfund) is a Node.js library for retrieving **funding** information for packages installed using [`arborist`](https://github.com/npm/arborist). ## Table of Contents * [Example](#example) * [Install](#install) * [Contributing](#contributing) * [API](#api) * [LICENSE](#license) ## Example ```js const { read } = require('libnpmfund') const fundingInfo = await read() console.log( JSON.stringify(fundingInfo, null, 2) ) // => { length: 2, name: 'foo', version: '1.0.0', funding: { url: 'https://example.com' }, dependencies: { bar: { version: '1.0.0', funding: { url: 'http://collective.example.com' } } } } ``` ## Install `$ npm install libnpmfund` ### Contributing The npm team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](https://github.com/npm/cli/blob/latest/CONTRIBUTING.md) outlines the process for community interaction and contribution. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow the [npm Code of Conduct](https://www.npmjs.com/policies/conduct), and just generally be excellent to each other. Please refer to the [Changelog](CHANGELOG.md) for project history details, too. Happy hacking! ### API ##### `> fund.read([opts]) -> Promise` Reads **funding** info from a npm install and returns a promise for a tree object that only contains packages in which funding info is defined. Options: - `countOnly`: Uses the tree-traversal logic from **npm fund** but skips over any obj definition and just returns an obj containing `{ length }` - useful for things such as printing a `6 packages are looking for funding` msg. - `workspaces`: `Array` List of workspaces names to filter for, the result will only include a subset of the resulting tree that includes only the nodes that are children of the listed workspaces names. - `path`, `registry` and more [Arborist](https://github.com/npm/arborist/) options. ##### `> fund.readTree(tree, [opts]) -> Promise` Reads **funding** info from a given install tree and returns a tree object that only contains packages in which funding info is defined. - `tree`: An [`arborist`](https://github.com/npm/arborist) tree to be used, e.g: ```js const Arborist = require('@npmcli/arborist') const { readTree } = require('libnpmfund') const arb = new Arborist({ path: process.cwd() }) const tree = await arb.loadActual() return readTree(tree, { countOnly: false }) ``` Options: - `countOnly`: Uses the tree-traversal logic from **npm fund** but skips over any obj definition and just returns an obj containing `{ length }` - useful for things such as printing a `6 packages are looking for funding` msg. ##### `> fund.normalizeFunding(funding) -> Object` From a `funding` ``, retrieves normalized funding objects containing a `url` property. e.g: ```js normalizeFunding('http://example.com') // => { url: 'http://example.com' } ``` ##### `> fund.isValidFunding(funding) -> Boolean` Returns `` if `funding` is a valid funding object, e.g: ```js isValidFunding({ foo: 'not a valid funding obj' }) // => false isValidFunding('http://example.com') // => true ``` ## LICENSE [ISC](./LICENSE) 'use strict' const URL = require('node:url').URL const Arborist = require('@npmcli/arborist') // supports object funding and string shorthand, or an array of these // if original was an array, returns an array; else returns the lone item function normalizeFunding (funding) { const normalizeItem = item => typeof item === 'string' ? { url: item } : item const sources = [].concat(funding || []).map(normalizeItem) return Array.isArray(funding) ? sources : sources[0] } // Is the value of a `funding` property of a `package.json` // a valid type+url for `npm fund` to display? function isValidFunding (funding) { if (!funding) { return false } if (Array.isArray(funding)) { return funding.every(f => !Array.isArray(f) && isValidFunding(f)) } try { var parsed = new URL(funding.url || funding) } catch (error) { return false } if ( parsed.protocol !== 'https:' && parsed.protocol !== 'http:' ) { return false } return Boolean(parsed.host) } const empty = () => Object.create(null) function readTree (tree, opts) { let packageWithFundingCount = 0 const seen = new Set() const { countOnly } = opts || {} const _trailingDependencies = Symbol('trailingDependencies') let filterSet if (opts && opts.workspaces && opts.workspaces.length) { const arb = new Arborist(opts) filterSet = arb.workspaceDependencySet(tree, opts.workspaces) } function tracked (name, version) { const key = String(name) + String(version) if (seen.has(key)) { return true } seen.add(key) } function retrieveDependencies (dependencies) { const trailing = dependencies[_trailingDependencies] if (trailing) { return Object.assign( empty(), dependencies, trailing ) } return dependencies } function hasDependencies (dependencies) { return dependencies && ( Object.keys(dependencies).length || dependencies[_trailingDependencies] ) } function attachFundingInfo (target, funding) { if (funding && isValidFunding(funding)) { target.funding = normalizeFunding(funding) packageWithFundingCount++ } } function getFundingDependencies (t) { const edges = t && t.edgesOut && t.edgesOut.values() if (!edges) { return empty() } const directDepsWithFunding = Array.from(edges).map(edge => { if (!edge || !edge.to) { return empty() } const node = edge.to.target || edge.to if (!node.package) { return empty() } if (filterSet && filterSet.size > 0 && !filterSet.has(node)) { return empty() } const { name, funding, version } = node.package // avoids duplicated items within the funding tree if (tracked(name, version)) { return empty() } const fundingItem = {} if (version) { fundingItem.version = version } attachFundingInfo(fundingItem, funding) return { node, fundingItem, } }) return directDepsWithFunding.reduce( (res, { node, fundingItem }) => { if (!fundingItem || fundingItem.length === 0 || !node) { return res } // recurse const transitiveDependencies = node.edgesOut && node.edgesOut.size > 0 && getFundingDependencies(node) // if we're only counting items there's no need // to add all the data to the resulting object if (countOnly) { return null } if (hasDependencies(transitiveDependencies)) { fundingItem.dependencies = retrieveDependencies(transitiveDependencies) } if (isValidFunding(fundingItem.funding)) { res[node.package.name] = fundingItem } else if (hasDependencies(fundingItem.dependencies)) { res[_trailingDependencies] = Object.assign( empty(), res[_trailingDependencies], fundingItem.dependencies ) } return res }, countOnly ? null : empty()) } const treeDependencies = getFundingDependencies(tree) const result = { length: packageWithFundingCount, } if (!countOnly) { const name = (tree && tree.package && tree.package.name) || (tree && tree.name) result.name = name || (tree && tree.path) if (tree && tree.package && tree.package.version) { result.version = tree.package.version } if (tree && tree.package && tree.package.funding) { result.funding = normalizeFunding(tree.package.funding) } result.dependencies = retrieveDependencies(treeDependencies) } return result } async function read (opts) { const arb = new Arborist(opts) const tree = await arb.loadActual(opts) return readTree(tree, opts) } module.exports = { read, readTree, normalizeFunding, isValidFunding, } { "name": "libnpmfund", "version": "7.0.0", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "description": "Programmatic API for npm fund", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmfund" }, "keywords": [ "npm", "npmcli", "libnpm", "cli", "git", "fund", "gitfund" ], "author": "GitHub Inc.", "contributors": [ { "name": "Ruy Adorno", "url": "https://ruyadorno.com", "twitter": "ruyadorno" } ], "license": "ISC", "scripts": { "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "posttest": "npm run lint", "test": "tap", "snap": "tap", "postlint": "template-oss-check", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/template-oss": "4.23.6", "tap": "^16.3.8" }, "dependencies": { "@npmcli/arborist": "^9.0.0" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmorg [![npm version](https://img.shields.io/npm/v/libnpmorg.svg)](https://npm.im/libnpmorg) [![license](https://img.shields.io/npm/l/libnpmorg.svg)](https://npm.im/libnpmorg) [![CI - libnpmorg](https://github.com/npm/cli/actions/workflows/ci-libnpmorg.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmorg.yml) [`libnpmorg`](https://github.com/npm/libnpmorg) is a Node.js library for programmatically accessing the [npm Org membership API](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#membership-detail). ## Table of Contents * [Example](#example) * [Install](#install) * [Contributing](#contributing) * [API](#api) * [hook opts](#opts) * [`set()`](#set) * [`rm()`](#rm) * [`ls()`](#ls) * [`ls.stream()`](#ls-stream) ## Example ```js const org = require('libnpmorg') console.log(await org.ls('myorg', {token: 'deadbeef'})) => Roster { zkat: 'developer', iarna: 'admin', isaacs: 'owner' } ``` ## Install `$ npm install libnpmorg` ### API #### `opts` for `libnpmorg` commands `libnpmorg` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch). All options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options) for options that can be passed in. A couple of options of note for those in a hurry: * `opts.token` - can be passed in and will be used as the authentication token for the registry. For other ways to pass in auth details, see the n-r-f docs. * `opts.otp` - certain operations will require an OTP token to be passed in. If a `libnpmorg` command fails with `err.code === EOTP`, please retry the request with `{otp: <2fa token>}` #### `> org.set(org, user, [role], [opts]) -> Promise` The returned Promise resolves to a [Membership Detail](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#membership-detail) object. The `role` is optional and should be one of `admin`, `owner`, or `developer`. `developer` is the default if no `role` is provided. `org` and `user` must be scope names for the org name and user name respectively. They can optionally be prefixed with `@`. See also: [`PUT /-/org/:scope/user`](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#org-membership-replace) ##### Example ```javascript await org.set('@myorg', '@myuser', 'admin', {token: 'deadbeef'}) => MembershipDetail { org: { name: 'myorg', size: 15 }, user: 'myuser', role: 'admin' } ``` #### `> org.rm(org, user, [opts]) -> Promise` The Promise resolves to `null` on success. `org` and `user` must be scope names for the org name and user name respectively. They can optionally be prefixed with `@`. See also: [`DELETE /-/org/:scope/user`](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#org-membership-delete) ##### Example ```javascript await org.rm('myorg', 'myuser', {token: 'deadbeef'}) ``` #### `> org.ls(org, [opts]) -> Promise` The Promise resolves to a [Roster](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#roster) object. `org` must be a scope name for an org, and can be optionally prefixed with `@`. See also: [`GET /-/org/:scope/user`](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#org-roster) ##### Example ```javascript await org.ls('myorg', {token: 'deadbeef'}) => Roster { zkat: 'developer', iarna: 'admin', isaacs: 'owner' } ``` #### `> org.ls.stream(org, [opts]) -> Stream` Returns a stream of entries for a [Roster](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#roster), with each emitted entry in `[key, value]` format. `org` must be a scope name for an org, and can be optionally prefixed with `@`. The returned stream is a valid `Symbol.asyncIterator`. See also: [`GET /-/org/:scope/user`](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#org-roster) ##### Example ```javascript for await (let [user, role] of org.ls.stream('myorg', {token: 'deadbeef'})) { console.log(`user: ${user} (${role})`) } => user: zkat (developer) user: iarna (admin) user: isaacs (owner) ``` 'use strict' const eu = encodeURIComponent const npmFetch = require('npm-registry-fetch') const validate = require('aproba') // From https://github.com/npm/registry/blob/master/docs/orgs/memberships.md const cmd = module.exports class MembershipDetail {} cmd.set = (org, user, role, opts = {}) => { if ( typeof role === 'object' && Object.keys(opts).length === 0 ) { opts = role role = undefined } validate('SSSO|SSZO', [org, user, role, opts]) user = user.replace(/^@?/, '') org = org.replace(/^@?/, '') return npmFetch.json(`/-/org/${eu(org)}/user`, { ...opts, method: 'PUT', body: { user, role }, }).then(ret => Object.assign(new MembershipDetail(), ret)) } cmd.rm = (org, user, opts = {}) => { validate('SSO', [org, user, opts]) user = user.replace(/^@?/, '') org = org.replace(/^@?/, '') return npmFetch(`/-/org/${eu(org)}/user`, { ...opts, method: 'DELETE', body: { user }, ignoreBody: true, }).then(() => null) } class Roster {} cmd.ls = (org, opts = {}) => { return cmd.ls.stream(org, opts) .collect() .then(data => data.reduce((acc, [key, val]) => { if (!acc) { acc = {} } acc[key] = val return acc }, null)) .then(ret => Object.assign(new Roster(), ret)) } cmd.ls.stream = (org, opts = {}) => { validate('SO', [org, opts]) org = org.replace(/^@?/, '') return npmFetch.json.stream(`/-/org/${eu(org)}/user`, '*', { ...opts, mapJSON: (value, [key]) => { return [key, value] }, }) } { "name": "libnpmorg", "version": "8.0.0", "description": "Programmatic api for `npm org` commands", "author": "GitHub Inc.", "main": "lib/index.js", "keywords": [ "libnpm", "npm", "package manager", "api", "orgs", "teams" ], "license": "ISC", "scripts": { "lint": "npm run eslint", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "files": [ "bin/", "lib/" ], "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/template-oss": "4.23.6", "minipass": "^7.1.1", "nock": "^13.3.3", "tap": "^16.3.8" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmorg" }, "bugs": "https://github.com/npm/libnpmorg/issues", "homepage": "https://npmjs.com/package/libnpmorg", "dependencies": { "aproba": "^2.0.0", "npm-registry-fetch": "^18.0.1" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmpack [![npm version](https://img.shields.io/npm/v/libnpmpack.svg)](https://npm.im/libnpmpack) [![license](https://img.shields.io/npm/l/libnpmpack.svg)](https://npm.im/libnpmpack) [![CI - libnpmpack](https://github.com/npm/cli/actions/workflows/ci-libnpmpack.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmpack.yml) [`libnpmpack`](https://github.com/npm/libnpmpack) is a Node.js library for programmatically packing tarballs from a local directory or from a registry or github spec. If packing from a local source, `libnpmpack` will also run the `prepack` and `postpack` lifecycles. ## Table of Contents * [Example](#example) * [Install](#install) * [API](#api) * [`pack()`](#pack) ## Example ```js const pack = require('libnpmpack') ``` ## Install `$ npm install libnpmpack` ### API #### `> pack(spec, [opts]) -> Promise` Packs a tarball from a local directory or from a registry or github spec and returns a Promise that resolves to the tarball data Buffer, with from, resolved, and integrity fields attached. If no options are passed, the tarball file will be saved on the same directory from which `pack` was called in. `libnpmpack` uses [`pacote`](https://npm.im/pacote). Most options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/pacote#options) for options that can be passed in. ##### Examples ```javascript // packs from cwd const tarball = await pack() // packs from a local directory const localTar = await pack('/Users/claudiahdz/projects/my-cool-pkg') // packs from a registry spec const registryTar = await pack('abbrev@1.0.3') // packs from a github spec const githubTar = await pack('isaacs/rimraf#PR-192') ``` 'use strict' const pacote = require('pacote') const npa = require('npm-package-arg') const runScript = require('@npmcli/run-script') const path = require('node:path') const Arborist = require('@npmcli/arborist') const { writeFile } = require('node:fs/promises') module.exports = pack async function pack (spec = 'file:.', opts = {}) { // gets spec spec = npa(spec) const manifest = await pacote.manifest(spec, { ...opts, Arborist }) const stdio = opts.foregroundScripts ? 'inherit' : 'pipe' if (spec.type === 'directory' && !opts.ignoreScripts) { // prepack await runScript({ ...opts, event: 'prepack', path: spec.fetchSpec, stdio, pkg: manifest, }) } // packs tarball const tarball = await pacote.tarball(manifest._resolved, { ...opts, Arborist, integrity: manifest._integrity, }) // check for explicit `false` so the default behavior is to skip writing to disk if (opts.dryRun === false) { const filename = `${manifest.name}-${manifest.version}.tgz` .replace(/^@/, '').replace(/\//, '-') const destination = path.resolve(opts.packDestination, filename) await writeFile(destination, tarball) } if (spec.type === 'directory' && !opts.ignoreScripts) { // postpack await runScript({ ...opts, event: 'postpack', path: spec.fetchSpec, stdio, pkg: manifest, env: { npm_package_from: tarball.from, npm_package_resolved: tarball.resolved, npm_package_integrity: tarball.integrity, }, }) } return tarball } { "name": "libnpmpack", "version": "9.0.0", "description": "Programmatic API for the bits behind npm pack", "author": "GitHub Inc.", "main": "lib/index.js", "contributors": [ "Claudia Hernández " ], "files": [ "bin/", "lib/" ], "license": "ISC", "scripts": { "lint": "npm run eslint", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/template-oss": "4.23.6", "nock": "^13.3.3", "spawk": "^1.7.1", "tap": "^16.3.8" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmpack" }, "bugs": "https://github.com/npm/libnpmpack/issues", "homepage": "https://npmjs.com/package/libnpmpack", "dependencies": { "@npmcli/arborist": "^9.0.0", "@npmcli/run-script": "^9.0.1", "npm-package-arg": "^12.0.0", "pacote": "^21.0.0" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmpublish [![npm version](https://img.shields.io/npm/v/libnpmpublish.svg)](https://npm.im/libnpmpublish) [![license](https://img.shields.io/npm/l/libnpmpublish.svg)](https://npm.im/libnpmpublish) [![CI - libnpmpublish](https://github.com/npm/cli/actions/workflows/ci-libnpmpublish.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmpublish.yml) [`libnpmpublish`](https://github.com/npm/libnpmpublish) is a Node.js library for programmatically publishing and unpublishing npm packages. Give it a manifest as an object and a tarball as a Buffer, and it'll put them on the registry for you. ## Table of Contents * [Example](#example) * [Install](#install) * [API](#api) * [publish/unpublish opts](#opts) * [`publish()`](#publish) * [`unpublish()`](#unpublish) ## Example ```js const { publish, unpublish } = require('libnpmpublish') ``` ## Install `$ npm install libnpmpublish` ### API #### `opts` for `libnpmpublish` commands `libnpmpublish` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch). Most options are passed through directly to that library, so please refer to [its own `opts` documentation](http://npm.im/npm-registry-fetch#fetch-options) for options that can be passed in. A couple of options of note: * `opts.defaultTag` - registers the published package with the given tag, defaults to `latest`. * `opts.access` - tells the registry whether this package should be published as `public` or `restricted`. Only applies to scoped packages. Defaults to `public`. * `opts.token` - can be passed in and will be used as the authentication token for the registry. For other ways to pass in auth details, see the n-r-f docs. * `opts.provenance` - when running in a supported CI environment, will trigger the generation of a signed provenance statement to be published alongside the package. Mutually exclusive with the `provenanceFile` option. * `opts.provenanceFile` - specifies the path to an externally-generated provenance statement to be published alongside the package. Mutually exclusive with the `provenance` option. The specified file should be a [Sigstore Bundle](https://github.com/sigstore/protobuf-specs/blob/main/protos/sigstore_bundle.proto) containing a [DSSE](https://github.com/secure-systems-lab/dsse)-packaged provenance statement. #### `> libpub.publish(manifest, tarData, [opts]) -> Promise` Sends the package represented by the `manifest` and `tarData` to the configured registry. `manifest` should be the parsed `package.json` for the package being published (which can also be the manifest pulled from a packument, a git repo, tarball, etc.) `tarData` is a `Buffer` of the tarball being published. If `opts.npmVersion` is passed in, it will be used as the `_npmVersion` field in the outgoing packument. You may put your own user-agent string in there to identify your publishes. If `opts.algorithms` is passed in, it should be an array of hashing algorithms to generate `integrity` hashes for. The default is `['sha512']`, which means you end up with `dist.integrity = 'sha512-deadbeefbadc0ffee'`. Any algorithm supported by your current node version is allowed -- npm clients that do not support those algorithms will simply ignore the unsupported hashes. ##### Example ```js // note that pacote.manifest() and pacote.tarball() can also take // any spec that npm can install. a folder shown here, since that's // far and away the most common use case. const path = '/a/path/to/your/source/code' const pacote = require('pacote') // see: http://npm.im/pacote const manifest = await pacote.manifest(path) const tarData = await pacote.tarball(path) await libpub.publish(manifest, tarData, { npmVersion: 'my-pub-script@1.0.2', token: 'my-auth-token-here' }, opts) // Package has been published to the npm registry. ``` #### `> libpub.unpublish(spec, [opts]) -> Promise` Unpublishes `spec` from the appropriate registry. The registry in question may have its own limitations on unpublishing. `spec` should be either a string, or a valid [`npm-package-arg`](https://npm.im/npm-package-arg) parsed spec object. For legacy compatibility reasons, only `tag` and `version` specs will work as expected. `range` specs will fail silently in most cases. ##### Example ```js await libpub.unpublish('lodash', { token: 'i-am-the-worst'}) // // `lodash` has now been unpublished, along with all its versions ``` module.exports = { publish: require('./publish.js'), unpublish: require('./unpublish.js'), } const sigstore = require('sigstore') const { readFile } = require('node:fs/promises') const ci = require('ci-info') const { env } = process const INTOTO_PAYLOAD_TYPE = 'application/vnd.in-toto+json' const INTOTO_STATEMENT_V01_TYPE = 'https://in-toto.io/Statement/v0.1' const INTOTO_STATEMENT_V1_TYPE = 'https://in-toto.io/Statement/v1' const SLSA_PREDICATE_V02_TYPE = 'https://slsa.dev/provenance/v0.2' const SLSA_PREDICATE_V1_TYPE = 'https://slsa.dev/provenance/v1' const GITHUB_BUILDER_ID_PREFIX = 'https://github.com/actions/runner' const GITHUB_BUILD_TYPE = 'https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1' const GITLAB_BUILD_TYPE_PREFIX = 'https://github.com/npm/cli/gitlab' const GITLAB_BUILD_TYPE_VERSION = 'v0alpha1' const generateProvenance = async (subject, opts) => { let payload if (ci.GITHUB_ACTIONS) { /* istanbul ignore next - not covering missing env var case */ const relativeRef = (env.GITHUB_WORKFLOW_REF || '').replace(env.GITHUB_REPOSITORY + '/', '') const delimiterIndex = relativeRef.indexOf('@') const workflowPath = relativeRef.slice(0, delimiterIndex) const workflowRef = relativeRef.slice(delimiterIndex + 1) payload = { _type: INTOTO_STATEMENT_V1_TYPE, subject, predicateType: SLSA_PREDICATE_V1_TYPE, predicate: { buildDefinition: { buildType: GITHUB_BUILD_TYPE, externalParameters: { workflow: { ref: workflowRef, repository: `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}`, path: workflowPath, }, }, internalParameters: { github: { event_name: env.GITHUB_EVENT_NAME, repository_id: env.GITHUB_REPOSITORY_ID, repository_owner_id: env.GITHUB_REPOSITORY_OWNER_ID, }, }, resolvedDependencies: [ { uri: `git+${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}@${env.GITHUB_REF}`, digest: { gitCommit: env.GITHUB_SHA, }, }, ], }, runDetails: { builder: { id: `${GITHUB_BUILDER_ID_PREFIX}/${env.RUNNER_ENVIRONMENT}` }, metadata: { /* eslint-disable-next-line max-len */ invocationId: `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}/attempts/${env.GITHUB_RUN_ATTEMPT}`, }, }, }, } } if (ci.GITLAB) { payload = { _type: INTOTO_STATEMENT_V01_TYPE, subject, predicateType: SLSA_PREDICATE_V02_TYPE, predicate: { buildType: `${GITLAB_BUILD_TYPE_PREFIX}/${GITLAB_BUILD_TYPE_VERSION}`, builder: { id: `${env.CI_PROJECT_URL}/-/runners/${env.CI_RUNNER_ID}` }, invocation: { configSource: { uri: `git+${env.CI_PROJECT_URL}`, digest: { sha1: env.CI_COMMIT_SHA, }, entryPoint: env.CI_JOB_NAME, }, parameters: { CI: env.CI, CI_API_GRAPHQL_URL: env.CI_API_GRAPHQL_URL, CI_API_V4_URL: env.CI_API_V4_URL, CI_BUILD_BEFORE_SHA: env.CI_BUILD_BEFORE_SHA, CI_BUILD_ID: env.CI_BUILD_ID, CI_BUILD_NAME: env.CI_BUILD_NAME, CI_BUILD_REF: env.CI_BUILD_REF, CI_BUILD_REF_NAME: env.CI_BUILD_REF_NAME, CI_BUILD_REF_SLUG: env.CI_BUILD_REF_SLUG, CI_BUILD_STAGE: env.CI_BUILD_STAGE, CI_COMMIT_BEFORE_SHA: env.CI_COMMIT_BEFORE_SHA, CI_COMMIT_BRANCH: env.CI_COMMIT_BRANCH, CI_COMMIT_REF_NAME: env.CI_COMMIT_REF_NAME, CI_COMMIT_REF_PROTECTED: env.CI_COMMIT_REF_PROTECTED, CI_COMMIT_REF_SLUG: env.CI_COMMIT_REF_SLUG, CI_COMMIT_SHA: env.CI_COMMIT_SHA, CI_COMMIT_SHORT_SHA: env.CI_COMMIT_SHORT_SHA, CI_COMMIT_TIMESTAMP: env.CI_COMMIT_TIMESTAMP, CI_COMMIT_TITLE: env.CI_COMMIT_TITLE, CI_CONFIG_PATH: env.CI_CONFIG_PATH, CI_DEFAULT_BRANCH: env.CI_DEFAULT_BRANCH, CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX: env.CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX, CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX: env.CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX, CI_DEPENDENCY_PROXY_SERVER: env.CI_DEPENDENCY_PROXY_SERVER, CI_DEPENDENCY_PROXY_USER: env.CI_DEPENDENCY_PROXY_USER, CI_JOB_ID: env.CI_JOB_ID, CI_JOB_NAME: env.CI_JOB_NAME, CI_JOB_NAME_SLUG: env.CI_JOB_NAME_SLUG, CI_JOB_STAGE: env.CI_JOB_STAGE, CI_JOB_STARTED_AT: env.CI_JOB_STARTED_AT, CI_JOB_URL: env.CI_JOB_URL, CI_NODE_TOTAL: env.CI_NODE_TOTAL, CI_PAGES_DOMAIN: env.CI_PAGES_DOMAIN, CI_PAGES_URL: env.CI_PAGES_URL, CI_PIPELINE_CREATED_AT: env.CI_PIPELINE_CREATED_AT, CI_PIPELINE_ID: env.CI_PIPELINE_ID, CI_PIPELINE_IID: env.CI_PIPELINE_IID, CI_PIPELINE_SOURCE: env.CI_PIPELINE_SOURCE, CI_PIPELINE_URL: env.CI_PIPELINE_URL, CI_PROJECT_CLASSIFICATION_LABEL: env.CI_PROJECT_CLASSIFICATION_LABEL, CI_PROJECT_DESCRIPTION: env.CI_PROJECT_DESCRIPTION, CI_PROJECT_ID: env.CI_PROJECT_ID, CI_PROJECT_NAME: env.CI_PROJECT_NAME, CI_PROJECT_NAMESPACE: env.CI_PROJECT_NAMESPACE, CI_PROJECT_NAMESPACE_ID: env.CI_PROJECT_NAMESPACE_ID, CI_PROJECT_PATH: env.CI_PROJECT_PATH, CI_PROJECT_PATH_SLUG: env.CI_PROJECT_PATH_SLUG, CI_PROJECT_REPOSITORY_LANGUAGES: env.CI_PROJECT_REPOSITORY_LANGUAGES, CI_PROJECT_ROOT_NAMESPACE: env.CI_PROJECT_ROOT_NAMESPACE, CI_PROJECT_TITLE: env.CI_PROJECT_TITLE, CI_PROJECT_URL: env.CI_PROJECT_URL, CI_PROJECT_VISIBILITY: env.CI_PROJECT_VISIBILITY, CI_REGISTRY: env.CI_REGISTRY, CI_REGISTRY_IMAGE: env.CI_REGISTRY_IMAGE, CI_REGISTRY_USER: env.CI_REGISTRY_USER, CI_RUNNER_DESCRIPTION: env.CI_RUNNER_DESCRIPTION, CI_RUNNER_ID: env.CI_RUNNER_ID, CI_RUNNER_TAGS: env.CI_RUNNER_TAGS, CI_SERVER_HOST: env.CI_SERVER_HOST, CI_SERVER_NAME: env.CI_SERVER_NAME, CI_SERVER_PORT: env.CI_SERVER_PORT, CI_SERVER_PROTOCOL: env.CI_SERVER_PROTOCOL, CI_SERVER_REVISION: env.CI_SERVER_REVISION, CI_SERVER_SHELL_SSH_HOST: env.CI_SERVER_SHELL_SSH_HOST, CI_SERVER_SHELL_SSH_PORT: env.CI_SERVER_SHELL_SSH_PORT, CI_SERVER_URL: env.CI_SERVER_URL, CI_SERVER_VERSION: env.CI_SERVER_VERSION, CI_SERVER_VERSION_MAJOR: env.CI_SERVER_VERSION_MAJOR, CI_SERVER_VERSION_MINOR: env.CI_SERVER_VERSION_MINOR, CI_SERVER_VERSION_PATCH: env.CI_SERVER_VERSION_PATCH, CI_TEMPLATE_REGISTRY_HOST: env.CI_TEMPLATE_REGISTRY_HOST, GITLAB_CI: env.GITLAB_CI, GITLAB_FEATURES: env.GITLAB_FEATURES, GITLAB_USER_ID: env.GITLAB_USER_ID, GITLAB_USER_LOGIN: env.GITLAB_USER_LOGIN, RUNNER_GENERATE_ARTIFACTS_METADATA: env.RUNNER_GENERATE_ARTIFACTS_METADATA, }, environment: { name: env.CI_RUNNER_DESCRIPTION, architecture: env.CI_RUNNER_EXECUTABLE_ARCH, server: env.CI_SERVER_URL, project: env.CI_PROJECT_PATH, job: { id: env.CI_JOB_ID, }, pipeline: { id: env.CI_PIPELINE_ID, ref: env.CI_CONFIG_PATH, }, }, }, metadata: { buildInvocationId: `${env.CI_JOB_URL}`, completeness: { parameters: true, environment: true, materials: false, }, reproducible: false, }, materials: [ { uri: `git+${env.CI_PROJECT_URL}`, digest: { sha1: env.CI_COMMIT_SHA, }, }, ], }, } } return sigstore.attest(Buffer.from(JSON.stringify(payload)), INTOTO_PAYLOAD_TYPE, opts) } const verifyProvenance = async (subject, provenancePath) => { let provenanceBundle try { provenanceBundle = JSON.parse(await readFile(provenancePath)) } catch (err) { err.message = `Invalid provenance provided: ${err.message}` throw err } const payload = extractProvenance(provenanceBundle) if (!payload.subject || !payload.subject.length) { throw new Error('No subject found in sigstore bundle payload') } if (payload.subject.length > 1) { throw new Error('Found more than one subject in the sigstore bundle payload') } const bundleSubject = payload.subject[0] if (subject.name !== bundleSubject.name) { throw new Error( `Provenance subject ${bundleSubject.name} does not match the package: ${subject.name}` ) } if (subject.digest.sha512 !== bundleSubject.digest.sha512) { throw new Error('Provenance subject digest does not match the package') } await sigstore.verify(provenanceBundle) return provenanceBundle } const extractProvenance = (bundle) => { if (!bundle?.dsseEnvelope?.payload) { throw new Error('No dsseEnvelope with payload found in sigstore bundle') } try { return JSON.parse(Buffer.from(bundle.dsseEnvelope.payload, 'base64').toString('utf8')) } catch (err) { err.message = `Failed to parse payload from dsseEnvelope: ${err.message}` throw err } } module.exports = { generateProvenance, verifyProvenance, } const { fixer } = require('normalize-package-data') const npmFetch = require('npm-registry-fetch') const npa = require('npm-package-arg') const { log } = require('proc-log') const semver = require('semver') const { URL } = require('node:url') const ssri = require('ssri') const ciInfo = require('ci-info') const { generateProvenance, verifyProvenance } = require('./provenance') const TLOG_BASE_URL = 'https://search.sigstore.dev/' const publish = async (manifest, tarballData, opts) => { if (manifest.private) { throw Object.assign( new Error(`This package has been marked as private Remove the 'private' field from the package.json to publish it.`), { code: 'EPRIVATE' } ) } // spec is used to pick the appropriate registry/auth combo const spec = npa.resolve(manifest.name, manifest.version) opts = { access: 'public', algorithms: ['sha512'], defaultTag: 'latest', ...opts, spec, } const reg = npmFetch.pickRegistry(spec, opts) const pubManifest = patchManifest(manifest, opts) // registry-frontdoor cares about the access level, // which is only configurable for scoped packages if (!spec.scope && opts.access === 'restricted') { throw Object.assign( new Error("Can't restrict access to unscoped packages."), { code: 'EUNSCOPED' } ) } const { metadata, transparencyLogUrl } = await buildMetadata( reg, pubManifest, tarballData, spec, opts ) const res = await npmFetch(spec.escapedName, { ...opts, method: 'PUT', body: metadata, ignoreBody: true, }) if (transparencyLogUrl) { res.transparencyLogUrl = transparencyLogUrl } return res } const patchManifest = (_manifest, opts) => { const { npmVersion } = opts // we only update top-level fields, so a shallow clone is fine const manifest = { ..._manifest } manifest._nodeVersion = process.versions.node if (npmVersion) { manifest._npmVersion = npmVersion } fixer.fixNameField(manifest, { strict: true, allowLegacyCase: true }) const version = semver.clean(manifest.version) if (!version) { throw Object.assign( new Error('invalid semver: ' + manifest.version), { code: 'EBADSEMVER' } ) } manifest.version = version return manifest } const buildMetadata = async (registry, manifest, tarballData, spec, opts) => { const { access, defaultTag, algorithms, provenance, provenanceFile } = opts const root = { _id: manifest.name, name: manifest.name, description: manifest.description, 'dist-tags': {}, versions: {}, access, } root.versions[manifest.version] = manifest const tag = manifest.tag || defaultTag root['dist-tags'][tag] = manifest.version const tarballName = `${manifest.name}-${manifest.version}.tgz` const provenanceBundleName = `${manifest.name}-${manifest.version}.sigstore` const tarballURI = `${manifest.name}/-/${tarballName}` const integrity = ssri.fromData(tarballData, { algorithms: [...new Set(['sha1'].concat(algorithms))], }) manifest._id = `${manifest.name}@${manifest.version}` manifest.dist = { ...manifest.dist } // Don't bother having sha1 in the actual integrity field manifest.dist.integrity = integrity.sha512[0].toString() // Legacy shasum support manifest.dist.shasum = integrity.sha1[0].hexDigest() // NB: the CLI always fetches via HTTPS if the registry is HTTPS, // regardless of what's here. This makes it so that installing // from an HTTP-only mirror doesn't cause problems, though. manifest.dist.tarball = new URL(tarballURI, registry).href .replace(/^https:\/\//, 'http://') root._attachments = {} root._attachments[tarballName] = { content_type: 'application/octet-stream', data: tarballData.toString('base64'), length: tarballData.length, } // Handle case where --provenance flag was set to true let transparencyLogUrl if (provenance === true || provenanceFile) { let provenanceBundle const subject = { name: npa.toPurl(spec), digest: { sha512: integrity.sha512[0].hexDigest() }, } if (provenance === true) { await ensureProvenanceGeneration(registry, spec, opts) provenanceBundle = await generateProvenance([subject], opts) /* eslint-disable-next-line max-len */ log.notice('publish', `Signed provenance statement with source and build information from ${ciInfo.name}`) const tlogEntry = provenanceBundle?.verificationMaterial?.tlogEntries[0] /* istanbul ignore else */ if (tlogEntry) { transparencyLogUrl = `${TLOG_BASE_URL}?logIndex=${tlogEntry.logIndex}` log.notice( 'publish', `Provenance statement published to transparency log: ${transparencyLogUrl}` ) } } else { provenanceBundle = await verifyProvenance(subject, provenanceFile) } const serializedBundle = JSON.stringify(provenanceBundle) root._attachments[provenanceBundleName] = { content_type: provenanceBundle.mediaType, data: serializedBundle, length: serializedBundle.length, } } return { metadata: root, transparencyLogUrl, } } // Check that all the prereqs are met for provenance generation const ensureProvenanceGeneration = async (registry, spec, opts) => { if (ciInfo.GITHUB_ACTIONS) { // Ensure that the GHA OIDC token is available if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL) { throw Object.assign( /* eslint-disable-next-line max-len */ new Error('Provenance generation in GitHub Actions requires "write" access to the "id-token" permission'), { code: 'EUSAGE' } ) } } else if (ciInfo.GITLAB) { // Ensure that the Sigstore OIDC token is available if (!process.env.SIGSTORE_ID_TOKEN) { throw Object.assign( /* eslint-disable-next-line max-len */ new Error('Provenance generation in GitLab CI requires "SIGSTORE_ID_TOKEN" with "sigstore" audience to be present in "id_tokens". For more info see:\nhttps://docs.gitlab.com/ee/ci/secrets/id_token_authentication.html'), { code: 'EUSAGE' } ) } } else { throw Object.assign( new Error('Automatic provenance generation not supported for provider: ' + ciInfo.name), { code: 'EUSAGE' } ) } // Some registries (e.g. GH packages) require auth to check visibility, // and always return 404 when no auth is supplied. In this case we assume // the package is always private and require `--access public` to publish // with provenance. let visibility = { public: false } if (opts.access !== 'public') { try { const res = await npmFetch .json(`${registry}/-/package/${spec.escapedName}/visibility`, opts) visibility = res } catch (err) { if (err.code !== 'E404') { throw err } } } if (!visibility.public && opts.provenance === true && opts.access !== 'public') { throw Object.assign( /* eslint-disable-next-line max-len */ new Error("Can't generate provenance for new or private package, you must set `access` to public."), { code: 'EUSAGE' } ) } } module.exports = publish 'use strict' const { URL } = require('node:url') const npa = require('npm-package-arg') const npmFetch = require('npm-registry-fetch') const semver = require('semver') // given a tarball url and a registry url, returns just the // relevant pathname portion of it, so that it can be handled // elegantly by npm-registry-fetch which only expects pathnames // and handles the registry hostname via opts const getPathname = (tarball, registry) => { const registryUrl = new URL(registry).pathname.slice(1) let tarballUrl = new URL(tarball).pathname.slice(1) // test the tarball url to see if it starts with a possible // pathname from the registry url, in that case strips that portion // of it so that we only return the post-registry-url pathname if (registryUrl) { tarballUrl = tarballUrl.slice(registryUrl.length) } return tarballUrl } const unpublish = async (spec, opts) => { spec = npa(spec) // spec is used to pick the appropriate registry/auth combo. opts = { force: false, ...opts, spec, } try { const pkgUri = spec.escapedName const pkg = await npmFetch.json(pkgUri, { ...opts, query: { write: true }, }) const version = spec.rawSpec const allVersions = pkg.versions || {} const versionData = allVersions[version] const rawSpecs = (!spec.rawSpec || spec.rawSpec === '*') const onlyVersion = Object.keys(allVersions).length === 1 const noVersions = !Object.keys(allVersions).length // if missing specific version, // assumed unpublished if (!versionData && !rawSpecs && !noVersions) { return true } // unpublish all versions of a package: // - no specs supplied "npm unpublish foo" // - all specs ("*") "npm unpublish foo@*" // - there was only one version // - has no versions field on packument if (rawSpecs || onlyVersion || noVersions) { await npmFetch(`${pkgUri}/-rev/${pkg._rev}`, { ...opts, method: 'DELETE', ignoreBody: true, }) return true } else { const dist = allVersions[version].dist delete allVersions[version] const latestVer = pkg['dist-tags'].latest // deleting dist tags associated to version Object.keys(pkg['dist-tags']).forEach(tag => { if (pkg['dist-tags'][tag] === version) { delete pkg['dist-tags'][tag] } }) if (latestVer === version) { pkg['dist-tags'].latest = Object.keys( allVersions ).sort(semver.compareLoose).pop() } delete pkg._revisions delete pkg._attachments // Update packument with removed versions await npmFetch(`${pkgUri}/-rev/${pkg._rev}`, { ...opts, method: 'PUT', body: pkg, ignoreBody: true, }) // Remove the tarball itself const { _rev } = await npmFetch.json(pkgUri, { ...opts, query: { write: true }, }) const tarballUrl = getPathname(dist.tarball, opts.registry) await npmFetch(`${tarballUrl}/-rev/${_rev}`, { ...opts, method: 'DELETE', ignoreBody: true, }) return true } } catch (err) { if (err.code !== 'E404') { throw err } return true } } module.exports = unpublish { "name": "libnpmpublish", "version": "11.0.0", "description": "Programmatic API for the bits behind npm publish and unpublish", "author": "GitHub Inc.", "main": "lib/index.js", "contributors": [ "Kat Marchán ", "Claudia Hernández " ], "files": [ "bin/", "lib/" ], "license": "ISC", "scripts": { "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/mock-globals": "^1.0.0", "@npmcli/mock-registry": "^1.0.0", "@npmcli/template-oss": "4.23.6", "tap": "^16.3.8" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmpublish" }, "bugs": "https://github.com/npm/cli/issues", "homepage": "https://npmjs.com/package/libnpmpublish", "dependencies": { "ci-info": "^4.0.0", "normalize-package-data": "^7.0.0", "npm-package-arg": "^12.0.0", "npm-registry-fetch": "^18.0.1", "proc-log": "^5.0.0", "semver": "^7.3.7", "sigstore": "^3.0.0", "ssri": "^12.0.0" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmsearch [![npm version](https://img.shields.io/npm/v/libnpmsearch.svg)](https://npm.im/libnpmsearch) [![license](https://img.shields.io/npm/l/libnpmsearch.svg)](https://npm.im/libnpmsearch) [![CI - libnpmsearch](https://github.com/npm/cli/actions/workflows/ci-libnpmsearch.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmsearch.yml) [`libnpmsearch`](https://github.com/npm/libnpmsearch) is a Node.js library for programmatically accessing the npm search endpoint. It does **not** support legacy search through `/-/all`. ## Table of Contents * [Example](#example) * [Install](#install) * [Contributing](#contributing) * [API](#api) * [search opts](#opts) * [`search()`](#search) * [`search.stream()`](#search-stream) ## Example ```js const search = require('libnpmsearch') console.log(await search('libnpm')) => [ { name: 'libnpm', description: 'programmatic npm API', ...etc }, { name: 'libnpmsearch', description: 'Programmatic API for searching in npm and compatible registries', ...etc }, ...more ] ``` ## Install `$ npm install libnpmsearch` ### API #### `opts` for `libnpmsearch` commands The following opts are used directly by `libnpmsearch` itself: * `opts.limit` - Number of results to limit the query to. Default: 20 * `opts.from` - Offset number for results. Used with `opts.limit` for pagination. Default: 0 * `opts.detailed` - If true, returns an object with `package`, `score`, and `searchScore` fields, with `package` being what would usually be returned, and the other two containing details about how that package scored. Useful for UIs. Default: false * `opts.sortBy` - Used as a shorthand to set `opts.quality`, `opts.maintenance`, and `opts.popularity` with values that prioritize each one. Should be one of `'optimal'`, `'quality'`, `'maintenance'`, or `'popularity'`. Default: `'optimal'` * `opts.maintenance` - Decimal number between `0` and `1` that defines the weight of `maintenance` metrics when scoring and sorting packages. Default: `0.65` (same as `opts.sortBy: 'optimal'`) * `opts.popularity` - Decimal number between `0` and `1` that defines the weight of `popularity` metrics when scoring and sorting packages. Default: `0.98` (same as `opts.sortBy: 'optimal'`) * `opts.quality` - Decimal number between `0` and `1` that defines the weight of `quality` metrics when scoring and sorting packages. Default: `0.5` (same as `opts.sortBy: 'optimal'`) `libnpmsearch` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch). Most options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options) for options that can be passed in. A couple of options of note for those in a hurry: * `opts.token` - can be passed in and will be used as the authentication token for the registry. For other ways to pass in auth details, see the n-r-f docs. #### `> search(query, [opts]) -> Promise` `query` must be either a String or an Array of search terms. If `opts.limit` is provided, it will be sent to the API to constrain the number of returned results. You may receive more, or fewer results, at the endpoint's discretion. The returned Promise resolved to an Array of search results with the following format: ```js { name: String, version: SemverString, description: String || null, maintainers: [ { username: String, email: String }, ...etc ] || null, keywords: [String] || null, date: Date || null } ``` If `opts.limit` is provided, it will be sent to the API to constrain the number of returned results. You may receive more, or fewer results, at the endpoint's discretion. For streamed results, see [`search.stream`](#search-stream). ##### Example ```javascript await search('libnpm') => [ { name: 'libnpm', description: 'programmatic npm API', ...etc }, { name: 'libnpmsearch', description: 'Programmatic API for searching in npm and compatible registries', ...etc }, ...more ] ``` #### `> search.stream(query, [opts]) -> Stream` `query` must be either a String or an Array of search terms. If `opts.limit` is provided, it will be sent to the API to constrain the number of returned results. You may receive more, or fewer results, at the endpoint's discretion. The returned Stream emits one entry per search result, with each entry having the following format: ```js { name: String, version: SemverString, description: String || null, maintainers: [ { username: String, email: String }, ...etc ] || null, keywords: [String] || null, date: Date || null } ``` For getting results in one chunk, see [`search`](#search-stream). ##### Example ```javascript search.stream('libnpm').on('data', console.log) => // entry 1 { name: 'libnpm', description: 'programmatic npm API', ...etc } // entry 2 { name: 'libnpmsearch', description: 'Programmatic API for searching in npm and compatible registries', ...etc } // etc ``` 'use strict' const npmFetch = require('npm-registry-fetch') module.exports = search function search (query, opts) { return search.stream(query, opts).collect() } search.stream = searchStream function searchStream (query, opts = {}) { opts = { detailed: false, limit: 20, from: 0, quality: 0.65, popularity: 0.98, maintenance: 0.5, ...opts.opts, // this is to support the cli's --searchopts parameter ...opts, } switch (opts.sortBy) { case 'optimal': { opts.quality = 0.65 opts.popularity = 0.98 opts.maintenance = 0.5 break } case 'quality': { opts.quality = 1 opts.popularity = 0 opts.maintenance = 0 break } case 'popularity': { opts.quality = 0 opts.popularity = 1 opts.maintenance = 0 break } case 'maintenance': { opts.quality = 0 opts.popularity = 0 opts.maintenance = 1 break } } return npmFetch.json.stream('/-/v1/search', 'objects.*', { ...opts, query: { text: Array.isArray(query) ? query.join(' ') : query, size: opts.limit, from: opts.from, quality: opts.quality, popularity: opts.popularity, maintenance: opts.maintenance, }, mapJSON: (obj) => { if (obj.package.date) { obj.package.date = new Date(obj.package.date) } if (opts.detailed) { return obj } else { return obj.package } }, } ) } { "name": "libnpmsearch", "version": "9.0.0", "description": "Programmatic API for searching in npm and compatible registries.", "author": "GitHub Inc.", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "keywords": [ "npm", "search", "api", "libnpm" ], "license": "ISC", "scripts": { "posttest": "npm run lint", "test": "tap", "lint": "npm run eslint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/template-oss": "4.23.6", "nock": "^13.3.3", "tap": "^16.3.8" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmsearch" }, "bugs": "https://github.com/npm/libnpmsearch/issues", "homepage": "https://npmjs.com/package/libnpmsearch", "dependencies": { "npm-registry-fetch": "^18.0.1" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmteam [![npm version](https://img.shields.io/npm/v/libnpmteam.svg)](https://npm.im/libnpmteam) [![license](https://img.shields.io/npm/l/libnpmteam.svg)](https://npm.im/libnpmteam) [![CI - libnpmteam](https://github.com/npm/cli/actions/workflows/ci-libnpmteam.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmteam.yml) [`libnpmteam`](https://github.com/npm/libnpmteam) is a Node.js library that provides programmatic access to the guts of the npm CLI's `npm team` command and its various subcommands. ## Example ```javascript const team = require('libnpmteam') // List all teams for the @npm org. console.log(await team.lsTeams('npm')) ``` ## Publishing 1. Manually create CHANGELOG.md file 1. Commit changes to CHANGELOG.md ```bash $ git commit -m "chore: updated CHANGELOG.md" ``` 1. Run `npm version {newVersion}` ```bash # Example $ npm version patch # 1. Runs `coverage` and `lint` scripts # 2. Bumps package version; and **create commit/tag** # 3. Runs `npm publish`; publishing directory with **unpushed commit** # 4. Runs `git push origin --follow-tags` ``` ## Table of Contents * [Installing](#install) * [Example](#example) * [API](#api) * [team opts](#opts) * [`create()`](#create) * [`destroy()`](#destroy) * [`add()`](#add) * [`rm()`](#rm) * [`lsTeams()`](#ls-teams) * [`lsTeams.stream()`](#ls-teams-stream) * [`lsUsers()`](#ls-users) * [`lsUsers.stream()`](#ls-users-stream) ### Install `$ npm install libnpmteam` ### API #### `opts` for `libnpmteam` commands `libnpmteam` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch). All options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options) for options that can be passed in. A couple of options of note for those in a hurry: * `opts.token` - can be passed in and will be used as the authentication token for the registry. For other ways to pass in auth details, see the n-r-f docs. * `opts.otp` - certain operations will require an OTP token to be passed in. If a `libnpmteam` command fails with `err.code === EOTP`, please retry the request with `{otp: <2fa token>}` #### `> team.create(team, [opts]) -> Promise` Creates a team named `team`. Team names use the format `@:`, with the `@` being optional. Additionally, `opts.description` may be passed in to include a description. ##### Example ```javascript await team.create('@npm:cli', {token: 'myregistrytoken'}) // The @npm:cli team now exists. ``` #### `> team.destroy(team, [opts]) -> Promise` Destroys a team named `team`. Team names use the format `@:`, with the `@` being optional. ##### Example ```javascript await team.destroy('@npm:cli', {token: 'myregistrytoken'}) // The @npm:cli team has been destroyed. ``` #### `> team.add(user, team, [opts]) -> Promise` Adds `user` to `team`. ##### Example ```javascript await team.add('zkat', '@npm:cli', {token: 'myregistrytoken'}) // @zkat now belongs to the @npm:cli team. ``` #### `> team.rm(user, team, [opts]) -> Promise` Removes `user` from `team`. ##### Example ```javascript await team.rm('zkat', '@npm:cli', {token: 'myregistrytoken'}) // @zkat is no longer part of the @npm:cli team. ``` #### `> team.lsTeams(scope, [opts]) -> Promise` Resolves to an array of team names belonging to `scope`. ##### Example ```javascript await team.lsTeams('@npm', {token: 'myregistrytoken'}) => [ 'npm:cli', 'npm:web', 'npm:registry', 'npm:developers' ] ``` #### `> team.lsTeams.stream(scope, [opts]) -> Stream` Returns a stream of teams belonging to `scope`. For a Promise-based version of these results, see [`team.lsTeams()`](#ls-teams). ##### Example ```javascript for await (let team of team.lsTeams.stream('@npm', {token: 'myregistrytoken'})) { console.log(team) } // outputs // npm:cli // npm:web // npm:registry // npm:developers ``` #### `> team.lsUsers(team, [opts]) -> Promise` Resolves to an array of usernames belonging to `team`. For a streamed version of these results, see [`team.lsUsers.stream()`](#ls-users-stream). ##### Example ```javascript await team.lsUsers('@npm:cli', {token: 'myregistrytoken'}) => [ 'iarna', 'zkat' ] ``` #### `> team.lsUsers.stream(team, [opts]) -> Stream` Returns a stream of usernames belonging to `team`. For a Promise-based version of these results, see [`team.lsUsers()`](#ls-users). ##### Example ```javascript for await (let user of team.lsUsers.stream('@npm:cli', {token: 'myregistrytoken'})) { console.log(user) } // outputs // iarna // zkat ``` 'use strict' const eu = encodeURIComponent const npmFetch = require('npm-registry-fetch') const validate = require('aproba') const cmd = module.exports cmd.create = (entity, opts = {}) => { return Promise.resolve().then(() => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/org/${eu(scope)}/team` return npmFetch.json(uri, { ...opts, method: 'PUT', scope, body: { name: team, description: opts.description }, }) }) } cmd.destroy = async (entity, opts = {}) => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/team/${eu(scope)}/${eu(team)}` await npmFetch(uri, { ...opts, method: 'DELETE', scope, ignoreBody: true, }) return true } cmd.add = (user, entity, opts = {}) => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/team/${eu(scope)}/${eu(team)}/user` return npmFetch.json(uri, { ...opts, method: 'PUT', scope, body: { user }, }) } cmd.rm = async (user, entity, opts = {}) => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/team/${eu(scope)}/${eu(team)}/user` await npmFetch(uri, { ...opts, method: 'DELETE', scope, body: { user }, ignoreBody: true, }) return true } cmd.lsTeams = (...args) => cmd.lsTeams.stream(...args).collect() cmd.lsTeams.stream = (scope, opts = {}) => { validate('SO', [scope, opts]) const uri = `/-/org/${eu(scope)}/team` return npmFetch.json.stream(uri, '.*', { ...opts, query: { format: 'cli' }, }) } cmd.lsUsers = (...args) => cmd.lsUsers.stream(...args).collect() cmd.lsUsers.stream = (entity, opts = {}) => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/team/${eu(scope)}/${eu(team)}/user` return npmFetch.json.stream(uri, '.*', { ...opts, query: { format: 'cli' }, }) } cmd.edit = () => { throw new Error('edit is not implemented yet') } function splitEntity (entity = '') { const [, scope, team] = entity.match(/^@?([^:]+):(.*)$/) || [] return { scope, team } } { "name": "libnpmteam", "description": "npm Team management APIs", "version": "8.0.0", "author": "GitHub Inc.", "license": "ISC", "main": "lib/index.js", "scripts": { "lint": "npm run eslint", "test": "tap", "posttest": "npm run lint", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/template-oss": "4.23.6", "nock": "^13.3.3", "tap": "^16.3.8" }, "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmteam" }, "files": [ "bin/", "lib/" ], "homepage": "https://npmjs.com/package/libnpmteam", "dependencies": { "aproba": "^2.0.0", "npm-registry-fetch": "^18.0.1" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # libnpmversion [![npm version](https://img.shields.io/npm/v/libnpmversion.svg)](https://npm.im/libnpmversion) [![license](https://img.shields.io/npm/l/libnpmversion.svg)](https://npm.im/libnpmversion) [![CI - libnpmversion](https://github.com/npm/cli/actions/workflows/ci-libnpmversion.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmversion.yml) Library to do the things that 'npm version' does. ## USAGE ```js const npmVersion = require('libnpmversion') // argument can be one of: // - any semver version string (set to that exact version) // - 'major', 'minor', 'patch', 'pre{major,minor,patch}' (increment at // that value) // - 'from-git' (set to the latest semver-lookin git tag - this skips // gitTagVersion, but will still sign if asked) npmVersion(arg, { path: '/path/to/my/pkg', // defaults to cwd allowSameVersion: false, // allow tagging/etc to the current version preid: '', // when arg=='pre', define the prerelease string, like 'beta' etc. tagVersionPrefix: 'v', // tag as 'v1.2.3' when versioning to 1.2.3 commitHooks: true, // default true, run git commit hooks, default true gitTagVersion: true, // default true, tag the version signGitCommit: false, // default false, gpg sign the git commit signGitTag: false, // default false, gpg sign the git tag force: false, // push forward recklessly if any problems happen ignoreScripts: false, // do not run pre/post/version lifecycle scripts scriptShell: '/bin/bash', // shell to run lifecycle scripts in message: 'v%s', // message for tag and commit, replace %s with the version }).then(newVersion => { console.error('version updated!', newVersion) }) ``` ## Description Run this in a package directory to bump the version and write the new data back to `package.json`, `package-lock.json`, and, if present, `npm-shrinkwrap.json`. The `newversion` argument should be a valid semver string, a valid second argument to [semver.inc](https://github.com/npm/node-semver#functions) (one of `patch`, `minor`, `major`, `prepatch`, `preminor`, `premajor`, `prerelease`), or `from-git`. In the second case, the existing version will be incremented by 1 in the specified field. `from-git` will try to read the latest git tag, and use that as the new npm version. If run in a git repo, it will also create a version commit and tag. This behavior is controlled by `gitTagVersion` (see below), and can be disabled by setting `gitTagVersion: false` in the options. It will fail if the working directory is not clean, unless `force: true` is set. If supplied with a `message` string option, it will use it as a commit message when creating a version commit. If the `message` option contains `%s` then that will be replaced with the resulting version number. If the `signGitTag` option is set, then the tag will be signed using the `-s` flag to git. Note that you must have a default GPG key set up in your git config for this to work properly. If `preversion`, `version`, or `postversion` are in the `scripts` property of the package.json, they will be executed in the appropriate sequence. The exact order of execution is as follows: 1. Check to make sure the git working directory is clean before we get started. Your scripts may add files to the commit in future steps. This step is skipped if the `force` flag is set. 2. Run the `preversion` script. These scripts have access to the old `version` in package.json. A typical use would be running your full test suite before deploying. Any files you want added to the commit should be explicitly added using `git add`. 3. Bump `version` in `package.json` as requested (`patch`, `minor`, `major`, explicit version number, etc). 4. Run the `version` script. These scripts have access to the new `version` in package.json (so they can incorporate it into file headers in generated files for example). Again, scripts should explicitly add generated files to the commit using `git add`. 5. Commit and tag. 6. Run the `postversion` script. Use it to clean up the file system or automatically push the commit and/or tag. Take the following example: ```json { "scripts": { "preversion": "npm test", "version": "npm run build && git add -A dist", "postversion": "git push && git push --tags && rm -rf build/temp" } } ``` This runs all your tests, and proceeds only if they pass. Then runs your `build` script, and adds everything in the `dist` directory to the commit. After the commit, it pushes the new commit and tag up to the server, and deletes the `build/temp` directory. ## API ### `npmVersion(newversion, options = {}) -> Promise` Do the things. Returns a promise that resolves to the new version if all is well, or rejects if any errors are encountered. ### Options #### `path` String The path to the package being versionified. Defaults to process.cwd(). #### `allowSameVersion` Boolean Allow setting the version to the current version in package.json. Default `false`. #### `preid` String When the `newversion` is pre, premajor, preminor, or prepatch, this defines the prerelease string, like 'beta' etc. #### `tagVersionPrefix` String The prefix to add to the raw semver string for the tag name. Defaults to `'v'`. (So, by default it tags as 'v1.2.3' when versioning to 1.2.3.) #### `commitHooks` Boolean Run git commit hooks. Default true. #### `gitTagVersion` Boolean Tag the version, default true. #### `signGitCommit` Boolean GPG sign the git commit. Default `false`. #### `signGitTag` Boolean GPG sign the git tag. Default `false`. #### `force` Boolean Push forward recklessly if any problems happen. Default `false`. #### `ignoreScripts` Boolean Do not run pre/post/version lifecycle scripts. Default `false`. #### `scriptShell` String Path to the shell, which should execute the lifecycle scripts. Defaults to `/bin/sh` on unix, or `cmd.exe` on windows. #### `message` String The message for the git commit and annotated git tag that are created. const git = require('@npmcli/git') module.exports = (version, opts) => { const { commitHooks, allowSameVersion, signGitCommit, message } = opts const args = ['commit'] if (commitHooks === false) { args.push('-n') } if (allowSameVersion) { args.push('--allow-empty') } if (signGitCommit) { args.push('-S') } args.push('-m') return git.spawn([...args, message.replace(/%s/g, version)], opts) } const git = require('@npmcli/git') const { log } = require('proc-log') // returns true if it's cool to do git stuff // throws if it's unclean, and not forced. module.exports = async opts => { const { force } = opts let hadError = false const clean = await git.isClean(opts).catch(er => { if (er.code === 'ENOGIT') { log.warn( 'version', 'This is a Git checkout, but the git command was not found.', 'npm could not create a Git tag for this release!' ) hadError = true // how can merges be real if our git isn't real? return true } else { throw er } }) if (!clean) { if (!force) { throw new Error('Git working directory not clean.') } log.warn('version', 'Git working directory not clean, proceeding forcefully.') } return !hadError } const readJson = require('./read-json.js') const version = require('./version.js') module.exports = async (newversion, opts = {}) => { const { path = process.cwd(), allowSameVersion = false, tagVersionPrefix = 'v', commitHooks = true, gitTagVersion = true, signGitCommit = false, signGitTag = false, force = false, ignoreScripts = false, scriptShell = undefined, preid = null, message = 'v%s', } = opts const pkg = opts.pkg || await readJson(path + '/package.json') return version(newversion, { path, cwd: path, allowSameVersion, tagVersionPrefix, commitHooks, gitTagVersion, signGitCommit, signGitTag, force, ignoreScripts, scriptShell, preid, pkg, message, }) } // can't use read-package-json-fast, because we want to ensure // that we make as few changes as possible, even for safety issues. const { readFile } = require('node:fs/promises') const parse = require('json-parse-even-better-errors') module.exports = async path => parse(await readFile(path)) const { spawn } = require('@npmcli/git') const semver = require('semver') module.exports = async opts => { const tag = (await spawn( ['describe', '--tags', '--abbrev=0', '--match=*.*.*'], opts)).stdout.trim() const ver = semver.coerce(tag, { loose: true }) if (ver) { return ver.version } throw new Error(`Tag is not a valid version: ${JSON.stringify(tag)}`) } const git = require('@npmcli/git') module.exports = async (version, opts) => { const { signGitTag, allowSameVersion, tagVersionPrefix, message, } = opts const tag = `${tagVersionPrefix}${version}` const flags = ['-'] if (signGitTag) { flags.push('s') } if (allowSameVersion) { flags.push('f') } flags.push('m') return git.spawn([ 'tag', flags.join(''), message.replace(/%s/g, version), tag, ], opts) } // called with all the options already set to their defaults const retrieveTag = require('./retrieve-tag.js') const semver = require('semver') const enforceClean = require('./enforce-clean.js') const writeJson = require('./write-json.js') const readJson = require('./read-json.js') const git = require('@npmcli/git') const commit = require('./commit.js') const tag = require('./tag.js') const { log } = require('proc-log') const runScript = require('@npmcli/run-script') module.exports = async (newversion, opts) => { const { path, allowSameVersion, gitTagVersion, ignoreScripts, preid, pkg, } = opts const { valid, clean, inc } = semver const current = pkg.version || '0.0.0' const currentClean = clean(current) let newV if (valid(newversion, { loose: true })) { newV = clean(newversion, { loose: true }) } else if (newversion === 'from-git') { newV = await retrieveTag(opts) } else { newV = inc(currentClean, newversion, { loose: true }, preid) } if (!newV) { throw Object.assign(new Error('Invalid version: ' + newversion), { current, requested: newversion, }) } if (newV === currentClean && !allowSameVersion) { throw Object.assign(new Error('Version not changed'), { current, requested: newversion, newVersion: newV, }) } const isGitDir = newversion === 'from-git' || await git.is(opts) // ok! now we know the new version, and the old version is in pkg // - check if git dir is clean // returns false if we should not keep doing git stuff const doGit = gitTagVersion && isGitDir && await enforceClean(opts) if (!ignoreScripts) { await runScript({ ...opts, pkg, stdio: 'inherit', event: 'preversion', env: { npm_old_version: current, npm_new_version: newV, }, }) } // - update the files pkg.version = newV delete pkg._id await writeJson(`${path}/package.json`, pkg) // try to update shrinkwrap, but ok if this fails const locks = [`${path}/package-lock.json`, `${path}/npm-shrinkwrap.json`] const haveLocks = [] for (const lock of locks) { try { const sw = await readJson(lock) sw.version = newV if (sw.packages && sw.packages['']) { sw.packages[''].version = newV } await writeJson(lock, sw) haveLocks.push(lock) } catch { // ignore errors } } if (!ignoreScripts) { await runScript({ ...opts, pkg, stdio: 'inherit', event: 'version', env: { npm_old_version: current, npm_new_version: newV, }, }) } if (doGit) { // - git add, git commit, git tag await git.spawn(['add', `${path}/package.json`], opts) // sometimes people .gitignore their lockfiles for (const lock of haveLocks) { await git.spawn(['add', lock], opts).catch(() => {}) } await commit(newV, opts) await tag(newV, opts) } else { log.verbose('version', 'Not tagging: not in a git repo or no git cmd') } if (!ignoreScripts) { await runScript({ ...opts, pkg, stdio: 'inherit', event: 'postversion', env: { npm_old_version: current, npm_new_version: newV, }, }) } return newV } // write the json back, preserving the line breaks and indent const { writeFile } = require('node:fs/promises') const kIndent = Symbol.for('indent') const kNewline = Symbol.for('newline') module.exports = async (path, pkg) => { const { [kIndent]: indent = 2, [kNewline]: newline = '\n', } = pkg delete pkg._id const raw = JSON.stringify(pkg, null, indent) + '\n' const data = newline === '\n' ? raw : raw.split('\n').join(newline) return writeFile(path, data) } { "name": "libnpmversion", "version": "8.0.0", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "description": "library to do the things that 'npm version' does", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmversion" }, "author": "GitHub Inc.", "license": "ISC", "scripts": { "lint": "npm run eslint", "test": "tap", "posttest": "npm run lint", "snap": "tap", "postlint": "template-oss-check", "lintfix": "npm run eslint -- --fix", "template-oss-apply": "template-oss-apply --force", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" }, "tap": { "coverage-map": "map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "devDependencies": { "@npmcli/eslint-config": "^5.0.1", "@npmcli/template-oss": "4.23.6", "require-inject": "^1.4.4", "tap": "^16.3.8" }, "dependencies": { "@npmcli/git": "^6.0.1", "@npmcli/run-script": "^9.0.1", "json-parse-even-better-errors": "^4.0.0", "proc-log": "^5.0.0", "semver": "^7.3.7" }, "engines": { "node": "^20.17.0 || >=22.9.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.6", "content": "../../scripts/template-oss/index.js" } } The ISC License Copyright (c) 2010-2023 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. "use strict"; /** * @module LRUCache */ Object.defineProperty(exports, "__esModule", { value: true }); exports.LRUCache = void 0; const perf = typeof performance === 'object' && performance && typeof performance.now === 'function' ? performance : Date; const warned = new Set(); /* c8 ignore start */ const PROCESS = (typeof process === 'object' && !!process ? process : {}); /* c8 ignore start */ const emitWarning = (msg, type, code, fn) => { typeof PROCESS.emitWarning === 'function' ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`); }; let AC = globalThis.AbortController; let AS = globalThis.AbortSignal; /* c8 ignore start */ if (typeof AC === 'undefined') { //@ts-ignore AS = class AbortSignal { onabort; _onabort = []; reason; aborted = false; addEventListener(_, fn) { this._onabort.push(fn); } }; //@ts-ignore AC = class AbortController { constructor() { warnACPolyfill(); } signal = new AS(); abort(reason) { if (this.signal.aborted) return; //@ts-ignore this.signal.reason = reason; //@ts-ignore this.signal.aborted = true; //@ts-ignore for (const fn of this.signal._onabort) { fn(reason); } this.signal.onabort?.(reason); } }; let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; const warnACPolyfill = () => { if (!printACPolyfillWarning) return; printACPolyfillWarning = false; emitWarning('AbortController is not defined. If using lru-cache in ' + 'node 14, load an AbortController polyfill from the ' + '`node-abort-controller` package. A minimal polyfill is ' + 'provided for use by LRUCache.fetch(), but it should not be ' + 'relied upon in other contexts (eg, passing it to other APIs that ' + 'use AbortController/AbortSignal might have undesirable effects). ' + 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill); }; } /* c8 ignore stop */ const shouldWarn = (code) => !warned.has(code); const TYPE = Symbol('type'); const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); /* c8 ignore start */ // This is a little bit ridiculous, tbh. // The maximum array length is 2^32-1 or thereabouts on most JS impls. // And well before that point, you're caching the entire world, I mean, // that's ~32GB of just integers for the next/prev links, plus whatever // else to hold that many keys and values. Just filling the memory with // zeroes at init time is brutal when you get that big. // But why not be complete? // Maybe in the future, these limits will have expanded. const getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null; /* c8 ignore stop */ class ZeroArray extends Array { constructor(size) { super(size); this.fill(0); } } class Stack { heap; length; // private constructor static #constructing = false; static create(max) { const HeapCls = getUintArray(max); if (!HeapCls) return []; Stack.#constructing = true; const s = new Stack(max, HeapCls); Stack.#constructing = false; return s; } constructor(max, HeapCls) { /* c8 ignore start */ if (!Stack.#constructing) { throw new TypeError('instantiate Stack using Stack.create(n)'); } /* c8 ignore stop */ this.heap = new HeapCls(max); this.length = 0; } push(n) { this.heap[this.length++] = n; } pop() { return this.heap[--this.length]; } } /** * Default export, the thing you're using this module to get. * * The `K` and `V` types define the key and value types, respectively. The * optional `FC` type defines the type of the `context` object passed to * `cache.fetch()` and `cache.memo()`. * * Keys and values **must not** be `null` or `undefined`. * * All properties from the options object (with the exception of `max`, * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are * added as normal public members. (The listed options are read-only getters.) * * Changing any of these will alter the defaults for subsequent method calls. */ class LRUCache { // options that cannot be changed without disaster #max; #maxSize; #dispose; #disposeAfter; #fetchMethod; #memoMethod; /** * {@link LRUCache.OptionsBase.ttl} */ ttl; /** * {@link LRUCache.OptionsBase.ttlResolution} */ ttlResolution; /** * {@link LRUCache.OptionsBase.ttlAutopurge} */ ttlAutopurge; /** * {@link LRUCache.OptionsBase.updateAgeOnGet} */ updateAgeOnGet; /** * {@link LRUCache.OptionsBase.updateAgeOnHas} */ updateAgeOnHas; /** * {@link LRUCache.OptionsBase.allowStale} */ allowStale; /** * {@link LRUCache.OptionsBase.noDisposeOnSet} */ noDisposeOnSet; /** * {@link LRUCache.OptionsBase.noUpdateTTL} */ noUpdateTTL; /** * {@link LRUCache.OptionsBase.maxEntrySize} */ maxEntrySize; /** * {@link LRUCache.OptionsBase.sizeCalculation} */ sizeCalculation; /** * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} */ noDeleteOnFetchRejection; /** * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} */ noDeleteOnStaleGet; /** * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} */ allowStaleOnFetchAbort; /** * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} */ allowStaleOnFetchRejection; /** * {@link LRUCache.OptionsBase.ignoreFetchAbort} */ ignoreFetchAbort; // computed properties #size; #calculatedSize; #keyMap; #keyList; #valList; #next; #prev; #head; #tail; #free; #disposed; #sizes; #starts; #ttls; #hasDispose; #hasFetchMethod; #hasDisposeAfter; /** * Do not call this method unless you need to inspect the * inner workings of the cache. If anything returned by this * object is modified in any way, strange breakage may occur. * * These fields are private for a reason! * * @internal */ static unsafeExposeInternals(c) { return { // properties starts: c.#starts, ttls: c.#ttls, sizes: c.#sizes, keyMap: c.#keyMap, keyList: c.#keyList, valList: c.#valList, next: c.#next, prev: c.#prev, get head() { return c.#head; }, get tail() { return c.#tail; }, free: c.#free, // methods isBackgroundFetch: (p) => c.#isBackgroundFetch(p), backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), moveToTail: (index) => c.#moveToTail(index), indexes: (options) => c.#indexes(options), rindexes: (options) => c.#rindexes(options), isStale: (index) => c.#isStale(index), }; } // Protected read-only members /** * {@link LRUCache.OptionsBase.max} (read-only) */ get max() { return this.#max; } /** * {@link LRUCache.OptionsBase.maxSize} (read-only) */ get maxSize() { return this.#maxSize; } /** * The total computed size of items in the cache (read-only) */ get calculatedSize() { return this.#calculatedSize; } /** * The number of items stored in the cache (read-only) */ get size() { return this.#size; } /** * {@link LRUCache.OptionsBase.fetchMethod} (read-only) */ get fetchMethod() { return this.#fetchMethod; } get memoMethod() { return this.#memoMethod; } /** * {@link LRUCache.OptionsBase.dispose} (read-only) */ get dispose() { return this.#dispose; } /** * {@link LRUCache.OptionsBase.disposeAfter} (read-only) */ get disposeAfter() { return this.#disposeAfter; } constructor(options) { const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; if (max !== 0 && !isPosInt(max)) { throw new TypeError('max option must be a nonnegative integer'); } const UintArray = max ? getUintArray(max) : Array; if (!UintArray) { throw new Error('invalid max value: ' + max); } this.#max = max; this.#maxSize = maxSize; this.maxEntrySize = maxEntrySize || this.#maxSize; this.sizeCalculation = sizeCalculation; if (this.sizeCalculation) { if (!this.#maxSize && !this.maxEntrySize) { throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize'); } if (typeof this.sizeCalculation !== 'function') { throw new TypeError('sizeCalculation set to non-function'); } } if (memoMethod !== undefined && typeof memoMethod !== 'function') { throw new TypeError('memoMethod must be a function if defined'); } this.#memoMethod = memoMethod; if (fetchMethod !== undefined && typeof fetchMethod !== 'function') { throw new TypeError('fetchMethod must be a function if specified'); } this.#fetchMethod = fetchMethod; this.#hasFetchMethod = !!fetchMethod; this.#keyMap = new Map(); this.#keyList = new Array(max).fill(undefined); this.#valList = new Array(max).fill(undefined); this.#next = new UintArray(max); this.#prev = new UintArray(max); this.#head = 0; this.#tail = 0; this.#free = Stack.create(max); this.#size = 0; this.#calculatedSize = 0; if (typeof dispose === 'function') { this.#dispose = dispose; } if (typeof disposeAfter === 'function') { this.#disposeAfter = disposeAfter; this.#disposed = []; } else { this.#disposeAfter = undefined; this.#disposed = undefined; } this.#hasDispose = !!this.#dispose; this.#hasDisposeAfter = !!this.#disposeAfter; this.noDisposeOnSet = !!noDisposeOnSet; this.noUpdateTTL = !!noUpdateTTL; this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection; this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection; this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort; this.ignoreFetchAbort = !!ignoreFetchAbort; // NB: maxEntrySize is set to maxSize if it's set if (this.maxEntrySize !== 0) { if (this.#maxSize !== 0) { if (!isPosInt(this.#maxSize)) { throw new TypeError('maxSize must be a positive integer if specified'); } } if (!isPosInt(this.maxEntrySize)) { throw new TypeError('maxEntrySize must be a positive integer if specified'); } this.#initializeSizeTracking(); } this.allowStale = !!allowStale; this.noDeleteOnStaleGet = !!noDeleteOnStaleGet; this.updateAgeOnGet = !!updateAgeOnGet; this.updateAgeOnHas = !!updateAgeOnHas; this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1; this.ttlAutopurge = !!ttlAutopurge; this.ttl = ttl || 0; if (this.ttl) { if (!isPosInt(this.ttl)) { throw new TypeError('ttl must be a positive integer if specified'); } this.#initializeTTLTracking(); } // do not allow completely unbounded caches if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { throw new TypeError('At least one of max, maxSize, or ttl is required'); } if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { const code = 'LRU_CACHE_UNBOUNDED'; if (shouldWarn(code)) { warned.add(code); const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + 'result in unbounded memory consumption.'; emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); } } } /** * Return the number of ms left in the item's TTL. If item is not in cache, * returns `0`. Returns `Infinity` if item is in cache without a defined TTL. */ getRemainingTTL(key) { return this.#keyMap.has(key) ? Infinity : 0; } #initializeTTLTracking() { const ttls = new ZeroArray(this.#max); const starts = new ZeroArray(this.#max); this.#ttls = ttls; this.#starts = starts; this.#setItemTTL = (index, ttl, start = perf.now()) => { starts[index] = ttl !== 0 ? start : 0; ttls[index] = ttl; if (ttl !== 0 && this.ttlAutopurge) { const t = setTimeout(() => { if (this.#isStale(index)) { this.#delete(this.#keyList[index], 'expire'); } }, ttl + 1); // unref() not supported on all platforms /* c8 ignore start */ if (t.unref) { t.unref(); } /* c8 ignore stop */ } }; this.#updateItemAge = index => { starts[index] = ttls[index] !== 0 ? perf.now() : 0; }; this.#statusTTL = (status, index) => { if (ttls[index]) { const ttl = ttls[index]; const start = starts[index]; /* c8 ignore next */ if (!ttl || !start) return; status.ttl = ttl; status.start = start; status.now = cachedNow || getNow(); const age = status.now - start; status.remainingTTL = ttl - age; } }; // debounce calls to perf.now() to 1s so we're not hitting // that costly call repeatedly. let cachedNow = 0; const getNow = () => { const n = perf.now(); if (this.ttlResolution > 0) { cachedNow = n; const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); // not available on all platforms /* c8 ignore start */ if (t.unref) { t.unref(); } /* c8 ignore stop */ } return n; }; this.getRemainingTTL = key => { const index = this.#keyMap.get(key); if (index === undefined) { return 0; } const ttl = ttls[index]; const start = starts[index]; if (!ttl || !start) { return Infinity; } const age = (cachedNow || getNow()) - start; return ttl - age; }; this.#isStale = index => { const s = starts[index]; const t = ttls[index]; return !!t && !!s && (cachedNow || getNow()) - s > t; }; } // conditionally set private methods related to TTL #updateItemAge = () => { }; #statusTTL = () => { }; #setItemTTL = () => { }; /* c8 ignore stop */ #isStale = () => false; #initializeSizeTracking() { const sizes = new ZeroArray(this.#max); this.#calculatedSize = 0; this.#sizes = sizes; this.#removeItemSize = index => { this.#calculatedSize -= sizes[index]; sizes[index] = 0; }; this.#requireSize = (k, v, size, sizeCalculation) => { // provisionally accept background fetches. // actual value size will be checked when they return. if (this.#isBackgroundFetch(v)) { return 0; } if (!isPosInt(size)) { if (sizeCalculation) { if (typeof sizeCalculation !== 'function') { throw new TypeError('sizeCalculation must be a function'); } size = sizeCalculation(v, k); if (!isPosInt(size)) { throw new TypeError('sizeCalculation return invalid (expect positive integer)'); } } else { throw new TypeError('invalid size value (must be positive integer). ' + 'When maxSize or maxEntrySize is used, sizeCalculation ' + 'or size must be set.'); } } return size; }; this.#addItemSize = (index, size, status) => { sizes[index] = size; if (this.#maxSize) { const maxSize = this.#maxSize - sizes[index]; while (this.#calculatedSize > maxSize) { this.#evict(true); } } this.#calculatedSize += sizes[index]; if (status) { status.entrySize = size; status.totalCalculatedSize = this.#calculatedSize; } }; } #removeItemSize = _i => { }; #addItemSize = (_i, _s, _st) => { }; #requireSize = (_k, _v, size, sizeCalculation) => { if (size || sizeCalculation) { throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache'); } return 0; }; *#indexes({ allowStale = this.allowStale } = {}) { if (this.#size) { for (let i = this.#tail; true;) { if (!this.#isValidIndex(i)) { break; } if (allowStale || !this.#isStale(i)) { yield i; } if (i === this.#head) { break; } else { i = this.#prev[i]; } } } } *#rindexes({ allowStale = this.allowStale } = {}) { if (this.#size) { for (let i = this.#head; true;) { if (!this.#isValidIndex(i)) { break; } if (allowStale || !this.#isStale(i)) { yield i; } if (i === this.#tail) { break; } else { i = this.#next[i]; } } } } #isValidIndex(index) { return (index !== undefined && this.#keyMap.get(this.#keyList[index]) === index); } /** * Return a generator yielding `[key, value]` pairs, * in order from most recently used to least recently used. */ *entries() { for (const i of this.#indexes()) { if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield [this.#keyList[i], this.#valList[i]]; } } } /** * Inverse order version of {@link LRUCache.entries} * * Return a generator yielding `[key, value]` pairs, * in order from least recently used to most recently used. */ *rentries() { for (const i of this.#rindexes()) { if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield [this.#keyList[i], this.#valList[i]]; } } } /** * Return a generator yielding the keys in the cache, * in order from most recently used to least recently used. */ *keys() { for (const i of this.#indexes()) { const k = this.#keyList[i]; if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } } /** * Inverse order version of {@link LRUCache.keys} * * Return a generator yielding the keys in the cache, * in order from least recently used to most recently used. */ *rkeys() { for (const i of this.#rindexes()) { const k = this.#keyList[i]; if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } } /** * Return a generator yielding the values in the cache, * in order from most recently used to least recently used. */ *values() { for (const i of this.#indexes()) { const v = this.#valList[i]; if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } } /** * Inverse order version of {@link LRUCache.values} * * Return a generator yielding the values in the cache, * in order from least recently used to most recently used. */ *rvalues() { for (const i of this.#rindexes()) { const v = this.#valList[i]; if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } } /** * Iterating over the cache itself yields the same results as * {@link LRUCache.entries} */ [Symbol.iterator]() { return this.entries(); } /** * A String value that is used in the creation of the default string * description of an object. Called by the built-in method * `Object.prototype.toString`. */ [Symbol.toStringTag] = 'LRUCache'; /** * Find a value for which the supplied fn method returns a truthy value, * similar to `Array.find()`. fn is called as `fn(value, key, cache)`. */ find(fn, getOptions = {}) { for (const i of this.#indexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; if (fn(value, this.#keyList[i], this)) { return this.get(this.#keyList[i], getOptions); } } } /** * Call the supplied function on each item in the cache, in order from most * recently used to least recently used. * * `fn` is called as `fn(value, key, cache)`. * * If `thisp` is provided, function will be called in the `this`-context of * the provided object, or the cache if no `thisp` object is provided. * * Does not update age or recenty of use, or iterate over stale values. */ forEach(fn, thisp = this) { for (const i of this.#indexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); } } /** * The same as {@link LRUCache.forEach} but items are iterated over in * reverse order. (ie, less recently used items are iterated over first.) */ rforEach(fn, thisp = this) { for (const i of this.#rindexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); } } /** * Delete any stale entries. Returns true if anything was removed, * false otherwise. */ purgeStale() { let deleted = false; for (const i of this.#rindexes({ allowStale: true })) { if (this.#isStale(i)) { this.#delete(this.#keyList[i], 'expire'); deleted = true; } } return deleted; } /** * Get the extended info about a given entry, to get its value, size, and * TTL info simultaneously. Returns `undefined` if the key is not present. * * Unlike {@link LRUCache#dump}, which is designed to be portable and survive * serialization, the `start` value is always the current timestamp, and the * `ttl` is a calculated remaining time to live (negative if expired). * * Always returns stale values, if their info is found in the cache, so be * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) * if relevant. */ info(key) { const i = this.#keyMap.get(key); if (i === undefined) return undefined; const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) return undefined; const entry = { value }; if (this.#ttls && this.#starts) { const ttl = this.#ttls[i]; const start = this.#starts[i]; if (ttl && start) { const remain = ttl - (perf.now() - start); entry.ttl = remain; entry.start = Date.now(); } } if (this.#sizes) { entry.size = this.#sizes[i]; } return entry; } /** * Return an array of [key, {@link LRUCache.Entry}] tuples which can be * passed to {@link LRLUCache#load}. * * The `start` fields are calculated relative to a portable `Date.now()` * timestamp, even if `performance.now()` is available. * * Stale entries are always included in the `dump`, even if * {@link LRUCache.OptionsBase.allowStale} is false. * * Note: this returns an actual array, not a generator, so it can be more * easily passed around. */ dump() { const arr = []; for (const i of this.#indexes({ allowStale: true })) { const key = this.#keyList[i]; const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined || key === undefined) continue; const entry = { value }; if (this.#ttls && this.#starts) { entry.ttl = this.#ttls[i]; // always dump the start relative to a portable timestamp // it's ok for this to be a bit slow, it's a rare operation. const age = perf.now() - this.#starts[i]; entry.start = Math.floor(Date.now() - age); } if (this.#sizes) { entry.size = this.#sizes[i]; } arr.unshift([key, entry]); } return arr; } /** * Reset the cache and load in the items in entries in the order listed. * * The shape of the resulting cache may be different if the same options are * not used in both caches. * * The `start` fields are assumed to be calculated relative to a portable * `Date.now()` timestamp, even if `performance.now()` is available. */ load(arr) { this.clear(); for (const [key, entry] of arr) { if (entry.start) { // entry.start is a portable timestamp, but we may be using // node's performance.now(), so calculate the offset, so that // we get the intended remaining TTL, no matter how long it's // been on ice. // // it's ok for this to be a bit slow, it's a rare operation. const age = Date.now() - entry.start; entry.start = perf.now() - age; } this.set(key, entry.value, entry); } } /** * Add a value to the cache. * * Note: if `undefined` is specified as a value, this is an alias for * {@link LRUCache#delete} * * Fields on the {@link LRUCache.SetOptions} options param will override * their corresponding values in the constructor options for the scope * of this single `set()` operation. * * If `start` is provided, then that will set the effective start * time for the TTL calculation. Note that this must be a previous * value of `performance.now()` if supported, or a previous value of * `Date.now()` if not. * * Options object may also include `size`, which will prevent * calling the `sizeCalculation` function and just use the specified * number if it is a positive integer, and `noDisposeOnSet` which * will prevent calling a `dispose` function in the case of * overwrites. * * If the `size` (or return value of `sizeCalculation`) for a given * entry is greater than `maxEntrySize`, then the item will not be * added to the cache. * * Will update the recency of the entry. * * If the value is `undefined`, then this is an alias for * `cache.delete(key)`. `undefined` is never stored in the cache. */ set(k, v, setOptions = {}) { if (v === undefined) { this.delete(k); return this; } const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; let { noUpdateTTL = this.noUpdateTTL } = setOptions; const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); // if the item doesn't fit, don't do anything // NB: maxEntrySize set to maxSize by default if (this.maxEntrySize && size > this.maxEntrySize) { if (status) { status.set = 'miss'; status.maxEntrySizeExceeded = true; } // have to delete, in case something is there already. this.#delete(k, 'set'); return this; } let index = this.#size === 0 ? undefined : this.#keyMap.get(k); if (index === undefined) { // addition index = (this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size); this.#keyList[index] = k; this.#valList[index] = v; this.#keyMap.set(k, index); this.#next[this.#tail] = index; this.#prev[index] = this.#tail; this.#tail = index; this.#size++; this.#addItemSize(index, size, status); if (status) status.set = 'add'; noUpdateTTL = false; } else { // update this.#moveToTail(index); const oldVal = this.#valList[index]; if (v !== oldVal) { if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { oldVal.__abortController.abort(new Error('replaced')); const { __staleWhileFetching: s } = oldVal; if (s !== undefined && !noDisposeOnSet) { if (this.#hasDispose) { this.#dispose?.(s, k, 'set'); } if (this.#hasDisposeAfter) { this.#disposed?.push([s, k, 'set']); } } } else if (!noDisposeOnSet) { if (this.#hasDispose) { this.#dispose?.(oldVal, k, 'set'); } if (this.#hasDisposeAfter) { this.#disposed?.push([oldVal, k, 'set']); } } this.#removeItemSize(index); this.#addItemSize(index, size, status); this.#valList[index] = v; if (status) { status.set = 'replace'; const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal; if (oldValue !== undefined) status.oldValue = oldValue; } } else if (status) { status.set = 'update'; } } if (ttl !== 0 && !this.#ttls) { this.#initializeTTLTracking(); } if (this.#ttls) { if (!noUpdateTTL) { this.#setItemTTL(index, ttl, start); } if (status) this.#statusTTL(status, index); } if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } return this; } /** * Evict the least recently used item, returning its value or * `undefined` if cache is empty. */ pop() { try { while (this.#size) { const val = this.#valList[this.#head]; this.#evict(true); if (this.#isBackgroundFetch(val)) { if (val.__staleWhileFetching) { return val.__staleWhileFetching; } } else if (val !== undefined) { return val; } } } finally { if (this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } } } #evict(free) { const head = this.#head; const k = this.#keyList[head]; const v = this.#valList[head]; if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('evicted')); } else if (this.#hasDispose || this.#hasDisposeAfter) { if (this.#hasDispose) { this.#dispose?.(v, k, 'evict'); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, 'evict']); } } this.#removeItemSize(head); // if we aren't about to use the index, then null these out if (free) { this.#keyList[head] = undefined; this.#valList[head] = undefined; this.#free.push(head); } if (this.#size === 1) { this.#head = this.#tail = 0; this.#free.length = 0; } else { this.#head = this.#next[head]; } this.#keyMap.delete(k); this.#size--; return head; } /** * Check if a key is in the cache, without updating the recency of use. * Will return false if the item is stale, even though it is technically * in the cache. * * Check if a key is in the cache, without updating the recency of * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set * to `true` in either the options or the constructor. * * Will return `false` if the item is stale, even though it is technically in * the cache. The difference can be determined (if it matters) by using a * `status` argument, and inspecting the `has` field. * * Will not update item age unless * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. */ has(k, hasOptions = {}) { const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; const index = this.#keyMap.get(k); if (index !== undefined) { const v = this.#valList[index]; if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === undefined) { return false; } if (!this.#isStale(index)) { if (updateAgeOnHas) { this.#updateItemAge(index); } if (status) { status.has = 'hit'; this.#statusTTL(status, index); } return true; } else if (status) { status.has = 'stale'; this.#statusTTL(status, index); } } else if (status) { status.has = 'miss'; } return false; } /** * Like {@link LRUCache#get} but doesn't update recency or delete stale * items. * * Returns `undefined` if the item is stale, unless * {@link LRUCache.OptionsBase.allowStale} is set. */ peek(k, peekOptions = {}) { const { allowStale = this.allowStale } = peekOptions; const index = this.#keyMap.get(k); if (index === undefined || (!allowStale && this.#isStale(index))) { return; } const v = this.#valList[index]; // either stale and allowed, or forcing a refresh of non-stale value return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; } #backgroundFetch(k, index, options, context) { const v = index === undefined ? undefined : this.#valList[index]; if (this.#isBackgroundFetch(v)) { return v; } const ac = new AC(); const { signal } = options; // when/if our AC signals, then stop listening to theirs. signal?.addEventListener('abort', () => ac.abort(signal.reason), { signal: ac.signal, }); const fetchOpts = { signal: ac.signal, options, context, }; const cb = (v, updateCache = false) => { const { aborted } = ac.signal; const ignoreAbort = options.ignoreFetchAbort && v !== undefined; if (options.status) { if (aborted && !updateCache) { options.status.fetchAborted = true; options.status.fetchError = ac.signal.reason; if (ignoreAbort) options.status.fetchAbortIgnored = true; } else { options.status.fetchResolved = true; } } if (aborted && !ignoreAbort && !updateCache) { return fetchFail(ac.signal.reason); } // either we didn't abort, and are still here, or we did, and ignored const bf = p; if (this.#valList[index] === p) { if (v === undefined) { if (bf.__staleWhileFetching) { this.#valList[index] = bf.__staleWhileFetching; } else { this.#delete(k, 'fetch'); } } else { if (options.status) options.status.fetchUpdated = true; this.set(k, v, fetchOpts.options); } } return v; }; const eb = (er) => { if (options.status) { options.status.fetchRejected = true; options.status.fetchError = er; } return fetchFail(er); }; const fetchFail = (er) => { const { aborted } = ac.signal; const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; const noDelete = allowStale || options.noDeleteOnFetchRejection; const bf = p; if (this.#valList[index] === p) { // if we allow stale on fetch rejections, then we need to ensure that // the stale value is not removed from the cache when the fetch fails. const del = !noDelete || bf.__staleWhileFetching === undefined; if (del) { this.#delete(k, 'fetch'); } else if (!allowStaleAborted) { // still replace the *promise* with the stale value, // since we are done with the promise at this point. // leave it untouched if we're still waiting for an // aborted background fetch that hasn't yet returned. this.#valList[index] = bf.__staleWhileFetching; } } if (allowStale) { if (options.status && bf.__staleWhileFetching !== undefined) { options.status.returnedStale = true; } return bf.__staleWhileFetching; } else if (bf.__returned === bf) { throw er; } }; const pcall = (res, rej) => { const fmp = this.#fetchMethod?.(k, v, fetchOpts); if (fmp && fmp instanceof Promise) { fmp.then(v => res(v === undefined ? undefined : v), rej); } // ignored, we go until we finish, regardless. // defer check until we are actually aborting, // so fetchMethod can override. ac.signal.addEventListener('abort', () => { if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) { res(undefined); // when it eventually resolves, update the cache. if (options.allowStaleOnFetchAbort) { res = v => cb(v, true); } } }); }; if (options.status) options.status.fetchDispatched = true; const p = new Promise(pcall).then(cb, eb); const bf = Object.assign(p, { __abortController: ac, __staleWhileFetching: v, __returned: undefined, }); if (index === undefined) { // internal, don't expose status. this.set(k, bf, { ...fetchOpts.options, status: undefined }); index = this.#keyMap.get(k); } else { this.#valList[index] = bf; } return bf; } #isBackgroundFetch(p) { if (!this.#hasFetchMethod) return false; const b = p; return (!!b && b instanceof Promise && b.hasOwnProperty('__staleWhileFetching') && b.__abortController instanceof AC); } async fetch(k, fetchOptions = {}) { const { // get options allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, // set options ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, // fetch exclusive options noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; if (!this.#hasFetchMethod) { if (status) status.fetch = 'get'; return this.get(k, { allowStale, updateAgeOnGet, noDeleteOnStaleGet, status, }); } const options = { allowStale, updateAgeOnGet, noDeleteOnStaleGet, ttl, noDisposeOnSet, size, sizeCalculation, noUpdateTTL, noDeleteOnFetchRejection, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, status, signal, }; let index = this.#keyMap.get(k); if (index === undefined) { if (status) status.fetch = 'miss'; const p = this.#backgroundFetch(k, index, options, context); return (p.__returned = p); } else { // in cache, maybe already fetching const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { const stale = allowStale && v.__staleWhileFetching !== undefined; if (status) { status.fetch = 'inflight'; if (stale) status.returnedStale = true; } return stale ? v.__staleWhileFetching : (v.__returned = v); } // if we force a refresh, that means do NOT serve the cached value, // unless we are already in the process of refreshing the cache. const isStale = this.#isStale(index); if (!forceRefresh && !isStale) { if (status) status.fetch = 'hit'; this.#moveToTail(index); if (updateAgeOnGet) { this.#updateItemAge(index); } if (status) this.#statusTTL(status, index); return v; } // ok, it is stale or a forced refresh, and not already fetching. // refresh the cache. const p = this.#backgroundFetch(k, index, options, context); const hasStale = p.__staleWhileFetching !== undefined; const staleVal = hasStale && allowStale; if (status) { status.fetch = isStale ? 'stale' : 'refresh'; if (staleVal && isStale) status.returnedStale = true; } return staleVal ? p.__staleWhileFetching : (p.__returned = p); } } async forceFetch(k, fetchOptions = {}) { const v = await this.fetch(k, fetchOptions); if (v === undefined) throw new Error('fetch() returned undefined'); return v; } memo(k, memoOptions = {}) { const memoMethod = this.#memoMethod; if (!memoMethod) { throw new Error('no memoMethod provided to constructor'); } const { context, forceRefresh, ...options } = memoOptions; const v = this.get(k, options); if (!forceRefresh && v !== undefined) return v; const vv = memoMethod(k, v, { options, context, }); this.set(k, vv, options); return vv; } /** * Return a value from the cache. Will update the recency of the cache * entry found. * * If the key is not found, get() will return `undefined`. */ get(k, getOptions = {}) { const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; const index = this.#keyMap.get(k); if (index !== undefined) { const value = this.#valList[index]; const fetching = this.#isBackgroundFetch(value); if (status) this.#statusTTL(status, index); if (this.#isStale(index)) { if (status) status.get = 'stale'; // delete only if not an in-flight background fetch if (!fetching) { if (!noDeleteOnStaleGet) { this.#delete(k, 'expire'); } if (status && allowStale) status.returnedStale = true; return allowStale ? value : undefined; } else { if (status && allowStale && value.__staleWhileFetching !== undefined) { status.returnedStale = true; } return allowStale ? value.__staleWhileFetching : undefined; } } else { if (status) status.get = 'hit'; // if we're currently fetching it, we don't actually have it yet // it's not stale, which means this isn't a staleWhileRefetching. // If it's not stale, and fetching, AND has a __staleWhileFetching // value, then that means the user fetched with {forceRefresh:true}, // so it's safe to return that value. if (fetching) { return value.__staleWhileFetching; } this.#moveToTail(index); if (updateAgeOnGet) { this.#updateItemAge(index); } return value; } } else if (status) { status.get = 'miss'; } } #connect(p, n) { this.#prev[n] = p; this.#next[p] = n; } #moveToTail(index) { // if tail already, nothing to do // if head, move head to next[index] // else // move next[prev[index]] to next[index] (head has no prev) // move prev[next[index]] to prev[index] // prev[index] = tail // next[tail] = index // tail = index if (index !== this.#tail) { if (index === this.#head) { this.#head = this.#next[index]; } else { this.#connect(this.#prev[index], this.#next[index]); } this.#connect(this.#tail, index); this.#tail = index; } } /** * Deletes a key out of the cache. * * Returns true if the key was deleted, false otherwise. */ delete(k) { return this.#delete(k, 'delete'); } #delete(k, reason) { let deleted = false; if (this.#size !== 0) { const index = this.#keyMap.get(k); if (index !== undefined) { deleted = true; if (this.#size === 1) { this.#clear(reason); } else { this.#removeItemSize(index); const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('deleted')); } else if (this.#hasDispose || this.#hasDisposeAfter) { if (this.#hasDispose) { this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, reason]); } } this.#keyMap.delete(k); this.#keyList[index] = undefined; this.#valList[index] = undefined; if (index === this.#tail) { this.#tail = this.#prev[index]; } else if (index === this.#head) { this.#head = this.#next[index]; } else { const pi = this.#prev[index]; this.#next[pi] = this.#next[index]; const ni = this.#next[index]; this.#prev[ni] = this.#prev[index]; } this.#size--; this.#free.push(index); } } } if (this.#hasDisposeAfter && this.#disposed?.length) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } return deleted; } /** * Clear the cache entirely, throwing away all values. */ clear() { return this.#clear('delete'); } #clear(reason) { for (const index of this.#rindexes({ allowStale: true })) { const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('deleted')); } else { const k = this.#keyList[index]; if (this.#hasDispose) { this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, reason]); } } } this.#keyMap.clear(); this.#valList.fill(undefined); this.#keyList.fill(undefined); if (this.#ttls && this.#starts) { this.#ttls.fill(0); this.#starts.fill(0); } if (this.#sizes) { this.#sizes.fill(0); } this.#head = 0; this.#tail = 0; this.#free.length = 0; this.#calculatedSize = 0; this.#size = 0; if (this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } } } exports.LRUCache = LRUCache; //# sourceMappingURL=index.js.map"use strict";var G=(l,t,e)=>{if(!t.has(l))throw TypeError("Cannot "+e)};var j=(l,t,e)=>(G(l,t,"read from private field"),e?e.call(l):t.get(l)),I=(l,t,e)=>{if(t.has(l))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(l):t.set(l,e)},x=(l,t,e,i)=>(G(l,t,"write to private field"),i?i.call(l,e):t.set(l,e),e);Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var T=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,P=new Set,U=typeof process=="object"&&process?process:{},H=(l,t,e,i)=>{typeof U.emitWarning=="function"?U.emitWarning(l,t,e,i):console.error(`[${e}] ${t}: ${l}`)},D=globalThis.AbortController,N=globalThis.AbortSignal;if(typeof D>"u"){N=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,s){this._onabort.push(s)}},D=class{constructor(){t()}signal=new N;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i)}}};let l=U.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{l&&(l=!1,H("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var V=l=>!P.has(l),Y=Symbol("type"),A=l=>l&&l===Math.floor(l)&&l>0&&isFinite(l),k=l=>A(l)?l<=Math.pow(2,8)?Uint8Array:l<=Math.pow(2,16)?Uint16Array:l<=Math.pow(2,32)?Uint32Array:l<=Number.MAX_SAFE_INTEGER?E:null:null,E=class extends Array{constructor(t){super(t),this.fill(0)}},v,O=class{heap;length;static create(t){let e=k(t);if(!e)return[];x(O,v,!0);let i=new O(t,e);return x(O,v,!1),i}constructor(t,e){if(!j(O,v))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},W=O;v=new WeakMap,I(W,v,!1);var C=class{#g;#f;#p;#w;#R;#W;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#S;#s;#i;#t;#l;#c;#o;#h;#_;#r;#b;#m;#u;#y;#E;#a;static unsafeExposeInternals(t){return{starts:t.#m,ttls:t.#u,sizes:t.#b,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#c,get head(){return t.#o},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#x(e,i,s,n),moveToTail:e=>t.#C(e),indexes:e=>t.#A(e),rindexes:e=>t.#F(e),isStale:e=>t.#d(e)}}get max(){return this.#g}get maxSize(){return this.#f}get calculatedSize(){return this.#S}get size(){return this.#n}get fetchMethod(){return this.#R}get memoMethod(){return this.#W}get dispose(){return this.#p}get disposeAfter(){return this.#w}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:h,updateAgeOnHas:o,allowStale:r,dispose:g,disposeAfter:b,noDisposeOnSet:f,noUpdateTTL:u,maxSize:c=0,maxEntrySize:F=0,sizeCalculation:d,fetchMethod:S,memoMethod:a,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:m,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:_,ignoreFetchAbort:z}=t;if(e!==0&&!A(e))throw new TypeError("max option must be a nonnegative integer");let y=e?k(e):Array;if(!y)throw new Error("invalid max value: "+e);if(this.#g=e,this.#f=c,this.maxEntrySize=F||this.#f,this.sizeCalculation=d,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(a!==void 0&&typeof a!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#W=a,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#R=S,this.#E=!!S,this.#s=new Map,this.#i=new Array(e).fill(void 0),this.#t=new Array(e).fill(void 0),this.#l=new y(e),this.#c=new y(e),this.#o=0,this.#h=0,this.#_=W.create(e),this.#n=0,this.#S=0,typeof g=="function"&&(this.#p=g),typeof b=="function"?(this.#w=b,this.#r=[]):(this.#w=void 0,this.#r=void 0),this.#y=!!this.#p,this.#a=!!this.#w,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!p,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#f!==0&&!A(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!A(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#P()}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!m,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!o,this.ttlResolution=A(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!A(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#U()}if(this.#g===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#g&&!this.#f){let R="LRU_CACHE_UNBOUNDED";V(R)&&(P.add(R),H("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",R,C))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#U(){let t=new E(this.#g),e=new E(this.#g);this.#u=t,this.#m=e,this.#M=(n,h,o=T.now())=>{if(e[n]=h!==0?o:0,t[n]=h,h!==0&&this.ttlAutopurge){let r=setTimeout(()=>{this.#d(n)&&this.#T(this.#i[n],"expire")},h+1);r.unref&&r.unref()}},this.#v=n=>{e[n]=t[n]!==0?T.now():0},this.#O=(n,h)=>{if(t[h]){let o=t[h],r=e[h];if(!o||!r)return;n.ttl=o,n.start=r,n.now=i||s();let g=n.now-r;n.remainingTTL=o-g}};let i=0,s=()=>{let n=T.now();if(this.ttlResolution>0){i=n;let h=setTimeout(()=>i=0,this.ttlResolution);h.unref&&h.unref()}return n};this.getRemainingTTL=n=>{let h=this.#s.get(n);if(h===void 0)return 0;let o=t[h],r=e[h];if(!o||!r)return 1/0;let g=(i||s())-r;return o-g},this.#d=n=>{let h=e[n],o=t[n];return!!o&&!!h&&(i||s())-h>o}}#v=()=>{};#O=()=>{};#M=()=>{};#d=()=>!1;#P(){let t=new E(this.#g);this.#S=0,this.#b=t,this.#z=e=>{this.#S-=t[e],t[e]=0},this.#G=(e,i,s,n)=>{if(this.#e(i))return 0;if(!A(s))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!A(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#D=(e,i,s)=>{if(t[e]=i,this.#f){let n=this.#f-t[e];for(;this.#S>n;)this.#L(!0)}this.#S+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#S)}}#z=t=>{};#D=(t,e,i)=>{};#G=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;!(!this.#j(e)||((t||!this.#d(e))&&(yield e),e===this.#o));)e=this.#c[e]}*#F({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#o;!(!this.#j(e)||((t||!this.#d(e))&&(yield e),e===this.#h));)e=this.#l[e]}#j(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#A())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#F())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#A()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#F()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#A())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#F())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#i[i],this))return this.get(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#F()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#F({allowStale:!0}))this.#d(e)&&(this.#T(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#u&&this.#m){let h=this.#u[e],o=this.#m[e];if(h&&o){let r=h-(T.now()-o);n.ttl=r,n.start=Date.now()}}return this.#b&&(n.size=this.#b[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let i=this.#i[e],s=this.#t[e],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let h={value:n};if(this.#u&&this.#m){h.ttl=this.#u[e];let o=T.now()-this.#m[e];h.start=Math.floor(Date.now()-o)}this.#b&&(h.size=this.#b[e]),t.unshift([i,h])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=T.now()-s}this.set(e,i.value,i)}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:s=this.ttl,start:n,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:r}=i,{noUpdateTTL:g=this.noUpdateTTL}=i,b=this.#G(t,e,i.size||0,o);if(this.maxEntrySize&&b>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this.#T(t,"set"),this;let f=this.#n===0?void 0:this.#s.get(t);if(f===void 0)f=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#g?this.#L(!1):this.#n,this.#i[f]=t,this.#t[f]=e,this.#s.set(t,f),this.#l[this.#h]=f,this.#c[f]=this.#h,this.#h=f,this.#n++,this.#D(f,b,r),r&&(r.set="add"),g=!1;else{this.#C(f);let u=this.#t[f];if(e!==u){if(this.#E&&this.#e(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:c}=u;c!==void 0&&!h&&(this.#y&&this.#p?.(c,t,"set"),this.#a&&this.#r?.push([c,t,"set"]))}else h||(this.#y&&this.#p?.(u,t,"set"),this.#a&&this.#r?.push([u,t,"set"]));if(this.#z(f),this.#D(f,b,r),this.#t[f]=e,r){r.set="replace";let c=u&&this.#e(u)?u.__staleWhileFetching:u;c!==void 0&&(r.oldValue=c)}}else r&&(r.set="update")}if(s!==0&&!this.#u&&this.#U(),this.#u&&(g||this.#M(f,s,n),r&&this.#O(r,f)),!h&&this.#a&&this.#r){let u=this.#r,c;for(;c=u?.shift();)this.#w?.(...c)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#o];if(this.#L(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#a&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#w?.(...e)}}}#L(t){let e=this.#o,i=this.#i[e],s=this.#t[e];return this.#E&&this.#e(s)?s.__abortController.abort(new Error("evicted")):(this.#y||this.#a)&&(this.#y&&this.#p?.(s,i,"evict"),this.#a&&this.#r?.push([s,i,"evict"])),this.#z(e),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#o=this.#h=0,this.#_.length=0):this.#o=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let h=this.#t[n];if(this.#e(h)&&h.__staleWhileFetching===void 0)return!1;if(this.#d(n))s&&(s.has="stale",this.#O(s,n));else return i&&this.#v(n),s&&(s.has="hit",this.#O(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{allowStale:i=this.allowStale}=e,s=this.#s.get(t);if(s===void 0||!i&&this.#d(s))return;let n=this.#t[s];return this.#e(n)?n.__staleWhileFetching:n}#x(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let h=new D,{signal:o}=i;o?.addEventListener("abort",()=>h.abort(o.reason),{signal:h.signal});let r={signal:h.signal,options:i,context:s},g=(d,S=!1)=>{let{aborted:a}=h.signal,w=i.ignoreFetchAbort&&d!==void 0;if(i.status&&(a&&!S?(i.status.fetchAborted=!0,i.status.fetchError=h.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),a&&!w&&!S)return f(h.signal.reason);let m=c;return this.#t[e]===c&&(d===void 0?m.__staleWhileFetching?this.#t[e]=m.__staleWhileFetching:this.#T(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,d,r.options))),d},b=d=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=d),f(d)),f=d=>{let{aborted:S}=h.signal,a=S&&i.allowStaleOnFetchAbort,w=a||i.allowStaleOnFetchRejection,m=w||i.noDeleteOnFetchRejection,p=c;if(this.#t[e]===c&&(!m||p.__staleWhileFetching===void 0?this.#T(t,"fetch"):a||(this.#t[e]=p.__staleWhileFetching)),w)return i.status&&p.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),p.__staleWhileFetching;if(p.__returned===p)throw d},u=(d,S)=>{let a=this.#R?.(t,n,r);a&&a instanceof Promise&&a.then(w=>d(w===void 0?void 0:w),S),h.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(d(void 0),i.allowStaleOnFetchAbort&&(d=w=>g(w,!0)))})};i.status&&(i.status.fetchDispatched=!0);let c=new Promise(u).then(g,b),F=Object.assign(c,{__abortController:h,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.set(t,F,{...r.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=F,F}#e(t){if(!this.#E)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof D}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:r=0,sizeCalculation:g=this.sizeCalculation,noUpdateTTL:b=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:c=this.ignoreFetchAbort,allowStaleOnFetchAbort:F=this.allowStaleOnFetchAbort,context:d,forceRefresh:S=!1,status:a,signal:w}=e;if(!this.#E)return a&&(a.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let m={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:h,noDisposeOnSet:o,size:r,sizeCalculation:g,noUpdateTTL:b,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:F,ignoreFetchAbort:c,status:a,signal:w},p=this.#s.get(t);if(p===void 0){a&&(a.fetch="miss");let _=this.#x(t,p,m,d);return _.__returned=_}else{let _=this.#t[p];if(this.#e(_)){let M=i&&_.__staleWhileFetching!==void 0;return a&&(a.fetch="inflight",M&&(a.returnedStale=!0)),M?_.__staleWhileFetching:_.__returned=_}let z=this.#d(p);if(!S&&!z)return a&&(a.fetch="hit"),this.#C(p),s&&this.#v(p),a&&this.#O(a,p),_;let y=this.#x(t,p,m,d),L=y.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=z?"stale":"refresh",L&&z&&(a.returnedStale=!0)),L?y.__staleWhileFetching:y.__returned=y}}async forceFetch(t,e={}){let i=await this.fetch(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let i=this.#W;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:n,...h}=e,o=this.get(t,h);if(!n&&o!==void 0)return o;let r=i(t,o,{options:h,context:s});return this.set(t,r,h),r}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:h}=e,o=this.#s.get(t);if(o!==void 0){let r=this.#t[o],g=this.#e(r);return h&&this.#O(h,o),this.#d(o)?(h&&(h.get="stale"),g?(h&&i&&r.__staleWhileFetching!==void 0&&(h.returnedStale=!0),i?r.__staleWhileFetching:void 0):(n||this.#T(t,"expire"),h&&i&&(h.returnedStale=!0),i?r:void 0)):(h&&(h.get="hit"),g?r.__staleWhileFetching:(this.#C(o),s&&this.#v(o),r))}else h&&(h.get="miss")}#I(t,e){this.#c[e]=t,this.#l[t]=e}#C(t){t!==this.#h&&(t===this.#o?this.#o=this.#l[t]:this.#I(this.#c[t],this.#l[t]),this.#I(this.#h,t),this.#h=t)}delete(t){return this.#T(t,"delete")}#T(t,e){let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(i=!0,this.#n===1)this.#N(e);else{this.#z(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#y||this.#a)&&(this.#y&&this.#p?.(n,t,e),this.#a&&this.#r?.push([n,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#c[s];else if(s===this.#o)this.#o=this.#l[s];else{let h=this.#c[s];this.#l[h]=this.#l[s];let o=this.#l[s];this.#c[o]=this.#c[s]}this.#n--,this.#_.push(s)}}if(this.#a&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#w?.(...n)}return i}clear(){return this.#N("delete")}#N(t){for(let e of this.#F({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#y&&this.#p?.(i,s,t),this.#a&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#u&&this.#m&&(this.#u.fill(0),this.#m.fill(0)),this.#b&&this.#b.fill(0),this.#o=0,this.#h=0,this.#_.length=0,this.#S=0,this.#n=0,this.#a&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#w?.(...i)}}};exports.LRUCache=C; //# sourceMappingURL=index.min.js.map { "type": "commonjs" } /** * @module LRUCache */ const perf = typeof performance === 'object' && performance && typeof performance.now === 'function' ? performance : Date; const warned = new Set(); /* c8 ignore start */ const PROCESS = (typeof process === 'object' && !!process ? process : {}); /* c8 ignore start */ const emitWarning = (msg, type, code, fn) => { typeof PROCESS.emitWarning === 'function' ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`); }; let AC = globalThis.AbortController; let AS = globalThis.AbortSignal; /* c8 ignore start */ if (typeof AC === 'undefined') { //@ts-ignore AS = class AbortSignal { onabort; _onabort = []; reason; aborted = false; addEventListener(_, fn) { this._onabort.push(fn); } }; //@ts-ignore AC = class AbortController { constructor() { warnACPolyfill(); } signal = new AS(); abort(reason) { if (this.signal.aborted) return; //@ts-ignore this.signal.reason = reason; //@ts-ignore this.signal.aborted = true; //@ts-ignore for (const fn of this.signal._onabort) { fn(reason); } this.signal.onabort?.(reason); } }; let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; const warnACPolyfill = () => { if (!printACPolyfillWarning) return; printACPolyfillWarning = false; emitWarning('AbortController is not defined. If using lru-cache in ' + 'node 14, load an AbortController polyfill from the ' + '`node-abort-controller` package. A minimal polyfill is ' + 'provided for use by LRUCache.fetch(), but it should not be ' + 'relied upon in other contexts (eg, passing it to other APIs that ' + 'use AbortController/AbortSignal might have undesirable effects). ' + 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill); }; } /* c8 ignore stop */ const shouldWarn = (code) => !warned.has(code); const TYPE = Symbol('type'); const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); /* c8 ignore start */ // This is a little bit ridiculous, tbh. // The maximum array length is 2^32-1 or thereabouts on most JS impls. // And well before that point, you're caching the entire world, I mean, // that's ~32GB of just integers for the next/prev links, plus whatever // else to hold that many keys and values. Just filling the memory with // zeroes at init time is brutal when you get that big. // But why not be complete? // Maybe in the future, these limits will have expanded. const getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null; /* c8 ignore stop */ class ZeroArray extends Array { constructor(size) { super(size); this.fill(0); } } class Stack { heap; length; // private constructor static #constructing = false; static create(max) { const HeapCls = getUintArray(max); if (!HeapCls) return []; Stack.#constructing = true; const s = new Stack(max, HeapCls); Stack.#constructing = false; return s; } constructor(max, HeapCls) { /* c8 ignore start */ if (!Stack.#constructing) { throw new TypeError('instantiate Stack using Stack.create(n)'); } /* c8 ignore stop */ this.heap = new HeapCls(max); this.length = 0; } push(n) { this.heap[this.length++] = n; } pop() { return this.heap[--this.length]; } } /** * Default export, the thing you're using this module to get. * * The `K` and `V` types define the key and value types, respectively. The * optional `FC` type defines the type of the `context` object passed to * `cache.fetch()` and `cache.memo()`. * * Keys and values **must not** be `null` or `undefined`. * * All properties from the options object (with the exception of `max`, * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are * added as normal public members. (The listed options are read-only getters.) * * Changing any of these will alter the defaults for subsequent method calls. */ export class LRUCache { // options that cannot be changed without disaster #max; #maxSize; #dispose; #disposeAfter; #fetchMethod; #memoMethod; /** * {@link LRUCache.OptionsBase.ttl} */ ttl; /** * {@link LRUCache.OptionsBase.ttlResolution} */ ttlResolution; /** * {@link LRUCache.OptionsBase.ttlAutopurge} */ ttlAutopurge; /** * {@link LRUCache.OptionsBase.updateAgeOnGet} */ updateAgeOnGet; /** * {@link LRUCache.OptionsBase.updateAgeOnHas} */ updateAgeOnHas; /** * {@link LRUCache.OptionsBase.allowStale} */ allowStale; /** * {@link LRUCache.OptionsBase.noDisposeOnSet} */ noDisposeOnSet; /** * {@link LRUCache.OptionsBase.noUpdateTTL} */ noUpdateTTL; /** * {@link LRUCache.OptionsBase.maxEntrySize} */ maxEntrySize; /** * {@link LRUCache.OptionsBase.sizeCalculation} */ sizeCalculation; /** * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} */ noDeleteOnFetchRejection; /** * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} */ noDeleteOnStaleGet; /** * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} */ allowStaleOnFetchAbort; /** * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} */ allowStaleOnFetchRejection; /** * {@link LRUCache.OptionsBase.ignoreFetchAbort} */ ignoreFetchAbort; // computed properties #size; #calculatedSize; #keyMap; #keyList; #valList; #next; #prev; #head; #tail; #free; #disposed; #sizes; #starts; #ttls; #hasDispose; #hasFetchMethod; #hasDisposeAfter; /** * Do not call this method unless you need to inspect the * inner workings of the cache. If anything returned by this * object is modified in any way, strange breakage may occur. * * These fields are private for a reason! * * @internal */ static unsafeExposeInternals(c) { return { // properties starts: c.#starts, ttls: c.#ttls, sizes: c.#sizes, keyMap: c.#keyMap, keyList: c.#keyList, valList: c.#valList, next: c.#next, prev: c.#prev, get head() { return c.#head; }, get tail() { return c.#tail; }, free: c.#free, // methods isBackgroundFetch: (p) => c.#isBackgroundFetch(p), backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), moveToTail: (index) => c.#moveToTail(index), indexes: (options) => c.#indexes(options), rindexes: (options) => c.#rindexes(options), isStale: (index) => c.#isStale(index), }; } // Protected read-only members /** * {@link LRUCache.OptionsBase.max} (read-only) */ get max() { return this.#max; } /** * {@link LRUCache.OptionsBase.maxSize} (read-only) */ get maxSize() { return this.#maxSize; } /** * The total computed size of items in the cache (read-only) */ get calculatedSize() { return this.#calculatedSize; } /** * The number of items stored in the cache (read-only) */ get size() { return this.#size; } /** * {@link LRUCache.OptionsBase.fetchMethod} (read-only) */ get fetchMethod() { return this.#fetchMethod; } get memoMethod() { return this.#memoMethod; } /** * {@link LRUCache.OptionsBase.dispose} (read-only) */ get dispose() { return this.#dispose; } /** * {@link LRUCache.OptionsBase.disposeAfter} (read-only) */ get disposeAfter() { return this.#disposeAfter; } constructor(options) { const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; if (max !== 0 && !isPosInt(max)) { throw new TypeError('max option must be a nonnegative integer'); } const UintArray = max ? getUintArray(max) : Array; if (!UintArray) { throw new Error('invalid max value: ' + max); } this.#max = max; this.#maxSize = maxSize; this.maxEntrySize = maxEntrySize || this.#maxSize; this.sizeCalculation = sizeCalculation; if (this.sizeCalculation) { if (!this.#maxSize && !this.maxEntrySize) { throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize'); } if (typeof this.sizeCalculation !== 'function') { throw new TypeError('sizeCalculation set to non-function'); } } if (memoMethod !== undefined && typeof memoMethod !== 'function') { throw new TypeError('memoMethod must be a function if defined'); } this.#memoMethod = memoMethod; if (fetchMethod !== undefined && typeof fetchMethod !== 'function') { throw new TypeError('fetchMethod must be a function if specified'); } this.#fetchMethod = fetchMethod; this.#hasFetchMethod = !!fetchMethod; this.#keyMap = new Map(); this.#keyList = new Array(max).fill(undefined); this.#valList = new Array(max).fill(undefined); this.#next = new UintArray(max); this.#prev = new UintArray(max); this.#head = 0; this.#tail = 0; this.#free = Stack.create(max); this.#size = 0; this.#calculatedSize = 0; if (typeof dispose === 'function') { this.#dispose = dispose; } if (typeof disposeAfter === 'function') { this.#disposeAfter = disposeAfter; this.#disposed = []; } else { this.#disposeAfter = undefined; this.#disposed = undefined; } this.#hasDispose = !!this.#dispose; this.#hasDisposeAfter = !!this.#disposeAfter; this.noDisposeOnSet = !!noDisposeOnSet; this.noUpdateTTL = !!noUpdateTTL; this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection; this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection; this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort; this.ignoreFetchAbort = !!ignoreFetchAbort; // NB: maxEntrySize is set to maxSize if it's set if (this.maxEntrySize !== 0) { if (this.#maxSize !== 0) { if (!isPosInt(this.#maxSize)) { throw new TypeError('maxSize must be a positive integer if specified'); } } if (!isPosInt(this.maxEntrySize)) { throw new TypeError('maxEntrySize must be a positive integer if specified'); } this.#initializeSizeTracking(); } this.allowStale = !!allowStale; this.noDeleteOnStaleGet = !!noDeleteOnStaleGet; this.updateAgeOnGet = !!updateAgeOnGet; this.updateAgeOnHas = !!updateAgeOnHas; this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1; this.ttlAutopurge = !!ttlAutopurge; this.ttl = ttl || 0; if (this.ttl) { if (!isPosInt(this.ttl)) { throw new TypeError('ttl must be a positive integer if specified'); } this.#initializeTTLTracking(); } // do not allow completely unbounded caches if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { throw new TypeError('At least one of max, maxSize, or ttl is required'); } if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { const code = 'LRU_CACHE_UNBOUNDED'; if (shouldWarn(code)) { warned.add(code); const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + 'result in unbounded memory consumption.'; emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); } } } /** * Return the number of ms left in the item's TTL. If item is not in cache, * returns `0`. Returns `Infinity` if item is in cache without a defined TTL. */ getRemainingTTL(key) { return this.#keyMap.has(key) ? Infinity : 0; } #initializeTTLTracking() { const ttls = new ZeroArray(this.#max); const starts = new ZeroArray(this.#max); this.#ttls = ttls; this.#starts = starts; this.#setItemTTL = (index, ttl, start = perf.now()) => { starts[index] = ttl !== 0 ? start : 0; ttls[index] = ttl; if (ttl !== 0 && this.ttlAutopurge) { const t = setTimeout(() => { if (this.#isStale(index)) { this.#delete(this.#keyList[index], 'expire'); } }, ttl + 1); // unref() not supported on all platforms /* c8 ignore start */ if (t.unref) { t.unref(); } /* c8 ignore stop */ } }; this.#updateItemAge = index => { starts[index] = ttls[index] !== 0 ? perf.now() : 0; }; this.#statusTTL = (status, index) => { if (ttls[index]) { const ttl = ttls[index]; const start = starts[index]; /* c8 ignore next */ if (!ttl || !start) return; status.ttl = ttl; status.start = start; status.now = cachedNow || getNow(); const age = status.now - start; status.remainingTTL = ttl - age; } }; // debounce calls to perf.now() to 1s so we're not hitting // that costly call repeatedly. let cachedNow = 0; const getNow = () => { const n = perf.now(); if (this.ttlResolution > 0) { cachedNow = n; const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); // not available on all platforms /* c8 ignore start */ if (t.unref) { t.unref(); } /* c8 ignore stop */ } return n; }; this.getRemainingTTL = key => { const index = this.#keyMap.get(key); if (index === undefined) { return 0; } const ttl = ttls[index]; const start = starts[index]; if (!ttl || !start) { return Infinity; } const age = (cachedNow || getNow()) - start; return ttl - age; }; this.#isStale = index => { const s = starts[index]; const t = ttls[index]; return !!t && !!s && (cachedNow || getNow()) - s > t; }; } // conditionally set private methods related to TTL #updateItemAge = () => { }; #statusTTL = () => { }; #setItemTTL = () => { }; /* c8 ignore stop */ #isStale = () => false; #initializeSizeTracking() { const sizes = new ZeroArray(this.#max); this.#calculatedSize = 0; this.#sizes = sizes; this.#removeItemSize = index => { this.#calculatedSize -= sizes[index]; sizes[index] = 0; }; this.#requireSize = (k, v, size, sizeCalculation) => { // provisionally accept background fetches. // actual value size will be checked when they return. if (this.#isBackgroundFetch(v)) { return 0; } if (!isPosInt(size)) { if (sizeCalculation) { if (typeof sizeCalculation !== 'function') { throw new TypeError('sizeCalculation must be a function'); } size = sizeCalculation(v, k); if (!isPosInt(size)) { throw new TypeError('sizeCalculation return invalid (expect positive integer)'); } } else { throw new TypeError('invalid size value (must be positive integer). ' + 'When maxSize or maxEntrySize is used, sizeCalculation ' + 'or size must be set.'); } } return size; }; this.#addItemSize = (index, size, status) => { sizes[index] = size; if (this.#maxSize) { const maxSize = this.#maxSize - sizes[index]; while (this.#calculatedSize > maxSize) { this.#evict(true); } } this.#calculatedSize += sizes[index]; if (status) { status.entrySize = size; status.totalCalculatedSize = this.#calculatedSize; } }; } #removeItemSize = _i => { }; #addItemSize = (_i, _s, _st) => { }; #requireSize = (_k, _v, size, sizeCalculation) => { if (size || sizeCalculation) { throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache'); } return 0; }; *#indexes({ allowStale = this.allowStale } = {}) { if (this.#size) { for (let i = this.#tail; true;) { if (!this.#isValidIndex(i)) { break; } if (allowStale || !this.#isStale(i)) { yield i; } if (i === this.#head) { break; } else { i = this.#prev[i]; } } } } *#rindexes({ allowStale = this.allowStale } = {}) { if (this.#size) { for (let i = this.#head; true;) { if (!this.#isValidIndex(i)) { break; } if (allowStale || !this.#isStale(i)) { yield i; } if (i === this.#tail) { break; } else { i = this.#next[i]; } } } } #isValidIndex(index) { return (index !== undefined && this.#keyMap.get(this.#keyList[index]) === index); } /** * Return a generator yielding `[key, value]` pairs, * in order from most recently used to least recently used. */ *entries() { for (const i of this.#indexes()) { if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield [this.#keyList[i], this.#valList[i]]; } } } /** * Inverse order version of {@link LRUCache.entries} * * Return a generator yielding `[key, value]` pairs, * in order from least recently used to most recently used. */ *rentries() { for (const i of this.#rindexes()) { if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield [this.#keyList[i], this.#valList[i]]; } } } /** * Return a generator yielding the keys in the cache, * in order from most recently used to least recently used. */ *keys() { for (const i of this.#indexes()) { const k = this.#keyList[i]; if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } } /** * Inverse order version of {@link LRUCache.keys} * * Return a generator yielding the keys in the cache, * in order from least recently used to most recently used. */ *rkeys() { for (const i of this.#rindexes()) { const k = this.#keyList[i]; if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } } /** * Return a generator yielding the values in the cache, * in order from most recently used to least recently used. */ *values() { for (const i of this.#indexes()) { const v = this.#valList[i]; if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } } /** * Inverse order version of {@link LRUCache.values} * * Return a generator yielding the values in the cache, * in order from least recently used to most recently used. */ *rvalues() { for (const i of this.#rindexes()) { const v = this.#valList[i]; if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } } /** * Iterating over the cache itself yields the same results as * {@link LRUCache.entries} */ [Symbol.iterator]() { return this.entries(); } /** * A String value that is used in the creation of the default string * description of an object. Called by the built-in method * `Object.prototype.toString`. */ [Symbol.toStringTag] = 'LRUCache'; /** * Find a value for which the supplied fn method returns a truthy value, * similar to `Array.find()`. fn is called as `fn(value, key, cache)`. */ find(fn, getOptions = {}) { for (const i of this.#indexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; if (fn(value, this.#keyList[i], this)) { return this.get(this.#keyList[i], getOptions); } } } /** * Call the supplied function on each item in the cache, in order from most * recently used to least recently used. * * `fn` is called as `fn(value, key, cache)`. * * If `thisp` is provided, function will be called in the `this`-context of * the provided object, or the cache if no `thisp` object is provided. * * Does not update age or recenty of use, or iterate over stale values. */ forEach(fn, thisp = this) { for (const i of this.#indexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); } } /** * The same as {@link LRUCache.forEach} but items are iterated over in * reverse order. (ie, less recently used items are iterated over first.) */ rforEach(fn, thisp = this) { for (const i of this.#rindexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); } } /** * Delete any stale entries. Returns true if anything was removed, * false otherwise. */ purgeStale() { let deleted = false; for (const i of this.#rindexes({ allowStale: true })) { if (this.#isStale(i)) { this.#delete(this.#keyList[i], 'expire'); deleted = true; } } return deleted; } /** * Get the extended info about a given entry, to get its value, size, and * TTL info simultaneously. Returns `undefined` if the key is not present. * * Unlike {@link LRUCache#dump}, which is designed to be portable and survive * serialization, the `start` value is always the current timestamp, and the * `ttl` is a calculated remaining time to live (negative if expired). * * Always returns stale values, if their info is found in the cache, so be * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) * if relevant. */ info(key) { const i = this.#keyMap.get(key); if (i === undefined) return undefined; const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) return undefined; const entry = { value }; if (this.#ttls && this.#starts) { const ttl = this.#ttls[i]; const start = this.#starts[i]; if (ttl && start) { const remain = ttl - (perf.now() - start); entry.ttl = remain; entry.start = Date.now(); } } if (this.#sizes) { entry.size = this.#sizes[i]; } return entry; } /** * Return an array of [key, {@link LRUCache.Entry}] tuples which can be * passed to {@link LRLUCache#load}. * * The `start` fields are calculated relative to a portable `Date.now()` * timestamp, even if `performance.now()` is available. * * Stale entries are always included in the `dump`, even if * {@link LRUCache.OptionsBase.allowStale} is false. * * Note: this returns an actual array, not a generator, so it can be more * easily passed around. */ dump() { const arr = []; for (const i of this.#indexes({ allowStale: true })) { const key = this.#keyList[i]; const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined || key === undefined) continue; const entry = { value }; if (this.#ttls && this.#starts) { entry.ttl = this.#ttls[i]; // always dump the start relative to a portable timestamp // it's ok for this to be a bit slow, it's a rare operation. const age = perf.now() - this.#starts[i]; entry.start = Math.floor(Date.now() - age); } if (this.#sizes) { entry.size = this.#sizes[i]; } arr.unshift([key, entry]); } return arr; } /** * Reset the cache and load in the items in entries in the order listed. * * The shape of the resulting cache may be different if the same options are * not used in both caches. * * The `start` fields are assumed to be calculated relative to a portable * `Date.now()` timestamp, even if `performance.now()` is available. */ load(arr) { this.clear(); for (const [key, entry] of arr) { if (entry.start) { // entry.start is a portable timestamp, but we may be using // node's performance.now(), so calculate the offset, so that // we get the intended remaining TTL, no matter how long it's // been on ice. // // it's ok for this to be a bit slow, it's a rare operation. const age = Date.now() - entry.start; entry.start = perf.now() - age; } this.set(key, entry.value, entry); } } /** * Add a value to the cache. * * Note: if `undefined` is specified as a value, this is an alias for * {@link LRUCache#delete} * * Fields on the {@link LRUCache.SetOptions} options param will override * their corresponding values in the constructor options for the scope * of this single `set()` operation. * * If `start` is provided, then that will set the effective start * time for the TTL calculation. Note that this must be a previous * value of `performance.now()` if supported, or a previous value of * `Date.now()` if not. * * Options object may also include `size`, which will prevent * calling the `sizeCalculation` function and just use the specified * number if it is a positive integer, and `noDisposeOnSet` which * will prevent calling a `dispose` function in the case of * overwrites. * * If the `size` (or return value of `sizeCalculation`) for a given * entry is greater than `maxEntrySize`, then the item will not be * added to the cache. * * Will update the recency of the entry. * * If the value is `undefined`, then this is an alias for * `cache.delete(key)`. `undefined` is never stored in the cache. */ set(k, v, setOptions = {}) { if (v === undefined) { this.delete(k); return this; } const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; let { noUpdateTTL = this.noUpdateTTL } = setOptions; const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); // if the item doesn't fit, don't do anything // NB: maxEntrySize set to maxSize by default if (this.maxEntrySize && size > this.maxEntrySize) { if (status) { status.set = 'miss'; status.maxEntrySizeExceeded = true; } // have to delete, in case something is there already. this.#delete(k, 'set'); return this; } let index = this.#size === 0 ? undefined : this.#keyMap.get(k); if (index === undefined) { // addition index = (this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size); this.#keyList[index] = k; this.#valList[index] = v; this.#keyMap.set(k, index); this.#next[this.#tail] = index; this.#prev[index] = this.#tail; this.#tail = index; this.#size++; this.#addItemSize(index, size, status); if (status) status.set = 'add'; noUpdateTTL = false; } else { // update this.#moveToTail(index); const oldVal = this.#valList[index]; if (v !== oldVal) { if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { oldVal.__abortController.abort(new Error('replaced')); const { __staleWhileFetching: s } = oldVal; if (s !== undefined && !noDisposeOnSet) { if (this.#hasDispose) { this.#dispose?.(s, k, 'set'); } if (this.#hasDisposeAfter) { this.#disposed?.push([s, k, 'set']); } } } else if (!noDisposeOnSet) { if (this.#hasDispose) { this.#dispose?.(oldVal, k, 'set'); } if (this.#hasDisposeAfter) { this.#disposed?.push([oldVal, k, 'set']); } } this.#removeItemSize(index); this.#addItemSize(index, size, status); this.#valList[index] = v; if (status) { status.set = 'replace'; const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal; if (oldValue !== undefined) status.oldValue = oldValue; } } else if (status) { status.set = 'update'; } } if (ttl !== 0 && !this.#ttls) { this.#initializeTTLTracking(); } if (this.#ttls) { if (!noUpdateTTL) { this.#setItemTTL(index, ttl, start); } if (status) this.#statusTTL(status, index); } if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } return this; } /** * Evict the least recently used item, returning its value or * `undefined` if cache is empty. */ pop() { try { while (this.#size) { const val = this.#valList[this.#head]; this.#evict(true); if (this.#isBackgroundFetch(val)) { if (val.__staleWhileFetching) { return val.__staleWhileFetching; } } else if (val !== undefined) { return val; } } } finally { if (this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } } } #evict(free) { const head = this.#head; const k = this.#keyList[head]; const v = this.#valList[head]; if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('evicted')); } else if (this.#hasDispose || this.#hasDisposeAfter) { if (this.#hasDispose) { this.#dispose?.(v, k, 'evict'); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, 'evict']); } } this.#removeItemSize(head); // if we aren't about to use the index, then null these out if (free) { this.#keyList[head] = undefined; this.#valList[head] = undefined; this.#free.push(head); } if (this.#size === 1) { this.#head = this.#tail = 0; this.#free.length = 0; } else { this.#head = this.#next[head]; } this.#keyMap.delete(k); this.#size--; return head; } /** * Check if a key is in the cache, without updating the recency of use. * Will return false if the item is stale, even though it is technically * in the cache. * * Check if a key is in the cache, without updating the recency of * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set * to `true` in either the options or the constructor. * * Will return `false` if the item is stale, even though it is technically in * the cache. The difference can be determined (if it matters) by using a * `status` argument, and inspecting the `has` field. * * Will not update item age unless * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. */ has(k, hasOptions = {}) { const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; const index = this.#keyMap.get(k); if (index !== undefined) { const v = this.#valList[index]; if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === undefined) { return false; } if (!this.#isStale(index)) { if (updateAgeOnHas) { this.#updateItemAge(index); } if (status) { status.has = 'hit'; this.#statusTTL(status, index); } return true; } else if (status) { status.has = 'stale'; this.#statusTTL(status, index); } } else if (status) { status.has = 'miss'; } return false; } /** * Like {@link LRUCache#get} but doesn't update recency or delete stale * items. * * Returns `undefined` if the item is stale, unless * {@link LRUCache.OptionsBase.allowStale} is set. */ peek(k, peekOptions = {}) { const { allowStale = this.allowStale } = peekOptions; const index = this.#keyMap.get(k); if (index === undefined || (!allowStale && this.#isStale(index))) { return; } const v = this.#valList[index]; // either stale and allowed, or forcing a refresh of non-stale value return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; } #backgroundFetch(k, index, options, context) { const v = index === undefined ? undefined : this.#valList[index]; if (this.#isBackgroundFetch(v)) { return v; } const ac = new AC(); const { signal } = options; // when/if our AC signals, then stop listening to theirs. signal?.addEventListener('abort', () => ac.abort(signal.reason), { signal: ac.signal, }); const fetchOpts = { signal: ac.signal, options, context, }; const cb = (v, updateCache = false) => { const { aborted } = ac.signal; const ignoreAbort = options.ignoreFetchAbort && v !== undefined; if (options.status) { if (aborted && !updateCache) { options.status.fetchAborted = true; options.status.fetchError = ac.signal.reason; if (ignoreAbort) options.status.fetchAbortIgnored = true; } else { options.status.fetchResolved = true; } } if (aborted && !ignoreAbort && !updateCache) { return fetchFail(ac.signal.reason); } // either we didn't abort, and are still here, or we did, and ignored const bf = p; if (this.#valList[index] === p) { if (v === undefined) { if (bf.__staleWhileFetching) { this.#valList[index] = bf.__staleWhileFetching; } else { this.#delete(k, 'fetch'); } } else { if (options.status) options.status.fetchUpdated = true; this.set(k, v, fetchOpts.options); } } return v; }; const eb = (er) => { if (options.status) { options.status.fetchRejected = true; options.status.fetchError = er; } return fetchFail(er); }; const fetchFail = (er) => { const { aborted } = ac.signal; const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; const noDelete = allowStale || options.noDeleteOnFetchRejection; const bf = p; if (this.#valList[index] === p) { // if we allow stale on fetch rejections, then we need to ensure that // the stale value is not removed from the cache when the fetch fails. const del = !noDelete || bf.__staleWhileFetching === undefined; if (del) { this.#delete(k, 'fetch'); } else if (!allowStaleAborted) { // still replace the *promise* with the stale value, // since we are done with the promise at this point. // leave it untouched if we're still waiting for an // aborted background fetch that hasn't yet returned. this.#valList[index] = bf.__staleWhileFetching; } } if (allowStale) { if (options.status && bf.__staleWhileFetching !== undefined) { options.status.returnedStale = true; } return bf.__staleWhileFetching; } else if (bf.__returned === bf) { throw er; } }; const pcall = (res, rej) => { const fmp = this.#fetchMethod?.(k, v, fetchOpts); if (fmp && fmp instanceof Promise) { fmp.then(v => res(v === undefined ? undefined : v), rej); } // ignored, we go until we finish, regardless. // defer check until we are actually aborting, // so fetchMethod can override. ac.signal.addEventListener('abort', () => { if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) { res(undefined); // when it eventually resolves, update the cache. if (options.allowStaleOnFetchAbort) { res = v => cb(v, true); } } }); }; if (options.status) options.status.fetchDispatched = true; const p = new Promise(pcall).then(cb, eb); const bf = Object.assign(p, { __abortController: ac, __staleWhileFetching: v, __returned: undefined, }); if (index === undefined) { // internal, don't expose status. this.set(k, bf, { ...fetchOpts.options, status: undefined }); index = this.#keyMap.get(k); } else { this.#valList[index] = bf; } return bf; } #isBackgroundFetch(p) { if (!this.#hasFetchMethod) return false; const b = p; return (!!b && b instanceof Promise && b.hasOwnProperty('__staleWhileFetching') && b.__abortController instanceof AC); } async fetch(k, fetchOptions = {}) { const { // get options allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, // set options ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, // fetch exclusive options noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; if (!this.#hasFetchMethod) { if (status) status.fetch = 'get'; return this.get(k, { allowStale, updateAgeOnGet, noDeleteOnStaleGet, status, }); } const options = { allowStale, updateAgeOnGet, noDeleteOnStaleGet, ttl, noDisposeOnSet, size, sizeCalculation, noUpdateTTL, noDeleteOnFetchRejection, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, status, signal, }; let index = this.#keyMap.get(k); if (index === undefined) { if (status) status.fetch = 'miss'; const p = this.#backgroundFetch(k, index, options, context); return (p.__returned = p); } else { // in cache, maybe already fetching const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { const stale = allowStale && v.__staleWhileFetching !== undefined; if (status) { status.fetch = 'inflight'; if (stale) status.returnedStale = true; } return stale ? v.__staleWhileFetching : (v.__returned = v); } // if we force a refresh, that means do NOT serve the cached value, // unless we are already in the process of refreshing the cache. const isStale = this.#isStale(index); if (!forceRefresh && !isStale) { if (status) status.fetch = 'hit'; this.#moveToTail(index); if (updateAgeOnGet) { this.#updateItemAge(index); } if (status) this.#statusTTL(status, index); return v; } // ok, it is stale or a forced refresh, and not already fetching. // refresh the cache. const p = this.#backgroundFetch(k, index, options, context); const hasStale = p.__staleWhileFetching !== undefined; const staleVal = hasStale && allowStale; if (status) { status.fetch = isStale ? 'stale' : 'refresh'; if (staleVal && isStale) status.returnedStale = true; } return staleVal ? p.__staleWhileFetching : (p.__returned = p); } } async forceFetch(k, fetchOptions = {}) { const v = await this.fetch(k, fetchOptions); if (v === undefined) throw new Error('fetch() returned undefined'); return v; } memo(k, memoOptions = {}) { const memoMethod = this.#memoMethod; if (!memoMethod) { throw new Error('no memoMethod provided to constructor'); } const { context, forceRefresh, ...options } = memoOptions; const v = this.get(k, options); if (!forceRefresh && v !== undefined) return v; const vv = memoMethod(k, v, { options, context, }); this.set(k, vv, options); return vv; } /** * Return a value from the cache. Will update the recency of the cache * entry found. * * If the key is not found, get() will return `undefined`. */ get(k, getOptions = {}) { const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; const index = this.#keyMap.get(k); if (index !== undefined) { const value = this.#valList[index]; const fetching = this.#isBackgroundFetch(value); if (status) this.#statusTTL(status, index); if (this.#isStale(index)) { if (status) status.get = 'stale'; // delete only if not an in-flight background fetch if (!fetching) { if (!noDeleteOnStaleGet) { this.#delete(k, 'expire'); } if (status && allowStale) status.returnedStale = true; return allowStale ? value : undefined; } else { if (status && allowStale && value.__staleWhileFetching !== undefined) { status.returnedStale = true; } return allowStale ? value.__staleWhileFetching : undefined; } } else { if (status) status.get = 'hit'; // if we're currently fetching it, we don't actually have it yet // it's not stale, which means this isn't a staleWhileRefetching. // If it's not stale, and fetching, AND has a __staleWhileFetching // value, then that means the user fetched with {forceRefresh:true}, // so it's safe to return that value. if (fetching) { return value.__staleWhileFetching; } this.#moveToTail(index); if (updateAgeOnGet) { this.#updateItemAge(index); } return value; } } else if (status) { status.get = 'miss'; } } #connect(p, n) { this.#prev[n] = p; this.#next[p] = n; } #moveToTail(index) { // if tail already, nothing to do // if head, move head to next[index] // else // move next[prev[index]] to next[index] (head has no prev) // move prev[next[index]] to prev[index] // prev[index] = tail // next[tail] = index // tail = index if (index !== this.#tail) { if (index === this.#head) { this.#head = this.#next[index]; } else { this.#connect(this.#prev[index], this.#next[index]); } this.#connect(this.#tail, index); this.#tail = index; } } /** * Deletes a key out of the cache. * * Returns true if the key was deleted, false otherwise. */ delete(k) { return this.#delete(k, 'delete'); } #delete(k, reason) { let deleted = false; if (this.#size !== 0) { const index = this.#keyMap.get(k); if (index !== undefined) { deleted = true; if (this.#size === 1) { this.#clear(reason); } else { this.#removeItemSize(index); const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('deleted')); } else if (this.#hasDispose || this.#hasDisposeAfter) { if (this.#hasDispose) { this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, reason]); } } this.#keyMap.delete(k); this.#keyList[index] = undefined; this.#valList[index] = undefined; if (index === this.#tail) { this.#tail = this.#prev[index]; } else if (index === this.#head) { this.#head = this.#next[index]; } else { const pi = this.#prev[index]; this.#next[pi] = this.#next[index]; const ni = this.#next[index]; this.#prev[ni] = this.#prev[index]; } this.#size--; this.#free.push(index); } } } if (this.#hasDisposeAfter && this.#disposed?.length) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } return deleted; } /** * Clear the cache entirely, throwing away all values. */ clear() { return this.#clear('delete'); } #clear(reason) { for (const index of this.#rindexes({ allowStale: true })) { const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('deleted')); } else { const k = this.#keyList[index]; if (this.#hasDispose) { this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, reason]); } } } this.#keyMap.clear(); this.#valList.fill(undefined); this.#keyList.fill(undefined); if (this.#ttls && this.#starts) { this.#ttls.fill(0); this.#starts.fill(0); } if (this.#sizes) { this.#sizes.fill(0); } this.#head = 0; this.#tail = 0; this.#free.length = 0; this.#calculatedSize = 0; this.#size = 0; if (this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } } } //# sourceMappingURL=index.js.mapvar G=(l,t,e)=>{if(!t.has(l))throw TypeError("Cannot "+e)};var I=(l,t,e)=>(G(l,t,"read from private field"),e?e.call(l):t.get(l)),j=(l,t,e)=>{if(t.has(l))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(l):t.set(l,e)},x=(l,t,e,i)=>(G(l,t,"write to private field"),i?i.call(l,e):t.set(l,e),e);var T=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,P=new Set,M=typeof process=="object"&&process?process:{},H=(l,t,e,i)=>{typeof M.emitWarning=="function"?M.emitWarning(l,t,e,i):console.error(`[${e}] ${t}: ${l}`)},W=globalThis.AbortController,N=globalThis.AbortSignal;if(typeof W>"u"){N=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,s){this._onabort.push(s)}},W=class{constructor(){t()}signal=new N;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i)}}};let l=M.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{l&&(l=!1,H("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var V=l=>!P.has(l),Y=Symbol("type"),A=l=>l&&l===Math.floor(l)&&l>0&&isFinite(l),k=l=>A(l)?l<=Math.pow(2,8)?Uint8Array:l<=Math.pow(2,16)?Uint16Array:l<=Math.pow(2,32)?Uint32Array:l<=Number.MAX_SAFE_INTEGER?O:null:null,O=class extends Array{constructor(t){super(t),this.fill(0)}},z,E=class{heap;length;static create(t){let e=k(t);if(!e)return[];x(E,z,!0);let i=new E(t,e);return x(E,z,!1),i}constructor(t,e){if(!I(E,z))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},R=E;z=new WeakMap,j(R,z,!1);var D=class{#g;#f;#p;#w;#R;#W;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#S;#s;#i;#t;#l;#c;#o;#h;#_;#r;#m;#b;#u;#y;#O;#a;static unsafeExposeInternals(t){return{starts:t.#b,ttls:t.#u,sizes:t.#m,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#c,get head(){return t.#o},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#x(e,i,s,n),moveToTail:e=>t.#C(e),indexes:e=>t.#A(e),rindexes:e=>t.#F(e),isStale:e=>t.#d(e)}}get max(){return this.#g}get maxSize(){return this.#f}get calculatedSize(){return this.#S}get size(){return this.#n}get fetchMethod(){return this.#R}get memoMethod(){return this.#W}get dispose(){return this.#p}get disposeAfter(){return this.#w}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:h,updateAgeOnHas:o,allowStale:r,dispose:g,disposeAfter:m,noDisposeOnSet:f,noUpdateTTL:u,maxSize:c=0,maxEntrySize:F=0,sizeCalculation:d,fetchMethod:S,memoMethod:a,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:_,ignoreFetchAbort:v}=t;if(e!==0&&!A(e))throw new TypeError("max option must be a nonnegative integer");let y=e?k(e):Array;if(!y)throw new Error("invalid max value: "+e);if(this.#g=e,this.#f=c,this.maxEntrySize=F||this.#f,this.sizeCalculation=d,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(a!==void 0&&typeof a!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#W=a,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#R=S,this.#O=!!S,this.#s=new Map,this.#i=new Array(e).fill(void 0),this.#t=new Array(e).fill(void 0),this.#l=new y(e),this.#c=new y(e),this.#o=0,this.#h=0,this.#_=R.create(e),this.#n=0,this.#S=0,typeof g=="function"&&(this.#p=g),typeof m=="function"?(this.#w=m,this.#r=[]):(this.#w=void 0,this.#r=void 0),this.#y=!!this.#p,this.#a=!!this.#w,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!p,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!v,this.maxEntrySize!==0){if(this.#f!==0&&!A(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!A(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#P()}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!o,this.ttlResolution=A(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!A(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#M()}if(this.#g===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#g&&!this.#f){let C="LRU_CACHE_UNBOUNDED";V(C)&&(P.add(C),H("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",C,D))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#M(){let t=new O(this.#g),e=new O(this.#g);this.#u=t,this.#b=e,this.#U=(n,h,o=T.now())=>{if(e[n]=h!==0?o:0,t[n]=h,h!==0&&this.ttlAutopurge){let r=setTimeout(()=>{this.#d(n)&&this.#T(this.#i[n],"expire")},h+1);r.unref&&r.unref()}},this.#z=n=>{e[n]=t[n]!==0?T.now():0},this.#E=(n,h)=>{if(t[h]){let o=t[h],r=e[h];if(!o||!r)return;n.ttl=o,n.start=r,n.now=i||s();let g=n.now-r;n.remainingTTL=o-g}};let i=0,s=()=>{let n=T.now();if(this.ttlResolution>0){i=n;let h=setTimeout(()=>i=0,this.ttlResolution);h.unref&&h.unref()}return n};this.getRemainingTTL=n=>{let h=this.#s.get(n);if(h===void 0)return 0;let o=t[h],r=e[h];if(!o||!r)return 1/0;let g=(i||s())-r;return o-g},this.#d=n=>{let h=e[n],o=t[n];return!!o&&!!h&&(i||s())-h>o}}#z=()=>{};#E=()=>{};#U=()=>{};#d=()=>!1;#P(){let t=new O(this.#g);this.#S=0,this.#m=t,this.#v=e=>{this.#S-=t[e],t[e]=0},this.#G=(e,i,s,n)=>{if(this.#e(i))return 0;if(!A(s))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!A(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#D=(e,i,s)=>{if(t[e]=i,this.#f){let n=this.#f-t[e];for(;this.#S>n;)this.#L(!0)}this.#S+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#S)}}#v=t=>{};#D=(t,e,i)=>{};#G=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;!(!this.#I(e)||((t||!this.#d(e))&&(yield e),e===this.#o));)e=this.#c[e]}*#F({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#o;!(!this.#I(e)||((t||!this.#d(e))&&(yield e),e===this.#h));)e=this.#l[e]}#I(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#A())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#F())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#A()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#F()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#A())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#F())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#i[i],this))return this.get(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#F()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#F({allowStale:!0}))this.#d(e)&&(this.#T(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#u&&this.#b){let h=this.#u[e],o=this.#b[e];if(h&&o){let r=h-(T.now()-o);n.ttl=r,n.start=Date.now()}}return this.#m&&(n.size=this.#m[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let i=this.#i[e],s=this.#t[e],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let h={value:n};if(this.#u&&this.#b){h.ttl=this.#u[e];let o=T.now()-this.#b[e];h.start=Math.floor(Date.now()-o)}this.#m&&(h.size=this.#m[e]),t.unshift([i,h])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=T.now()-s}this.set(e,i.value,i)}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:s=this.ttl,start:n,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:r}=i,{noUpdateTTL:g=this.noUpdateTTL}=i,m=this.#G(t,e,i.size||0,o);if(this.maxEntrySize&&m>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this.#T(t,"set"),this;let f=this.#n===0?void 0:this.#s.get(t);if(f===void 0)f=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#g?this.#L(!1):this.#n,this.#i[f]=t,this.#t[f]=e,this.#s.set(t,f),this.#l[this.#h]=f,this.#c[f]=this.#h,this.#h=f,this.#n++,this.#D(f,m,r),r&&(r.set="add"),g=!1;else{this.#C(f);let u=this.#t[f];if(e!==u){if(this.#O&&this.#e(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:c}=u;c!==void 0&&!h&&(this.#y&&this.#p?.(c,t,"set"),this.#a&&this.#r?.push([c,t,"set"]))}else h||(this.#y&&this.#p?.(u,t,"set"),this.#a&&this.#r?.push([u,t,"set"]));if(this.#v(f),this.#D(f,m,r),this.#t[f]=e,r){r.set="replace";let c=u&&this.#e(u)?u.__staleWhileFetching:u;c!==void 0&&(r.oldValue=c)}}else r&&(r.set="update")}if(s!==0&&!this.#u&&this.#M(),this.#u&&(g||this.#U(f,s,n),r&&this.#E(r,f)),!h&&this.#a&&this.#r){let u=this.#r,c;for(;c=u?.shift();)this.#w?.(...c)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#o];if(this.#L(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#a&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#w?.(...e)}}}#L(t){let e=this.#o,i=this.#i[e],s=this.#t[e];return this.#O&&this.#e(s)?s.__abortController.abort(new Error("evicted")):(this.#y||this.#a)&&(this.#y&&this.#p?.(s,i,"evict"),this.#a&&this.#r?.push([s,i,"evict"])),this.#v(e),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#o=this.#h=0,this.#_.length=0):this.#o=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let h=this.#t[n];if(this.#e(h)&&h.__staleWhileFetching===void 0)return!1;if(this.#d(n))s&&(s.has="stale",this.#E(s,n));else return i&&this.#z(n),s&&(s.has="hit",this.#E(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{allowStale:i=this.allowStale}=e,s=this.#s.get(t);if(s===void 0||!i&&this.#d(s))return;let n=this.#t[s];return this.#e(n)?n.__staleWhileFetching:n}#x(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let h=new W,{signal:o}=i;o?.addEventListener("abort",()=>h.abort(o.reason),{signal:h.signal});let r={signal:h.signal,options:i,context:s},g=(d,S=!1)=>{let{aborted:a}=h.signal,w=i.ignoreFetchAbort&&d!==void 0;if(i.status&&(a&&!S?(i.status.fetchAborted=!0,i.status.fetchError=h.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),a&&!w&&!S)return f(h.signal.reason);let b=c;return this.#t[e]===c&&(d===void 0?b.__staleWhileFetching?this.#t[e]=b.__staleWhileFetching:this.#T(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,d,r.options))),d},m=d=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=d),f(d)),f=d=>{let{aborted:S}=h.signal,a=S&&i.allowStaleOnFetchAbort,w=a||i.allowStaleOnFetchRejection,b=w||i.noDeleteOnFetchRejection,p=c;if(this.#t[e]===c&&(!b||p.__staleWhileFetching===void 0?this.#T(t,"fetch"):a||(this.#t[e]=p.__staleWhileFetching)),w)return i.status&&p.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),p.__staleWhileFetching;if(p.__returned===p)throw d},u=(d,S)=>{let a=this.#R?.(t,n,r);a&&a instanceof Promise&&a.then(w=>d(w===void 0?void 0:w),S),h.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(d(void 0),i.allowStaleOnFetchAbort&&(d=w=>g(w,!0)))})};i.status&&(i.status.fetchDispatched=!0);let c=new Promise(u).then(g,m),F=Object.assign(c,{__abortController:h,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.set(t,F,{...r.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=F,F}#e(t){if(!this.#O)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof W}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:r=0,sizeCalculation:g=this.sizeCalculation,noUpdateTTL:m=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:c=this.ignoreFetchAbort,allowStaleOnFetchAbort:F=this.allowStaleOnFetchAbort,context:d,forceRefresh:S=!1,status:a,signal:w}=e;if(!this.#O)return a&&(a.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let b={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:h,noDisposeOnSet:o,size:r,sizeCalculation:g,noUpdateTTL:m,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:F,ignoreFetchAbort:c,status:a,signal:w},p=this.#s.get(t);if(p===void 0){a&&(a.fetch="miss");let _=this.#x(t,p,b,d);return _.__returned=_}else{let _=this.#t[p];if(this.#e(_)){let U=i&&_.__staleWhileFetching!==void 0;return a&&(a.fetch="inflight",U&&(a.returnedStale=!0)),U?_.__staleWhileFetching:_.__returned=_}let v=this.#d(p);if(!S&&!v)return a&&(a.fetch="hit"),this.#C(p),s&&this.#z(p),a&&this.#E(a,p),_;let y=this.#x(t,p,b,d),L=y.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=v?"stale":"refresh",L&&v&&(a.returnedStale=!0)),L?y.__staleWhileFetching:y.__returned=y}}async forceFetch(t,e={}){let i=await this.fetch(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let i=this.#W;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:n,...h}=e,o=this.get(t,h);if(!n&&o!==void 0)return o;let r=i(t,o,{options:h,context:s});return this.set(t,r,h),r}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:h}=e,o=this.#s.get(t);if(o!==void 0){let r=this.#t[o],g=this.#e(r);return h&&this.#E(h,o),this.#d(o)?(h&&(h.get="stale"),g?(h&&i&&r.__staleWhileFetching!==void 0&&(h.returnedStale=!0),i?r.__staleWhileFetching:void 0):(n||this.#T(t,"expire"),h&&i&&(h.returnedStale=!0),i?r:void 0)):(h&&(h.get="hit"),g?r.__staleWhileFetching:(this.#C(o),s&&this.#z(o),r))}else h&&(h.get="miss")}#j(t,e){this.#c[e]=t,this.#l[t]=e}#C(t){t!==this.#h&&(t===this.#o?this.#o=this.#l[t]:this.#j(this.#c[t],this.#l[t]),this.#j(this.#h,t),this.#h=t)}delete(t){return this.#T(t,"delete")}#T(t,e){let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(i=!0,this.#n===1)this.#N(e);else{this.#v(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#y||this.#a)&&(this.#y&&this.#p?.(n,t,e),this.#a&&this.#r?.push([n,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#c[s];else if(s===this.#o)this.#o=this.#l[s];else{let h=this.#c[s];this.#l[h]=this.#l[s];let o=this.#l[s];this.#c[o]=this.#c[s]}this.#n--,this.#_.push(s)}}if(this.#a&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#w?.(...n)}return i}clear(){return this.#N("delete")}#N(t){for(let e of this.#F({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#y&&this.#p?.(i,s,t),this.#a&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#u&&this.#b&&(this.#u.fill(0),this.#b.fill(0)),this.#m&&this.#m.fill(0),this.#o=0,this.#h=0,this.#_.length=0,this.#S=0,this.#n=0,this.#a&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#w?.(...i)}}};export{D as LRUCache}; //# sourceMappingURL=index.min.js.map { "type": "module" } { "name": "lru-cache", "publishConfig": { "tag": "legacy-v10" }, "description": "A cache object that deletes the least-recently-used items.", "version": "10.4.3", "author": "Isaac Z. Schlueter ", "keywords": [ "mru", "lru", "cache" ], "sideEffects": false, "scripts": { "build": "npm run prepare", "prepare": "tshy && bash fixup.sh", "pretest": "npm run prepare", "presnap": "npm run prepare", "test": "tap", "snap": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "format": "prettier --write .", "typedoc": "typedoc --tsconfig ./.tshy/esm.json ./src/*.ts", "benchmark-results-typedoc": "bash scripts/benchmark-results-typedoc.sh", "prebenchmark": "npm run prepare", "benchmark": "make -C benchmark", "preprofile": "npm run prepare", "profile": "make -C benchmark profile" }, "main": "./dist/commonjs/index.js", "types": "./dist/commonjs/index.d.ts", "tshy": { "exports": { ".": "./src/index.ts", "./min": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.min.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.min.js" } } } }, "repository": { "type": "git", "url": "git://github.com/isaacs/node-lru-cache.git" }, "devDependencies": { "@types/node": "^20.2.5", "@types/tap": "^15.0.6", "benchmark": "^2.1.4", "esbuild": "^0.17.11", "eslint-config-prettier": "^8.5.0", "marked": "^4.2.12", "mkdirp": "^2.1.5", "prettier": "^2.6.2", "tap": "^20.0.3", "tshy": "^2.0.0", "tslib": "^2.4.0", "typedoc": "^0.25.3", "typescript": "^5.2.2" }, "license": "ISC", "files": [ "dist" ], "prettier": { "semi": false, "printWidth": 70, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "tap": { "node-arg": [ "--expose-gc" ], "plugin": [ "@tapjs/clock" ] }, "exports": { ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } }, "./min": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.min.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.min.js" } } }, "type": "module", "module": "./dist/esm/index.js" } ISC License Copyright 2017-2022 (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. const { Request, Response } = require('minipass-fetch') const { Minipass } = require('minipass') const MinipassFlush = require('minipass-flush') const cacache = require('cacache') const url = require('url') const CachingMinipassPipeline = require('../pipeline.js') const CachePolicy = require('./policy.js') const cacheKey = require('./key.js') const remote = require('../remote.js') const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop) // allow list for request headers that will be written to the cache index // note: we will also store any request headers // that are named in a response's vary header const KEEP_REQUEST_HEADERS = [ 'accept-charset', 'accept-encoding', 'accept-language', 'accept', 'cache-control', ] // allow list for response headers that will be written to the cache index // note: we must not store the real response's age header, or when we load // a cache policy based on the metadata it will think the cached response // is always stale const KEEP_RESPONSE_HEADERS = [ 'cache-control', 'content-encoding', 'content-language', 'content-type', 'date', 'etag', 'expires', 'last-modified', 'link', 'location', 'pragma', 'vary', ] // return an object containing all metadata to be written to the index const getMetadata = (request, response, options) => { const metadata = { time: Date.now(), url: request.url, reqHeaders: {}, resHeaders: {}, // options on which we must match the request and vary the response options: { compress: options.compress != null ? options.compress : request.compress, }, } // only save the status if it's not a 200 or 304 if (response.status !== 200 && response.status !== 304) { metadata.status = response.status } for (const name of KEEP_REQUEST_HEADERS) { if (request.headers.has(name)) { metadata.reqHeaders[name] = request.headers.get(name) } } // if the request's host header differs from the host in the url // we need to keep it, otherwise it's just noise and we ignore it const host = request.headers.get('host') const parsedUrl = new url.URL(request.url) if (host && parsedUrl.host !== host) { metadata.reqHeaders.host = host } // if the response has a vary header, make sure // we store the relevant request headers too if (response.headers.has('vary')) { const vary = response.headers.get('vary') // a vary of "*" means every header causes a different response. // in that scenario, we do not include any additional headers // as the freshness check will always fail anyway and we don't // want to bloat the cache indexes if (vary !== '*') { // copy any other request headers that will vary the response const varyHeaders = vary.trim().toLowerCase().split(/\s*,\s*/) for (const name of varyHeaders) { if (request.headers.has(name)) { metadata.reqHeaders[name] = request.headers.get(name) } } } } for (const name of KEEP_RESPONSE_HEADERS) { if (response.headers.has(name)) { metadata.resHeaders[name] = response.headers.get(name) } } for (const name of options.cacheAdditionalHeaders) { if (response.headers.has(name)) { metadata.resHeaders[name] = response.headers.get(name) } } return metadata } // symbols used to hide objects that may be lazily evaluated in a getter const _request = Symbol('request') const _response = Symbol('response') const _policy = Symbol('policy') class CacheEntry { constructor ({ entry, request, response, options }) { if (entry) { this.key = entry.key this.entry = entry // previous versions of this module didn't write an explicit timestamp in // the metadata, so fall back to the entry's timestamp. we can't use the // entry timestamp to determine staleness because cacache will update it // when it verifies its data this.entry.metadata.time = this.entry.metadata.time || this.entry.time } else { this.key = cacheKey(request) } this.options = options // these properties are behind getters that lazily evaluate this[_request] = request this[_response] = response this[_policy] = null } // returns a CacheEntry instance that satisfies the given request // or undefined if no existing entry satisfies static async find (request, options) { try { // compacts the index and returns an array of unique entries var matches = await cacache.index.compact(options.cachePath, cacheKey(request), (A, B) => { const entryA = new CacheEntry({ entry: A, options }) const entryB = new CacheEntry({ entry: B, options }) return entryA.policy.satisfies(entryB.request) }, { validateEntry: (entry) => { // clean out entries with a buggy content-encoding value if (entry.metadata && entry.metadata.resHeaders && entry.metadata.resHeaders['content-encoding'] === null) { return false } // if an integrity is null, it needs to have a status specified if (entry.integrity === null) { return !!(entry.metadata && entry.metadata.status) } return true }, }) } catch (err) { // if the compact request fails, ignore the error and return return } // a cache mode of 'reload' means to behave as though we have no cache // on the way to the network. return undefined to allow cacheFetch to // create a brand new request no matter what. if (options.cache === 'reload') { return } // find the specific entry that satisfies the request let match for (const entry of matches) { const _entry = new CacheEntry({ entry, options, }) if (_entry.policy.satisfies(request)) { match = _entry break } } return match } // if the user made a PUT/POST/PATCH then we invalidate our // cache for the same url by deleting the index entirely static async invalidate (request, options) { const key = cacheKey(request) try { await cacache.rm.entry(options.cachePath, key, { removeFully: true }) } catch (err) { // ignore errors } } get request () { if (!this[_request]) { this[_request] = new Request(this.entry.metadata.url, { method: 'GET', headers: this.entry.metadata.reqHeaders, ...this.entry.metadata.options, }) } return this[_request] } get response () { if (!this[_response]) { this[_response] = new Response(null, { url: this.entry.metadata.url, counter: this.options.counter, status: this.entry.metadata.status || 200, headers: { ...this.entry.metadata.resHeaders, 'content-length': this.entry.size, }, }) } return this[_response] } get policy () { if (!this[_policy]) { this[_policy] = new CachePolicy({ entry: this.entry, request: this.request, response: this.response, options: this.options, }) } return this[_policy] } // wraps the response in a pipeline that stores the data // in the cache while the user consumes it async store (status) { // if we got a status other than 200, 301, or 308, // or the CachePolicy forbid storage, append the // cache status header and return it untouched if ( this.request.method !== 'GET' || ![200, 301, 308].includes(this.response.status) || !this.policy.storable() ) { this.response.headers.set('x-local-cache-status', 'skip') return this.response } const size = this.response.headers.get('content-length') const cacheOpts = { algorithms: this.options.algorithms, metadata: getMetadata(this.request, this.response, this.options), size, integrity: this.options.integrity, integrityEmitter: this.response.body.hasIntegrityEmitter && this.response.body, } let body = null // we only set a body if the status is a 200, redirects are // stored as metadata only if (this.response.status === 200) { let cacheWriteResolve, cacheWriteReject const cacheWritePromise = new Promise((resolve, reject) => { cacheWriteResolve = resolve cacheWriteReject = reject }).catch((err) => { body.emit('error', err) }) body = new CachingMinipassPipeline({ events: ['integrity', 'size'] }, new MinipassFlush({ flush () { return cacheWritePromise }, })) // this is always true since if we aren't reusing the one from the remote fetch, we // are using the one from cacache body.hasIntegrityEmitter = true const onResume = () => { const tee = new Minipass() const cacheStream = cacache.put.stream(this.options.cachePath, this.key, cacheOpts) // re-emit the integrity and size events on our new response body so they can be reused cacheStream.on('integrity', i => body.emit('integrity', i)) cacheStream.on('size', s => body.emit('size', s)) // stick a flag on here so downstream users will know if they can expect integrity events tee.pipe(cacheStream) // TODO if the cache write fails, log a warning but return the response anyway // eslint-disable-next-line promise/catch-or-return cacheStream.promise().then(cacheWriteResolve, cacheWriteReject) body.unshift(tee) body.unshift(this.response.body) } body.once('resume', onResume) body.once('end', () => body.removeListener('resume', onResume)) } else { await cacache.index.insert(this.options.cachePath, this.key, null, cacheOpts) } // note: we do not set the x-local-cache-hash header because we do not know // the hash value until after the write to the cache completes, which doesn't // happen until after the response has been sent and it's too late to write // the header anyway this.response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) this.response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) this.response.headers.set('x-local-cache-mode', 'stream') this.response.headers.set('x-local-cache-status', status) this.response.headers.set('x-local-cache-time', new Date().toISOString()) const newResponse = new Response(body, { url: this.response.url, status: this.response.status, headers: this.response.headers, counter: this.options.counter, }) return newResponse } // use the cached data to create a response and return it async respond (method, options, status) { let response if (method === 'HEAD' || [301, 308].includes(this.response.status)) { // if the request is a HEAD, or the response is a redirect, // then the metadata in the entry already includes everything // we need to build a response response = this.response } else { // we're responding with a full cached response, so create a body // that reads from cacache and attach it to a new Response const body = new Minipass() const headers = { ...this.policy.responseHeaders() } const onResume = () => { const cacheStream = cacache.get.stream.byDigest( this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } ) cacheStream.on('error', async (err) => { cacheStream.pause() if (err.code === 'EINTEGRITY') { await cacache.rm.content( this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } ) } if (err.code === 'ENOENT' || err.code === 'EINTEGRITY') { await CacheEntry.invalidate(this.request, this.options) } body.emit('error', err) cacheStream.resume() }) // emit the integrity and size events based on our metadata so we're consistent body.emit('integrity', this.entry.integrity) body.emit('size', Number(headers['content-length'])) cacheStream.pipe(body) } body.once('resume', onResume) body.once('end', () => body.removeListener('resume', onResume)) response = new Response(body, { url: this.entry.metadata.url, counter: options.counter, status: 200, headers, }) } response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) response.headers.set('x-local-cache-hash', encodeURIComponent(this.entry.integrity)) response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) response.headers.set('x-local-cache-mode', 'stream') response.headers.set('x-local-cache-status', status) response.headers.set('x-local-cache-time', new Date(this.entry.metadata.time).toUTCString()) return response } // use the provided request along with this cache entry to // revalidate the stored response. returns a response, either // from the cache or from the update async revalidate (request, options) { const revalidateRequest = new Request(request, { headers: this.policy.revalidationHeaders(request), }) try { // NOTE: be sure to remove the headers property from the // user supplied options, since we have already defined // them on the new request object. if they're still in the // options then those will overwrite the ones from the policy var response = await remote(revalidateRequest, { ...options, headers: undefined, }) } catch (err) { // if the network fetch fails, return the stale // cached response unless it has a cache-control // of 'must-revalidate' if (!this.policy.mustRevalidate) { return this.respond(request.method, options, 'stale') } throw err } if (this.policy.revalidated(revalidateRequest, response)) { // we got a 304, write a new index to the cache and respond from cache const metadata = getMetadata(request, response, options) // 304 responses do not include headers that are specific to the response data // since they do not include a body, so we copy values for headers that were // in the old cache entry to the new one, if the new metadata does not already // include that header for (const name of KEEP_RESPONSE_HEADERS) { if ( !hasOwnProperty(metadata.resHeaders, name) && hasOwnProperty(this.entry.metadata.resHeaders, name) ) { metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] } } for (const name of options.cacheAdditionalHeaders) { const inMeta = hasOwnProperty(metadata.resHeaders, name) const inEntry = hasOwnProperty(this.entry.metadata.resHeaders, name) const inPolicy = hasOwnProperty(this.policy.response.headers, name) // if the header is in the existing entry, but it is not in the metadata // then we need to write it to the metadata as this will refresh the on-disk cache if (!inMeta && inEntry) { metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] } // if the header is in the metadata, but not in the policy, then we need to set // it in the policy so that it's included in the immediate response. future // responses will load a new cache entry, so we don't need to change that if (!inPolicy && inMeta) { this.policy.response.headers[name] = metadata.resHeaders[name] } } try { await cacache.index.insert(options.cachePath, this.key, this.entry.integrity, { size: this.entry.size, metadata, }) } catch (err) { // if updating the cache index fails, we ignore it and // respond anyway } return this.respond(request.method, options, 'revalidated') } // if we got a modified response, create a new entry based on it const newEntry = new CacheEntry({ request, response, options, }) // respond with the new entry while writing it to the cache return newEntry.store('updated') } } module.exports = CacheEntry class NotCachedError extends Error { constructor (url) { /* eslint-disable-next-line max-len */ super(`request to ${url} failed: cache mode is 'only-if-cached' but no cached response is available.`) this.code = 'ENOTCACHED' } } module.exports = { NotCachedError, } const { NotCachedError } = require('./errors.js') const CacheEntry = require('./entry.js') const remote = require('../remote.js') // do whatever is necessary to get a Response and return it const cacheFetch = async (request, options) => { // try to find a cached entry that satisfies this request const entry = await CacheEntry.find(request, options) if (!entry) { // no cached result, if the cache mode is 'only-if-cached' that's a failure if (options.cache === 'only-if-cached') { throw new NotCachedError(request.url) } // otherwise, we make a request, store it and return it const response = await remote(request, options) const newEntry = new CacheEntry({ request, response, options }) return newEntry.store('miss') } // we have a cached response that satisfies this request, however if the cache // mode is 'no-cache' then we send the revalidation request no matter what if (options.cache === 'no-cache') { return entry.revalidate(request, options) } // if the cached entry is not stale, or if the cache mode is 'force-cache' or // 'only-if-cached' we can respond with the cached entry. set the status // based on the result of needsRevalidation and respond const _needsRevalidation = entry.policy.needsRevalidation(request) if (options.cache === 'force-cache' || options.cache === 'only-if-cached' || !_needsRevalidation) { return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit') } // if we got here, the cache entry is stale so revalidate it return entry.revalidate(request, options) } cacheFetch.invalidate = async (request, options) => { if (!options.cachePath) { return } return CacheEntry.invalidate(request, options) } module.exports = cacheFetch const { URL, format } = require('url') // options passed to url.format() when generating a key const formatOptions = { auth: false, fragment: false, search: true, unicode: false, } // returns a string to be used as the cache key for the Request const cacheKey = (request) => { const parsed = new URL(request.url) return `make-fetch-happen:request-cache:${format(parsed, formatOptions)}` } module.exports = cacheKey const CacheSemantics = require('http-cache-semantics') const Negotiator = require('negotiator') const ssri = require('ssri') // options passed to http-cache-semantics constructor const policyOptions = { shared: false, ignoreCargoCult: true, } // a fake empty response, used when only testing the // request for storability const emptyResponse = { status: 200, headers: {} } // returns a plain object representation of the Request const requestObject = (request) => { const _obj = { method: request.method, url: request.url, headers: {}, compress: request.compress, } request.headers.forEach((value, key) => { _obj.headers[key] = value }) return _obj } // returns a plain object representation of the Response const responseObject = (response) => { const _obj = { status: response.status, headers: {}, } response.headers.forEach((value, key) => { _obj.headers[key] = value }) return _obj } class CachePolicy { constructor ({ entry, request, response, options }) { this.entry = entry this.request = requestObject(request) this.response = responseObject(response) this.options = options this.policy = new CacheSemantics(this.request, this.response, policyOptions) if (this.entry) { // if we have an entry, copy the timestamp to the _responseTime // this is necessary because the CacheSemantics constructor forces // the value to Date.now() which means a policy created from a // cache entry is likely to always identify itself as stale this.policy._responseTime = this.entry.metadata.time } } // static method to quickly determine if a request alone is storable static storable (request, options) { // no cachePath means no caching if (!options.cachePath) { return false } // user explicitly asked not to cache if (options.cache === 'no-store') { return false } // we only cache GET and HEAD requests if (!['GET', 'HEAD'].includes(request.method)) { return false } // otherwise, let http-cache-semantics make the decision // based on the request's headers const policy = new CacheSemantics(requestObject(request), emptyResponse, policyOptions) return policy.storable() } // returns true if the policy satisfies the request satisfies (request) { const _req = requestObject(request) if (this.request.headers.host !== _req.headers.host) { return false } if (this.request.compress !== _req.compress) { return false } const negotiatorA = new Negotiator(this.request) const negotiatorB = new Negotiator(_req) if (JSON.stringify(negotiatorA.mediaTypes()) !== JSON.stringify(negotiatorB.mediaTypes())) { return false } if (JSON.stringify(negotiatorA.languages()) !== JSON.stringify(negotiatorB.languages())) { return false } if (JSON.stringify(negotiatorA.encodings()) !== JSON.stringify(negotiatorB.encodings())) { return false } if (this.options.integrity) { return ssri.parse(this.options.integrity).match(this.entry.integrity) } return true } // returns true if the request and response allow caching storable () { return this.policy.storable() } // NOTE: this is a hack to avoid parsing the cache-control // header ourselves, it returns true if the response's // cache-control contains must-revalidate get mustRevalidate () { return !!this.policy._rescc['must-revalidate'] } // returns true if the cached response requires revalidation // for the given request needsRevalidation (request) { const _req = requestObject(request) // force method to GET because we only cache GETs // but can serve a HEAD from a cached GET _req.method = 'GET' return !this.policy.satisfiesWithoutRevalidation(_req) } responseHeaders () { return this.policy.responseHeaders() } // returns a new object containing the appropriate headers // to send a revalidation request revalidationHeaders (request) { const _req = requestObject(request) return this.policy.revalidationHeaders(_req) } // returns true if the request/response was revalidated // successfully. returns false if a new response was received revalidated (request, response) { const _req = requestObject(request) const _res = responseObject(response) const policy = this.policy.revalidatedPolicy(_req, _res) return !policy.modified } } module.exports = CachePolicy 'use strict' const { FetchError, Request, isRedirect } = require('minipass-fetch') const url = require('url') const CachePolicy = require('./cache/policy.js') const cache = require('./cache/index.js') const remote = require('./remote.js') // given a Request, a Response and user options // return true if the response is a redirect that // can be followed. we throw errors that will result // in the fetch being rejected if the redirect is // possible but invalid for some reason const canFollowRedirect = (request, response, options) => { if (!isRedirect(response.status)) { return false } if (options.redirect === 'manual') { return false } if (options.redirect === 'error') { throw new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect', { code: 'ENOREDIRECT' }) } if (!response.headers.has('location')) { throw new FetchError(`redirect location header missing for: ${request.url}`, 'no-location', { code: 'EINVALIDREDIRECT' }) } if (request.counter >= request.follow) { throw new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect', { code: 'EMAXREDIRECT' }) } return true } // given a Request, a Response, and the user's options return an object // with a new Request and a new options object that will be used for // following the redirect const getRedirect = (request, response, options) => { const _opts = { ...options } const location = response.headers.get('location') const redirectUrl = new url.URL(location, /^https?:/.test(location) ? undefined : request.url) // Comment below is used under the following license: /** * @license * Copyright (c) 2010-2012 Mikeal Rogers * Licensed under the Apache License, Version 2.0 (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-2.0 * 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. */ // Remove authorization if changing hostnames (but not if just // changing ports or protocols). This matches the behavior of request: // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 if (new url.URL(request.url).hostname !== redirectUrl.hostname) { request.headers.delete('authorization') request.headers.delete('cookie') } // for POST request with 301/302 response, or any request with 303 response, // use GET when following redirect if ( response.status === 303 || (request.method === 'POST' && [301, 302].includes(response.status)) ) { _opts.method = 'GET' _opts.body = null request.headers.delete('content-length') } _opts.headers = {} request.headers.forEach((value, key) => { _opts.headers[key] = value }) _opts.counter = ++request.counter const redirectReq = new Request(url.format(redirectUrl), _opts) return { request: redirectReq, options: _opts, } } const fetch = async (request, options) => { const response = CachePolicy.storable(request, options) ? await cache(request, options) : await remote(request, options) // if the request wasn't a GET or HEAD, and the response // status is between 200 and 399 inclusive, invalidate the // request url if (!['GET', 'HEAD'].includes(request.method) && response.status >= 200 && response.status <= 399) { await cache.invalidate(request, options) } if (!canFollowRedirect(request, response, options)) { return response } const redirect = getRedirect(request, response, options) return fetch(redirect.request, redirect.options) } module.exports = fetch const { FetchError, Headers, Request, Response } = require('minipass-fetch') const configureOptions = require('./options.js') const fetch = require('./fetch.js') const makeFetchHappen = (url, opts) => { const options = configureOptions(opts) const request = new Request(url, options) return fetch(request, options) } makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => { if (typeof defaultUrl === 'object') { defaultOptions = defaultUrl defaultUrl = null } const defaultedFetch = (url, options = {}) => { const finalUrl = url || defaultUrl const finalOptions = { ...defaultOptions, ...options, headers: { ...defaultOptions.headers, ...options.headers, }, } return wrappedFetch(finalUrl, finalOptions) } defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) => makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch) return defaultedFetch } module.exports = makeFetchHappen module.exports.FetchError = FetchError module.exports.Headers = Headers module.exports.Request = Request module.exports.Response = Response const dns = require('dns') const conditionalHeaders = [ 'if-modified-since', 'if-none-match', 'if-unmodified-since', 'if-match', 'if-range', ] const configureOptions = (opts) => { const { strictSSL, ...options } = { ...opts } options.method = options.method ? options.method.toUpperCase() : 'GET' if (strictSSL === undefined || strictSSL === null) { options.rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0' } else { options.rejectUnauthorized = strictSSL !== false } if (!options.retry) { options.retry = { retries: 0 } } else if (typeof options.retry === 'string') { const retries = parseInt(options.retry, 10) if (isFinite(retries)) { options.retry = { retries } } else { options.retry = { retries: 0 } } } else if (typeof options.retry === 'number') { options.retry = { retries: options.retry } } else { options.retry = { retries: 0, ...options.retry } } options.dns = { ttl: 5 * 60 * 1000, lookup: dns.lookup, ...options.dns } options.cache = options.cache || 'default' if (options.cache === 'default') { const hasConditionalHeader = Object.keys(options.headers || {}).some((name) => { return conditionalHeaders.includes(name.toLowerCase()) }) if (hasConditionalHeader) { options.cache = 'no-store' } } options.cacheAdditionalHeaders = options.cacheAdditionalHeaders || [] // cacheManager is deprecated, but if it's set and // cachePath is not we should copy it to the new field if (options.cacheManager && !options.cachePath) { options.cachePath = options.cacheManager } return options } module.exports = configureOptions 'use strict' const MinipassPipeline = require('minipass-pipeline') class CachingMinipassPipeline extends MinipassPipeline { #events = [] #data = new Map() constructor (opts, ...streams) { // CRITICAL: do NOT pass the streams to the call to super(), this will start // the flow of data and potentially cause the events we need to catch to emit // before we've finished our own setup. instead we call super() with no args, // finish our setup, and then push the streams into ourselves to start the // data flow super() this.#events = opts.events /* istanbul ignore next - coverage disabled because this is pointless to test here */ if (streams.length) { this.push(...streams) } } on (event, handler) { if (this.#events.includes(event) && this.#data.has(event)) { return handler(...this.#data.get(event)) } return super.on(event, handler) } emit (event, ...data) { if (this.#events.includes(event)) { this.#data.set(event, data) } return super.emit(event, ...data) } } module.exports = CachingMinipassPipeline const { Minipass } = require('minipass') const fetch = require('minipass-fetch') const promiseRetry = require('promise-retry') const ssri = require('ssri') const { log } = require('proc-log') const CachingMinipassPipeline = require('./pipeline.js') const { getAgent } = require('@npmcli/agent') const pkg = require('../package.json') const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})` const RETRY_ERRORS = [ 'ECONNRESET', // remote socket closed on us 'ECONNREFUSED', // remote host refused to open connection 'EADDRINUSE', // failed to bind to a local port (proxy?) 'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW // from @npmcli/agent 'ECONNECTIONTIMEOUT', 'EIDLETIMEOUT', 'ERESPONSETIMEOUT', 'ETRANSFERTIMEOUT', // Known codes we do NOT retry on: // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline) // EINVALIDPROXY // invalid protocol from @npmcli/agent // EINVALIDRESPONSE // invalid status code from @npmcli/agent ] const RETRY_TYPES = [ 'request-timeout', ] // make a request directly to the remote source, // retrying certain classes of errors as well as // following redirects (through the cache if necessary) // and verifying response integrity const remoteFetch = (request, options) => { // options.signal is intended for the fetch itself, not the agent. Attaching it to the agent will re-use that signal across multiple requests, which prevents any connections beyond the first one. const agent = getAgent(request.url, { ...options, signal: undefined }) if (!request.headers.has('connection')) { request.headers.set('connection', agent ? 'keep-alive' : 'close') } if (!request.headers.has('user-agent')) { request.headers.set('user-agent', USER_AGENT) } // keep our own options since we're overriding the agent // and the redirect mode const _opts = { ...options, agent, redirect: 'manual', } return promiseRetry(async (retryHandler, attemptNum) => { const req = new fetch.Request(request, _opts) try { let res = await fetch(req, _opts) if (_opts.integrity && res.status === 200) { // we got a 200 response and the user has specified an expected // integrity value, so wrap the response in an ssri stream to verify it const integrityStream = ssri.integrityStream({ algorithms: _opts.algorithms, integrity: _opts.integrity, size: _opts.size, }) const pipeline = new CachingMinipassPipeline({ events: ['integrity', 'size'], }, res.body, integrityStream) // we also propagate the integrity and size events out to the pipeline so we can use // this new response body as an integrityEmitter for cacache integrityStream.on('integrity', i => pipeline.emit('integrity', i)) integrityStream.on('size', s => pipeline.emit('size', s)) res = new fetch.Response(pipeline, res) // set an explicit flag so we know if our response body will emit integrity and size res.body.hasIntegrityEmitter = true } res.headers.set('x-fetch-attempts', attemptNum) // do not retry POST requests, or requests with a streaming body // do retry requests with a 408, 420, 429 or 500+ status in the response const isStream = Minipass.isStream(req.body) const isRetriable = req.method !== 'POST' && !isStream && ([408, 420, 429].includes(res.status) || res.status >= 500) if (isRetriable) { if (typeof options.onRetry === 'function') { options.onRetry(res) } /* eslint-disable-next-line max-len */ log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`) return retryHandler(res) } return res } catch (err) { const code = (err.code === 'EPROMISERETRY') ? err.retried.code : err.code // err.retried will be the thing that was thrown from above // if it's a response, we just got a bad status code and we // can re-throw to allow the retry const isRetryError = err.retried instanceof fetch.Response || (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type)) if (req.method === 'POST' || isRetryError) { throw err } if (typeof options.onRetry === 'function') { options.onRetry(err) } log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`) return retryHandler(err) } }, options.retry).catch((err) => { // don't reject for http errors, just return them if (err.status >= 400 && err.type !== 'system') { return err } throw err }) } module.exports = remoteFetch 1.0.0 / 2024-08-31 ================== * Drop support for node <18 * Added an option preferred encodings array #59 0.6.3 / 2022-01-22 ================== * Revert "Lazy-load modules from main entry point" 0.6.2 / 2019-04-29 ================== * Fix sorting charset, encoding, and language with extra parameters 0.6.1 / 2016-05-02 ================== * perf: improve `Accept` parsing speed * perf: improve `Accept-Charset` parsing speed * perf: improve `Accept-Encoding` parsing speed * perf: improve `Accept-Language` parsing speed 0.6.0 / 2015-09-29 ================== * Fix including type extensions in parameters in `Accept` parsing * Fix parsing `Accept` parameters with quoted equals * Fix parsing `Accept` parameters with quoted semicolons * Lazy-load modules from main entry point * perf: delay type concatenation until needed * perf: enable strict mode * perf: hoist regular expressions * perf: remove closures getting spec properties * perf: remove a closure from media type parsing * perf: remove property delete from media type parsing 0.5.3 / 2015-05-10 ================== * Fix media type parameter matching to be case-insensitive 0.5.2 / 2015-05-06 ================== * Fix comparing media types with quoted values * Fix splitting media types with quoted commas 0.5.1 / 2015-02-14 ================== * Fix preference sorting to be stable for long acceptable lists 0.5.0 / 2014-12-18 ================== * Fix list return order when large accepted list * Fix missing identity encoding when q=0 exists * Remove dynamic building of Negotiator class 0.4.9 / 2014-10-14 ================== * Fix error when media type has invalid parameter 0.4.8 / 2014-09-28 ================== * Fix all negotiations to be case-insensitive * Stable sort preferences of same quality according to client order * Support Node.js 0.6 0.4.7 / 2014-06-24 ================== * Handle invalid provided languages * Handle invalid provided media types 0.4.6 / 2014-06-11 ================== * Order by specificity when quality is the same 0.4.5 / 2014-05-29 ================== * Fix regression in empty header handling 0.4.4 / 2014-05-29 ================== * Fix behaviors when headers are not present 0.4.3 / 2014-04-16 ================== * Handle slashes on media params correctly 0.4.2 / 2014-02-28 ================== * Fix media type sorting * Handle media types params strictly 0.4.1 / 2014-01-16 ================== * Use most specific matches 0.4.0 / 2014-01-09 ================== * Remove preferred prefix from methods (The MIT License) Copyright (c) 2012-2014 Federico Romero Copyright (c) 2012-2014 Isaac Z. Schlueter Copyright (c) 2014-2015 Douglas Christopher Wilson 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. /*! * negotiator * Copyright(c) 2012 Federico Romero * Copyright(c) 2012-2014 Isaac Z. Schlueter * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; var preferredCharsets = require('./lib/charset') var preferredEncodings = require('./lib/encoding') var preferredLanguages = require('./lib/language') var preferredMediaTypes = require('./lib/mediaType') /** * Module exports. * @public */ module.exports = Negotiator; module.exports.Negotiator = Negotiator; /** * Create a Negotiator instance from a request. * @param {object} request * @public */ function Negotiator(request) { if (!(this instanceof Negotiator)) { return new Negotiator(request); } this.request = request; } Negotiator.prototype.charset = function charset(available) { var set = this.charsets(available); return set && set[0]; }; Negotiator.prototype.charsets = function charsets(available) { return preferredCharsets(this.request.headers['accept-charset'], available); }; Negotiator.prototype.encoding = function encoding(available, opts) { var set = this.encodings(available, opts); return set && set[0]; }; Negotiator.prototype.encodings = function encodings(available, options) { var opts = options || {}; return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred); }; Negotiator.prototype.language = function language(available) { var set = this.languages(available); return set && set[0]; }; Negotiator.prototype.languages = function languages(available) { return preferredLanguages(this.request.headers['accept-language'], available); }; Negotiator.prototype.mediaType = function mediaType(available) { var set = this.mediaTypes(available); return set && set[0]; }; Negotiator.prototype.mediaTypes = function mediaTypes(available) { return preferredMediaTypes(this.request.headers.accept, available); }; // Backwards compatibility Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; /** * negotiator * Copyright(c) 2012 Isaac Z. Schlueter * Copyright(c) 2014 Federico Romero * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module exports. * @public */ module.exports = preferredCharsets; module.exports.preferredCharsets = preferredCharsets; /** * Module variables. * @private */ var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; /** * Parse the Accept-Charset header. * @private */ function parseAcceptCharset(accept) { var accepts = accept.split(','); for (var i = 0, j = 0; i < accepts.length; i++) { var charset = parseCharset(accepts[i].trim(), i); if (charset) { accepts[j++] = charset; } } // trim accepts accepts.length = j; return accepts; } /** * Parse a charset from the Accept-Charset header. * @private */ function parseCharset(str, i) { var match = simpleCharsetRegExp.exec(str); if (!match) return null; var charset = match[1]; var q = 1; if (match[2]) { var params = match[2].split(';') for (var j = 0; j < params.length; j++) { var p = params[j].trim().split('='); if (p[0] === 'q') { q = parseFloat(p[1]); break; } } } return { charset: charset, q: q, i: i }; } /** * Get the priority of a charset. * @private */ function getCharsetPriority(charset, accepted, index) { var priority = {o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(charset, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } /** * Get the specificity of the charset. * @private */ function specify(charset, spec, index) { var s = 0; if(spec.charset.toLowerCase() === charset.toLowerCase()){ s |= 1; } else if (spec.charset !== '*' ) { return null } return { i: index, o: spec.i, q: spec.q, s: s } } /** * Get the preferred charsets from an Accept-Charset header. * @public */ function preferredCharsets(accept, provided) { // RFC 2616 sec 14.2: no header = * var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); if (!provided) { // sorted list of all charsets return accepts .filter(isQuality) .sort(compareSpecs) .map(getFullCharset); } var priorities = provided.map(function getPriority(type, index) { return getCharsetPriority(type, accepts, index); }); // sorted list of accepted charsets return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { return provided[priorities.indexOf(priority)]; }); } /** * Compare two specs. * @private */ function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } /** * Get full charset string. * @private */ function getFullCharset(spec) { return spec.charset; } /** * Check if a spec has any quality. * @private */ function isQuality(spec) { return spec.q > 0; } /** * negotiator * Copyright(c) 2012 Isaac Z. Schlueter * Copyright(c) 2014 Federico Romero * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module exports. * @public */ module.exports = preferredEncodings; module.exports.preferredEncodings = preferredEncodings; /** * Module variables. * @private */ var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; /** * Parse the Accept-Encoding header. * @private */ function parseAcceptEncoding(accept) { var accepts = accept.split(','); var hasIdentity = false; var minQuality = 1; for (var i = 0, j = 0; i < accepts.length; i++) { var encoding = parseEncoding(accepts[i].trim(), i); if (encoding) { accepts[j++] = encoding; hasIdentity = hasIdentity || specify('identity', encoding); minQuality = Math.min(minQuality, encoding.q || 1); } } if (!hasIdentity) { /* * If identity doesn't explicitly appear in the accept-encoding header, * it's added to the list of acceptable encoding with the lowest q */ accepts[j++] = { encoding: 'identity', q: minQuality, i: i }; } // trim accepts accepts.length = j; return accepts; } /** * Parse an encoding from the Accept-Encoding header. * @private */ function parseEncoding(str, i) { var match = simpleEncodingRegExp.exec(str); if (!match) return null; var encoding = match[1]; var q = 1; if (match[2]) { var params = match[2].split(';'); for (var j = 0; j < params.length; j++) { var p = params[j].trim().split('='); if (p[0] === 'q') { q = parseFloat(p[1]); break; } } } return { encoding: encoding, q: q, i: i }; } /** * Get the priority of an encoding. * @private */ function getEncodingPriority(encoding, accepted, index) { var priority = {encoding: encoding, o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(encoding, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } /** * Get the specificity of the encoding. * @private */ function specify(encoding, spec, index) { var s = 0; if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ s |= 1; } else if (spec.encoding !== '*' ) { return null } return { encoding: encoding, i: index, o: spec.i, q: spec.q, s: s } }; /** * Get the preferred encodings from an Accept-Encoding header. * @public */ function preferredEncodings(accept, provided, preferred) { var accepts = parseAcceptEncoding(accept || ''); var comparator = preferred ? function comparator (a, b) { if (a.q !== b.q) { return b.q - a.q // higher quality first } var aPreferred = preferred.indexOf(a.encoding) var bPreferred = preferred.indexOf(b.encoding) if (aPreferred === -1 && bPreferred === -1) { // consider the original specifity/order return (b.s - a.s) || (a.o - b.o) || (a.i - b.i) } if (aPreferred !== -1 && bPreferred !== -1) { return aPreferred - bPreferred // consider the preferred order } return aPreferred === -1 ? 1 : -1 // preferred first } : compareSpecs; if (!provided) { // sorted list of all encodings return accepts .filter(isQuality) .sort(comparator) .map(getFullEncoding); } var priorities = provided.map(function getPriority(type, index) { return getEncodingPriority(type, accepts, index); }); // sorted list of accepted encodings return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { return provided[priorities.indexOf(priority)]; }); } /** * Compare two specs. * @private */ function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i); } /** * Get full encoding string. * @private */ function getFullEncoding(spec) { return spec.encoding; } /** * Check if a spec has any quality. * @private */ function isQuality(spec) { return spec.q > 0; } /** * negotiator * Copyright(c) 2012 Isaac Z. Schlueter * Copyright(c) 2014 Federico Romero * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module exports. * @public */ module.exports = preferredLanguages; module.exports.preferredLanguages = preferredLanguages; /** * Module variables. * @private */ var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; /** * Parse the Accept-Language header. * @private */ function parseAcceptLanguage(accept) { var accepts = accept.split(','); for (var i = 0, j = 0; i < accepts.length; i++) { var language = parseLanguage(accepts[i].trim(), i); if (language) { accepts[j++] = language; } } // trim accepts accepts.length = j; return accepts; } /** * Parse a language from the Accept-Language header. * @private */ function parseLanguage(str, i) { var match = simpleLanguageRegExp.exec(str); if (!match) return null; var prefix = match[1] var suffix = match[2] var full = prefix if (suffix) full += "-" + suffix; var q = 1; if (match[3]) { var params = match[3].split(';') for (var j = 0; j < params.length; j++) { var p = params[j].split('='); if (p[0] === 'q') q = parseFloat(p[1]); } } return { prefix: prefix, suffix: suffix, q: q, i: i, full: full }; } /** * Get the priority of a language. * @private */ function getLanguagePriority(language, accepted, index) { var priority = {o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(language, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } /** * Get the specificity of the language. * @private */ function specify(language, spec, index) { var p = parseLanguage(language) if (!p) return null; var s = 0; if(spec.full.toLowerCase() === p.full.toLowerCase()){ s |= 4; } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { s |= 2; } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { s |= 1; } else if (spec.full !== '*' ) { return null } return { i: index, o: spec.i, q: spec.q, s: s } }; /** * Get the preferred languages from an Accept-Language header. * @public */ function preferredLanguages(accept, provided) { // RFC 2616 sec 14.4: no header = * var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); if (!provided) { // sorted list of all languages return accepts .filter(isQuality) .sort(compareSpecs) .map(getFullLanguage); } var priorities = provided.map(function getPriority(type, index) { return getLanguagePriority(type, accepts, index); }); // sorted list of accepted languages return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { return provided[priorities.indexOf(priority)]; }); } /** * Compare two specs. * @private */ function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } /** * Get full language string. * @private */ function getFullLanguage(spec) { return spec.full; } /** * Check if a spec has any quality. * @private */ function isQuality(spec) { return spec.q > 0; } /** * negotiator * Copyright(c) 2012 Isaac Z. Schlueter * Copyright(c) 2014 Federico Romero * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module exports. * @public */ module.exports = preferredMediaTypes; module.exports.preferredMediaTypes = preferredMediaTypes; /** * Module variables. * @private */ var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; /** * Parse the Accept header. * @private */ function parseAccept(accept) { var accepts = splitMediaTypes(accept); for (var i = 0, j = 0; i < accepts.length; i++) { var mediaType = parseMediaType(accepts[i].trim(), i); if (mediaType) { accepts[j++] = mediaType; } } // trim accepts accepts.length = j; return accepts; } /** * Parse a media type from the Accept header. * @private */ function parseMediaType(str, i) { var match = simpleMediaTypeRegExp.exec(str); if (!match) return null; var params = Object.create(null); var q = 1; var subtype = match[2]; var type = match[1]; if (match[3]) { var kvps = splitParameters(match[3]).map(splitKeyValuePair); for (var j = 0; j < kvps.length; j++) { var pair = kvps[j]; var key = pair[0].toLowerCase(); var val = pair[1]; // get the value, unwrapping quotes var value = val && val[0] === '"' && val[val.length - 1] === '"' ? val.slice(1, -1) : val; if (key === 'q') { q = parseFloat(value); break; } // store parameter params[key] = value; } } return { type: type, subtype: subtype, params: params, q: q, i: i }; } /** * Get the priority of a media type. * @private */ function getMediaTypePriority(type, accepted, index) { var priority = {o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(type, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } /** * Get the specificity of the media type. * @private */ function specify(type, spec, index) { var p = parseMediaType(type); var s = 0; if (!p) { return null; } if(spec.type.toLowerCase() == p.type.toLowerCase()) { s |= 4 } else if(spec.type != '*') { return null; } if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { s |= 2 } else if(spec.subtype != '*') { return null; } var keys = Object.keys(spec.params); if (keys.length > 0) { if (keys.every(function (k) { return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); })) { s |= 1 } else { return null } } return { i: index, o: spec.i, q: spec.q, s: s, } } /** * Get the preferred media types from an Accept header. * @public */ function preferredMediaTypes(accept, provided) { // RFC 2616 sec 14.2: no header = */* var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); if (!provided) { // sorted list of all types return accepts .filter(isQuality) .sort(compareSpecs) .map(getFullType); } var priorities = provided.map(function getPriority(type, index) { return getMediaTypePriority(type, accepts, index); }); // sorted list of accepted types return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { return provided[priorities.indexOf(priority)]; }); } /** * Compare two specs. * @private */ function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } /** * Get full type string. * @private */ function getFullType(spec) { return spec.type + '/' + spec.subtype; } /** * Check if a spec has any quality. * @private */ function isQuality(spec) { return spec.q > 0; } /** * Count the number of quotes in a string. * @private */ function quoteCount(string) { var count = 0; var index = 0; while ((index = string.indexOf('"', index)) !== -1) { count++; index++; } return count; } /** * Split a key value pair. * @private */ function splitKeyValuePair(str) { var index = str.indexOf('='); var key; var val; if (index === -1) { key = str; } else { key = str.slice(0, index); val = str.slice(index + 1); } return [key, val]; } /** * Split an Accept header into media types. * @private */ function splitMediaTypes(accept) { var accepts = accept.split(','); for (var i = 1, j = 0; i < accepts.length; i++) { if (quoteCount(accepts[j]) % 2 == 0) { accepts[++j] = accepts[i]; } else { accepts[j] += ',' + accepts[i]; } } // trim accepts accepts.length = j + 1; return accepts; } /** * Split a string of parameters. * @private */ function splitParameters(str) { var parameters = str.split(';'); for (var i = 1, j = 0; i < parameters.length; i++) { if (quoteCount(parameters[j]) % 2 == 0) { parameters[++j] = parameters[i]; } else { parameters[j] += ';' + parameters[i]; } } // trim parameters parameters.length = j + 1; for (var i = 0; i < parameters.length; i++) { parameters[i] = parameters[i].trim(); } return parameters; } { "name": "negotiator", "description": "HTTP content negotiation", "version": "1.0.0", "contributors": [ "Douglas Christopher Wilson ", "Federico Romero ", "Isaac Z. Schlueter (http://blog.izs.me/)" ], "license": "MIT", "keywords": [ "http", "content negotiation", "accept", "accept-language", "accept-encoding", "accept-charset" ], "repository": "jshttp/negotiator", "devDependencies": { "eslint": "7.32.0", "eslint-plugin-markdown": "2.2.1", "mocha": "9.1.3", "nyc": "15.1.0" }, "files": [ "lib/", "HISTORY.md", "LICENSE", "index.js", "README.md" ], "engines": { "node": ">= 0.6" }, "scripts": { "lint": "eslint .", "test": "mocha --reporter spec --check-leaks --bail test/", "test:debug": "mocha --reporter spec --check-leaks --inspect --inspect-brk test/", "test-ci": "nyc --reporter=lcov --reporter=text npm test", "test-cov": "nyc --reporter=html --reporter=text npm test" } } { "name": "make-fetch-happen", "version": "14.0.3", "description": "Opinionated, caching, retrying fetch client", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "scripts": { "test": "tap", "posttest": "npm run lint", "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lint": "npm run eslint", "lintfix": "npm run eslint -- --fix", "postlint": "template-oss-check", "snap": "tap", "template-oss-apply": "template-oss-apply --force" }, "repository": { "type": "git", "url": "git+https://github.com/npm/make-fetch-happen.git" }, "keywords": [ "http", "request", "fetch", "mean girls", "caching", "cache", "subresource integrity" ], "author": "GitHub Inc.", "license": "ISC", "dependencies": { "@npmcli/agent": "^3.0.0", "cacache": "^19.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^4.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^5.0.0", "promise-retry": "^2.0.1", "ssri": "^12.0.0" }, "devDependencies": { "@npmcli/eslint-config": "^5.0.0", "@npmcli/template-oss": "4.23.4", "nock": "^13.2.4", "safe-buffer": "^5.2.1", "standard-version": "^9.3.2", "tap": "^16.0.0" }, "engines": { "node": "^18.17.0 || >=20.5.0" }, "tap": { "color": 1, "files": "test/*.js", "check-coverage": true, "timeout": 60, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.23.4", "publish": "true" } } The ISC License Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assertValidPattern = void 0; const MAX_PATTERN_LENGTH = 1024 * 64; const assertValidPattern = (pattern) => { if (typeof pattern !== 'string') { throw new TypeError('invalid pattern'); } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError('pattern is too long'); } }; exports.assertValidPattern = assertValidPattern; //# sourceMappingURL=assert-valid-pattern.js.map"use strict"; // parse a single path portion Object.defineProperty(exports, "__esModule", { value: true }); exports.AST = void 0; const brace_expressions_js_1 = require("./brace-expressions.js"); const unescape_js_1 = require("./unescape.js"); const types = new Set(['!', '?', '+', '*', '@']); const isExtglobType = (c) => types.has(c); // Patterns that get prepended to bind to the start of either the // entire string, or just a single path portion, to prevent dots // and/or traversal patterns, when needed. // Exts don't need the ^ or / bit, because the root binds that already. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))'; const startNoDot = '(?!\\.)'; // characters that indicate a start of pattern needs the "no dots" bit, // because a dot *might* be matched. ( is not in the list, because in // the case of a child extglob, it will handle the prevention itself. const addPatternStart = new Set(['[', '.']); // cases where traversal is A-OK, no dot prevention needed const justDots = new Set(['..', '.']); const reSpecials = new Set('().*{}+?[]^$\\!'); const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); // any single thing other than / const qmark = '[^/]'; // * => any number of characters const star = qmark + '*?'; // use + when we need to ensure that *something* matches, because the * is // the only thing in the path portion. const starNoEmpty = qmark + '+?'; // remove the \ chars that we added if we end up doing a nonmagic compare // const deslash = (s: string) => s.replace(/\\(.)/g, '$1') class AST { type; #root; #hasMagic; #uflag = false; #parts = []; #parent; #parentIndex; #negs; #filledNegs = false; #options; #toString; // set to true if it's an extglob with no children // (which really means one child of '') #emptyExt = false; constructor(type, parent, options = {}) { this.type = type; // extglobs are inherently magical if (type) this.#hasMagic = true; this.#parent = parent; this.#root = this.#parent ? this.#parent.#root : this; this.#options = this.#root === this ? options : this.#root.#options; this.#negs = this.#root === this ? [] : this.#root.#negs; if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this); this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; } get hasMagic() { /* c8 ignore start */ if (this.#hasMagic !== undefined) return this.#hasMagic; /* c8 ignore stop */ for (const p of this.#parts) { if (typeof p === 'string') continue; if (p.type || p.hasMagic) return (this.#hasMagic = true); } // note: will be undefined until we generate the regexp src and find out return this.#hasMagic; } // reconstructs the pattern toString() { if (this.#toString !== undefined) return this.#toString; if (!this.type) { return (this.#toString = this.#parts.map(p => String(p)).join('')); } else { return (this.#toString = this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')'); } } #fillNegs() { /* c8 ignore start */ if (this !== this.#root) throw new Error('should only call on root'); if (this.#filledNegs) return this; /* c8 ignore stop */ // call toString() once to fill this out this.toString(); this.#filledNegs = true; let n; while ((n = this.#negs.pop())) { if (n.type !== '!') continue; // walk up the tree, appending everthing that comes AFTER parentIndex let p = n; let pp = p.#parent; while (pp) { for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { for (const part of n.#parts) { /* c8 ignore start */ if (typeof part === 'string') { throw new Error('string part in extglob AST??'); } /* c8 ignore stop */ part.copyIn(pp.#parts[i]); } } p = pp; pp = p.#parent; } } return this; } push(...parts) { for (const p of parts) { if (p === '') continue; /* c8 ignore start */ if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) { throw new Error('invalid part: ' + p); } /* c8 ignore stop */ this.#parts.push(p); } } toJSON() { const ret = this.type === null ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON())) : [this.type, ...this.#parts.map(p => p.toJSON())]; if (this.isStart() && !this.type) ret.unshift([]); if (this.isEnd() && (this === this.#root || (this.#root.#filledNegs && this.#parent?.type === '!'))) { ret.push({}); } return ret; } isStart() { if (this.#root === this) return true; // if (this.type) return !!this.#parent?.isStart() if (!this.#parent?.isStart()) return false; if (this.#parentIndex === 0) return true; // if everything AHEAD of this is a negation, then it's still the "start" const p = this.#parent; for (let i = 0; i < this.#parentIndex; i++) { const pp = p.#parts[i]; if (!(pp instanceof AST && pp.type === '!')) { return false; } } return true; } isEnd() { if (this.#root === this) return true; if (this.#parent?.type === '!') return true; if (!this.#parent?.isEnd()) return false; if (!this.type) return this.#parent?.isEnd(); // if not root, it'll always have a parent /* c8 ignore start */ const pl = this.#parent ? this.#parent.#parts.length : 0; /* c8 ignore stop */ return this.#parentIndex === pl - 1; } copyIn(part) { if (typeof part === 'string') this.push(part); else this.push(part.clone(this)); } clone(parent) { const c = new AST(this.type, parent); for (const p of this.#parts) { c.copyIn(p); } return c; } static #parseAST(str, ast, pos, opt) { let escaping = false; let inBrace = false; let braceStart = -1; let braceNeg = false; if (ast.type === null) { // outside of a extglob, append until we find a start let i = pos; let acc = ''; while (i < str.length) { const c = str.charAt(i++); // still accumulate escapes at this point, but we do ignore // starts that are escaped if (escaping || c === '\\') { escaping = !escaping; acc += c; continue; } if (inBrace) { if (i === braceStart + 1) { if (c === '^' || c === '!') { braceNeg = true; } } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { inBrace = false; } acc += c; continue; } else if (c === '[') { inBrace = true; braceStart = i; braceNeg = false; acc += c; continue; } if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') { ast.push(acc); acc = ''; const ext = new AST(c, ast); i = AST.#parseAST(str, ext, i, opt); ast.push(ext); continue; } acc += c; } ast.push(acc); return i; } // some kind of extglob, pos is at the ( // find the next | or ) let i = pos + 1; let part = new AST(null, ast); const parts = []; let acc = ''; while (i < str.length) { const c = str.charAt(i++); // still accumulate escapes at this point, but we do ignore // starts that are escaped if (escaping || c === '\\') { escaping = !escaping; acc += c; continue; } if (inBrace) { if (i === braceStart + 1) { if (c === '^' || c === '!') { braceNeg = true; } } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { inBrace = false; } acc += c; continue; } else if (c === '[') { inBrace = true; braceStart = i; braceNeg = false; acc += c; continue; } if (isExtglobType(c) && str.charAt(i) === '(') { part.push(acc); acc = ''; const ext = new AST(c, part); part.push(ext); i = AST.#parseAST(str, ext, i, opt); continue; } if (c === '|') { part.push(acc); acc = ''; parts.push(part); part = new AST(null, ast); continue; } if (c === ')') { if (acc === '' && ast.#parts.length === 0) { ast.#emptyExt = true; } part.push(acc); acc = ''; ast.push(...parts, part); return i; } acc += c; } // unfinished extglob // if we got here, it was a malformed extglob! not an extglob, but // maybe something else in there. ast.type = null; ast.#hasMagic = undefined; ast.#parts = [str.substring(pos - 1)]; return i; } static fromGlob(pattern, options = {}) { const ast = new AST(null, undefined, options); AST.#parseAST(pattern, ast, 0, options); return ast; } // returns the regular expression if there's magic, or the unescaped // string if not. toMMPattern() { // should only be called on root /* c8 ignore start */ if (this !== this.#root) return this.#root.toMMPattern(); /* c8 ignore stop */ const glob = this.toString(); const [re, body, hasMagic, uflag] = this.toRegExpSource(); // if we're in nocase mode, and not nocaseMagicOnly, then we do // still need a regular expression if we have to case-insensitively // match capital/lowercase characters. const anyMagic = hasMagic || this.#hasMagic || (this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase()); if (!anyMagic) { return body; } const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : ''); return Object.assign(new RegExp(`^${re}$`, flags), { _src: re, _glob: glob, }); } get options() { return this.#options; } // returns the string match, the regexp source, whether there's magic // in the regexp (so a regular expression is required) and whether or // not the uflag is needed for the regular expression (for posix classes) // TODO: instead of injecting the start/end at this point, just return // the BODY of the regexp, along with the start/end portions suitable // for binding the start/end in either a joined full-path makeRe context // (where we bind to (^|/), or a standalone matchPart context (where // we bind to ^, and not /). Otherwise slashes get duped! // // In part-matching mode, the start is: // - if not isStart: nothing // - if traversal possible, but not allowed: ^(?!\.\.?$) // - if dots allowed or not possible: ^ // - if dots possible and not allowed: ^(?!\.) // end is: // - if not isEnd(): nothing // - else: $ // // In full-path matching mode, we put the slash at the START of the // pattern, so start is: // - if first pattern: same as part-matching mode // - if not isStart(): nothing // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) // - if dots allowed or not possible: / // - if dots possible and not allowed: /(?!\.) // end is: // - if last pattern, same as part-matching mode // - else nothing // // Always put the (?:$|/) on negated tails, though, because that has to be // there to bind the end of the negated pattern portion, and it's easier to // just stick it in now rather than try to inject it later in the middle of // the pattern. // // We can just always return the same end, and leave it up to the caller // to know whether it's going to be used joined or in parts. // And, if the start is adjusted slightly, can do the same there: // - if not isStart: nothing // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) // - if dots allowed or not possible: (?:/|^) // - if dots possible and not allowed: (?:/|^)(?!\.) // // But it's better to have a simpler binding without a conditional, for // performance, so probably better to return both start options. // // Then the caller just ignores the end if it's not the first pattern, // and the start always gets applied. // // But that's always going to be $ if it's the ending pattern, or nothing, // so the caller can just attach $ at the end of the pattern when building. // // So the todo is: // - better detect what kind of start is needed // - return both flavors of starting pattern // - attach $ at the end of the pattern when creating the actual RegExp // // Ah, but wait, no, that all only applies to the root when the first pattern // is not an extglob. If the first pattern IS an extglob, then we need all // that dot prevention biz to live in the extglob portions, because eg // +(*|.x*) can match .xy but not .yx. // // So, return the two flavors if it's #root and the first child is not an // AST, otherwise leave it to the child AST to handle it, and there, // use the (?:^|/) style of start binding. // // Even simplified further: // - Since the start for a join is eg /(?!\.) and the start for a part // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root // or start or whatever) and prepend ^ or / at the Regexp construction. toRegExpSource(allowDot) { const dot = allowDot ?? !!this.#options.dot; if (this.#root === this) this.#fillNegs(); if (!this.type) { const noEmpty = this.isStart() && this.isEnd(); const src = this.#parts .map(p => { const [re, _, hasMagic, uflag] = typeof p === 'string' ? AST.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot); this.#hasMagic = this.#hasMagic || hasMagic; this.#uflag = this.#uflag || uflag; return re; }) .join(''); let start = ''; if (this.isStart()) { if (typeof this.#parts[0] === 'string') { // this is the string that will match the start of the pattern, // so we need to protect against dots and such. // '.' and '..' cannot match unless the pattern is that exactly, // even if it starts with . or dot:true is set. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); if (!dotTravAllowed) { const aps = addPatternStart; // check if we have a possibility of matching . or .., // and prevent that. const needNoTrav = // dots are allowed, and the pattern starts with [ or . (dot && aps.has(src.charAt(0))) || // the pattern starts with \., and then [ or . (src.startsWith('\\.') && aps.has(src.charAt(2))) || // the pattern starts with \.\., and then [ or . (src.startsWith('\\.\\.') && aps.has(src.charAt(4))); // no need to prevent dots if it can't match a dot, or if a // sub-pattern will be preventing it anyway. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0)); start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''; } } } // append the "end of path portion" pattern to negation tails let end = ''; if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === '!') { end = '(?:$|\\/)'; } const final = start + src + end; return [ final, (0, unescape_js_1.unescape)(src), (this.#hasMagic = !!this.#hasMagic), this.#uflag, ]; } // We need to calculate the body *twice* if it's a repeat pattern // at the start, once in nodot mode, then again in dot mode, so a // pattern like *(?) can match 'x.y' const repeated = this.type === '*' || this.type === '+'; // some kind of extglob const start = this.type === '!' ? '(?:(?!(?:' : '(?:'; let body = this.#partsToRegExp(dot); if (this.isStart() && this.isEnd() && !body && this.type !== '!') { // invalid extglob, has to at least be *something* present, if it's // the entire path portion. const s = this.toString(); this.#parts = [s]; this.type = null; this.#hasMagic = undefined; return [s, (0, unescape_js_1.unescape)(this.toString()), false, false]; } // XXX abstract out this map method let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? '' : this.#partsToRegExp(true); if (bodyDotAllowed === body) { bodyDotAllowed = ''; } if (bodyDotAllowed) { body = `(?:${body})(?:${bodyDotAllowed})*?`; } // an empty !() is exactly equivalent to a starNoEmpty let final = ''; if (this.type === '!' && this.#emptyExt) { final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty; } else { const close = this.type === '!' ? // !() must match something,but !(x) can match '' '))' + (this.isStart() && !dot && !allowDot ? startNoDot : '') + star + ')' : this.type === '@' ? ')' : this.type === '?' ? ')?' : this.type === '+' && bodyDotAllowed ? ')' : this.type === '*' && bodyDotAllowed ? `)?` : `)${this.type}`; final = start + body + close; } return [ final, (0, unescape_js_1.unescape)(body), (this.#hasMagic = !!this.#hasMagic), this.#uflag, ]; } #partsToRegExp(dot) { return this.#parts .map(p => { // extglob ASTs should only contain parent ASTs /* c8 ignore start */ if (typeof p === 'string') { throw new Error('string type in extglob ast??'); } /* c8 ignore stop */ // can ignore hasMagic, because extglobs are already always magic const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot); this.#uflag = this.#uflag || uflag; return re; }) .filter(p => !(this.isStart() && this.isEnd()) || !!p) .join('|'); } static #parseGlob(glob, hasMagic, noEmpty = false) { let escaping = false; let re = ''; let uflag = false; for (let i = 0; i < glob.length; i++) { const c = glob.charAt(i); if (escaping) { escaping = false; re += (reSpecials.has(c) ? '\\' : '') + c; continue; } if (c === '\\') { if (i === glob.length - 1) { re += '\\\\'; } else { escaping = true; } continue; } if (c === '[') { const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i); if (consumed) { re += src; uflag = uflag || needUflag; i += consumed - 1; hasMagic = hasMagic || magic; continue; } } if (c === '*') { if (noEmpty && glob === '*') re += starNoEmpty; else re += star; hasMagic = true; continue; } if (c === '?') { re += qmark; hasMagic = true; continue; } re += regExpEscape(c); } return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag]; } } exports.AST = AST; //# sourceMappingURL=ast.js.map"use strict"; // translate the various posix character classes into unicode properties // this works across all unicode locales Object.defineProperty(exports, "__esModule", { value: true }); exports.parseClass = void 0; // { : [, /u flag required, negated] const posixClasses = { '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], '[:alpha:]': ['\\p{L}\\p{Nl}', true], '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], '[:blank:]': ['\\p{Zs}\\t', true], '[:cntrl:]': ['\\p{Cc}', true], '[:digit:]': ['\\p{Nd}', true], '[:graph:]': ['\\p{Z}\\p{C}', true, true], '[:lower:]': ['\\p{Ll}', true], '[:print:]': ['\\p{C}', true], '[:punct:]': ['\\p{P}', true], '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], '[:upper:]': ['\\p{Lu}', true], '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], '[:xdigit:]': ['A-Fa-f0-9', false], }; // only need to escape a few things inside of brace expressions // escapes: [ \ ] - const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); // escape all regexp magic characters const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); // everything has already been escaped, we just have to join const rangesToString = (ranges) => ranges.join(''); // takes a glob string at a posix brace expression, and returns // an equivalent regular expression source, and boolean indicating // whether the /u flag needs to be applied, and the number of chars // consumed to parse the character class. // This also removes out of order ranges, and returns ($.) if the // entire class just no good. const parseClass = (glob, position) => { const pos = position; /* c8 ignore start */ if (glob.charAt(pos) !== '[') { throw new Error('not in a brace expression'); } /* c8 ignore stop */ const ranges = []; const negs = []; let i = pos + 1; let sawStart = false; let uflag = false; let escaping = false; let negate = false; let endPos = pos; let rangeStart = ''; WHILE: while (i < glob.length) { const c = glob.charAt(i); if ((c === '!' || c === '^') && i === pos + 1) { negate = true; i++; continue; } if (c === ']' && sawStart && !escaping) { endPos = i + 1; break; } sawStart = true; if (c === '\\') { if (!escaping) { escaping = true; i++; continue; } // escaped \ char, fall through and treat like normal char } if (c === '[' && !escaping) { // either a posix class, a collation equivalent, or just a [ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { if (glob.startsWith(cls, i)) { // invalid, [a-[] is fine, but not [a-[:alpha]] if (rangeStart) { return ['$.', false, glob.length - pos, true]; } i += cls.length; if (neg) negs.push(unip); else ranges.push(unip); uflag = uflag || u; continue WHILE; } } } // now it's just a normal character, effectively escaping = false; if (rangeStart) { // throw this range away if it's not valid, but others // can still match. if (c > rangeStart) { ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); } else if (c === rangeStart) { ranges.push(braceEscape(c)); } rangeStart = ''; i++; continue; } // now might be the start of a range. // can be either c-d or c-] or c] or c] at this point if (glob.startsWith('-]', i + 1)) { ranges.push(braceEscape(c + '-')); i += 2; continue; } if (glob.startsWith('-', i + 1)) { rangeStart = c; i += 2; continue; } // not the start of a range, just a single character ranges.push(braceEscape(c)); i++; } if (endPos < i) { // didn't see the end of the class, not a valid class, // but might still be valid as a literal match. return ['', false, 0, false]; } // if we got no ranges and no negates, then we have a range that // cannot possibly match anything, and that poisons the whole glob if (!ranges.length && !negs.length) { return ['$.', false, glob.length - pos, true]; } // if we got one positive range, and it's a single character, then that's // not actually a magic pattern, it's just that one literal character. // we should not treat that as "magic", we should just return the literal // character. [_] is a perfectly valid way to escape glob magic chars. if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) { const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; return [regexpEscape(r), false, endPos - pos, false]; } const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' : ranges.length ? sranges : snegs; return [comb, uflag, endPos - pos, true]; }; exports.parseClass = parseClass; //# sourceMappingURL=brace-expressions.js.map"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.escape = void 0; /** * Escape all magic characters in a glob pattern. * * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} * option is used, then characters are escaped by wrapping in `[]`, because * a magic character wrapped in a character class can only be satisfied by * that exact character. In this mode, `\` is _not_ escaped, because it is * not interpreted as a magic character, but instead as a path separator. */ const escape = (s, { windowsPathsNoEscape = false, } = {}) => { // don't need to escape +@! because we escape the parens // that make those magic, and escaping ! as [!] isn't valid, // because [!]] is a valid glob class meaning not ']'. return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, '[$&]') : s.replace(/[?*()[\]\\]/g, '\\$&'); }; exports.escape = escape; //# sourceMappingURL=escape.js.map"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; const brace_expansion_1 = __importDefault(require("brace-expansion")); const assert_valid_pattern_js_1 = require("./assert-valid-pattern.js"); const ast_js_1 = require("./ast.js"); const escape_js_1 = require("./escape.js"); const unescape_js_1 = require("./unescape.js"); const minimatch = (p, pattern, options = {}) => { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false; } return new Minimatch(pattern, options).match(p); }; exports.minimatch = minimatch; // Optimized checking for the most common glob patterns. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); const starDotExtTestNocase = (ext) => { ext = ext.toLowerCase(); return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); }; const starDotExtTestNocaseDot = (ext) => { ext = ext.toLowerCase(); return (f) => f.toLowerCase().endsWith(ext); }; const starDotStarRE = /^\*+\.\*+$/; const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); const dotStarRE = /^\.\*+$/; const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); const starRE = /^\*+$/; const starTest = (f) => f.length !== 0 && !f.startsWith('.'); const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; const qmarksTestNocase = ([$0, ext = '']) => { const noext = qmarksTestNoExt([$0]); if (!ext) return noext; ext = ext.toLowerCase(); return (f) => noext(f) && f.toLowerCase().endsWith(ext); }; const qmarksTestNocaseDot = ([$0, ext = '']) => { const noext = qmarksTestNoExtDot([$0]); if (!ext) return noext; ext = ext.toLowerCase(); return (f) => noext(f) && f.toLowerCase().endsWith(ext); }; const qmarksTestDot = ([$0, ext = '']) => { const noext = qmarksTestNoExtDot([$0]); return !ext ? noext : (f) => noext(f) && f.endsWith(ext); }; const qmarksTest = ([$0, ext = '']) => { const noext = qmarksTestNoExt([$0]); return !ext ? noext : (f) => noext(f) && f.endsWith(ext); }; const qmarksTestNoExt = ([$0]) => { const len = $0.length; return (f) => f.length === len && !f.startsWith('.'); }; const qmarksTestNoExtDot = ([$0]) => { const len = $0.length; return (f) => f.length === len && f !== '.' && f !== '..'; }; /* c8 ignore start */ const defaultPlatform = (typeof process === 'object' && process ? (typeof process.env === 'object' && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__) || process.platform : 'posix'); const path = { win32: { sep: '\\' }, posix: { sep: '/' }, }; /* c8 ignore stop */ exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep; exports.minimatch.sep = exports.sep; exports.GLOBSTAR = Symbol('globstar **'); exports.minimatch.GLOBSTAR = exports.GLOBSTAR; // any single thing other than / // don't need to escape / when using new RegExp() const qmark = '[^/]'; // * => any number of characters const star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; // not a ^ or / followed by a dot, // followed by anything, any number of times. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); exports.filter = filter; exports.minimatch.filter = exports.filter; const ext = (a, b = {}) => Object.assign({}, a, b); const defaults = (def) => { if (!def || typeof def !== 'object' || !Object.keys(def).length) { return exports.minimatch; } const orig = exports.minimatch; const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); return Object.assign(m, { Minimatch: class Minimatch extends orig.Minimatch { constructor(pattern, options = {}) { super(pattern, ext(def, options)); } static defaults(options) { return orig.defaults(ext(def, options)).Minimatch; } }, AST: class AST extends orig.AST { /* c8 ignore start */ constructor(type, parent, options = {}) { super(type, parent, ext(def, options)); } /* c8 ignore stop */ static fromGlob(pattern, options = {}) { return orig.AST.fromGlob(pattern, ext(def, options)); } }, unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), escape: (s, options = {}) => orig.escape(s, ext(def, options)), filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), defaults: (options) => orig.defaults(ext(def, options)), makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), sep: orig.sep, GLOBSTAR: exports.GLOBSTAR, }); }; exports.defaults = defaults; exports.minimatch.defaults = exports.defaults; // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c const braceExpand = (pattern, options = {}) => { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); // Thanks to Yeting Li for // improving this regexp to avoid a ReDOS vulnerability. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern]; } return (0, brace_expansion_1.default)(pattern); }; exports.braceExpand = braceExpand; exports.minimatch.braceExpand = exports.braceExpand; // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); exports.makeRe = makeRe; exports.minimatch.makeRe = exports.makeRe; const match = (list, pattern, options = {}) => { const mm = new Minimatch(pattern, options); list = list.filter(f => mm.match(f)); if (mm.options.nonull && !list.length) { list.push(pattern); } return list; }; exports.match = match; exports.minimatch.match = exports.match; // replace stuff like \* with * const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); class Minimatch { options; set; pattern; windowsPathsNoEscape; nonegate; negate; comment; empty; preserveMultipleSlashes; partial; globSet; globParts; nocase; isWindows; platform; windowsNoMagicRoot; regexp; constructor(pattern, options = {}) { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); options = options || {}; this.options = options; this.pattern = pattern; this.platform = options.platform || defaultPlatform; this.isWindows = this.platform === 'win32'; this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; if (this.windowsPathsNoEscape) { this.pattern = this.pattern.replace(/\\/g, '/'); } this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; this.regexp = null; this.negate = false; this.nonegate = !!options.nonegate; this.comment = false; this.empty = false; this.partial = !!options.partial; this.nocase = !!this.options.nocase; this.windowsNoMagicRoot = options.windowsNoMagicRoot !== undefined ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase); this.globSet = []; this.globParts = []; this.set = []; // make the set of regexps etc. this.make(); } hasMagic() { if (this.options.magicalBraces && this.set.length > 1) { return true; } for (const pattern of this.set) { for (const part of pattern) { if (typeof part !== 'string') return true; } } return false; } debug(..._) { } make() { const pattern = this.pattern; const options = this.options; // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true; return; } if (!pattern) { this.empty = true; return; } // step 1: figure out negation, etc. this.parseNegate(); // step 2: expand braces this.globSet = [...new Set(this.braceExpand())]; if (options.debug) { this.debug = (...args) => console.error(...args); } this.debug(this.pattern, this.globSet); // step 3: now we have a set, so turn each one into a series of // path-portion matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters // // First, we preprocess to make the glob pattern sets a bit simpler // and deduped. There are some perf-killing patterns that can cause // problems with a glob walk, but we can simplify them down a bit. const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); this.globParts = this.preprocess(rawGlobParts); this.debug(this.pattern, this.globParts); // glob --> regexps let set = this.globParts.map((s, _, __) => { if (this.isWindows && this.windowsNoMagicRoot) { // check if it's a drive or unc path. const isUNC = s[0] === '' && s[1] === '' && (s[2] === '?' || !globMagic.test(s[2])) && !globMagic.test(s[3]); const isDrive = /^[a-z]:/i.test(s[0]); if (isUNC) { return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]; } else if (isDrive) { return [s[0], ...s.slice(1).map(ss => this.parse(ss))]; } } return s.map(ss => this.parse(ss)); }); this.debug(this.pattern, set); // filter out everything that didn't compile properly. this.set = set.filter(s => s.indexOf(false) === -1); // do not treat the ? in UNC paths as magic if (this.isWindows) { for (let i = 0; i < this.set.length; i++) { const p = this.set[i]; if (p[0] === '' && p[1] === '' && this.globParts[i][2] === '?' && typeof p[3] === 'string' && /^[a-z]:$/i.test(p[3])) { p[2] = '?'; } } } this.debug(this.pattern, this.set); } // various transforms to equivalent pattern sets that are // faster to process in a filesystem walk. The goal is to // eliminate what we can, and push all ** patterns as far // to the right as possible, even if it increases the number // of patterns that we have to process. preprocess(globParts) { // if we're not in globstar mode, then turn all ** into * if (this.options.noglobstar) { for (let i = 0; i < globParts.length; i++) { for (let j = 0; j < globParts[i].length; j++) { if (globParts[i][j] === '**') { globParts[i][j] = '*'; } } } } const { optimizationLevel = 1 } = this.options; if (optimizationLevel >= 2) { // aggressive optimization for the purpose of fs walking globParts = this.firstPhasePreProcess(globParts); globParts = this.secondPhasePreProcess(globParts); } else if (optimizationLevel >= 1) { // just basic optimizations to remove some .. parts globParts = this.levelOneOptimize(globParts); } else { // just collapse multiple ** portions into one globParts = this.adjascentGlobstarOptimize(globParts); } return globParts; } // just get rid of adjascent ** portions adjascentGlobstarOptimize(globParts) { return globParts.map(parts => { let gs = -1; while (-1 !== (gs = parts.indexOf('**', gs + 1))) { let i = gs; while (parts[i + 1] === '**') { i++; } if (i !== gs) { parts.splice(gs, i - gs); } } return parts; }); } // get rid of adjascent ** and resolve .. portions levelOneOptimize(globParts) { return globParts.map(parts => { parts = parts.reduce((set, part) => { const prev = set[set.length - 1]; if (part === '**' && prev === '**') { return set; } if (part === '..') { if (prev && prev !== '..' && prev !== '.' && prev !== '**') { set.pop(); return set; } } set.push(part); return set; }, []); return parts.length === 0 ? [''] : parts; }); } levelTwoFileOptimize(parts) { if (!Array.isArray(parts)) { parts = this.slashSplit(parts); } let didSomething = false; do { didSomething = false; //
// -> 
/
            if (!this.preserveMultipleSlashes) {
                for (let i = 1; i < parts.length - 1; i++) {
                    const p = parts[i];
                    // don't squeeze out UNC patterns
                    if (i === 1 && p === '' && parts[0] === '')
                        continue;
                    if (p === '.' || p === '') {
                        didSomething = true;
                        parts.splice(i, 1);
                        i--;
                    }
                }
                if (parts[0] === '.' &&
                    parts.length === 2 &&
                    (parts[1] === '.' || parts[1] === '')) {
                    didSomething = true;
                    parts.pop();
                }
            }
            // 
/

/../ ->

/
            let dd = 0;
            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                const p = parts[dd - 1];
                if (p && p !== '.' && p !== '..' && p !== '**') {
                    didSomething = true;
                    parts.splice(dd - 1, 2);
                    dd -= 2;
                }
            }
        } while (didSomething);
        return parts.length === 0 ? [''] : parts;
    }
    // First phase: single-pattern processing
    // 
 is 1 or more portions
    //  is 1 or more portions
    // 

is any portion other than ., .., '', or ** // is . or '' // // **/.. is *brutal* for filesystem walking performance, because // it effectively resets the recursive walk each time it occurs, // and ** cannot be reduced out by a .. pattern part like a regexp // or most strings (other than .., ., and '') can be. // //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} //

// -> 
/
    // 
/

/../ ->

/
    // **/**/ -> **/
    //
    // **/*/ -> */**/ <== not valid because ** doesn't follow
    // this WOULD be allowed if ** did follow symlinks, or * didn't
    firstPhasePreProcess(globParts) {
        let didSomething = false;
        do {
            didSomething = false;
            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} for (let parts of globParts) { let gs = -1; while (-1 !== (gs = parts.indexOf('**', gs + 1))) { let gss = gs; while (parts[gss + 1] === '**') { //

/**/**/ -> 
/**/
                        gss++;
                    }
                    // eg, if gs is 2 and gss is 4, that means we have 3 **
                    // parts, and can remove 2 of them.
                    if (gss > gs) {
                        parts.splice(gs + 1, gss - gs);
                    }
                    let next = parts[gs + 1];
                    const p = parts[gs + 2];
                    const p2 = parts[gs + 3];
                    if (next !== '..')
                        continue;
                    if (!p ||
                        p === '.' ||
                        p === '..' ||
                        !p2 ||
                        p2 === '.' ||
                        p2 === '..') {
                        continue;
                    }
                    didSomething = true;
                    // edit parts in place, and push the new one
                    parts.splice(gs, 1);
                    const other = parts.slice(0);
                    other[gs] = '**';
                    globParts.push(other);
                    gs--;
                }
                // 
// -> 
/
                if (!this.preserveMultipleSlashes) {
                    for (let i = 1; i < parts.length - 1; i++) {
                        const p = parts[i];
                        // don't squeeze out UNC patterns
                        if (i === 1 && p === '' && parts[0] === '')
                            continue;
                        if (p === '.' || p === '') {
                            didSomething = true;
                            parts.splice(i, 1);
                            i--;
                        }
                    }
                    if (parts[0] === '.' &&
                        parts.length === 2 &&
                        (parts[1] === '.' || parts[1] === '')) {
                        didSomething = true;
                        parts.pop();
                    }
                }
                // 
/

/../ ->

/
                let dd = 0;
                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                    const p = parts[dd - 1];
                    if (p && p !== '.' && p !== '..' && p !== '**') {
                        didSomething = true;
                        const needDot = dd === 1 && parts[dd + 1] === '**';
                        const splin = needDot ? ['.'] : [];
                        parts.splice(dd - 1, 2, ...splin);
                        if (parts.length === 0)
                            parts.push('');
                        dd -= 2;
                    }
                }
            }
        } while (didSomething);
        return globParts;
    }
    // second phase: multi-pattern dedupes
    // {
/*/,
/

/} ->

/*/
    // {
/,
/} -> 
/
    // {
/**/,
/} -> 
/**/
    //
    // {
/**/,
/**/

/} ->

/**/
    // ^-- not valid because ** doens't follow symlinks
    secondPhasePreProcess(globParts) {
        for (let i = 0; i < globParts.length - 1; i++) {
            for (let j = i + 1; j < globParts.length; j++) {
                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
                if (matched) {
                    globParts[i] = [];
                    globParts[j] = matched;
                    break;
                }
            }
        }
        return globParts.filter(gs => gs.length);
    }
    partsMatch(a, b, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = '';
        while (ai < a.length && bi < b.length) {
            if (a[ai] === b[bi]) {
                result.push(which === 'b' ? b[bi] : a[ai]);
                ai++;
                bi++;
            }
            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
                result.push(a[ai]);
                ai++;
            }
            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
                result.push(b[bi]);
                bi++;
            }
            else if (a[ai] === '*' &&
                b[bi] &&
                (this.options.dot || !b[bi].startsWith('.')) &&
                b[bi] !== '**') {
                if (which === 'b')
                    return false;
                which = 'a';
                result.push(a[ai]);
                ai++;
                bi++;
            }
            else if (b[bi] === '*' &&
                a[ai] &&
                (this.options.dot || !a[ai].startsWith('.')) &&
                a[ai] !== '**') {
                if (which === 'a')
                    return false;
                which = 'b';
                result.push(b[bi]);
                ai++;
                bi++;
            }
            else {
                return false;
            }
        }
        // if we fall out of the loop, it means they two are identical
        // as long as their lengths match
        return a.length === b.length && result;
    }
    parseNegate() {
        if (this.nonegate)
            return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
            negate = !negate;
            negateOffset++;
        }
        if (negateOffset)
            this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
    }
    // set partial to true to test if, for example,
    // "/a/b" matches the start of "/*/b/*/d"
    // Partial means, if you run out of file before you run
    // out of pattern, then that's fine, as long as all
    // the parts match.
    matchOne(file, pattern, partial = false) {
        const options = this.options;
        // UNC paths like //?/X:/... can match X:/... and vice versa
        // Drive letters in absolute drive or unc paths are always compared
        // case-insensitively.
        if (this.isWindows) {
            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
            const fileUNC = !fileDrive &&
                file[0] === '' &&
                file[1] === '' &&
                file[2] === '?' &&
                /^[a-z]:$/i.test(file[3]);
            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
            const patternUNC = !patternDrive &&
                pattern[0] === '' &&
                pattern[1] === '' &&
                pattern[2] === '?' &&
                typeof pattern[3] === 'string' &&
                /^[a-z]:$/i.test(pattern[3]);
            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
            if (typeof fdi === 'number' && typeof pdi === 'number') {
                const [fd, pd] = [file[fdi], pattern[pdi]];
                if (fd.toLowerCase() === pd.toLowerCase()) {
                    pattern[pdi] = fd;
                    if (pdi > fdi) {
                        pattern = pattern.slice(pdi);
                    }
                    else if (fdi > pdi) {
                        file = file.slice(fdi);
                    }
                }
            }
        }
        // resolve and reduce . and .. portions in the file as well.
        // dont' need to do the second phase, because it's only one string[]
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
            file = this.levelTwoFileOptimize(file);
        }
        this.debug('matchOne', this, { file, pattern });
        this.debug('matchOne', file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
            this.debug('matchOne loop');
            var p = pattern[pi];
            var f = file[fi];
            this.debug(pattern, p, f);
            // should be impossible.
            // some invalid regexp stuff in the set.
            /* c8 ignore start */
            if (p === false) {
                return false;
            }
            /* c8 ignore stop */
            if (p === exports.GLOBSTAR) {
                this.debug('GLOBSTAR', [pattern, p, f]);
                // "**"
                // a/**/b/**/c would match the following:
                // a/b/x/y/z/c
                // a/x/y/z/b/c
                // a/b/x/b/x/c
                // a/b/c
                // To do this, take the rest of the pattern after
                // the **, and see if it would match the file remainder.
                // If so, return success.
                // If not, the ** "swallows" a segment, and try again.
                // This is recursively awful.
                //
                // a/**/b/**/c matching a/b/x/y/z/c
                // - a matches a
                // - doublestar
                //   - matchOne(b/x/y/z/c, b/**/c)
                //     - b matches b
                //     - doublestar
                //       - matchOne(x/y/z/c, c) -> no
                //       - matchOne(y/z/c, c) -> no
                //       - matchOne(z/c, c) -> no
                //       - matchOne(c, c) yes, hit
                var fr = fi;
                var pr = pi + 1;
                if (pr === pl) {
                    this.debug('** at the end');
                    // a ** at the end will just swallow the rest.
                    // We have found a match.
                    // however, it will not swallow /.x, unless
                    // options.dot is set.
                    // . and .. are *never* matched by **, for explosively
                    // exponential reasons.
                    for (; fi < fl; fi++) {
                        if (file[fi] === '.' ||
                            file[fi] === '..' ||
                            (!options.dot && file[fi].charAt(0) === '.'))
                            return false;
                    }
                    return true;
                }
                // ok, let's see if we can swallow whatever we can.
                while (fr < fl) {
                    var swallowee = file[fr];
                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
                    // XXX remove this slice.  Just pass the start index.
                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                        this.debug('globstar found match!', fr, fl, swallowee);
                        // found a match.
                        return true;
                    }
                    else {
                        // can't swallow "." or ".." ever.
                        // can only swallow ".foo" when explicitly asked.
                        if (swallowee === '.' ||
                            swallowee === '..' ||
                            (!options.dot && swallowee.charAt(0) === '.')) {
                            this.debug('dot detected!', file, fr, pattern, pr);
                            break;
                        }
                        // ** swallows a segment, and continue.
                        this.debug('globstar swallow a segment, and continue');
                        fr++;
                    }
                }
                // no match was found.
                // However, in partial mode, we can't say this is necessarily over.
                /* c8 ignore start */
                if (partial) {
                    // ran out of file
                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
                    if (fr === fl) {
                        return true;
                    }
                }
                /* c8 ignore stop */
                return false;
            }
            // something other than **
            // non-magic patterns just have to match exactly
            // patterns with magic have been turned into regexps.
            let hit;
            if (typeof p === 'string') {
                hit = f === p;
                this.debug('string match', p, f, hit);
            }
            else {
                hit = p.test(f);
                this.debug('pattern match', p, f, hit);
            }
            if (!hit)
                return false;
        }
        // Note: ending in / means that we'll get a final ""
        // at the end of the pattern.  This can only match a
        // corresponding "" at the end of the file.
        // If the file ends in /, then it can only match a
        // a pattern that ends in /, unless the pattern just
        // doesn't have any more for it. But, a/b/ should *not*
        // match "a/b/*", even though "" matches against the
        // [^/]*? pattern, except in partial mode, where it might
        // simply not be reached yet.
        // However, a/b/ should still satisfy a/*
        // now either we fell off the end of the pattern, or we're done.
        if (fi === fl && pi === pl) {
            // ran out of pattern and filename at the same time.
            // an exact hit!
            return true;
        }
        else if (fi === fl) {
            // ran out of file, but still had pattern left.
            // this is ok if we're doing the match as part of
            // a glob fs traversal.
            return partial;
        }
        else if (pi === pl) {
            // ran out of pattern, still have file left.
            // this is only acceptable if we're on the very last
            // empty segment of a file with a trailing slash.
            // a/* should match a/b/
            return fi === fl - 1 && file[fi] === '';
            /* c8 ignore start */
        }
        else {
            // should be unreachable.
            throw new Error('wtf?');
        }
        /* c8 ignore stop */
    }
    braceExpand() {
        return (0, exports.braceExpand)(this.pattern, this.options);
    }
    parse(pattern) {
        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
        const options = this.options;
        // shortcuts
        if (pattern === '**')
            return exports.GLOBSTAR;
        if (pattern === '')
            return '';
        // far and away, the most common glob pattern parts are
        // *, *.*, and *.  Add a fast check method for those.
        let m;
        let fastTest = null;
        if ((m = pattern.match(starRE))) {
            fastTest = options.dot ? starTestDot : starTest;
        }
        else if ((m = pattern.match(starDotExtRE))) {
            fastTest = (options.nocase
                ? options.dot
                    ? starDotExtTestNocaseDot
                    : starDotExtTestNocase
                : options.dot
                    ? starDotExtTestDot
                    : starDotExtTest)(m[1]);
        }
        else if ((m = pattern.match(qmarksRE))) {
            fastTest = (options.nocase
                ? options.dot
                    ? qmarksTestNocaseDot
                    : qmarksTestNocase
                : options.dot
                    ? qmarksTestDot
                    : qmarksTest)(m);
        }
        else if ((m = pattern.match(starDotStarRE))) {
            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
        }
        else if ((m = pattern.match(dotStarRE))) {
            fastTest = dotStarTest;
        }
        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
        if (fastTest && typeof re === 'object') {
            // Avoids overriding in frozen environments
            Reflect.defineProperty(re, 'test', { value: fastTest });
        }
        return re;
    }
    makeRe() {
        if (this.regexp || this.regexp === false)
            return this.regexp;
        // at this point, this.set is a 2d array of partial
        // pattern strings, or "**".
        //
        // It's better to use .match().  This function shouldn't
        // be used, really, but it's pretty convenient sometimes,
        // when you just want to work with a regex.
        const set = this.set;
        if (!set.length) {
            this.regexp = false;
            return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar
            ? star
            : options.dot
                ? twoStarDot
                : twoStarNoDot;
        const flags = new Set(options.nocase ? ['i'] : []);
        // regexpify non-globstar patterns
        // if ** is only item, then we just do one twoStar
        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
        // if ** is last, append (\/twoStar|) to previous
        // if ** is in the middle, append (\/|\/twoStar\/) to previous
        // then filter out GLOBSTAR symbols
        let re = set
            .map(pattern => {
            const pp = pattern.map(p => {
                if (p instanceof RegExp) {
                    for (const f of p.flags.split(''))
                        flags.add(f);
                }
                return typeof p === 'string'
                    ? regExpEscape(p)
                    : p === exports.GLOBSTAR
                        ? exports.GLOBSTAR
                        : p._src;
            });
            pp.forEach((p, i) => {
                const next = pp[i + 1];
                const prev = pp[i - 1];
                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
                    return;
                }
                if (prev === undefined) {
                    if (next !== undefined && next !== exports.GLOBSTAR) {
                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
                    }
                    else {
                        pp[i] = twoStar;
                    }
                }
                else if (next === undefined) {
                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
                }
                else if (next !== exports.GLOBSTAR) {
                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
                    pp[i + 1] = exports.GLOBSTAR;
                }
            });
            return pp.filter(p => p !== exports.GLOBSTAR).join('/');
        })
            .join('|');
        // need to wrap in parens if we had more than one thing with |,
        // otherwise only the first will be anchored to ^ and the last to $
        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
        // must match entire pattern
        // ending in a * or ** will make it less strict.
        re = '^' + open + re + close + '$';
        // can match anything, as long as it's not this.
        if (this.negate)
            re = '^(?!' + re + ').+$';
        try {
            this.regexp = new RegExp(re, [...flags].join(''));
            /* c8 ignore start */
        }
        catch (ex) {
            // should be impossible
            this.regexp = false;
        }
        /* c8 ignore stop */
        return this.regexp;
    }
    slashSplit(p) {
        // if p starts with // on windows, we preserve that
        // so that UNC paths aren't broken.  Otherwise, any number of
        // / characters are coalesced into one, unless
        // preserveMultipleSlashes is set to true.
        if (this.preserveMultipleSlashes) {
            return p.split('/');
        }
        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
            // add an extra '' for the one we lose
            return ['', ...p.split(/\/+/)];
        }
        else {
            return p.split(/\/+/);
        }
    }
    match(f, partial = this.partial) {
        this.debug('match', f, this.pattern);
        // short-circuit in the case of busted things.
        // comments, etc.
        if (this.comment) {
            return false;
        }
        if (this.empty) {
            return f === '';
        }
        if (f === '/' && partial) {
            return true;
        }
        const options = this.options;
        // windows: need to use /, not \
        if (this.isWindows) {
            f = f.split('\\').join('/');
        }
        // treat the test path as a set of pathparts.
        const ff = this.slashSplit(f);
        this.debug(this.pattern, 'split', ff);
        // just ONE of the pattern sets in this.set needs to match
        // in order for it to be valid.  If negating, then just one
        // match means that we have failed.
        // Either way, return on the first hit.
        const set = this.set;
        this.debug(this.pattern, 'set', set);
        // Find the basename of the path by looking for the last non-empty segment
        let filename = ff[ff.length - 1];
        if (!filename) {
            for (let i = ff.length - 2; !filename && i >= 0; i--) {
                filename = ff[i];
            }
        }
        for (let i = 0; i < set.length; i++) {
            const pattern = set[i];
            let file = ff;
            if (options.matchBase && pattern.length === 1) {
                file = [filename];
            }
            const hit = this.matchOne(file, pattern, partial);
            if (hit) {
                if (options.flipNegate) {
                    return true;
                }
                return !this.negate;
            }
        }
        // didn't get any hits.  this is success if it's a negative
        // pattern, failure otherwise.
        if (options.flipNegate) {
            return false;
        }
        return this.negate;
    }
    static defaults(def) {
        return exports.minimatch.defaults(def).Minimatch;
    }
}
exports.Minimatch = Minimatch;
/* c8 ignore start */
var ast_js_2 = require("./ast.js");
Object.defineProperty(exports, "AST", { enumerable: true, get: function () { return ast_js_2.AST; } });
var escape_js_2 = require("./escape.js");
Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return escape_js_2.escape; } });
var unescape_js_2 = require("./unescape.js");
Object.defineProperty(exports, "unescape", { enumerable: true, get: function () { return unescape_js_2.unescape; } });
/* c8 ignore stop */
exports.minimatch.AST = ast_js_1.AST;
exports.minimatch.Minimatch = Minimatch;
exports.minimatch.escape = escape_js_1.escape;
exports.minimatch.unescape = unescape_js_1.unescape;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unescape = void 0;
/**
 * Un-escape a string that has been escaped with {@link escape}.
 *
 * If the {@link windowsPathsNoEscape} option is used, then square-brace
 * escapes are removed, but not backslash escapes.  For example, it will turn
 * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
 * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
 *
 * When `windowsPathsNoEscape` is not set, then both brace escapes and
 * backslash escapes are removed.
 *
 * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
 * or unescaped.
 */
const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
    return windowsPathsNoEscape
        ? s.replace(/\[([^\/\\])\]/g, '$1')
        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
};
exports.unescape = unescape;
//# sourceMappingURL=unescape.js.mapconst MAX_PATTERN_LENGTH = 1024 * 64;
export const assertValidPattern = (pattern) => {
    if (typeof pattern !== 'string') {
        throw new TypeError('invalid pattern');
    }
    if (pattern.length > MAX_PATTERN_LENGTH) {
        throw new TypeError('pattern is too long');
    }
};
//# sourceMappingURL=assert-valid-pattern.js.map// parse a single path portion
import { parseClass } from './brace-expressions.js';
import { unescape } from './unescape.js';
const types = new Set(['!', '?', '+', '*', '@']);
const isExtglobType = (c) => types.has(c);
// Patterns that get prepended to bind to the start of either the
// entire string, or just a single path portion, to prevent dots
// and/or traversal patterns, when needed.
// Exts don't need the ^ or / bit, because the root binds that already.
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
const startNoDot = '(?!\\.)';
// characters that indicate a start of pattern needs the "no dots" bit,
// because a dot *might* be matched. ( is not in the list, because in
// the case of a child extglob, it will handle the prevention itself.
const addPatternStart = new Set(['[', '.']);
// cases where traversal is A-OK, no dot prevention needed
const justDots = new Set(['..', '.']);
const reSpecials = new Set('().*{}+?[]^$\\!');
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// any single thing other than /
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// use + when we need to ensure that *something* matches, because the * is
// the only thing in the path portion.
const starNoEmpty = qmark + '+?';
// remove the \ chars that we added if we end up doing a nonmagic compare
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
export class AST {
    type;
    #root;
    #hasMagic;
    #uflag = false;
    #parts = [];
    #parent;
    #parentIndex;
    #negs;
    #filledNegs = false;
    #options;
    #toString;
    // set to true if it's an extglob with no children
    // (which really means one child of '')
    #emptyExt = false;
    constructor(type, parent, options = {}) {
        this.type = type;
        // extglobs are inherently magical
        if (type)
            this.#hasMagic = true;
        this.#parent = parent;
        this.#root = this.#parent ? this.#parent.#root : this;
        this.#options = this.#root === this ? options : this.#root.#options;
        this.#negs = this.#root === this ? [] : this.#root.#negs;
        if (type === '!' && !this.#root.#filledNegs)
            this.#negs.push(this);
        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
    }
    get hasMagic() {
        /* c8 ignore start */
        if (this.#hasMagic !== undefined)
            return this.#hasMagic;
        /* c8 ignore stop */
        for (const p of this.#parts) {
            if (typeof p === 'string')
                continue;
            if (p.type || p.hasMagic)
                return (this.#hasMagic = true);
        }
        // note: will be undefined until we generate the regexp src and find out
        return this.#hasMagic;
    }
    // reconstructs the pattern
    toString() {
        if (this.#toString !== undefined)
            return this.#toString;
        if (!this.type) {
            return (this.#toString = this.#parts.map(p => String(p)).join(''));
        }
        else {
            return (this.#toString =
                this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
        }
    }
    #fillNegs() {
        /* c8 ignore start */
        if (this !== this.#root)
            throw new Error('should only call on root');
        if (this.#filledNegs)
            return this;
        /* c8 ignore stop */
        // call toString() once to fill this out
        this.toString();
        this.#filledNegs = true;
        let n;
        while ((n = this.#negs.pop())) {
            if (n.type !== '!')
                continue;
            // walk up the tree, appending everthing that comes AFTER parentIndex
            let p = n;
            let pp = p.#parent;
            while (pp) {
                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
                    for (const part of n.#parts) {
                        /* c8 ignore start */
                        if (typeof part === 'string') {
                            throw new Error('string part in extglob AST??');
                        }
                        /* c8 ignore stop */
                        part.copyIn(pp.#parts[i]);
                    }
                }
                p = pp;
                pp = p.#parent;
            }
        }
        return this;
    }
    push(...parts) {
        for (const p of parts) {
            if (p === '')
                continue;
            /* c8 ignore start */
            if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
                throw new Error('invalid part: ' + p);
            }
            /* c8 ignore stop */
            this.#parts.push(p);
        }
    }
    toJSON() {
        const ret = this.type === null
            ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
            : [this.type, ...this.#parts.map(p => p.toJSON())];
        if (this.isStart() && !this.type)
            ret.unshift([]);
        if (this.isEnd() &&
            (this === this.#root ||
                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
            ret.push({});
        }
        return ret;
    }
    isStart() {
        if (this.#root === this)
            return true;
        // if (this.type) return !!this.#parent?.isStart()
        if (!this.#parent?.isStart())
            return false;
        if (this.#parentIndex === 0)
            return true;
        // if everything AHEAD of this is a negation, then it's still the "start"
        const p = this.#parent;
        for (let i = 0; i < this.#parentIndex; i++) {
            const pp = p.#parts[i];
            if (!(pp instanceof AST && pp.type === '!')) {
                return false;
            }
        }
        return true;
    }
    isEnd() {
        if (this.#root === this)
            return true;
        if (this.#parent?.type === '!')
            return true;
        if (!this.#parent?.isEnd())
            return false;
        if (!this.type)
            return this.#parent?.isEnd();
        // if not root, it'll always have a parent
        /* c8 ignore start */
        const pl = this.#parent ? this.#parent.#parts.length : 0;
        /* c8 ignore stop */
        return this.#parentIndex === pl - 1;
    }
    copyIn(part) {
        if (typeof part === 'string')
            this.push(part);
        else
            this.push(part.clone(this));
    }
    clone(parent) {
        const c = new AST(this.type, parent);
        for (const p of this.#parts) {
            c.copyIn(p);
        }
        return c;
    }
    static #parseAST(str, ast, pos, opt) {
        let escaping = false;
        let inBrace = false;
        let braceStart = -1;
        let braceNeg = false;
        if (ast.type === null) {
            // outside of a extglob, append until we find a start
            let i = pos;
            let acc = '';
            while (i < str.length) {
                const c = str.charAt(i++);
                // still accumulate escapes at this point, but we do ignore
                // starts that are escaped
                if (escaping || c === '\\') {
                    escaping = !escaping;
                    acc += c;
                    continue;
                }
                if (inBrace) {
                    if (i === braceStart + 1) {
                        if (c === '^' || c === '!') {
                            braceNeg = true;
                        }
                    }
                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
                        inBrace = false;
                    }
                    acc += c;
                    continue;
                }
                else if (c === '[') {
                    inBrace = true;
                    braceStart = i;
                    braceNeg = false;
                    acc += c;
                    continue;
                }
                if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
                    ast.push(acc);
                    acc = '';
                    const ext = new AST(c, ast);
                    i = AST.#parseAST(str, ext, i, opt);
                    ast.push(ext);
                    continue;
                }
                acc += c;
            }
            ast.push(acc);
            return i;
        }
        // some kind of extglob, pos is at the (
        // find the next | or )
        let i = pos + 1;
        let part = new AST(null, ast);
        const parts = [];
        let acc = '';
        while (i < str.length) {
            const c = str.charAt(i++);
            // still accumulate escapes at this point, but we do ignore
            // starts that are escaped
            if (escaping || c === '\\') {
                escaping = !escaping;
                acc += c;
                continue;
            }
            if (inBrace) {
                if (i === braceStart + 1) {
                    if (c === '^' || c === '!') {
                        braceNeg = true;
                    }
                }
                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
                    inBrace = false;
                }
                acc += c;
                continue;
            }
            else if (c === '[') {
                inBrace = true;
                braceStart = i;
                braceNeg = false;
                acc += c;
                continue;
            }
            if (isExtglobType(c) && str.charAt(i) === '(') {
                part.push(acc);
                acc = '';
                const ext = new AST(c, part);
                part.push(ext);
                i = AST.#parseAST(str, ext, i, opt);
                continue;
            }
            if (c === '|') {
                part.push(acc);
                acc = '';
                parts.push(part);
                part = new AST(null, ast);
                continue;
            }
            if (c === ')') {
                if (acc === '' && ast.#parts.length === 0) {
                    ast.#emptyExt = true;
                }
                part.push(acc);
                acc = '';
                ast.push(...parts, part);
                return i;
            }
            acc += c;
        }
        // unfinished extglob
        // if we got here, it was a malformed extglob! not an extglob, but
        // maybe something else in there.
        ast.type = null;
        ast.#hasMagic = undefined;
        ast.#parts = [str.substring(pos - 1)];
        return i;
    }
    static fromGlob(pattern, options = {}) {
        const ast = new AST(null, undefined, options);
        AST.#parseAST(pattern, ast, 0, options);
        return ast;
    }
    // returns the regular expression if there's magic, or the unescaped
    // string if not.
    toMMPattern() {
        // should only be called on root
        /* c8 ignore start */
        if (this !== this.#root)
            return this.#root.toMMPattern();
        /* c8 ignore stop */
        const glob = this.toString();
        const [re, body, hasMagic, uflag] = this.toRegExpSource();
        // if we're in nocase mode, and not nocaseMagicOnly, then we do
        // still need a regular expression if we have to case-insensitively
        // match capital/lowercase characters.
        const anyMagic = hasMagic ||
            this.#hasMagic ||
            (this.#options.nocase &&
                !this.#options.nocaseMagicOnly &&
                glob.toUpperCase() !== glob.toLowerCase());
        if (!anyMagic) {
            return body;
        }
        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
        return Object.assign(new RegExp(`^${re}$`, flags), {
            _src: re,
            _glob: glob,
        });
    }
    get options() {
        return this.#options;
    }
    // returns the string match, the regexp source, whether there's magic
    // in the regexp (so a regular expression is required) and whether or
    // not the uflag is needed for the regular expression (for posix classes)
    // TODO: instead of injecting the start/end at this point, just return
    // the BODY of the regexp, along with the start/end portions suitable
    // for binding the start/end in either a joined full-path makeRe context
    // (where we bind to (^|/), or a standalone matchPart context (where
    // we bind to ^, and not /).  Otherwise slashes get duped!
    //
    // In part-matching mode, the start is:
    // - if not isStart: nothing
    // - if traversal possible, but not allowed: ^(?!\.\.?$)
    // - if dots allowed or not possible: ^
    // - if dots possible and not allowed: ^(?!\.)
    // end is:
    // - if not isEnd(): nothing
    // - else: $
    //
    // In full-path matching mode, we put the slash at the START of the
    // pattern, so start is:
    // - if first pattern: same as part-matching mode
    // - if not isStart(): nothing
    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
    // - if dots allowed or not possible: /
    // - if dots possible and not allowed: /(?!\.)
    // end is:
    // - if last pattern, same as part-matching mode
    // - else nothing
    //
    // Always put the (?:$|/) on negated tails, though, because that has to be
    // there to bind the end of the negated pattern portion, and it's easier to
    // just stick it in now rather than try to inject it later in the middle of
    // the pattern.
    //
    // We can just always return the same end, and leave it up to the caller
    // to know whether it's going to be used joined or in parts.
    // And, if the start is adjusted slightly, can do the same there:
    // - if not isStart: nothing
    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
    // - if dots allowed or not possible: (?:/|^)
    // - if dots possible and not allowed: (?:/|^)(?!\.)
    //
    // But it's better to have a simpler binding without a conditional, for
    // performance, so probably better to return both start options.
    //
    // Then the caller just ignores the end if it's not the first pattern,
    // and the start always gets applied.
    //
    // But that's always going to be $ if it's the ending pattern, or nothing,
    // so the caller can just attach $ at the end of the pattern when building.
    //
    // So the todo is:
    // - better detect what kind of start is needed
    // - return both flavors of starting pattern
    // - attach $ at the end of the pattern when creating the actual RegExp
    //
    // Ah, but wait, no, that all only applies to the root when the first pattern
    // is not an extglob. If the first pattern IS an extglob, then we need all
    // that dot prevention biz to live in the extglob portions, because eg
    // +(*|.x*) can match .xy but not .yx.
    //
    // So, return the two flavors if it's #root and the first child is not an
    // AST, otherwise leave it to the child AST to handle it, and there,
    // use the (?:^|/) style of start binding.
    //
    // Even simplified further:
    // - Since the start for a join is eg /(?!\.) and the start for a part
    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
    // or start or whatever) and prepend ^ or / at the Regexp construction.
    toRegExpSource(allowDot) {
        const dot = allowDot ?? !!this.#options.dot;
        if (this.#root === this)
            this.#fillNegs();
        if (!this.type) {
            const noEmpty = this.isStart() && this.isEnd();
            const src = this.#parts
                .map(p => {
                const [re, _, hasMagic, uflag] = typeof p === 'string'
                    ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
                    : p.toRegExpSource(allowDot);
                this.#hasMagic = this.#hasMagic || hasMagic;
                this.#uflag = this.#uflag || uflag;
                return re;
            })
                .join('');
            let start = '';
            if (this.isStart()) {
                if (typeof this.#parts[0] === 'string') {
                    // this is the string that will match the start of the pattern,
                    // so we need to protect against dots and such.
                    // '.' and '..' cannot match unless the pattern is that exactly,
                    // even if it starts with . or dot:true is set.
                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
                    if (!dotTravAllowed) {
                        const aps = addPatternStart;
                        // check if we have a possibility of matching . or ..,
                        // and prevent that.
                        const needNoTrav = 
                        // dots are allowed, and the pattern starts with [ or .
                        (dot && aps.has(src.charAt(0))) ||
                            // the pattern starts with \., and then [ or .
                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
                            // the pattern starts with \.\., and then [ or .
                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
                        // no need to prevent dots if it can't match a dot, or if a
                        // sub-pattern will be preventing it anyway.
                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
                        start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
                    }
                }
            }
            // append the "end of path portion" pattern to negation tails
            let end = '';
            if (this.isEnd() &&
                this.#root.#filledNegs &&
                this.#parent?.type === '!') {
                end = '(?:$|\\/)';
            }
            const final = start + src + end;
            return [
                final,
                unescape(src),
                (this.#hasMagic = !!this.#hasMagic),
                this.#uflag,
            ];
        }
        // We need to calculate the body *twice* if it's a repeat pattern
        // at the start, once in nodot mode, then again in dot mode, so a
        // pattern like *(?) can match 'x.y'
        const repeated = this.type === '*' || this.type === '+';
        // some kind of extglob
        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
        let body = this.#partsToRegExp(dot);
        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
            // invalid extglob, has to at least be *something* present, if it's
            // the entire path portion.
            const s = this.toString();
            this.#parts = [s];
            this.type = null;
            this.#hasMagic = undefined;
            return [s, unescape(this.toString()), false, false];
        }
        // XXX abstract out this map method
        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
            ? ''
            : this.#partsToRegExp(true);
        if (bodyDotAllowed === body) {
            bodyDotAllowed = '';
        }
        if (bodyDotAllowed) {
            body = `(?:${body})(?:${bodyDotAllowed})*?`;
        }
        // an empty !() is exactly equivalent to a starNoEmpty
        let final = '';
        if (this.type === '!' && this.#emptyExt) {
            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
        }
        else {
            const close = this.type === '!'
                ? // !() must match something,but !(x) can match ''
                    '))' +
                        (this.isStart() && !dot && !allowDot ? startNoDot : '') +
                        star +
                        ')'
                : this.type === '@'
                    ? ')'
                    : this.type === '?'
                        ? ')?'
                        : this.type === '+' && bodyDotAllowed
                            ? ')'
                            : this.type === '*' && bodyDotAllowed
                                ? `)?`
                                : `)${this.type}`;
            final = start + body + close;
        }
        return [
            final,
            unescape(body),
            (this.#hasMagic = !!this.#hasMagic),
            this.#uflag,
        ];
    }
    #partsToRegExp(dot) {
        return this.#parts
            .map(p => {
            // extglob ASTs should only contain parent ASTs
            /* c8 ignore start */
            if (typeof p === 'string') {
                throw new Error('string type in extglob ast??');
            }
            /* c8 ignore stop */
            // can ignore hasMagic, because extglobs are already always magic
            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
            this.#uflag = this.#uflag || uflag;
            return re;
        })
            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
            .join('|');
    }
    static #parseGlob(glob, hasMagic, noEmpty = false) {
        let escaping = false;
        let re = '';
        let uflag = false;
        for (let i = 0; i < glob.length; i++) {
            const c = glob.charAt(i);
            if (escaping) {
                escaping = false;
                re += (reSpecials.has(c) ? '\\' : '') + c;
                continue;
            }
            if (c === '\\') {
                if (i === glob.length - 1) {
                    re += '\\\\';
                }
                else {
                    escaping = true;
                }
                continue;
            }
            if (c === '[') {
                const [src, needUflag, consumed, magic] = parseClass(glob, i);
                if (consumed) {
                    re += src;
                    uflag = uflag || needUflag;
                    i += consumed - 1;
                    hasMagic = hasMagic || magic;
                    continue;
                }
            }
            if (c === '*') {
                if (noEmpty && glob === '*')
                    re += starNoEmpty;
                else
                    re += star;
                hasMagic = true;
                continue;
            }
            if (c === '?') {
                re += qmark;
                hasMagic = true;
                continue;
            }
            re += regExpEscape(c);
        }
        return [re, unescape(glob), !!hasMagic, uflag];
    }
}
//# sourceMappingURL=ast.js.map// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { : [, /u flag required, negated]
const posixClasses = {
    '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
    '[:alpha:]': ['\\p{L}\\p{Nl}', true],
    '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
    '[:blank:]': ['\\p{Zs}\\t', true],
    '[:cntrl:]': ['\\p{Cc}', true],
    '[:digit:]': ['\\p{Nd}', true],
    '[:graph:]': ['\\p{Z}\\p{C}', true, true],
    '[:lower:]': ['\\p{Ll}', true],
    '[:print:]': ['\\p{C}', true],
    '[:punct:]': ['\\p{P}', true],
    '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
    '[:upper:]': ['\\p{Lu}', true],
    '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
    '[:xdigit:]': ['A-Fa-f0-9', false],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
// escape all regexp magic characters
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// everything has already been escaped, we just have to join
const rangesToString = (ranges) => ranges.join('');
// takes a glob string at a posix brace expression, and returns
// an equivalent regular expression source, and boolean indicating
// whether the /u flag needs to be applied, and the number of chars
// consumed to parse the character class.
// This also removes out of order ranges, and returns ($.) if the
// entire class just no good.
export const parseClass = (glob, position) => {
    const pos = position;
    /* c8 ignore start */
    if (glob.charAt(pos) !== '[') {
        throw new Error('not in a brace expression');
    }
    /* c8 ignore stop */
    const ranges = [];
    const negs = [];
    let i = pos + 1;
    let sawStart = false;
    let uflag = false;
    let escaping = false;
    let negate = false;
    let endPos = pos;
    let rangeStart = '';
    WHILE: while (i < glob.length) {
        const c = glob.charAt(i);
        if ((c === '!' || c === '^') && i === pos + 1) {
            negate = true;
            i++;
            continue;
        }
        if (c === ']' && sawStart && !escaping) {
            endPos = i + 1;
            break;
        }
        sawStart = true;
        if (c === '\\') {
            if (!escaping) {
                escaping = true;
                i++;
                continue;
            }
            // escaped \ char, fall through and treat like normal char
        }
        if (c === '[' && !escaping) {
            // either a posix class, a collation equivalent, or just a [
            for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
                if (glob.startsWith(cls, i)) {
                    // invalid, [a-[] is fine, but not [a-[:alpha]]
                    if (rangeStart) {
                        return ['$.', false, glob.length - pos, true];
                    }
                    i += cls.length;
                    if (neg)
                        negs.push(unip);
                    else
                        ranges.push(unip);
                    uflag = uflag || u;
                    continue WHILE;
                }
            }
        }
        // now it's just a normal character, effectively
        escaping = false;
        if (rangeStart) {
            // throw this range away if it's not valid, but others
            // can still match.
            if (c > rangeStart) {
                ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
            }
            else if (c === rangeStart) {
                ranges.push(braceEscape(c));
            }
            rangeStart = '';
            i++;
            continue;
        }
        // now might be the start of a range.
        // can be either c-d or c-] or c] or c] at this point
        if (glob.startsWith('-]', i + 1)) {
            ranges.push(braceEscape(c + '-'));
            i += 2;
            continue;
        }
        if (glob.startsWith('-', i + 1)) {
            rangeStart = c;
            i += 2;
            continue;
        }
        // not the start of a range, just a single character
        ranges.push(braceEscape(c));
        i++;
    }
    if (endPos < i) {
        // didn't see the end of the class, not a valid class,
        // but might still be valid as a literal match.
        return ['', false, 0, false];
    }
    // if we got no ranges and no negates, then we have a range that
    // cannot possibly match anything, and that poisons the whole glob
    if (!ranges.length && !negs.length) {
        return ['$.', false, glob.length - pos, true];
    }
    // if we got one positive range, and it's a single character, then that's
    // not actually a magic pattern, it's just that one literal character.
    // we should not treat that as "magic", we should just return the literal
    // character. [_] is a perfectly valid way to escape glob magic chars.
    if (negs.length === 0 &&
        ranges.length === 1 &&
        /^\\?.$/.test(ranges[0]) &&
        !negate) {
        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
        return [regexpEscape(r), false, endPos - pos, false];
    }
    const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
    const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
    const comb = ranges.length && negs.length
        ? '(' + sranges + '|' + snegs + ')'
        : ranges.length
            ? sranges
            : snegs;
    return [comb, uflag, endPos - pos, true];
};
//# sourceMappingURL=brace-expressions.js.map/**
 * Escape all magic characters in a glob pattern.
 *
 * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
 * option is used, then characters are escaped by wrapping in `[]`, because
 * a magic character wrapped in a character class can only be satisfied by
 * that exact character.  In this mode, `\` is _not_ escaped, because it is
 * not interpreted as a magic character, but instead as a path separator.
 */
export const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
    // don't need to escape +@! because we escape the parens
    // that make those magic, and escaping ! as [!] isn't valid,
    // because [!]] is a valid glob class meaning not ']'.
    return windowsPathsNoEscape
        ? s.replace(/[?*()[\]]/g, '[$&]')
        : s.replace(/[?*()[\]\\]/g, '\\$&');
};
//# sourceMappingURL=escape.js.mapimport expand from 'brace-expansion';
import { assertValidPattern } from './assert-valid-pattern.js';
import { AST } from './ast.js';
import { escape } from './escape.js';
import { unescape } from './unescape.js';
export const minimatch = (p, pattern, options = {}) => {
    assertValidPattern(pattern);
    // shortcut: comments match nothing.
    if (!options.nocomment && pattern.charAt(0) === '#') {
        return false;
    }
    return new Minimatch(pattern, options).match(p);
};
// Optimized checking for the most common glob patterns.
const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
const starDotExtTestNocase = (ext) => {
    ext = ext.toLowerCase();
    return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
};
const starDotExtTestNocaseDot = (ext) => {
    ext = ext.toLowerCase();
    return (f) => f.toLowerCase().endsWith(ext);
};
const starDotStarRE = /^\*+\.\*+$/;
const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
const dotStarRE = /^\.\*+$/;
const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
const starRE = /^\*+$/;
const starTest = (f) => f.length !== 0 && !f.startsWith('.');
const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
const qmarksTestNocase = ([$0, ext = '']) => {
    const noext = qmarksTestNoExt([$0]);
    if (!ext)
        return noext;
    ext = ext.toLowerCase();
    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
};
const qmarksTestNocaseDot = ([$0, ext = '']) => {
    const noext = qmarksTestNoExtDot([$0]);
    if (!ext)
        return noext;
    ext = ext.toLowerCase();
    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
};
const qmarksTestDot = ([$0, ext = '']) => {
    const noext = qmarksTestNoExtDot([$0]);
    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
};
const qmarksTest = ([$0, ext = '']) => {
    const noext = qmarksTestNoExt([$0]);
    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
};
const qmarksTestNoExt = ([$0]) => {
    const len = $0.length;
    return (f) => f.length === len && !f.startsWith('.');
};
const qmarksTestNoExtDot = ([$0]) => {
    const len = $0.length;
    return (f) => f.length === len && f !== '.' && f !== '..';
};
/* c8 ignore start */
const defaultPlatform = (typeof process === 'object' && process
    ? (typeof process.env === 'object' &&
        process.env &&
        process.env.__MINIMATCH_TESTING_PLATFORM__) ||
        process.platform
    : 'posix');
const path = {
    win32: { sep: '\\' },
    posix: { sep: '/' },
};
/* c8 ignore stop */
export const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
minimatch.sep = sep;
export const GLOBSTAR = Symbol('globstar **');
minimatch.GLOBSTAR = GLOBSTAR;
// any single thing other than /
// don't need to escape / when using new RegExp()
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// ** when dots are allowed.  Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
export const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
minimatch.filter = filter;
const ext = (a, b = {}) => Object.assign({}, a, b);
export const defaults = (def) => {
    if (!def || typeof def !== 'object' || !Object.keys(def).length) {
        return minimatch;
    }
    const orig = minimatch;
    const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
    return Object.assign(m, {
        Minimatch: class Minimatch extends orig.Minimatch {
            constructor(pattern, options = {}) {
                super(pattern, ext(def, options));
            }
            static defaults(options) {
                return orig.defaults(ext(def, options)).Minimatch;
            }
        },
        AST: class AST extends orig.AST {
            /* c8 ignore start */
            constructor(type, parent, options = {}) {
                super(type, parent, ext(def, options));
            }
            /* c8 ignore stop */
            static fromGlob(pattern, options = {}) {
                return orig.AST.fromGlob(pattern, ext(def, options));
            }
        },
        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
        defaults: (options) => orig.defaults(ext(def, options)),
        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
        sep: orig.sep,
        GLOBSTAR: GLOBSTAR,
    });
};
minimatch.defaults = defaults;
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
export const braceExpand = (pattern, options = {}) => {
    assertValidPattern(pattern);
    // Thanks to Yeting Li  for
    // improving this regexp to avoid a ReDOS vulnerability.
    if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        // shortcut. no need to expand.
        return [pattern];
    }
    return expand(pattern);
};
minimatch.braceExpand = braceExpand;
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion.  Otherwise, any series
// of * is equivalent to a single *.  Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
export const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
minimatch.makeRe = makeRe;
export const match = (list, pattern, options = {}) => {
    const mm = new Minimatch(pattern, options);
    list = list.filter(f => mm.match(f));
    if (mm.options.nonull && !list.length) {
        list.push(pattern);
    }
    return list;
};
minimatch.match = match;
// replace stuff like \* with *
const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
export class Minimatch {
    options;
    set;
    pattern;
    windowsPathsNoEscape;
    nonegate;
    negate;
    comment;
    empty;
    preserveMultipleSlashes;
    partial;
    globSet;
    globParts;
    nocase;
    isWindows;
    platform;
    windowsNoMagicRoot;
    regexp;
    constructor(pattern, options = {}) {
        assertValidPattern(pattern);
        options = options || {};
        this.options = options;
        this.pattern = pattern;
        this.platform = options.platform || defaultPlatform;
        this.isWindows = this.platform === 'win32';
        this.windowsPathsNoEscape =
            !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
            this.pattern = this.pattern.replace(/\\/g, '/');
        }
        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
        this.regexp = null;
        this.negate = false;
        this.nonegate = !!options.nonegate;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.nocase = !!this.options.nocase;
        this.windowsNoMagicRoot =
            options.windowsNoMagicRoot !== undefined
                ? options.windowsNoMagicRoot
                : !!(this.isWindows && this.nocase);
        this.globSet = [];
        this.globParts = [];
        this.set = [];
        // make the set of regexps etc.
        this.make();
    }
    hasMagic() {
        if (this.options.magicalBraces && this.set.length > 1) {
            return true;
        }
        for (const pattern of this.set) {
            for (const part of pattern) {
                if (typeof part !== 'string')
                    return true;
            }
        }
        return false;
    }
    debug(..._) { }
    make() {
        const pattern = this.pattern;
        const options = this.options;
        // empty patterns and comments match nothing.
        if (!options.nocomment && pattern.charAt(0) === '#') {
            this.comment = true;
            return;
        }
        if (!pattern) {
            this.empty = true;
            return;
        }
        // step 1: figure out negation, etc.
        this.parseNegate();
        // step 2: expand braces
        this.globSet = [...new Set(this.braceExpand())];
        if (options.debug) {
            this.debug = (...args) => console.error(...args);
        }
        this.debug(this.pattern, this.globSet);
        // step 3: now we have a set, so turn each one into a series of
        // path-portion matching patterns.
        // These will be regexps, except in the case of "**", which is
        // set to the GLOBSTAR object for globstar behavior,
        // and will not contain any / characters
        //
        // First, we preprocess to make the glob pattern sets a bit simpler
        // and deduped.  There are some perf-killing patterns that can cause
        // problems with a glob walk, but we can simplify them down a bit.
        const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
        this.globParts = this.preprocess(rawGlobParts);
        this.debug(this.pattern, this.globParts);
        // glob --> regexps
        let set = this.globParts.map((s, _, __) => {
            if (this.isWindows && this.windowsNoMagicRoot) {
                // check if it's a drive or unc path.
                const isUNC = s[0] === '' &&
                    s[1] === '' &&
                    (s[2] === '?' || !globMagic.test(s[2])) &&
                    !globMagic.test(s[3]);
                const isDrive = /^[a-z]:/i.test(s[0]);
                if (isUNC) {
                    return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
                }
                else if (isDrive) {
                    return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
                }
            }
            return s.map(ss => this.parse(ss));
        });
        this.debug(this.pattern, set);
        // filter out everything that didn't compile properly.
        this.set = set.filter(s => s.indexOf(false) === -1);
        // do not treat the ? in UNC paths as magic
        if (this.isWindows) {
            for (let i = 0; i < this.set.length; i++) {
                const p = this.set[i];
                if (p[0] === '' &&
                    p[1] === '' &&
                    this.globParts[i][2] === '?' &&
                    typeof p[3] === 'string' &&
                    /^[a-z]:$/i.test(p[3])) {
                    p[2] = '?';
                }
            }
        }
        this.debug(this.pattern, this.set);
    }
    // various transforms to equivalent pattern sets that are
    // faster to process in a filesystem walk.  The goal is to
    // eliminate what we can, and push all ** patterns as far
    // to the right as possible, even if it increases the number
    // of patterns that we have to process.
    preprocess(globParts) {
        // if we're not in globstar mode, then turn all ** into *
        if (this.options.noglobstar) {
            for (let i = 0; i < globParts.length; i++) {
                for (let j = 0; j < globParts[i].length; j++) {
                    if (globParts[i][j] === '**') {
                        globParts[i][j] = '*';
                    }
                }
            }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
            // aggressive optimization for the purpose of fs walking
            globParts = this.firstPhasePreProcess(globParts);
            globParts = this.secondPhasePreProcess(globParts);
        }
        else if (optimizationLevel >= 1) {
            // just basic optimizations to remove some .. parts
            globParts = this.levelOneOptimize(globParts);
        }
        else {
            // just collapse multiple ** portions into one
            globParts = this.adjascentGlobstarOptimize(globParts);
        }
        return globParts;
    }
    // just get rid of adjascent ** portions
    adjascentGlobstarOptimize(globParts) {
        return globParts.map(parts => {
            let gs = -1;
            while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
                let i = gs;
                while (parts[i + 1] === '**') {
                    i++;
                }
                if (i !== gs) {
                    parts.splice(gs, i - gs);
                }
            }
            return parts;
        });
    }
    // get rid of adjascent ** and resolve .. portions
    levelOneOptimize(globParts) {
        return globParts.map(parts => {
            parts = parts.reduce((set, part) => {
                const prev = set[set.length - 1];
                if (part === '**' && prev === '**') {
                    return set;
                }
                if (part === '..') {
                    if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
                        set.pop();
                        return set;
                    }
                }
                set.push(part);
                return set;
            }, []);
            return parts.length === 0 ? [''] : parts;
        });
    }
    levelTwoFileOptimize(parts) {
        if (!Array.isArray(parts)) {
            parts = this.slashSplit(parts);
        }
        let didSomething = false;
        do {
            didSomething = false;
            // 
// -> 
/
            if (!this.preserveMultipleSlashes) {
                for (let i = 1; i < parts.length - 1; i++) {
                    const p = parts[i];
                    // don't squeeze out UNC patterns
                    if (i === 1 && p === '' && parts[0] === '')
                        continue;
                    if (p === '.' || p === '') {
                        didSomething = true;
                        parts.splice(i, 1);
                        i--;
                    }
                }
                if (parts[0] === '.' &&
                    parts.length === 2 &&
                    (parts[1] === '.' || parts[1] === '')) {
                    didSomething = true;
                    parts.pop();
                }
            }
            // 
/

/../ ->

/
            let dd = 0;
            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                const p = parts[dd - 1];
                if (p && p !== '.' && p !== '..' && p !== '**') {
                    didSomething = true;
                    parts.splice(dd - 1, 2);
                    dd -= 2;
                }
            }
        } while (didSomething);
        return parts.length === 0 ? [''] : parts;
    }
    // First phase: single-pattern processing
    // 
 is 1 or more portions
    //  is 1 or more portions
    // 

is any portion other than ., .., '', or ** // is . or '' // // **/.. is *brutal* for filesystem walking performance, because // it effectively resets the recursive walk each time it occurs, // and ** cannot be reduced out by a .. pattern part like a regexp // or most strings (other than .., ., and '') can be. // //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} //

// -> 
/
    // 
/

/../ ->

/
    // **/**/ -> **/
    //
    // **/*/ -> */**/ <== not valid because ** doesn't follow
    // this WOULD be allowed if ** did follow symlinks, or * didn't
    firstPhasePreProcess(globParts) {
        let didSomething = false;
        do {
            didSomething = false;
            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} for (let parts of globParts) { let gs = -1; while (-1 !== (gs = parts.indexOf('**', gs + 1))) { let gss = gs; while (parts[gss + 1] === '**') { //

/**/**/ -> 
/**/
                        gss++;
                    }
                    // eg, if gs is 2 and gss is 4, that means we have 3 **
                    // parts, and can remove 2 of them.
                    if (gss > gs) {
                        parts.splice(gs + 1, gss - gs);
                    }
                    let next = parts[gs + 1];
                    const p = parts[gs + 2];
                    const p2 = parts[gs + 3];
                    if (next !== '..')
                        continue;
                    if (!p ||
                        p === '.' ||
                        p === '..' ||
                        !p2 ||
                        p2 === '.' ||
                        p2 === '..') {
                        continue;
                    }
                    didSomething = true;
                    // edit parts in place, and push the new one
                    parts.splice(gs, 1);
                    const other = parts.slice(0);
                    other[gs] = '**';
                    globParts.push(other);
                    gs--;
                }
                // 
// -> 
/
                if (!this.preserveMultipleSlashes) {
                    for (let i = 1; i < parts.length - 1; i++) {
                        const p = parts[i];
                        // don't squeeze out UNC patterns
                        if (i === 1 && p === '' && parts[0] === '')
                            continue;
                        if (p === '.' || p === '') {
                            didSomething = true;
                            parts.splice(i, 1);
                            i--;
                        }
                    }
                    if (parts[0] === '.' &&
                        parts.length === 2 &&
                        (parts[1] === '.' || parts[1] === '')) {
                        didSomething = true;
                        parts.pop();
                    }
                }
                // 
/

/../ ->

/
                let dd = 0;
                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                    const p = parts[dd - 1];
                    if (p && p !== '.' && p !== '..' && p !== '**') {
                        didSomething = true;
                        const needDot = dd === 1 && parts[dd + 1] === '**';
                        const splin = needDot ? ['.'] : [];
                        parts.splice(dd - 1, 2, ...splin);
                        if (parts.length === 0)
                            parts.push('');
                        dd -= 2;
                    }
                }
            }
        } while (didSomething);
        return globParts;
    }
    // second phase: multi-pattern dedupes
    // {
/*/,
/

/} ->

/*/
    // {
/,
/} -> 
/
    // {
/**/,
/} -> 
/**/
    //
    // {
/**/,
/**/

/} ->

/**/
    // ^-- not valid because ** doens't follow symlinks
    secondPhasePreProcess(globParts) {
        for (let i = 0; i < globParts.length - 1; i++) {
            for (let j = i + 1; j < globParts.length; j++) {
                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
                if (matched) {
                    globParts[i] = [];
                    globParts[j] = matched;
                    break;
                }
            }
        }
        return globParts.filter(gs => gs.length);
    }
    partsMatch(a, b, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = '';
        while (ai < a.length && bi < b.length) {
            if (a[ai] === b[bi]) {
                result.push(which === 'b' ? b[bi] : a[ai]);
                ai++;
                bi++;
            }
            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
                result.push(a[ai]);
                ai++;
            }
            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
                result.push(b[bi]);
                bi++;
            }
            else if (a[ai] === '*' &&
                b[bi] &&
                (this.options.dot || !b[bi].startsWith('.')) &&
                b[bi] !== '**') {
                if (which === 'b')
                    return false;
                which = 'a';
                result.push(a[ai]);
                ai++;
                bi++;
            }
            else if (b[bi] === '*' &&
                a[ai] &&
                (this.options.dot || !a[ai].startsWith('.')) &&
                a[ai] !== '**') {
                if (which === 'a')
                    return false;
                which = 'b';
                result.push(b[bi]);
                ai++;
                bi++;
            }
            else {
                return false;
            }
        }
        // if we fall out of the loop, it means they two are identical
        // as long as their lengths match
        return a.length === b.length && result;
    }
    parseNegate() {
        if (this.nonegate)
            return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
            negate = !negate;
            negateOffset++;
        }
        if (negateOffset)
            this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
    }
    // set partial to true to test if, for example,
    // "/a/b" matches the start of "/*/b/*/d"
    // Partial means, if you run out of file before you run
    // out of pattern, then that's fine, as long as all
    // the parts match.
    matchOne(file, pattern, partial = false) {
        const options = this.options;
        // UNC paths like //?/X:/... can match X:/... and vice versa
        // Drive letters in absolute drive or unc paths are always compared
        // case-insensitively.
        if (this.isWindows) {
            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
            const fileUNC = !fileDrive &&
                file[0] === '' &&
                file[1] === '' &&
                file[2] === '?' &&
                /^[a-z]:$/i.test(file[3]);
            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
            const patternUNC = !patternDrive &&
                pattern[0] === '' &&
                pattern[1] === '' &&
                pattern[2] === '?' &&
                typeof pattern[3] === 'string' &&
                /^[a-z]:$/i.test(pattern[3]);
            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
            if (typeof fdi === 'number' && typeof pdi === 'number') {
                const [fd, pd] = [file[fdi], pattern[pdi]];
                if (fd.toLowerCase() === pd.toLowerCase()) {
                    pattern[pdi] = fd;
                    if (pdi > fdi) {
                        pattern = pattern.slice(pdi);
                    }
                    else if (fdi > pdi) {
                        file = file.slice(fdi);
                    }
                }
            }
        }
        // resolve and reduce . and .. portions in the file as well.
        // dont' need to do the second phase, because it's only one string[]
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
            file = this.levelTwoFileOptimize(file);
        }
        this.debug('matchOne', this, { file, pattern });
        this.debug('matchOne', file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
            this.debug('matchOne loop');
            var p = pattern[pi];
            var f = file[fi];
            this.debug(pattern, p, f);
            // should be impossible.
            // some invalid regexp stuff in the set.
            /* c8 ignore start */
            if (p === false) {
                return false;
            }
            /* c8 ignore stop */
            if (p === GLOBSTAR) {
                this.debug('GLOBSTAR', [pattern, p, f]);
                // "**"
                // a/**/b/**/c would match the following:
                // a/b/x/y/z/c
                // a/x/y/z/b/c
                // a/b/x/b/x/c
                // a/b/c
                // To do this, take the rest of the pattern after
                // the **, and see if it would match the file remainder.
                // If so, return success.
                // If not, the ** "swallows" a segment, and try again.
                // This is recursively awful.
                //
                // a/**/b/**/c matching a/b/x/y/z/c
                // - a matches a
                // - doublestar
                //   - matchOne(b/x/y/z/c, b/**/c)
                //     - b matches b
                //     - doublestar
                //       - matchOne(x/y/z/c, c) -> no
                //       - matchOne(y/z/c, c) -> no
                //       - matchOne(z/c, c) -> no
                //       - matchOne(c, c) yes, hit
                var fr = fi;
                var pr = pi + 1;
                if (pr === pl) {
                    this.debug('** at the end');
                    // a ** at the end will just swallow the rest.
                    // We have found a match.
                    // however, it will not swallow /.x, unless
                    // options.dot is set.
                    // . and .. are *never* matched by **, for explosively
                    // exponential reasons.
                    for (; fi < fl; fi++) {
                        if (file[fi] === '.' ||
                            file[fi] === '..' ||
                            (!options.dot && file[fi].charAt(0) === '.'))
                            return false;
                    }
                    return true;
                }
                // ok, let's see if we can swallow whatever we can.
                while (fr < fl) {
                    var swallowee = file[fr];
                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
                    // XXX remove this slice.  Just pass the start index.
                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                        this.debug('globstar found match!', fr, fl, swallowee);
                        // found a match.
                        return true;
                    }
                    else {
                        // can't swallow "." or ".." ever.
                        // can only swallow ".foo" when explicitly asked.
                        if (swallowee === '.' ||
                            swallowee === '..' ||
                            (!options.dot && swallowee.charAt(0) === '.')) {
                            this.debug('dot detected!', file, fr, pattern, pr);
                            break;
                        }
                        // ** swallows a segment, and continue.
                        this.debug('globstar swallow a segment, and continue');
                        fr++;
                    }
                }
                // no match was found.
                // However, in partial mode, we can't say this is necessarily over.
                /* c8 ignore start */
                if (partial) {
                    // ran out of file
                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
                    if (fr === fl) {
                        return true;
                    }
                }
                /* c8 ignore stop */
                return false;
            }
            // something other than **
            // non-magic patterns just have to match exactly
            // patterns with magic have been turned into regexps.
            let hit;
            if (typeof p === 'string') {
                hit = f === p;
                this.debug('string match', p, f, hit);
            }
            else {
                hit = p.test(f);
                this.debug('pattern match', p, f, hit);
            }
            if (!hit)
                return false;
        }
        // Note: ending in / means that we'll get a final ""
        // at the end of the pattern.  This can only match a
        // corresponding "" at the end of the file.
        // If the file ends in /, then it can only match a
        // a pattern that ends in /, unless the pattern just
        // doesn't have any more for it. But, a/b/ should *not*
        // match "a/b/*", even though "" matches against the
        // [^/]*? pattern, except in partial mode, where it might
        // simply not be reached yet.
        // However, a/b/ should still satisfy a/*
        // now either we fell off the end of the pattern, or we're done.
        if (fi === fl && pi === pl) {
            // ran out of pattern and filename at the same time.
            // an exact hit!
            return true;
        }
        else if (fi === fl) {
            // ran out of file, but still had pattern left.
            // this is ok if we're doing the match as part of
            // a glob fs traversal.
            return partial;
        }
        else if (pi === pl) {
            // ran out of pattern, still have file left.
            // this is only acceptable if we're on the very last
            // empty segment of a file with a trailing slash.
            // a/* should match a/b/
            return fi === fl - 1 && file[fi] === '';
            /* c8 ignore start */
        }
        else {
            // should be unreachable.
            throw new Error('wtf?');
        }
        /* c8 ignore stop */
    }
    braceExpand() {
        return braceExpand(this.pattern, this.options);
    }
    parse(pattern) {
        assertValidPattern(pattern);
        const options = this.options;
        // shortcuts
        if (pattern === '**')
            return GLOBSTAR;
        if (pattern === '')
            return '';
        // far and away, the most common glob pattern parts are
        // *, *.*, and *.  Add a fast check method for those.
        let m;
        let fastTest = null;
        if ((m = pattern.match(starRE))) {
            fastTest = options.dot ? starTestDot : starTest;
        }
        else if ((m = pattern.match(starDotExtRE))) {
            fastTest = (options.nocase
                ? options.dot
                    ? starDotExtTestNocaseDot
                    : starDotExtTestNocase
                : options.dot
                    ? starDotExtTestDot
                    : starDotExtTest)(m[1]);
        }
        else if ((m = pattern.match(qmarksRE))) {
            fastTest = (options.nocase
                ? options.dot
                    ? qmarksTestNocaseDot
                    : qmarksTestNocase
                : options.dot
                    ? qmarksTestDot
                    : qmarksTest)(m);
        }
        else if ((m = pattern.match(starDotStarRE))) {
            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
        }
        else if ((m = pattern.match(dotStarRE))) {
            fastTest = dotStarTest;
        }
        const re = AST.fromGlob(pattern, this.options).toMMPattern();
        if (fastTest && typeof re === 'object') {
            // Avoids overriding in frozen environments
            Reflect.defineProperty(re, 'test', { value: fastTest });
        }
        return re;
    }
    makeRe() {
        if (this.regexp || this.regexp === false)
            return this.regexp;
        // at this point, this.set is a 2d array of partial
        // pattern strings, or "**".
        //
        // It's better to use .match().  This function shouldn't
        // be used, really, but it's pretty convenient sometimes,
        // when you just want to work with a regex.
        const set = this.set;
        if (!set.length) {
            this.regexp = false;
            return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar
            ? star
            : options.dot
                ? twoStarDot
                : twoStarNoDot;
        const flags = new Set(options.nocase ? ['i'] : []);
        // regexpify non-globstar patterns
        // if ** is only item, then we just do one twoStar
        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
        // if ** is last, append (\/twoStar|) to previous
        // if ** is in the middle, append (\/|\/twoStar\/) to previous
        // then filter out GLOBSTAR symbols
        let re = set
            .map(pattern => {
            const pp = pattern.map(p => {
                if (p instanceof RegExp) {
                    for (const f of p.flags.split(''))
                        flags.add(f);
                }
                return typeof p === 'string'
                    ? regExpEscape(p)
                    : p === GLOBSTAR
                        ? GLOBSTAR
                        : p._src;
            });
            pp.forEach((p, i) => {
                const next = pp[i + 1];
                const prev = pp[i - 1];
                if (p !== GLOBSTAR || prev === GLOBSTAR) {
                    return;
                }
                if (prev === undefined) {
                    if (next !== undefined && next !== GLOBSTAR) {
                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
                    }
                    else {
                        pp[i] = twoStar;
                    }
                }
                else if (next === undefined) {
                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
                }
                else if (next !== GLOBSTAR) {
                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
                    pp[i + 1] = GLOBSTAR;
                }
            });
            return pp.filter(p => p !== GLOBSTAR).join('/');
        })
            .join('|');
        // need to wrap in parens if we had more than one thing with |,
        // otherwise only the first will be anchored to ^ and the last to $
        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
        // must match entire pattern
        // ending in a * or ** will make it less strict.
        re = '^' + open + re + close + '$';
        // can match anything, as long as it's not this.
        if (this.negate)
            re = '^(?!' + re + ').+$';
        try {
            this.regexp = new RegExp(re, [...flags].join(''));
            /* c8 ignore start */
        }
        catch (ex) {
            // should be impossible
            this.regexp = false;
        }
        /* c8 ignore stop */
        return this.regexp;
    }
    slashSplit(p) {
        // if p starts with // on windows, we preserve that
        // so that UNC paths aren't broken.  Otherwise, any number of
        // / characters are coalesced into one, unless
        // preserveMultipleSlashes is set to true.
        if (this.preserveMultipleSlashes) {
            return p.split('/');
        }
        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
            // add an extra '' for the one we lose
            return ['', ...p.split(/\/+/)];
        }
        else {
            return p.split(/\/+/);
        }
    }
    match(f, partial = this.partial) {
        this.debug('match', f, this.pattern);
        // short-circuit in the case of busted things.
        // comments, etc.
        if (this.comment) {
            return false;
        }
        if (this.empty) {
            return f === '';
        }
        if (f === '/' && partial) {
            return true;
        }
        const options = this.options;
        // windows: need to use /, not \
        if (this.isWindows) {
            f = f.split('\\').join('/');
        }
        // treat the test path as a set of pathparts.
        const ff = this.slashSplit(f);
        this.debug(this.pattern, 'split', ff);
        // just ONE of the pattern sets in this.set needs to match
        // in order for it to be valid.  If negating, then just one
        // match means that we have failed.
        // Either way, return on the first hit.
        const set = this.set;
        this.debug(this.pattern, 'set', set);
        // Find the basename of the path by looking for the last non-empty segment
        let filename = ff[ff.length - 1];
        if (!filename) {
            for (let i = ff.length - 2; !filename && i >= 0; i--) {
                filename = ff[i];
            }
        }
        for (let i = 0; i < set.length; i++) {
            const pattern = set[i];
            let file = ff;
            if (options.matchBase && pattern.length === 1) {
                file = [filename];
            }
            const hit = this.matchOne(file, pattern, partial);
            if (hit) {
                if (options.flipNegate) {
                    return true;
                }
                return !this.negate;
            }
        }
        // didn't get any hits.  this is success if it's a negative
        // pattern, failure otherwise.
        if (options.flipNegate) {
            return false;
        }
        return this.negate;
    }
    static defaults(def) {
        return minimatch.defaults(def).Minimatch;
    }
}
/* c8 ignore start */
export { AST } from './ast.js';
export { escape } from './escape.js';
export { unescape } from './unescape.js';
/* c8 ignore stop */
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape;
minimatch.unescape = unescape;
//# sourceMappingURL=index.js.map{
  "type": "module"
}
/**
 * Un-escape a string that has been escaped with {@link escape}.
 *
 * If the {@link windowsPathsNoEscape} option is used, then square-brace
 * escapes are removed, but not backslash escapes.  For example, it will turn
 * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
 * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
 *
 * When `windowsPathsNoEscape` is not set, then both brace escapes and
 * backslash escapes are removed.
 *
 * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
 * or unescaped.
 */
export const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
    return windowsPathsNoEscape
        ? s.replace(/\[([^\/\\])\]/g, '$1')
        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
};
//# sourceMappingURL=unescape.js.map{
  "author": "Isaac Z. Schlueter  (http://blog.izs.me)",
  "name": "minimatch",
  "description": "a glob matcher in javascript",
  "version": "9.0.5",
  "repository": {
    "type": "git",
    "url": "git://github.com/isaacs/minimatch.git"
  },
  "main": "./dist/commonjs/index.js",
  "types": "./dist/commonjs/index.d.ts",
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "presnap": "npm run prepare",
    "test": "tap",
    "snap": "tap",
    "format": "prettier --write . --loglevel warn",
    "benchmark": "node benchmark/index.js",
    "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
  },
  "prettier": {
    "semi": false,
    "printWidth": 80,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "engines": {
    "node": ">=16 || 14 >=14.17"
  },
  "dependencies": {
    "brace-expansion": "^2.0.1"
  },
  "devDependencies": {
    "@types/brace-expansion": "^1.1.0",
    "@types/node": "^18.15.11",
    "@types/tap": "^15.0.8",
    "eslint-config-prettier": "^8.6.0",
    "mkdirp": "1",
    "prettier": "^2.8.2",
    "tap": "^18.7.2",
    "ts-node": "^10.9.1",
    "tshy": "^1.12.0",
    "typedoc": "^0.23.21",
    "typescript": "^4.9.3"
  },
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  },
  "license": "ISC",
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "type": "module"
}
The ISC License

Copyright (c) 2019-2023 Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const { Minipass } = require('minipass')
const _data = Symbol('_data')
const _length = Symbol('_length')
class Collect extends Minipass {
  constructor (options) {
    super(options)
    this[_data] = []
    this[_length] = 0
  }
  write (chunk, encoding, cb) {
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'

    if (!encoding)
      encoding = 'utf8'

    const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
    this[_data].push(c)
    this[_length] += c.length
    if (cb)
      cb()
    return true
  }
  end (chunk, encoding, cb) {
    if (typeof chunk === 'function')
      cb = chunk, chunk = null
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'
    if (chunk)
      this.write(chunk, encoding)
    const result = Buffer.concat(this[_data], this[_length])
    super.write(result)
    return super.end(cb)
  }
}
module.exports = Collect

// it would be possible to DRY this a bit by doing something like
// this.collector = new Collect() and listening on its data event,
// but it's not much code, and we may as well save the extra obj
class CollectPassThrough extends Minipass {
  constructor (options) {
    super(options)
    this[_data] = []
    this[_length] = 0
  }
  write (chunk, encoding, cb) {
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'

    if (!encoding)
      encoding = 'utf8'

    const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
    this[_data].push(c)
    this[_length] += c.length
    return super.write(chunk, encoding, cb)
  }
  end (chunk, encoding, cb) {
    if (typeof chunk === 'function')
      cb = chunk, chunk = null
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'
    if (chunk)
      this.write(chunk, encoding)
    const result = Buffer.concat(this[_data], this[_length])
    this.emit('collect', result)
    return super.end(cb)
  }
}
module.exports.PassThrough = CollectPassThrough
{
  "name": "minipass-collect",
  "version": "2.0.1",
  "description": "A Minipass stream that collects all the data into a single chunk",
  "author": "Isaac Z. Schlueter  (https://izs.me)",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags"
  },
  "tap": {
    "check-coverage": true
  },
  "devDependencies": {
    "tap": "^16.3.8"
  },
  "dependencies": {
    "minipass": "^7.0.3"
  },
  "files": [
    "index.js"
  ],
  "engines": {
    "node": ">=16 || 14 >=14.17"
  },
  "repository": "https://github.com/isaacs/minipass-collect"
}
The MIT License (MIT)

Copyright (c) Isaac Z. Schlueter and Contributors
Copyright (c) 2016 David Frank

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.

---

Note: This is a derivative work based on "node-fetch" by David Frank,
modified and distributed under the terms of the MIT license above.
https://github.com/bitinn/node-fetch
'use strict'
class AbortError extends Error {
  constructor (message) {
    super(message)
    this.code = 'FETCH_ABORTED'
    this.type = 'aborted'
    Error.captureStackTrace(this, this.constructor)
  }

  get name () {
    return 'AbortError'
  }

  // don't allow name to be overridden, but don't throw either
  set name (s) {}
}
module.exports = AbortError
'use strict'
const { Minipass } = require('minipass')
const TYPE = Symbol('type')
const BUFFER = Symbol('buffer')

class Blob {
  constructor (blobParts, options) {
    this[TYPE] = ''

    const buffers = []
    let size = 0

    if (blobParts) {
      const a = blobParts
      const length = Number(a.length)
      for (let i = 0; i < length; i++) {
        const element = a[i]
        const buffer = element instanceof Buffer ? element
          : ArrayBuffer.isView(element)
            ? Buffer.from(element.buffer, element.byteOffset, element.byteLength)
            : element instanceof ArrayBuffer ? Buffer.from(element)
            : element instanceof Blob ? element[BUFFER]
            : typeof element === 'string' ? Buffer.from(element)
            : Buffer.from(String(element))
        size += buffer.length
        buffers.push(buffer)
      }
    }

    this[BUFFER] = Buffer.concat(buffers, size)

    const type = options && options.type !== undefined
      && String(options.type).toLowerCase()
    if (type && !/[^\u0020-\u007E]/.test(type)) {
      this[TYPE] = type
    }
  }

  get size () {
    return this[BUFFER].length
  }

  get type () {
    return this[TYPE]
  }

  text () {
    return Promise.resolve(this[BUFFER].toString())
  }

  arrayBuffer () {
    const buf = this[BUFFER]
    const off = buf.byteOffset
    const len = buf.byteLength
    const ab = buf.buffer.slice(off, off + len)
    return Promise.resolve(ab)
  }

  stream () {
    return new Minipass().end(this[BUFFER])
  }

  slice (start, end, type) {
    const size = this.size
    const relativeStart = start === undefined ? 0
      : start < 0 ? Math.max(size + start, 0)
      : Math.min(start, size)
    const relativeEnd = end === undefined ? size
      : end < 0 ? Math.max(size + end, 0)
      : Math.min(end, size)
    const span = Math.max(relativeEnd - relativeStart, 0)

    const buffer = this[BUFFER]
    const slicedBuffer = buffer.slice(
      relativeStart,
      relativeStart + span
    )
    const blob = new Blob([], { type })
    blob[BUFFER] = slicedBuffer
    return blob
  }

  get [Symbol.toStringTag] () {
    return 'Blob'
  }

  static get BUFFER () {
    return BUFFER
  }
}

Object.defineProperties(Blob.prototype, {
  size: { enumerable: true },
  type: { enumerable: true },
})

module.exports = Blob
'use strict'
const { Minipass } = require('minipass')
const MinipassSized = require('minipass-sized')

const Blob = require('./blob.js')
const { BUFFER } = Blob
const FetchError = require('./fetch-error.js')

// optional dependency on 'encoding'
let convert
try {
  convert = require('encoding').convert
} catch (e) {
  // defer error until textConverted is called
}

const INTERNALS = Symbol('Body internals')
const CONSUME_BODY = Symbol('consumeBody')

class Body {
  constructor (bodyArg, options = {}) {
    const { size = 0, timeout = 0 } = options
    const body = bodyArg === undefined || bodyArg === null ? null
      : isURLSearchParams(bodyArg) ? Buffer.from(bodyArg.toString())
      : isBlob(bodyArg) ? bodyArg
      : Buffer.isBuffer(bodyArg) ? bodyArg
      : Object.prototype.toString.call(bodyArg) === '[object ArrayBuffer]'
        ? Buffer.from(bodyArg)
        : ArrayBuffer.isView(bodyArg)
          ? Buffer.from(bodyArg.buffer, bodyArg.byteOffset, bodyArg.byteLength)
          : Minipass.isStream(bodyArg) ? bodyArg
          : Buffer.from(String(bodyArg))

    this[INTERNALS] = {
      body,
      disturbed: false,
      error: null,
    }

    this.size = size
    this.timeout = timeout

    if (Minipass.isStream(body)) {
      body.on('error', er => {
        const error = er.name === 'AbortError' ? er
          : new FetchError(`Invalid response while trying to fetch ${
            this.url}: ${er.message}`, 'system', er)
        this[INTERNALS].error = error
      })
    }
  }

  get body () {
    return this[INTERNALS].body
  }

  get bodyUsed () {
    return this[INTERNALS].disturbed
  }

  arrayBuffer () {
    return this[CONSUME_BODY]().then(buf =>
      buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))
  }

  blob () {
    const ct = this.headers && this.headers.get('content-type') || ''
    return this[CONSUME_BODY]().then(buf => Object.assign(
      new Blob([], { type: ct.toLowerCase() }),
      { [BUFFER]: buf }
    ))
  }

  async json () {
    const buf = await this[CONSUME_BODY]()
    try {
      return JSON.parse(buf.toString())
    } catch (er) {
      throw new FetchError(
        `invalid json response body at ${this.url} reason: ${er.message}`,
        'invalid-json'
      )
    }
  }

  text () {
    return this[CONSUME_BODY]().then(buf => buf.toString())
  }

  buffer () {
    return this[CONSUME_BODY]()
  }

  textConverted () {
    return this[CONSUME_BODY]().then(buf => convertBody(buf, this.headers))
  }

  [CONSUME_BODY] () {
    if (this[INTERNALS].disturbed) {
      return Promise.reject(new TypeError(`body used already for: ${
        this.url}`))
    }

    this[INTERNALS].disturbed = true

    if (this[INTERNALS].error) {
      return Promise.reject(this[INTERNALS].error)
    }

    // body is null
    if (this.body === null) {
      return Promise.resolve(Buffer.alloc(0))
    }

    if (Buffer.isBuffer(this.body)) {
      return Promise.resolve(this.body)
    }

    const upstream = isBlob(this.body) ? this.body.stream() : this.body

    /* istanbul ignore if: should never happen */
    if (!Minipass.isStream(upstream)) {
      return Promise.resolve(Buffer.alloc(0))
    }

    const stream = this.size && upstream instanceof MinipassSized ? upstream
      : !this.size && upstream instanceof Minipass &&
        !(upstream instanceof MinipassSized) ? upstream
      : this.size ? new MinipassSized({ size: this.size })
      : new Minipass()

    // allow timeout on slow response body, but only if the stream is still writable. this
    // makes the timeout center on the socket stream from lib/index.js rather than the
    // intermediary minipass stream we create to receive the data
    const resTimeout = this.timeout && stream.writable ? setTimeout(() => {
      stream.emit('error', new FetchError(
        `Response timeout while trying to fetch ${
          this.url} (over ${this.timeout}ms)`, 'body-timeout'))
    }, this.timeout) : null

    // do not keep the process open just for this timeout, even
    // though we expect it'll get cleared eventually.
    if (resTimeout && resTimeout.unref) {
      resTimeout.unref()
    }

    // do the pipe in the promise, because the pipe() can send too much
    // data through right away and upset the MP Sized object
    return new Promise((resolve) => {
      // if the stream is some other kind of stream, then pipe through a MP
      // so we can collect it more easily.
      if (stream !== upstream) {
        upstream.on('error', er => stream.emit('error', er))
        upstream.pipe(stream)
      }
      resolve()
    }).then(() => stream.concat()).then(buf => {
      clearTimeout(resTimeout)
      return buf
    }).catch(er => {
      clearTimeout(resTimeout)
      // request was aborted, reject with this Error
      if (er.name === 'AbortError' || er.name === 'FetchError') {
        throw er
      } else if (er.name === 'RangeError') {
        throw new FetchError(`Could not create Buffer from response body for ${
          this.url}: ${er.message}`, 'system', er)
      } else {
        // other errors, such as incorrect content-encoding or content-length
        throw new FetchError(`Invalid response body while trying to fetch ${
          this.url}: ${er.message}`, 'system', er)
      }
    })
  }

  static clone (instance) {
    if (instance.bodyUsed) {
      throw new Error('cannot clone body after it is used')
    }

    const body = instance.body

    // check that body is a stream and not form-data object
    // NB: can't clone the form-data object without having it as a dependency
    if (Minipass.isStream(body) && typeof body.getBoundary !== 'function') {
      // create a dedicated tee stream so that we don't lose data
      // potentially sitting in the body stream's buffer by writing it
      // immediately to p1 and not having it for p2.
      const tee = new Minipass()
      const p1 = new Minipass()
      const p2 = new Minipass()
      tee.on('error', er => {
        p1.emit('error', er)
        p2.emit('error', er)
      })
      body.on('error', er => tee.emit('error', er))
      tee.pipe(p1)
      tee.pipe(p2)
      body.pipe(tee)
      // set instance body to one fork, return the other
      instance[INTERNALS].body = p1
      return p2
    } else {
      return instance.body
    }
  }

  static extractContentType (body) {
    return body === null || body === undefined ? null
      : typeof body === 'string' ? 'text/plain;charset=UTF-8'
      : isURLSearchParams(body)
        ? 'application/x-www-form-urlencoded;charset=UTF-8'
        : isBlob(body) ? body.type || null
        : Buffer.isBuffer(body) ? null
        : Object.prototype.toString.call(body) === '[object ArrayBuffer]' ? null
        : ArrayBuffer.isView(body) ? null
        : typeof body.getBoundary === 'function'
          ? `multipart/form-data;boundary=${body.getBoundary()}`
          : Minipass.isStream(body) ? null
          : 'text/plain;charset=UTF-8'
  }

  static getTotalBytes (instance) {
    const { body } = instance
    return (body === null || body === undefined) ? 0
      : isBlob(body) ? body.size
      : Buffer.isBuffer(body) ? body.length
      : body && typeof body.getLengthSync === 'function' && (
        // detect form data input from form-data module
        body._lengthRetrievers &&
        /* istanbul ignore next */ body._lengthRetrievers.length === 0 || // 1.x
        body.hasKnownLength && body.hasKnownLength()) // 2.x
        ? body.getLengthSync()
        : null
  }

  static writeToStream (dest, instance) {
    const { body } = instance

    if (body === null || body === undefined) {
      dest.end()
    } else if (Buffer.isBuffer(body) || typeof body === 'string') {
      dest.end(body)
    } else {
      // body is stream or blob
      const stream = isBlob(body) ? body.stream() : body
      stream.on('error', er => dest.emit('error', er)).pipe(dest)
    }

    return dest
  }
}

Object.defineProperties(Body.prototype, {
  body: { enumerable: true },
  bodyUsed: { enumerable: true },
  arrayBuffer: { enumerable: true },
  blob: { enumerable: true },
  json: { enumerable: true },
  text: { enumerable: true },
})

const isURLSearchParams = obj =>
  // Duck-typing as a necessary condition.
  (typeof obj !== 'object' ||
    typeof obj.append !== 'function' ||
    typeof obj.delete !== 'function' ||
    typeof obj.get !== 'function' ||
    typeof obj.getAll !== 'function' ||
    typeof obj.has !== 'function' ||
    typeof obj.set !== 'function') ? false
  // Brand-checking and more duck-typing as optional condition.
  : obj.constructor.name === 'URLSearchParams' ||
    Object.prototype.toString.call(obj) === '[object URLSearchParams]' ||
    typeof obj.sort === 'function'

const isBlob = obj =>
  typeof obj === 'object' &&
  typeof obj.arrayBuffer === 'function' &&
  typeof obj.type === 'string' &&
  typeof obj.stream === 'function' &&
  typeof obj.constructor === 'function' &&
  typeof obj.constructor.name === 'string' &&
  /^(Blob|File)$/.test(obj.constructor.name) &&
  /^(Blob|File)$/.test(obj[Symbol.toStringTag])

const convertBody = (buffer, headers) => {
  /* istanbul ignore if */
  if (typeof convert !== 'function') {
    throw new Error('The package `encoding` must be installed to use the textConverted() function')
  }

  const ct = headers && headers.get('content-type')
  let charset = 'utf-8'
  let res

  // header
  if (ct) {
    res = /charset=([^;]*)/i.exec(ct)
  }

  // no charset in content type, peek at response body for at most 1024 bytes
  const str = buffer.slice(0, 1024).toString()

  // html5
  if (!res && str) {
    res = / this.expect
      ? 'max-size' : type
    this.message = message
    Error.captureStackTrace(this, this.constructor)
  }

  get name () {
    return 'FetchError'
  }

  // don't allow name to be overwritten
  set name (n) {}

  get [Symbol.toStringTag] () {
    return 'FetchError'
  }
}
module.exports = FetchError
'use strict'
const invalidTokenRegex = /[^^_`a-zA-Z\-0-9!#$%&'*+.|~]/
const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/

const validateName = name => {
  name = `${name}`
  if (invalidTokenRegex.test(name) || name === '') {
    throw new TypeError(`${name} is not a legal HTTP header name`)
  }
}

const validateValue = value => {
  value = `${value}`
  if (invalidHeaderCharRegex.test(value)) {
    throw new TypeError(`${value} is not a legal HTTP header value`)
  }
}

const find = (map, name) => {
  name = name.toLowerCase()
  for (const key in map) {
    if (key.toLowerCase() === name) {
      return key
    }
  }
  return undefined
}

const MAP = Symbol('map')
class Headers {
  constructor (init = undefined) {
    this[MAP] = Object.create(null)
    if (init instanceof Headers) {
      const rawHeaders = init.raw()
      const headerNames = Object.keys(rawHeaders)
      for (const headerName of headerNames) {
        for (const value of rawHeaders[headerName]) {
          this.append(headerName, value)
        }
      }
      return
    }

    // no-op
    if (init === undefined || init === null) {
      return
    }

    if (typeof init === 'object') {
      const method = init[Symbol.iterator]
      if (method !== null && method !== undefined) {
        if (typeof method !== 'function') {
          throw new TypeError('Header pairs must be iterable')
        }

        // sequence>
        // Note: per spec we have to first exhaust the lists then process them
        const pairs = []
        for (const pair of init) {
          if (typeof pair !== 'object' ||
              typeof pair[Symbol.iterator] !== 'function') {
            throw new TypeError('Each header pair must be iterable')
          }
          const arrPair = Array.from(pair)
          if (arrPair.length !== 2) {
            throw new TypeError('Each header pair must be a name/value tuple')
          }
          pairs.push(arrPair)
        }

        for (const pair of pairs) {
          this.append(pair[0], pair[1])
        }
      } else {
        // record
        for (const key of Object.keys(init)) {
          this.append(key, init[key])
        }
      }
    } else {
      throw new TypeError('Provided initializer must be an object')
    }
  }

  get (name) {
    name = `${name}`
    validateName(name)
    const key = find(this[MAP], name)
    if (key === undefined) {
      return null
    }

    return this[MAP][key].join(', ')
  }

  forEach (callback, thisArg = undefined) {
    let pairs = getHeaders(this)
    for (let i = 0; i < pairs.length; i++) {
      const [name, value] = pairs[i]
      callback.call(thisArg, value, name, this)
      // refresh in case the callback added more headers
      pairs = getHeaders(this)
    }
  }

  set (name, value) {
    name = `${name}`
    value = `${value}`
    validateName(name)
    validateValue(value)
    const key = find(this[MAP], name)
    this[MAP][key !== undefined ? key : name] = [value]
  }

  append (name, value) {
    name = `${name}`
    value = `${value}`
    validateName(name)
    validateValue(value)
    const key = find(this[MAP], name)
    if (key !== undefined) {
      this[MAP][key].push(value)
    } else {
      this[MAP][name] = [value]
    }
  }

  has (name) {
    name = `${name}`
    validateName(name)
    return find(this[MAP], name) !== undefined
  }

  delete (name) {
    name = `${name}`
    validateName(name)
    const key = find(this[MAP], name)
    if (key !== undefined) {
      delete this[MAP][key]
    }
  }

  raw () {
    return this[MAP]
  }

  keys () {
    return new HeadersIterator(this, 'key')
  }

  values () {
    return new HeadersIterator(this, 'value')
  }

  [Symbol.iterator] () {
    return new HeadersIterator(this, 'key+value')
  }

  entries () {
    return new HeadersIterator(this, 'key+value')
  }

  get [Symbol.toStringTag] () {
    return 'Headers'
  }

  static exportNodeCompatibleHeaders (headers) {
    const obj = Object.assign(Object.create(null), headers[MAP])

    // http.request() only supports string as Host header. This hack makes
    // specifying custom Host header possible.
    const hostHeaderKey = find(headers[MAP], 'Host')
    if (hostHeaderKey !== undefined) {
      obj[hostHeaderKey] = obj[hostHeaderKey][0]
    }

    return obj
  }

  static createHeadersLenient (obj) {
    const headers = new Headers()
    for (const name of Object.keys(obj)) {
      if (invalidTokenRegex.test(name)) {
        continue
      }

      if (Array.isArray(obj[name])) {
        for (const val of obj[name]) {
          if (invalidHeaderCharRegex.test(val)) {
            continue
          }

          if (headers[MAP][name] === undefined) {
            headers[MAP][name] = [val]
          } else {
            headers[MAP][name].push(val)
          }
        }
      } else if (!invalidHeaderCharRegex.test(obj[name])) {
        headers[MAP][name] = [obj[name]]
      }
    }
    return headers
  }
}

Object.defineProperties(Headers.prototype, {
  get: { enumerable: true },
  forEach: { enumerable: true },
  set: { enumerable: true },
  append: { enumerable: true },
  has: { enumerable: true },
  delete: { enumerable: true },
  keys: { enumerable: true },
  values: { enumerable: true },
  entries: { enumerable: true },
})

const getHeaders = (headers, kind = 'key+value') =>
  Object.keys(headers[MAP]).sort().map(
    kind === 'key' ? k => k.toLowerCase()
    : kind === 'value' ? k => headers[MAP][k].join(', ')
    : k => [k.toLowerCase(), headers[MAP][k].join(', ')]
  )

const INTERNAL = Symbol('internal')

class HeadersIterator {
  constructor (target, kind) {
    this[INTERNAL] = {
      target,
      kind,
      index: 0,
    }
  }

  get [Symbol.toStringTag] () {
    return 'HeadersIterator'
  }

  next () {
    /* istanbul ignore if: should be impossible */
    if (!this || Object.getPrototypeOf(this) !== HeadersIterator.prototype) {
      throw new TypeError('Value of `this` is not a HeadersIterator')
    }

    const { target, kind, index } = this[INTERNAL]
    const values = getHeaders(target, kind)
    const len = values.length
    if (index >= len) {
      return {
        value: undefined,
        done: true,
      }
    }

    this[INTERNAL].index++

    return { value: values[index], done: false }
  }
}

// manually extend because 'extends' requires a ctor
Object.setPrototypeOf(HeadersIterator.prototype,
  Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())))

module.exports = Headers
'use strict'
const { URL } = require('url')
const http = require('http')
const https = require('https')
const zlib = require('minizlib')
const { Minipass } = require('minipass')

const Body = require('./body.js')
const { writeToStream, getTotalBytes } = Body
const Response = require('./response.js')
const Headers = require('./headers.js')
const { createHeadersLenient } = Headers
const Request = require('./request.js')
const { getNodeRequestOptions } = Request
const FetchError = require('./fetch-error.js')
const AbortError = require('./abort-error.js')

// XXX this should really be split up and unit-ized for easier testing
// and better DRY implementation of data/http request aborting
const fetch = async (url, opts) => {
  if (/^data:/.test(url)) {
    const request = new Request(url, opts)
    // delay 1 promise tick so that the consumer can abort right away
    return Promise.resolve().then(() => new Promise((resolve, reject) => {
      let type, data
      try {
        const { pathname, search } = new URL(url)
        const split = pathname.split(',')
        if (split.length < 2) {
          throw new Error('invalid data: URI')
        }
        const mime = split.shift()
        const base64 = /;base64$/.test(mime)
        type = base64 ? mime.slice(0, -1 * ';base64'.length) : mime
        const rawData = decodeURIComponent(split.join(',') + search)
        data = base64 ? Buffer.from(rawData, 'base64') : Buffer.from(rawData)
      } catch (er) {
        return reject(new FetchError(`[${request.method}] ${
          request.url} invalid URL, ${er.message}`, 'system', er))
      }

      const { signal } = request
      if (signal && signal.aborted) {
        return reject(new AbortError('The user aborted a request.'))
      }

      const headers = { 'Content-Length': data.length }
      if (type) {
        headers['Content-Type'] = type
      }
      return resolve(new Response(data, { headers }))
    }))
  }

  return new Promise((resolve, reject) => {
    // build request object
    const request = new Request(url, opts)
    let options
    try {
      options = getNodeRequestOptions(request)
    } catch (er) {
      return reject(er)
    }

    const send = (options.protocol === 'https:' ? https : http).request
    const { signal } = request
    let response = null
    const abort = () => {
      const error = new AbortError('The user aborted a request.')
      reject(error)
      if (Minipass.isStream(request.body) &&
          typeof request.body.destroy === 'function') {
        request.body.destroy(error)
      }
      if (response && response.body) {
        response.body.emit('error', error)
      }
    }

    if (signal && signal.aborted) {
      return abort()
    }

    const abortAndFinalize = () => {
      abort()
      finalize()
    }

    const finalize = () => {
      req.abort()
      if (signal) {
        signal.removeEventListener('abort', abortAndFinalize)
      }
      clearTimeout(reqTimeout)
    }

    // send request
    const req = send(options)

    if (signal) {
      signal.addEventListener('abort', abortAndFinalize)
    }

    let reqTimeout = null
    if (request.timeout) {
      req.once('socket', () => {
        reqTimeout = setTimeout(() => {
          reject(new FetchError(`network timeout at: ${
            request.url}`, 'request-timeout'))
          finalize()
        }, request.timeout)
      })
    }

    req.on('error', er => {
      // if a 'response' event is emitted before the 'error' event, then by the
      // time this handler is run it's too late to reject the Promise for the
      // response. instead, we forward the error event to the response stream
      // so that the error will surface to the user when they try to consume
      // the body. this is done as a side effect of aborting the request except
      // for in windows, where we must forward the event manually, otherwise
      // there is no longer a ref'd socket attached to the request and the
      // stream never ends so the event loop runs out of work and the process
      // exits without warning.
      // coverage skipped here due to the difficulty in testing
      // istanbul ignore next
      if (req.res) {
        req.res.emit('error', er)
      }
      reject(new FetchError(`request to ${request.url} failed, reason: ${
        er.message}`, 'system', er))
      finalize()
    })

    req.on('response', res => {
      clearTimeout(reqTimeout)

      const headers = createHeadersLenient(res.headers)

      // HTTP fetch step 5
      if (fetch.isRedirect(res.statusCode)) {
        // HTTP fetch step 5.2
        const location = headers.get('Location')

        // HTTP fetch step 5.3
        let locationURL = null
        try {
          locationURL = location === null ? null : new URL(location, request.url).toString()
        } catch {
          // error here can only be invalid URL in Location: header
          // do not throw when options.redirect == manual
          // let the user extract the errorneous redirect URL
          if (request.redirect !== 'manual') {
            /* eslint-disable-next-line max-len */
            reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'))
            finalize()
            return
          }
        }

        // HTTP fetch step 5.5
        if (request.redirect === 'error') {
          reject(new FetchError('uri requested responds with a redirect, ' +
            `redirect mode is set to error: ${request.url}`, 'no-redirect'))
          finalize()
          return
        } else if (request.redirect === 'manual') {
          // node-fetch-specific step: make manual redirect a bit easier to
          // use by setting the Location header value to the resolved URL.
          if (locationURL !== null) {
            // handle corrupted header
            try {
              headers.set('Location', locationURL)
            } catch (err) {
              /* istanbul ignore next: nodejs server prevent invalid
                 response headers, we can't test this through normal
                 request */
              reject(err)
            }
          }
        } else if (request.redirect === 'follow' && locationURL !== null) {
          // HTTP-redirect fetch step 5
          if (request.counter >= request.follow) {
            reject(new FetchError(`maximum redirect reached at: ${
              request.url}`, 'max-redirect'))
            finalize()
            return
          }

          // HTTP-redirect fetch step 9
          if (res.statusCode !== 303 &&
              request.body &&
              getTotalBytes(request) === null) {
            reject(new FetchError(
              'Cannot follow redirect with body being a readable stream',
              'unsupported-redirect'
            ))
            finalize()
            return
          }

          // Update host due to redirection
          request.headers.set('host', (new URL(locationURL)).host)

          // HTTP-redirect fetch step 6 (counter increment)
          // Create a new Request object.
          const requestOpts = {
            headers: new Headers(request.headers),
            follow: request.follow,
            counter: request.counter + 1,
            agent: request.agent,
            compress: request.compress,
            method: request.method,
            body: request.body,
            signal: request.signal,
            timeout: request.timeout,
          }

          // if the redirect is to a new hostname, strip the authorization and cookie headers
          const parsedOriginal = new URL(request.url)
          const parsedRedirect = new URL(locationURL)
          if (parsedOriginal.hostname !== parsedRedirect.hostname) {
            requestOpts.headers.delete('authorization')
            requestOpts.headers.delete('cookie')
          }

          // HTTP-redirect fetch step 11
          if (res.statusCode === 303 || (
            (res.statusCode === 301 || res.statusCode === 302) &&
              request.method === 'POST'
          )) {
            requestOpts.method = 'GET'
            requestOpts.body = undefined
            requestOpts.headers.delete('content-length')
          }

          // HTTP-redirect fetch step 15
          resolve(fetch(new Request(locationURL, requestOpts)))
          finalize()
          return
        }
      } // end if(isRedirect)

      // prepare response
      res.once('end', () =>
        signal && signal.removeEventListener('abort', abortAndFinalize))

      const body = new Minipass()
      // if an error occurs, either on the response stream itself, on one of the
      // decoder streams, or a response length timeout from the Body class, we
      // forward the error through to our internal body stream. If we see an
      // error event on that, we call finalize to abort the request and ensure
      // we don't leave a socket believing a request is in flight.
      // this is difficult to test, so lacks specific coverage.
      body.on('error', finalize)
      // exceedingly rare that the stream would have an error,
      // but just in case we proxy it to the stream in use.
      res.on('error', /* istanbul ignore next */ er => body.emit('error', er))
      res.on('data', (chunk) => body.write(chunk))
      res.on('end', () => body.end())

      const responseOptions = {
        url: request.url,
        status: res.statusCode,
        statusText: res.statusMessage,
        headers: headers,
        size: request.size,
        timeout: request.timeout,
        counter: request.counter,
        trailer: new Promise(resolveTrailer =>
          res.on('end', () => resolveTrailer(createHeadersLenient(res.trailers)))),
      }

      // HTTP-network fetch step 12.1.1.3
      const codings = headers.get('Content-Encoding')

      // HTTP-network fetch step 12.1.1.4: handle content codings

      // in following scenarios we ignore compression support
      // 1. compression support is disabled
      // 2. HEAD request
      // 3. no Content-Encoding header
      // 4. no content response (204)
      // 5. content not modified response (304)
      if (!request.compress ||
          request.method === 'HEAD' ||
          codings === null ||
          res.statusCode === 204 ||
          res.statusCode === 304) {
        response = new Response(body, responseOptions)
        resolve(response)
        return
      }

      // Be less strict when decoding compressed responses, since sometimes
      // servers send slightly invalid responses that are still accepted
      // by common browsers.
      // Always using Z_SYNC_FLUSH is what cURL does.
      const zlibOptions = {
        flush: zlib.constants.Z_SYNC_FLUSH,
        finishFlush: zlib.constants.Z_SYNC_FLUSH,
      }

      // for gzip
      if (codings === 'gzip' || codings === 'x-gzip') {
        const unzip = new zlib.Gunzip(zlibOptions)
        response = new Response(
          // exceedingly rare that the stream would have an error,
          // but just in case we proxy it to the stream in use.
          body.on('error', /* istanbul ignore next */ er => unzip.emit('error', er)).pipe(unzip),
          responseOptions
        )
        resolve(response)
        return
      }

      // for deflate
      if (codings === 'deflate' || codings === 'x-deflate') {
        // handle the infamous raw deflate response from old servers
        // a hack for old IIS and Apache servers
        const raw = res.pipe(new Minipass())
        raw.once('data', chunk => {
          // see http://stackoverflow.com/questions/37519828
          const decoder = (chunk[0] & 0x0F) === 0x08
            ? new zlib.Inflate()
            : new zlib.InflateRaw()
          // exceedingly rare that the stream would have an error,
          // but just in case we proxy it to the stream in use.
          body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder)
          response = new Response(decoder, responseOptions)
          resolve(response)
        })
        return
      }

      // for br
      if (codings === 'br') {
        // ignoring coverage so tests don't have to fake support (or lack of) for brotli
        // istanbul ignore next
        try {
          var decoder = new zlib.BrotliDecompress()
        } catch (err) {
          reject(err)
          finalize()
          return
        }
        // exceedingly rare that the stream would have an error,
        // but just in case we proxy it to the stream in use.
        body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder)
        response = new Response(decoder, responseOptions)
        resolve(response)
        return
      }

      // otherwise, use response as-is
      response = new Response(body, responseOptions)
      resolve(response)
    })

    writeToStream(req, request)
  })
}

module.exports = fetch

fetch.isRedirect = code =>
  code === 301 ||
  code === 302 ||
  code === 303 ||
  code === 307 ||
  code === 308

fetch.Headers = Headers
fetch.Request = Request
fetch.Response = Response
fetch.FetchError = FetchError
fetch.AbortError = AbortError
'use strict'
const { URL } = require('url')
const { Minipass } = require('minipass')
const Headers = require('./headers.js')
const { exportNodeCompatibleHeaders } = Headers
const Body = require('./body.js')
const { clone, extractContentType, getTotalBytes } = Body

const version = require('../package.json').version
const defaultUserAgent =
  `minipass-fetch/${version} (+https://github.com/isaacs/minipass-fetch)`

const INTERNALS = Symbol('Request internals')

const isRequest = input =>
  typeof input === 'object' && typeof input[INTERNALS] === 'object'

const isAbortSignal = signal => {
  const proto = (
    signal
    && typeof signal === 'object'
    && Object.getPrototypeOf(signal)
  )
  return !!(proto && proto.constructor.name === 'AbortSignal')
}

class Request extends Body {
  constructor (input, init = {}) {
    const parsedURL = isRequest(input) ? new URL(input.url)
      : input && input.href ? new URL(input.href)
      : new URL(`${input}`)

    if (isRequest(input)) {
      init = { ...input[INTERNALS], ...init }
    } else if (!input || typeof input === 'string') {
      input = {}
    }

    const method = (init.method || input.method || 'GET').toUpperCase()
    const isGETHEAD = method === 'GET' || method === 'HEAD'

    if ((init.body !== null && init.body !== undefined ||
        isRequest(input) && input.body !== null) && isGETHEAD) {
      throw new TypeError('Request with GET/HEAD method cannot have body')
    }

    const inputBody = init.body !== null && init.body !== undefined ? init.body
      : isRequest(input) && input.body !== null ? clone(input)
      : null

    super(inputBody, {
      timeout: init.timeout || input.timeout || 0,
      size: init.size || input.size || 0,
    })

    const headers = new Headers(init.headers || input.headers || {})

    if (inputBody !== null && inputBody !== undefined &&
        !headers.has('Content-Type')) {
      const contentType = extractContentType(inputBody)
      if (contentType) {
        headers.append('Content-Type', contentType)
      }
    }

    const signal = 'signal' in init ? init.signal
      : null

    if (signal !== null && signal !== undefined && !isAbortSignal(signal)) {
      throw new TypeError('Expected signal must be an instanceof AbortSignal')
    }

    // TLS specific options that are handled by node
    const {
      ca,
      cert,
      ciphers,
      clientCertEngine,
      crl,
      dhparam,
      ecdhCurve,
      family,
      honorCipherOrder,
      key,
      passphrase,
      pfx,
      rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0',
      secureOptions,
      secureProtocol,
      servername,
      sessionIdContext,
    } = init

    this[INTERNALS] = {
      method,
      redirect: init.redirect || input.redirect || 'follow',
      headers,
      parsedURL,
      signal,
      ca,
      cert,
      ciphers,
      clientCertEngine,
      crl,
      dhparam,
      ecdhCurve,
      family,
      honorCipherOrder,
      key,
      passphrase,
      pfx,
      rejectUnauthorized,
      secureOptions,
      secureProtocol,
      servername,
      sessionIdContext,
    }

    // node-fetch-only options
    this.follow = init.follow !== undefined ? init.follow
      : input.follow !== undefined ? input.follow
      : 20
    this.compress = init.compress !== undefined ? init.compress
      : input.compress !== undefined ? input.compress
      : true
    this.counter = init.counter || input.counter || 0
    this.agent = init.agent || input.agent
  }

  get method () {
    return this[INTERNALS].method
  }

  get url () {
    return this[INTERNALS].parsedURL.toString()
  }

  get headers () {
    return this[INTERNALS].headers
  }

  get redirect () {
    return this[INTERNALS].redirect
  }

  get signal () {
    return this[INTERNALS].signal
  }

  clone () {
    return new Request(this)
  }

  get [Symbol.toStringTag] () {
    return 'Request'
  }

  static getNodeRequestOptions (request) {
    const parsedURL = request[INTERNALS].parsedURL
    const headers = new Headers(request[INTERNALS].headers)

    // fetch step 1.3
    if (!headers.has('Accept')) {
      headers.set('Accept', '*/*')
    }

    // Basic fetch
    if (!/^https?:$/.test(parsedURL.protocol)) {
      throw new TypeError('Only HTTP(S) protocols are supported')
    }

    if (request.signal &&
        Minipass.isStream(request.body) &&
        typeof request.body.destroy !== 'function') {
      throw new Error(
        'Cancellation of streamed requests with AbortSignal is not supported')
    }

    // HTTP-network-or-cache fetch steps 2.4-2.7
    const contentLengthValue =
      (request.body === null || request.body === undefined) &&
        /^(POST|PUT)$/i.test(request.method) ? '0'
      : request.body !== null && request.body !== undefined
        ? getTotalBytes(request)
        : null

    if (contentLengthValue) {
      headers.set('Content-Length', contentLengthValue + '')
    }

    // HTTP-network-or-cache fetch step 2.11
    if (!headers.has('User-Agent')) {
      headers.set('User-Agent', defaultUserAgent)
    }

    // HTTP-network-or-cache fetch step 2.15
    if (request.compress && !headers.has('Accept-Encoding')) {
      headers.set('Accept-Encoding', 'gzip,deflate')
    }

    const agent = typeof request.agent === 'function'
      ? request.agent(parsedURL)
      : request.agent

    if (!headers.has('Connection') && !agent) {
      headers.set('Connection', 'close')
    }

    // TLS specific options that are handled by node
    const {
      ca,
      cert,
      ciphers,
      clientCertEngine,
      crl,
      dhparam,
      ecdhCurve,
      family,
      honorCipherOrder,
      key,
      passphrase,
      pfx,
      rejectUnauthorized,
      secureOptions,
      secureProtocol,
      servername,
      sessionIdContext,
    } = request[INTERNALS]

    // HTTP-network fetch step 4.2
    // chunked encoding is handled by Node.js

    // we cannot spread parsedURL directly, so we have to read each property one-by-one
    // and map them to the equivalent https?.request() method options
    const urlProps = {
      auth: parsedURL.username || parsedURL.password
        ? `${parsedURL.username}:${parsedURL.password}`
        : '',
      host: parsedURL.host,
      hostname: parsedURL.hostname,
      path: `${parsedURL.pathname}${parsedURL.search}`,
      port: parsedURL.port,
      protocol: parsedURL.protocol,
    }

    return {
      ...urlProps,
      method: request.method,
      headers: exportNodeCompatibleHeaders(headers),
      agent,
      ca,
      cert,
      ciphers,
      clientCertEngine,
      crl,
      dhparam,
      ecdhCurve,
      family,
      honorCipherOrder,
      key,
      passphrase,
      pfx,
      rejectUnauthorized,
      secureOptions,
      secureProtocol,
      servername,
      sessionIdContext,
      timeout: request.timeout,
    }
  }
}

module.exports = Request

Object.defineProperties(Request.prototype, {
  method: { enumerable: true },
  url: { enumerable: true },
  headers: { enumerable: true },
  redirect: { enumerable: true },
  clone: { enumerable: true },
  signal: { enumerable: true },
})
'use strict'
const http = require('http')
const { STATUS_CODES } = http

const Headers = require('./headers.js')
const Body = require('./body.js')
const { clone, extractContentType } = Body

const INTERNALS = Symbol('Response internals')

class Response extends Body {
  constructor (body = null, opts = {}) {
    super(body, opts)

    const status = opts.status || 200
    const headers = new Headers(opts.headers)

    if (body !== null && body !== undefined && !headers.has('Content-Type')) {
      const contentType = extractContentType(body)
      if (contentType) {
        headers.append('Content-Type', contentType)
      }
    }

    this[INTERNALS] = {
      url: opts.url,
      status,
      statusText: opts.statusText || STATUS_CODES[status],
      headers,
      counter: opts.counter,
      trailer: Promise.resolve(opts.trailer || new Headers()),
    }
  }

  get trailer () {
    return this[INTERNALS].trailer
  }

  get url () {
    return this[INTERNALS].url || ''
  }

  get status () {
    return this[INTERNALS].status
  }

  get ok () {
    return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300
  }

  get redirected () {
    return this[INTERNALS].counter > 0
  }

  get statusText () {
    return this[INTERNALS].statusText
  }

  get headers () {
    return this[INTERNALS].headers
  }

  clone () {
    return new Response(clone(this), {
      url: this.url,
      status: this.status,
      statusText: this.statusText,
      headers: this.headers,
      ok: this.ok,
      redirected: this.redirected,
      trailer: this.trailer,
    })
  }

  get [Symbol.toStringTag] () {
    return 'Response'
  }
}

module.exports = Response

Object.defineProperties(Response.prototype, {
  url: { enumerable: true },
  status: { enumerable: true },
  ok: { enumerable: true },
  redirected: { enumerable: true },
  statusText: { enumerable: true },
  headers: { enumerable: true },
  clone: { enumerable: true },
})
Minizlib was created by Isaac Z. Schlueter.
It is a derivative work of the Node.js project.

"""
Copyright (c) 2017-2023 Isaac Z. Schlueter and Contributors
Copyright (c) 2017-2023 Node.js contributors. All rights reserved.
Copyright (c) 2017-2023 Joyent, Inc. and other Node contributors. All rights reserved.

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.
"""
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.constants = void 0;
// Update with any zlib constants that are added or changed in the future.
// Node v6 didn't export this, so we just hard code the version and rely
// on all the other hard-coded values from zlib v4736.  When node v6
// support drops, we can just export the realZlibConstants object.
const zlib_1 = __importDefault(require("zlib"));
/* c8 ignore start */
const realZlibConstants = zlib_1.default.constants || { ZLIB_VERNUM: 4736 };
/* c8 ignore stop */
exports.constants = Object.freeze(Object.assign(Object.create(null), {
    Z_NO_FLUSH: 0,
    Z_PARTIAL_FLUSH: 1,
    Z_SYNC_FLUSH: 2,
    Z_FULL_FLUSH: 3,
    Z_FINISH: 4,
    Z_BLOCK: 5,
    Z_OK: 0,
    Z_STREAM_END: 1,
    Z_NEED_DICT: 2,
    Z_ERRNO: -1,
    Z_STREAM_ERROR: -2,
    Z_DATA_ERROR: -3,
    Z_MEM_ERROR: -4,
    Z_BUF_ERROR: -5,
    Z_VERSION_ERROR: -6,
    Z_NO_COMPRESSION: 0,
    Z_BEST_SPEED: 1,
    Z_BEST_COMPRESSION: 9,
    Z_DEFAULT_COMPRESSION: -1,
    Z_FILTERED: 1,
    Z_HUFFMAN_ONLY: 2,
    Z_RLE: 3,
    Z_FIXED: 4,
    Z_DEFAULT_STRATEGY: 0,
    DEFLATE: 1,
    INFLATE: 2,
    GZIP: 3,
    GUNZIP: 4,
    DEFLATERAW: 5,
    INFLATERAW: 6,
    UNZIP: 7,
    BROTLI_DECODE: 8,
    BROTLI_ENCODE: 9,
    Z_MIN_WINDOWBITS: 8,
    Z_MAX_WINDOWBITS: 15,
    Z_DEFAULT_WINDOWBITS: 15,
    Z_MIN_CHUNK: 64,
    Z_MAX_CHUNK: Infinity,
    Z_DEFAULT_CHUNK: 16384,
    Z_MIN_MEMLEVEL: 1,
    Z_MAX_MEMLEVEL: 9,
    Z_DEFAULT_MEMLEVEL: 8,
    Z_MIN_LEVEL: -1,
    Z_MAX_LEVEL: 9,
    Z_DEFAULT_LEVEL: -1,
    BROTLI_OPERATION_PROCESS: 0,
    BROTLI_OPERATION_FLUSH: 1,
    BROTLI_OPERATION_FINISH: 2,
    BROTLI_OPERATION_EMIT_METADATA: 3,
    BROTLI_MODE_GENERIC: 0,
    BROTLI_MODE_TEXT: 1,
    BROTLI_MODE_FONT: 2,
    BROTLI_DEFAULT_MODE: 0,
    BROTLI_MIN_QUALITY: 0,
    BROTLI_MAX_QUALITY: 11,
    BROTLI_DEFAULT_QUALITY: 11,
    BROTLI_MIN_WINDOW_BITS: 10,
    BROTLI_MAX_WINDOW_BITS: 24,
    BROTLI_LARGE_MAX_WINDOW_BITS: 30,
    BROTLI_DEFAULT_WINDOW: 22,
    BROTLI_MIN_INPUT_BLOCK_BITS: 16,
    BROTLI_MAX_INPUT_BLOCK_BITS: 24,
    BROTLI_PARAM_MODE: 0,
    BROTLI_PARAM_QUALITY: 1,
    BROTLI_PARAM_LGWIN: 2,
    BROTLI_PARAM_LGBLOCK: 3,
    BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
    BROTLI_PARAM_SIZE_HINT: 5,
    BROTLI_PARAM_LARGE_WINDOW: 6,
    BROTLI_PARAM_NPOSTFIX: 7,
    BROTLI_PARAM_NDIRECT: 8,
    BROTLI_DECODER_RESULT_ERROR: 0,
    BROTLI_DECODER_RESULT_SUCCESS: 1,
    BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
    BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
    BROTLI_DECODER_NO_ERROR: 0,
    BROTLI_DECODER_SUCCESS: 1,
    BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
    BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
    BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
    BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
    BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
    BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
    BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
    BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
    BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
    BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
    BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
    BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
    BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
    BROTLI_DECODER_ERROR_UNREACHABLE: -31,
}, realZlibConstants));
//# sourceMappingURL=constants.js.map"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrotliDecompress = exports.BrotliCompress = exports.Brotli = exports.Unzip = exports.InflateRaw = exports.DeflateRaw = exports.Gunzip = exports.Gzip = exports.Inflate = exports.Deflate = exports.Zlib = exports.ZlibError = exports.constants = void 0;
const assert_1 = __importDefault(require("assert"));
const buffer_1 = require("buffer");
const minipass_1 = require("minipass");
const zlib_1 = __importDefault(require("zlib"));
const constants_js_1 = require("./constants.js");
var constants_js_2 = require("./constants.js");
Object.defineProperty(exports, "constants", { enumerable: true, get: function () { return constants_js_2.constants; } });
const OriginalBufferConcat = buffer_1.Buffer.concat;
const _superWrite = Symbol('_superWrite');
class ZlibError extends Error {
    code;
    errno;
    constructor(err) {
        super('zlib: ' + err.message);
        this.code = err.code;
        this.errno = err.errno;
        /* c8 ignore next */
        if (!this.code)
            this.code = 'ZLIB_ERROR';
        this.message = 'zlib: ' + err.message;
        Error.captureStackTrace(this, this.constructor);
    }
    get name() {
        return 'ZlibError';
    }
}
exports.ZlibError = ZlibError;
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
const _flushFlag = Symbol('flushFlag');
class ZlibBase extends minipass_1.Minipass {
    #sawError = false;
    #ended = false;
    #flushFlag;
    #finishFlushFlag;
    #fullFlushFlag;
    #handle;
    #onError;
    get sawError() {
        return this.#sawError;
    }
    get handle() {
        return this.#handle;
    }
    /* c8 ignore start */
    get flushFlag() {
        return this.#flushFlag;
    }
    /* c8 ignore stop */
    constructor(opts, mode) {
        if (!opts || typeof opts !== 'object')
            throw new TypeError('invalid options for ZlibBase constructor');
        //@ts-ignore
        super(opts);
        /* c8 ignore start */
        this.#flushFlag = opts.flush ?? 0;
        this.#finishFlushFlag = opts.finishFlush ?? 0;
        this.#fullFlushFlag = opts.fullFlushFlag ?? 0;
        /* c8 ignore stop */
        // this will throw if any options are invalid for the class selected
        try {
            // @types/node doesn't know that it exports the classes, but they're there
            //@ts-ignore
            this.#handle = new zlib_1.default[mode](opts);
        }
        catch (er) {
            // make sure that all errors get decorated properly
            throw new ZlibError(er);
        }
        this.#onError = err => {
            // no sense raising multiple errors, since we abort on the first one.
            if (this.#sawError)
                return;
            this.#sawError = true;
            // there is no way to cleanly recover.
            // continuing only obscures problems.
            this.close();
            this.emit('error', err);
        };
        this.#handle?.on('error', er => this.#onError(new ZlibError(er)));
        this.once('end', () => this.close);
    }
    close() {
        if (this.#handle) {
            this.#handle.close();
            this.#handle = undefined;
            this.emit('close');
        }
    }
    reset() {
        if (!this.#sawError) {
            (0, assert_1.default)(this.#handle, 'zlib binding closed');
            //@ts-ignore
            return this.#handle.reset?.();
        }
    }
    flush(flushFlag) {
        if (this.ended)
            return;
        if (typeof flushFlag !== 'number')
            flushFlag = this.#fullFlushFlag;
        this.write(Object.assign(buffer_1.Buffer.alloc(0), { [_flushFlag]: flushFlag }));
    }
    end(chunk, encoding, cb) {
        /* c8 ignore start */
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (chunk) {
            if (encoding)
                this.write(chunk, encoding);
            else
                this.write(chunk);
        }
        this.flush(this.#finishFlushFlag);
        this.#ended = true;
        return super.end(cb);
    }
    get ended() {
        return this.#ended;
    }
    // overridden in the gzip classes to do portable writes
    [_superWrite](data) {
        return super.write(data);
    }
    write(chunk, encoding, cb) {
        // process the chunk using the sync process
        // then super.write() all the outputted chunks
        if (typeof encoding === 'function')
            (cb = encoding), (encoding = 'utf8');
        if (typeof chunk === 'string')
            chunk = buffer_1.Buffer.from(chunk, encoding);
        if (this.#sawError)
            return;
        (0, assert_1.default)(this.#handle, 'zlib binding closed');
        // _processChunk tries to .close() the native handle after it's done, so we
        // intercept that by temporarily making it a no-op.
        // diving into the node:zlib internals a bit here
        const nativeHandle = this.#handle
            ._handle;
        const originalNativeClose = nativeHandle.close;
        nativeHandle.close = () => { };
        const originalClose = this.#handle.close;
        this.#handle.close = () => { };
        // It also calls `Buffer.concat()` at the end, which may be convenient
        // for some, but which we are not interested in as it slows us down.
        buffer_1.Buffer.concat = args => args;
        let result = undefined;
        try {
            const flushFlag = typeof chunk[_flushFlag] === 'number'
                ? chunk[_flushFlag]
                : this.#flushFlag;
            result = this.#handle._processChunk(chunk, flushFlag);
            // if we don't throw, reset it back how it was
            buffer_1.Buffer.concat = OriginalBufferConcat;
        }
        catch (err) {
            // or if we do, put Buffer.concat() back before we emit error
            // Error events call into user code, which may call Buffer.concat()
            buffer_1.Buffer.concat = OriginalBufferConcat;
            this.#onError(new ZlibError(err));
        }
        finally {
            if (this.#handle) {
                // Core zlib resets `_handle` to null after attempting to close the
                // native handle. Our no-op handler prevented actual closure, but we
                // need to restore the `._handle` property.
                ;
                this.#handle._handle =
                    nativeHandle;
                nativeHandle.close = originalNativeClose;
                this.#handle.close = originalClose;
                // `_processChunk()` adds an 'error' listener. If we don't remove it
                // after each call, these handlers start piling up.
                this.#handle.removeAllListeners('error');
                // make sure OUR error listener is still attached tho
            }
        }
        if (this.#handle)
            this.#handle.on('error', er => this.#onError(new ZlibError(er)));
        let writeReturn;
        if (result) {
            if (Array.isArray(result) && result.length > 0) {
                const r = result[0];
                // The first buffer is always `handle._outBuffer`, which would be
                // re-used for later invocations; so, we always have to copy that one.
                writeReturn = this[_superWrite](buffer_1.Buffer.from(r));
                for (let i = 1; i < result.length; i++) {
                    writeReturn = this[_superWrite](result[i]);
                }
            }
            else {
                // either a single Buffer or an empty array
                writeReturn = this[_superWrite](buffer_1.Buffer.from(result));
            }
        }
        if (cb)
            cb();
        return writeReturn;
    }
}
class Zlib extends ZlibBase {
    #level;
    #strategy;
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants_js_1.constants.Z_NO_FLUSH;
        opts.finishFlush = opts.finishFlush || constants_js_1.constants.Z_FINISH;
        opts.fullFlushFlag = constants_js_1.constants.Z_FULL_FLUSH;
        super(opts, mode);
        this.#level = opts.level;
        this.#strategy = opts.strategy;
    }
    params(level, strategy) {
        if (this.sawError)
            return;
        if (!this.handle)
            throw new Error('cannot switch params when binding is closed');
        // no way to test this without also not supporting params at all
        /* c8 ignore start */
        if (!this.handle.params)
            throw new Error('not supported in this implementation');
        /* c8 ignore stop */
        if (this.#level !== level || this.#strategy !== strategy) {
            this.flush(constants_js_1.constants.Z_SYNC_FLUSH);
            (0, assert_1.default)(this.handle, 'zlib binding closed');
            // .params() calls .flush(), but the latter is always async in the
            // core zlib. We override .flush() temporarily to intercept that and
            // flush synchronously.
            const origFlush = this.handle.flush;
            this.handle.flush = (flushFlag, cb) => {
                /* c8 ignore start */
                if (typeof flushFlag === 'function') {
                    cb = flushFlag;
                    flushFlag = this.flushFlag;
                }
                /* c8 ignore stop */
                this.flush(flushFlag);
                cb?.();
            };
            try {
                ;
                this.handle.params(level, strategy);
            }
            finally {
                this.handle.flush = origFlush;
            }
            /* c8 ignore start */
            if (this.handle) {
                this.#level = level;
                this.#strategy = strategy;
            }
            /* c8 ignore stop */
        }
    }
}
exports.Zlib = Zlib;
// minimal 2-byte header
class Deflate extends Zlib {
    constructor(opts) {
        super(opts, 'Deflate');
    }
}
exports.Deflate = Deflate;
class Inflate extends Zlib {
    constructor(opts) {
        super(opts, 'Inflate');
    }
}
exports.Inflate = Inflate;
class Gzip extends Zlib {
    #portable;
    constructor(opts) {
        super(opts, 'Gzip');
        this.#portable = opts && !!opts.portable;
    }
    [_superWrite](data) {
        if (!this.#portable)
            return super[_superWrite](data);
        // we'll always get the header emitted in one first chunk
        // overwrite the OS indicator byte with 0xFF
        this.#portable = false;
        data[9] = 255;
        return super[_superWrite](data);
    }
}
exports.Gzip = Gzip;
class Gunzip extends Zlib {
    constructor(opts) {
        super(opts, 'Gunzip');
    }
}
exports.Gunzip = Gunzip;
// raw - no header
class DeflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'DeflateRaw');
    }
}
exports.DeflateRaw = DeflateRaw;
class InflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'InflateRaw');
    }
}
exports.InflateRaw = InflateRaw;
// auto-detect header.
class Unzip extends Zlib {
    constructor(opts) {
        super(opts, 'Unzip');
    }
}
exports.Unzip = Unzip;
class Brotli extends ZlibBase {
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants_js_1.constants.BROTLI_OPERATION_PROCESS;
        opts.finishFlush =
            opts.finishFlush || constants_js_1.constants.BROTLI_OPERATION_FINISH;
        opts.fullFlushFlag = constants_js_1.constants.BROTLI_OPERATION_FLUSH;
        super(opts, mode);
    }
}
exports.Brotli = Brotli;
class BrotliCompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliCompress');
    }
}
exports.BrotliCompress = BrotliCompress;
class BrotliDecompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliDecompress');
    }
}
exports.BrotliDecompress = BrotliDecompress;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
// Update with any zlib constants that are added or changed in the future.
// Node v6 didn't export this, so we just hard code the version and rely
// on all the other hard-coded values from zlib v4736.  When node v6
// support drops, we can just export the realZlibConstants object.
import realZlib from 'zlib';
/* c8 ignore start */
const realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 };
/* c8 ignore stop */
export const constants = Object.freeze(Object.assign(Object.create(null), {
    Z_NO_FLUSH: 0,
    Z_PARTIAL_FLUSH: 1,
    Z_SYNC_FLUSH: 2,
    Z_FULL_FLUSH: 3,
    Z_FINISH: 4,
    Z_BLOCK: 5,
    Z_OK: 0,
    Z_STREAM_END: 1,
    Z_NEED_DICT: 2,
    Z_ERRNO: -1,
    Z_STREAM_ERROR: -2,
    Z_DATA_ERROR: -3,
    Z_MEM_ERROR: -4,
    Z_BUF_ERROR: -5,
    Z_VERSION_ERROR: -6,
    Z_NO_COMPRESSION: 0,
    Z_BEST_SPEED: 1,
    Z_BEST_COMPRESSION: 9,
    Z_DEFAULT_COMPRESSION: -1,
    Z_FILTERED: 1,
    Z_HUFFMAN_ONLY: 2,
    Z_RLE: 3,
    Z_FIXED: 4,
    Z_DEFAULT_STRATEGY: 0,
    DEFLATE: 1,
    INFLATE: 2,
    GZIP: 3,
    GUNZIP: 4,
    DEFLATERAW: 5,
    INFLATERAW: 6,
    UNZIP: 7,
    BROTLI_DECODE: 8,
    BROTLI_ENCODE: 9,
    Z_MIN_WINDOWBITS: 8,
    Z_MAX_WINDOWBITS: 15,
    Z_DEFAULT_WINDOWBITS: 15,
    Z_MIN_CHUNK: 64,
    Z_MAX_CHUNK: Infinity,
    Z_DEFAULT_CHUNK: 16384,
    Z_MIN_MEMLEVEL: 1,
    Z_MAX_MEMLEVEL: 9,
    Z_DEFAULT_MEMLEVEL: 8,
    Z_MIN_LEVEL: -1,
    Z_MAX_LEVEL: 9,
    Z_DEFAULT_LEVEL: -1,
    BROTLI_OPERATION_PROCESS: 0,
    BROTLI_OPERATION_FLUSH: 1,
    BROTLI_OPERATION_FINISH: 2,
    BROTLI_OPERATION_EMIT_METADATA: 3,
    BROTLI_MODE_GENERIC: 0,
    BROTLI_MODE_TEXT: 1,
    BROTLI_MODE_FONT: 2,
    BROTLI_DEFAULT_MODE: 0,
    BROTLI_MIN_QUALITY: 0,
    BROTLI_MAX_QUALITY: 11,
    BROTLI_DEFAULT_QUALITY: 11,
    BROTLI_MIN_WINDOW_BITS: 10,
    BROTLI_MAX_WINDOW_BITS: 24,
    BROTLI_LARGE_MAX_WINDOW_BITS: 30,
    BROTLI_DEFAULT_WINDOW: 22,
    BROTLI_MIN_INPUT_BLOCK_BITS: 16,
    BROTLI_MAX_INPUT_BLOCK_BITS: 24,
    BROTLI_PARAM_MODE: 0,
    BROTLI_PARAM_QUALITY: 1,
    BROTLI_PARAM_LGWIN: 2,
    BROTLI_PARAM_LGBLOCK: 3,
    BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
    BROTLI_PARAM_SIZE_HINT: 5,
    BROTLI_PARAM_LARGE_WINDOW: 6,
    BROTLI_PARAM_NPOSTFIX: 7,
    BROTLI_PARAM_NDIRECT: 8,
    BROTLI_DECODER_RESULT_ERROR: 0,
    BROTLI_DECODER_RESULT_SUCCESS: 1,
    BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
    BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
    BROTLI_DECODER_NO_ERROR: 0,
    BROTLI_DECODER_SUCCESS: 1,
    BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
    BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
    BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
    BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
    BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
    BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
    BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
    BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
    BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
    BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
    BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
    BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
    BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
    BROTLI_DECODER_ERROR_UNREACHABLE: -31,
}, realZlibConstants));
//# sourceMappingURL=constants.js.mapimport assert from 'assert';
import { Buffer } from 'buffer';
import { Minipass } from 'minipass';
import realZlib from 'zlib';
import { constants } from './constants.js';
export { constants } from './constants.js';
const OriginalBufferConcat = Buffer.concat;
const _superWrite = Symbol('_superWrite');
export class ZlibError extends Error {
    code;
    errno;
    constructor(err) {
        super('zlib: ' + err.message);
        this.code = err.code;
        this.errno = err.errno;
        /* c8 ignore next */
        if (!this.code)
            this.code = 'ZLIB_ERROR';
        this.message = 'zlib: ' + err.message;
        Error.captureStackTrace(this, this.constructor);
    }
    get name() {
        return 'ZlibError';
    }
}
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
const _flushFlag = Symbol('flushFlag');
class ZlibBase extends Minipass {
    #sawError = false;
    #ended = false;
    #flushFlag;
    #finishFlushFlag;
    #fullFlushFlag;
    #handle;
    #onError;
    get sawError() {
        return this.#sawError;
    }
    get handle() {
        return this.#handle;
    }
    /* c8 ignore start */
    get flushFlag() {
        return this.#flushFlag;
    }
    /* c8 ignore stop */
    constructor(opts, mode) {
        if (!opts || typeof opts !== 'object')
            throw new TypeError('invalid options for ZlibBase constructor');
        //@ts-ignore
        super(opts);
        /* c8 ignore start */
        this.#flushFlag = opts.flush ?? 0;
        this.#finishFlushFlag = opts.finishFlush ?? 0;
        this.#fullFlushFlag = opts.fullFlushFlag ?? 0;
        /* c8 ignore stop */
        // this will throw if any options are invalid for the class selected
        try {
            // @types/node doesn't know that it exports the classes, but they're there
            //@ts-ignore
            this.#handle = new realZlib[mode](opts);
        }
        catch (er) {
            // make sure that all errors get decorated properly
            throw new ZlibError(er);
        }
        this.#onError = err => {
            // no sense raising multiple errors, since we abort on the first one.
            if (this.#sawError)
                return;
            this.#sawError = true;
            // there is no way to cleanly recover.
            // continuing only obscures problems.
            this.close();
            this.emit('error', err);
        };
        this.#handle?.on('error', er => this.#onError(new ZlibError(er)));
        this.once('end', () => this.close);
    }
    close() {
        if (this.#handle) {
            this.#handle.close();
            this.#handle = undefined;
            this.emit('close');
        }
    }
    reset() {
        if (!this.#sawError) {
            assert(this.#handle, 'zlib binding closed');
            //@ts-ignore
            return this.#handle.reset?.();
        }
    }
    flush(flushFlag) {
        if (this.ended)
            return;
        if (typeof flushFlag !== 'number')
            flushFlag = this.#fullFlushFlag;
        this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }));
    }
    end(chunk, encoding, cb) {
        /* c8 ignore start */
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (chunk) {
            if (encoding)
                this.write(chunk, encoding);
            else
                this.write(chunk);
        }
        this.flush(this.#finishFlushFlag);
        this.#ended = true;
        return super.end(cb);
    }
    get ended() {
        return this.#ended;
    }
    // overridden in the gzip classes to do portable writes
    [_superWrite](data) {
        return super.write(data);
    }
    write(chunk, encoding, cb) {
        // process the chunk using the sync process
        // then super.write() all the outputted chunks
        if (typeof encoding === 'function')
            (cb = encoding), (encoding = 'utf8');
        if (typeof chunk === 'string')
            chunk = Buffer.from(chunk, encoding);
        if (this.#sawError)
            return;
        assert(this.#handle, 'zlib binding closed');
        // _processChunk tries to .close() the native handle after it's done, so we
        // intercept that by temporarily making it a no-op.
        // diving into the node:zlib internals a bit here
        const nativeHandle = this.#handle
            ._handle;
        const originalNativeClose = nativeHandle.close;
        nativeHandle.close = () => { };
        const originalClose = this.#handle.close;
        this.#handle.close = () => { };
        // It also calls `Buffer.concat()` at the end, which may be convenient
        // for some, but which we are not interested in as it slows us down.
        Buffer.concat = args => args;
        let result = undefined;
        try {
            const flushFlag = typeof chunk[_flushFlag] === 'number'
                ? chunk[_flushFlag]
                : this.#flushFlag;
            result = this.#handle._processChunk(chunk, flushFlag);
            // if we don't throw, reset it back how it was
            Buffer.concat = OriginalBufferConcat;
        }
        catch (err) {
            // or if we do, put Buffer.concat() back before we emit error
            // Error events call into user code, which may call Buffer.concat()
            Buffer.concat = OriginalBufferConcat;
            this.#onError(new ZlibError(err));
        }
        finally {
            if (this.#handle) {
                // Core zlib resets `_handle` to null after attempting to close the
                // native handle. Our no-op handler prevented actual closure, but we
                // need to restore the `._handle` property.
                ;
                this.#handle._handle =
                    nativeHandle;
                nativeHandle.close = originalNativeClose;
                this.#handle.close = originalClose;
                // `_processChunk()` adds an 'error' listener. If we don't remove it
                // after each call, these handlers start piling up.
                this.#handle.removeAllListeners('error');
                // make sure OUR error listener is still attached tho
            }
        }
        if (this.#handle)
            this.#handle.on('error', er => this.#onError(new ZlibError(er)));
        let writeReturn;
        if (result) {
            if (Array.isArray(result) && result.length > 0) {
                const r = result[0];
                // The first buffer is always `handle._outBuffer`, which would be
                // re-used for later invocations; so, we always have to copy that one.
                writeReturn = this[_superWrite](Buffer.from(r));
                for (let i = 1; i < result.length; i++) {
                    writeReturn = this[_superWrite](result[i]);
                }
            }
            else {
                // either a single Buffer or an empty array
                writeReturn = this[_superWrite](Buffer.from(result));
            }
        }
        if (cb)
            cb();
        return writeReturn;
    }
}
export class Zlib extends ZlibBase {
    #level;
    #strategy;
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.Z_NO_FLUSH;
        opts.finishFlush = opts.finishFlush || constants.Z_FINISH;
        opts.fullFlushFlag = constants.Z_FULL_FLUSH;
        super(opts, mode);
        this.#level = opts.level;
        this.#strategy = opts.strategy;
    }
    params(level, strategy) {
        if (this.sawError)
            return;
        if (!this.handle)
            throw new Error('cannot switch params when binding is closed');
        // no way to test this without also not supporting params at all
        /* c8 ignore start */
        if (!this.handle.params)
            throw new Error('not supported in this implementation');
        /* c8 ignore stop */
        if (this.#level !== level || this.#strategy !== strategy) {
            this.flush(constants.Z_SYNC_FLUSH);
            assert(this.handle, 'zlib binding closed');
            // .params() calls .flush(), but the latter is always async in the
            // core zlib. We override .flush() temporarily to intercept that and
            // flush synchronously.
            const origFlush = this.handle.flush;
            this.handle.flush = (flushFlag, cb) => {
                /* c8 ignore start */
                if (typeof flushFlag === 'function') {
                    cb = flushFlag;
                    flushFlag = this.flushFlag;
                }
                /* c8 ignore stop */
                this.flush(flushFlag);
                cb?.();
            };
            try {
                ;
                this.handle.params(level, strategy);
            }
            finally {
                this.handle.flush = origFlush;
            }
            /* c8 ignore start */
            if (this.handle) {
                this.#level = level;
                this.#strategy = strategy;
            }
            /* c8 ignore stop */
        }
    }
}
// minimal 2-byte header
export class Deflate extends Zlib {
    constructor(opts) {
        super(opts, 'Deflate');
    }
}
export class Inflate extends Zlib {
    constructor(opts) {
        super(opts, 'Inflate');
    }
}
export class Gzip extends Zlib {
    #portable;
    constructor(opts) {
        super(opts, 'Gzip');
        this.#portable = opts && !!opts.portable;
    }
    [_superWrite](data) {
        if (!this.#portable)
            return super[_superWrite](data);
        // we'll always get the header emitted in one first chunk
        // overwrite the OS indicator byte with 0xFF
        this.#portable = false;
        data[9] = 255;
        return super[_superWrite](data);
    }
}
export class Gunzip extends Zlib {
    constructor(opts) {
        super(opts, 'Gunzip');
    }
}
// raw - no header
export class DeflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'DeflateRaw');
    }
}
export class InflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'InflateRaw');
    }
}
// auto-detect header.
export class Unzip extends Zlib {
    constructor(opts) {
        super(opts, 'Unzip');
    }
}
export class Brotli extends ZlibBase {
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS;
        opts.finishFlush =
            opts.finishFlush || constants.BROTLI_OPERATION_FINISH;
        opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH;
        super(opts, mode);
    }
}
export class BrotliCompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliCompress');
    }
}
export class BrotliDecompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliDecompress');
    }
}
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "name": "minizlib",
  "version": "3.0.1",
  "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.",
  "main": "./dist/commonjs/index.js",
  "dependencies": {
    "minipass": "^7.0.4",
    "rimraf": "^5.0.5"
  },
  "scripts": {
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "format": "prettier --write . --loglevel warn",
    "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minizlib.git"
  },
  "keywords": [
    "zlib",
    "gzip",
    "gunzip",
    "deflate",
    "inflate",
    "compression",
    "zip",
    "unzip"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "MIT",
  "devDependencies": {
    "@types/node": "^20.11.29",
    "mkdirp": "^3.0.1",
    "tap": "^18.7.1",
    "tshy": "^1.12.0",
    "typedoc": "^0.25.12"
  },
  "files": [
    "dist"
  ],
  "engines": {
    "node": ">= 18"
  },
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "types": "./dist/commonjs/index.d.ts",
  "type": "module",
  "prettier": {
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  }
}
{
  "name": "minipass-fetch",
  "version": "4.0.0",
  "description": "An implementation of window.fetch in Node.js using Minipass streams",
  "license": "MIT",
  "main": "lib/index.js",
  "scripts": {
    "test:tls-fixtures": "./test/fixtures/tls/setup.sh",
    "test": "tap",
    "snap": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "tap": {
    "coverage-map": "map.js",
    "check-coverage": true,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "@ungap/url-search-params": "^0.2.2",
    "abort-controller": "^3.0.0",
    "abortcontroller-polyfill": "~1.7.3",
    "encoding": "^0.1.13",
    "form-data": "^4.0.0",
    "nock": "^13.2.4",
    "parted": "^0.1.1",
    "string-to-arraybuffer": "^1.0.2",
    "tap": "^16.0.0"
  },
  "dependencies": {
    "minipass": "^7.0.3",
    "minipass-sized": "^1.0.3",
    "minizlib": "^3.0.1"
  },
  "optionalDependencies": {
    "encoding": "^0.1.13"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/minipass-fetch.git"
  },
  "keywords": [
    "fetch",
    "minipass",
    "node-fetch",
    "window.fetch"
  ],
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "author": "GitHub Inc.",
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": "true"
  }
}
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const Minipass = require('minipass')
const _flush = Symbol('_flush')
const _flushed = Symbol('_flushed')
const _flushing = Symbol('_flushing')
class Flush extends Minipass {
  constructor (opt = {}) {
    if (typeof opt === 'function')
      opt = { flush: opt }

    super(opt)

    // or extend this class and provide a 'flush' method in your subclass
    if (typeof opt.flush !== 'function' && typeof this.flush !== 'function')
      throw new TypeError('must provide flush function in options')

    this[_flush] = opt.flush || this.flush
  }

  emit (ev, ...data) {
    if ((ev !== 'end' && ev !== 'finish') || this[_flushed])
      return super.emit(ev, ...data)

    if (this[_flushing])
      return

    this[_flushing] = true

    const afterFlush = er => {
      this[_flushed] = true
      er ? super.emit('error', er) : super.emit('end')
    }

    const ret = this[_flush](afterFlush)
    if (ret && ret.then)
      ret.then(() => afterFlush(), er => afterFlush(er))
  }
}

module.exports = Flush
The ISC License

Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'
const proc = typeof process === 'object' && process ? process : {
  stdout: null,
  stderr: null,
}
const EE = require('events')
const Stream = require('stream')
const SD = require('string_decoder').StringDecoder

const EOF = Symbol('EOF')
const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
const EMITTED_END = Symbol('emittedEnd')
const EMITTING_END = Symbol('emittingEnd')
const EMITTED_ERROR = Symbol('emittedError')
const CLOSED = Symbol('closed')
const READ = Symbol('read')
const FLUSH = Symbol('flush')
const FLUSHCHUNK = Symbol('flushChunk')
const ENCODING = Symbol('encoding')
const DECODER = Symbol('decoder')
const FLOWING = Symbol('flowing')
const PAUSED = Symbol('paused')
const RESUME = Symbol('resume')
const BUFFERLENGTH = Symbol('bufferLength')
const BUFFERPUSH = Symbol('bufferPush')
const BUFFERSHIFT = Symbol('bufferShift')
const OBJECTMODE = Symbol('objectMode')
const DESTROYED = Symbol('destroyed')
const EMITDATA = Symbol('emitData')
const EMITEND = Symbol('emitEnd')
const EMITEND2 = Symbol('emitEnd2')
const ASYNC = Symbol('async')

const defer = fn => Promise.resolve().then(fn)

// TODO remove when Node v8 support drops
const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
const ASYNCITERATOR = doIter && Symbol.asyncIterator
  || Symbol('asyncIterator not implemented')
const ITERATOR = doIter && Symbol.iterator
  || Symbol('iterator not implemented')

// events that mean 'the stream is over'
// these are treated specially, and re-emitted
// if they are listened for after emitting.
const isEndish = ev =>
  ev === 'end' ||
  ev === 'finish' ||
  ev === 'prefinish'

const isArrayBuffer = b => b instanceof ArrayBuffer ||
  typeof b === 'object' &&
  b.constructor &&
  b.constructor.name === 'ArrayBuffer' &&
  b.byteLength >= 0

const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)

class Pipe {
  constructor (src, dest, opts) {
    this.src = src
    this.dest = dest
    this.opts = opts
    this.ondrain = () => src[RESUME]()
    dest.on('drain', this.ondrain)
  }
  unpipe () {
    this.dest.removeListener('drain', this.ondrain)
  }
  // istanbul ignore next - only here for the prototype
  proxyErrors () {}
  end () {
    this.unpipe()
    if (this.opts.end)
      this.dest.end()
  }
}

class PipeProxyErrors extends Pipe {
  unpipe () {
    this.src.removeListener('error', this.proxyErrors)
    super.unpipe()
  }
  constructor (src, dest, opts) {
    super(src, dest, opts)
    this.proxyErrors = er => dest.emit('error', er)
    src.on('error', this.proxyErrors)
  }
}

module.exports = class Minipass extends Stream {
  constructor (options) {
    super()
    this[FLOWING] = false
    // whether we're explicitly paused
    this[PAUSED] = false
    this.pipes = []
    this.buffer = []
    this[OBJECTMODE] = options && options.objectMode || false
    if (this[OBJECTMODE])
      this[ENCODING] = null
    else
      this[ENCODING] = options && options.encoding || null
    if (this[ENCODING] === 'buffer')
      this[ENCODING] = null
    this[ASYNC] = options && !!options.async || false
    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
    this[EOF] = false
    this[EMITTED_END] = false
    this[EMITTING_END] = false
    this[CLOSED] = false
    this[EMITTED_ERROR] = null
    this.writable = true
    this.readable = true
    this[BUFFERLENGTH] = 0
    this[DESTROYED] = false
  }

  get bufferLength () { return this[BUFFERLENGTH] }

  get encoding () { return this[ENCODING] }
  set encoding (enc) {
    if (this[OBJECTMODE])
      throw new Error('cannot set encoding in objectMode')

    if (this[ENCODING] && enc !== this[ENCODING] &&
        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
      throw new Error('cannot change encoding')

    if (this[ENCODING] !== enc) {
      this[DECODER] = enc ? new SD(enc) : null
      if (this.buffer.length)
        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
    }

    this[ENCODING] = enc
  }

  setEncoding (enc) {
    this.encoding = enc
  }

  get objectMode () { return this[OBJECTMODE] }
  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }

  get ['async'] () { return this[ASYNC] }
  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }

  write (chunk, encoding, cb) {
    if (this[EOF])
      throw new Error('write after end')

    if (this[DESTROYED]) {
      this.emit('error', Object.assign(
        new Error('Cannot call write after a stream was destroyed'),
        { code: 'ERR_STREAM_DESTROYED' }
      ))
      return true
    }

    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'

    if (!encoding)
      encoding = 'utf8'

    const fn = this[ASYNC] ? defer : f => f()

    // convert array buffers and typed array views into buffers
    // at some point in the future, we may want to do the opposite!
    // leave strings and buffers as-is
    // anything else switches us into object mode
    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
      if (isArrayBufferView(chunk))
        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
      else if (isArrayBuffer(chunk))
        chunk = Buffer.from(chunk)
      else if (typeof chunk !== 'string')
        // use the setter so we throw if we have encoding set
        this.objectMode = true
    }

    // handle object mode up front, since it's simpler
    // this yields better performance, fewer checks later.
    if (this[OBJECTMODE]) {
      /* istanbul ignore if - maybe impossible? */
      if (this.flowing && this[BUFFERLENGTH] !== 0)
        this[FLUSH](true)

      if (this.flowing)
        this.emit('data', chunk)
      else
        this[BUFFERPUSH](chunk)

      if (this[BUFFERLENGTH] !== 0)
        this.emit('readable')

      if (cb)
        fn(cb)

      return this.flowing
    }

    // at this point the chunk is a buffer or string
    // don't buffer it up or send it to the decoder
    if (!chunk.length) {
      if (this[BUFFERLENGTH] !== 0)
        this.emit('readable')
      if (cb)
        fn(cb)
      return this.flowing
    }

    // fast-path writing strings of same encoding to a stream with
    // an empty buffer, skipping the buffer/decoder dance
    if (typeof chunk === 'string' &&
        // unless it is a string already ready for us to use
        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
      chunk = Buffer.from(chunk, encoding)
    }

    if (Buffer.isBuffer(chunk) && this[ENCODING])
      chunk = this[DECODER].write(chunk)

    // Note: flushing CAN potentially switch us into not-flowing mode
    if (this.flowing && this[BUFFERLENGTH] !== 0)
      this[FLUSH](true)

    if (this.flowing)
      this.emit('data', chunk)
    else
      this[BUFFERPUSH](chunk)

    if (this[BUFFERLENGTH] !== 0)
      this.emit('readable')

    if (cb)
      fn(cb)

    return this.flowing
  }

  read (n) {
    if (this[DESTROYED])
      return null

    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
      this[MAYBE_EMIT_END]()
      return null
    }

    if (this[OBJECTMODE])
      n = null

    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
      if (this.encoding)
        this.buffer = [this.buffer.join('')]
      else
        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
    }

    const ret = this[READ](n || null, this.buffer[0])
    this[MAYBE_EMIT_END]()
    return ret
  }

  [READ] (n, chunk) {
    if (n === chunk.length || n === null)
      this[BUFFERSHIFT]()
    else {
      this.buffer[0] = chunk.slice(n)
      chunk = chunk.slice(0, n)
      this[BUFFERLENGTH] -= n
    }

    this.emit('data', chunk)

    if (!this.buffer.length && !this[EOF])
      this.emit('drain')

    return chunk
  }

  end (chunk, encoding, cb) {
    if (typeof chunk === 'function')
      cb = chunk, chunk = null
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'
    if (chunk)
      this.write(chunk, encoding)
    if (cb)
      this.once('end', cb)
    this[EOF] = true
    this.writable = false

    // if we haven't written anything, then go ahead and emit,
    // even if we're not reading.
    // we'll re-emit if a new 'end' listener is added anyway.
    // This makes MP more suitable to write-only use cases.
    if (this.flowing || !this[PAUSED])
      this[MAYBE_EMIT_END]()
    return this
  }

  // don't let the internal resume be overwritten
  [RESUME] () {
    if (this[DESTROYED])
      return

    this[PAUSED] = false
    this[FLOWING] = true
    this.emit('resume')
    if (this.buffer.length)
      this[FLUSH]()
    else if (this[EOF])
      this[MAYBE_EMIT_END]()
    else
      this.emit('drain')
  }

  resume () {
    return this[RESUME]()
  }

  pause () {
    this[FLOWING] = false
    this[PAUSED] = true
  }

  get destroyed () {
    return this[DESTROYED]
  }

  get flowing () {
    return this[FLOWING]
  }

  get paused () {
    return this[PAUSED]
  }

  [BUFFERPUSH] (chunk) {
    if (this[OBJECTMODE])
      this[BUFFERLENGTH] += 1
    else
      this[BUFFERLENGTH] += chunk.length
    this.buffer.push(chunk)
  }

  [BUFFERSHIFT] () {
    if (this.buffer.length) {
      if (this[OBJECTMODE])
        this[BUFFERLENGTH] -= 1
      else
        this[BUFFERLENGTH] -= this.buffer[0].length
    }
    return this.buffer.shift()
  }

  [FLUSH] (noDrain) {
    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))

    if (!noDrain && !this.buffer.length && !this[EOF])
      this.emit('drain')
  }

  [FLUSHCHUNK] (chunk) {
    return chunk ? (this.emit('data', chunk), this.flowing) : false
  }

  pipe (dest, opts) {
    if (this[DESTROYED])
      return

    const ended = this[EMITTED_END]
    opts = opts || {}
    if (dest === proc.stdout || dest === proc.stderr)
      opts.end = false
    else
      opts.end = opts.end !== false
    opts.proxyErrors = !!opts.proxyErrors

    // piping an ended stream ends immediately
    if (ended) {
      if (opts.end)
        dest.end()
    } else {
      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
        : new PipeProxyErrors(this, dest, opts))
      if (this[ASYNC])
        defer(() => this[RESUME]())
      else
        this[RESUME]()
    }

    return dest
  }

  unpipe (dest) {
    const p = this.pipes.find(p => p.dest === dest)
    if (p) {
      this.pipes.splice(this.pipes.indexOf(p), 1)
      p.unpipe()
    }
  }

  addListener (ev, fn) {
    return this.on(ev, fn)
  }

  on (ev, fn) {
    const ret = super.on(ev, fn)
    if (ev === 'data' && !this.pipes.length && !this.flowing)
      this[RESUME]()
    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
      super.emit('readable')
    else if (isEndish(ev) && this[EMITTED_END]) {
      super.emit(ev)
      this.removeAllListeners(ev)
    } else if (ev === 'error' && this[EMITTED_ERROR]) {
      if (this[ASYNC])
        defer(() => fn.call(this, this[EMITTED_ERROR]))
      else
        fn.call(this, this[EMITTED_ERROR])
    }
    return ret
  }

  get emittedEnd () {
    return this[EMITTED_END]
  }

  [MAYBE_EMIT_END] () {
    if (!this[EMITTING_END] &&
        !this[EMITTED_END] &&
        !this[DESTROYED] &&
        this.buffer.length === 0 &&
        this[EOF]) {
      this[EMITTING_END] = true
      this.emit('end')
      this.emit('prefinish')
      this.emit('finish')
      if (this[CLOSED])
        this.emit('close')
      this[EMITTING_END] = false
    }
  }

  emit (ev, data, ...extra) {
    // error and close are only events allowed after calling destroy()
    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
      return
    else if (ev === 'data') {
      return !data ? false
        : this[ASYNC] ? defer(() => this[EMITDATA](data))
        : this[EMITDATA](data)
    } else if (ev === 'end') {
      return this[EMITEND]()
    } else if (ev === 'close') {
      this[CLOSED] = true
      // don't emit close before 'end' and 'finish'
      if (!this[EMITTED_END] && !this[DESTROYED])
        return
      const ret = super.emit('close')
      this.removeAllListeners('close')
      return ret
    } else if (ev === 'error') {
      this[EMITTED_ERROR] = data
      const ret = super.emit('error', data)
      this[MAYBE_EMIT_END]()
      return ret
    } else if (ev === 'resume') {
      const ret = super.emit('resume')
      this[MAYBE_EMIT_END]()
      return ret
    } else if (ev === 'finish' || ev === 'prefinish') {
      const ret = super.emit(ev)
      this.removeAllListeners(ev)
      return ret
    }

    // Some other unknown event
    const ret = super.emit(ev, data, ...extra)
    this[MAYBE_EMIT_END]()
    return ret
  }

  [EMITDATA] (data) {
    for (const p of this.pipes) {
      if (p.dest.write(data) === false)
        this.pause()
    }
    const ret = super.emit('data', data)
    this[MAYBE_EMIT_END]()
    return ret
  }

  [EMITEND] () {
    if (this[EMITTED_END])
      return

    this[EMITTED_END] = true
    this.readable = false
    if (this[ASYNC])
      defer(() => this[EMITEND2]())
    else
      this[EMITEND2]()
  }

  [EMITEND2] () {
    if (this[DECODER]) {
      const data = this[DECODER].end()
      if (data) {
        for (const p of this.pipes) {
          p.dest.write(data)
        }
        super.emit('data', data)
      }
    }

    for (const p of this.pipes) {
      p.end()
    }
    const ret = super.emit('end')
    this.removeAllListeners('end')
    return ret
  }

  // const all = await stream.collect()
  collect () {
    const buf = []
    if (!this[OBJECTMODE])
      buf.dataLength = 0
    // set the promise first, in case an error is raised
    // by triggering the flow here.
    const p = this.promise()
    this.on('data', c => {
      buf.push(c)
      if (!this[OBJECTMODE])
        buf.dataLength += c.length
    })
    return p.then(() => buf)
  }

  // const data = await stream.concat()
  concat () {
    return this[OBJECTMODE]
      ? Promise.reject(new Error('cannot concat in objectMode'))
      : this.collect().then(buf =>
          this[OBJECTMODE]
            ? Promise.reject(new Error('cannot concat in objectMode'))
            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
  }

  // stream.promise().then(() => done, er => emitted error)
  promise () {
    return new Promise((resolve, reject) => {
      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
      this.on('error', er => reject(er))
      this.on('end', () => resolve())
    })
  }

  // for await (let chunk of stream)
  [ASYNCITERATOR] () {
    const next = () => {
      const res = this.read()
      if (res !== null)
        return Promise.resolve({ done: false, value: res })

      if (this[EOF])
        return Promise.resolve({ done: true })

      let resolve = null
      let reject = null
      const onerr = er => {
        this.removeListener('data', ondata)
        this.removeListener('end', onend)
        reject(er)
      }
      const ondata = value => {
        this.removeListener('error', onerr)
        this.removeListener('end', onend)
        this.pause()
        resolve({ value: value, done: !!this[EOF] })
      }
      const onend = () => {
        this.removeListener('error', onerr)
        this.removeListener('data', ondata)
        resolve({ done: true })
      }
      const ondestroy = () => onerr(new Error('stream destroyed'))
      return new Promise((res, rej) => {
        reject = rej
        resolve = res
        this.once(DESTROYED, ondestroy)
        this.once('error', onerr)
        this.once('end', onend)
        this.once('data', ondata)
      })
    }

    return { next }
  }

  // for (let chunk of stream)
  [ITERATOR] () {
    const next = () => {
      const value = this.read()
      const done = value === null
      return { value, done }
    }
    return { next }
  }

  destroy (er) {
    if (this[DESTROYED]) {
      if (er)
        this.emit('error', er)
      else
        this.emit(DESTROYED)
      return this
    }

    this[DESTROYED] = true

    // throw away all buffered data, it's never coming out
    this.buffer.length = 0
    this[BUFFERLENGTH] = 0

    if (typeof this.close === 'function' && !this[CLOSED])
      this.close()

    if (er)
      this.emit('error', er)
    else // if no error to emit, still reject pending promises
      this.emit(DESTROYED)

    return this
  }

  static isStream (s) {
    return !!s && (s instanceof Minipass || s instanceof Stream ||
      s instanceof EE && (
        typeof s.pipe === 'function' || // readable
        (typeof s.write === 'function' && typeof s.end === 'function') // writable
      ))
  }
}
{
  "name": "minipass",
  "version": "3.3.6",
  "description": "minimal implementation of a PassThrough stream",
  "main": "index.js",
  "types": "index.d.ts",
  "dependencies": {
    "yallist": "^4.0.0"
  },
  "devDependencies": {
    "@types/node": "^17.0.41",
    "end-of-stream": "^1.4.0",
    "prettier": "^2.6.2",
    "tap": "^16.2.0",
    "through2": "^2.0.3",
    "ts-node": "^10.8.1",
    "typescript": "^4.7.3"
  },
  "scripts": {
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --follow-tags"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minipass.git"
  },
  "keywords": [
    "passthrough",
    "stream"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "ISC",
  "files": [
    "index.d.ts",
    "index.js"
  ],
  "tap": {
    "check-coverage": true
  },
  "engines": {
    "node": ">=8"
  },
  "prettier": {
    "semi": false,
    "printWidth": 80,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  }
}
{
  "name": "minipass-flush",
  "version": "1.0.5",
  "description": "A Minipass stream that calls a flush function before emitting 'end'",
  "author": "Isaac Z. Schlueter  (https://izs.me)",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --follow-tags"
  },
  "tap": {
    "check-coverage": true
  },
  "devDependencies": {
    "tap": "^14.6.9"
  },
  "dependencies": {
    "minipass": "^3.0.0"
  },
  "files": [
    "index.js"
  ],
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minipass-flush.git"
  },
  "keywords": [
    "minipass",
    "flush",
    "stream"
  ],
  "engines": {
    "node": ">= 8"
  }
}
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const Minipass = require('minipass')
const EE = require('events')
const isStream = s => s && s instanceof EE && (
  typeof s.pipe === 'function' || // readable
  (typeof s.write === 'function' && typeof s.end === 'function') // writable
)

const _head = Symbol('_head')
const _tail = Symbol('_tail')
const _linkStreams = Symbol('_linkStreams')
const _setHead = Symbol('_setHead')
const _setTail = Symbol('_setTail')
const _onError = Symbol('_onError')
const _onData = Symbol('_onData')
const _onEnd = Symbol('_onEnd')
const _onDrain = Symbol('_onDrain')
const _streams = Symbol('_streams')
class Pipeline extends Minipass {
  constructor (opts, ...streams) {
    if (isStream(opts)) {
      streams.unshift(opts)
      opts = {}
    }

    super(opts)
    this[_streams] = []
    if (streams.length)
      this.push(...streams)
  }

  [_linkStreams] (streams) {
    // reduce takes (left,right), and we return right to make it the
    // new left value.
    return streams.reduce((src, dest) => {
      src.on('error', er => dest.emit('error', er))
      src.pipe(dest)
      return dest
    })
  }

  push (...streams) {
    this[_streams].push(...streams)
    if (this[_tail])
      streams.unshift(this[_tail])

    const linkRet = this[_linkStreams](streams)

    this[_setTail](linkRet)
    if (!this[_head])
      this[_setHead](streams[0])
  }

  unshift (...streams) {
    this[_streams].unshift(...streams)
    if (this[_head])
      streams.push(this[_head])

    const linkRet = this[_linkStreams](streams)
    this[_setHead](streams[0])
    if (!this[_tail])
      this[_setTail](linkRet)
  }

  destroy (er) {
    // set fire to the whole thing.
    this[_streams].forEach(s =>
      typeof s.destroy === 'function' && s.destroy())
    return super.destroy(er)
  }

  // readable interface -> tail
  [_setTail] (stream) {
    this[_tail] = stream
    stream.on('error', er => this[_onError](stream, er))
    stream.on('data', chunk => this[_onData](stream, chunk))
    stream.on('end', () => this[_onEnd](stream))
    stream.on('finish', () => this[_onEnd](stream))
  }

  // errors proxied down the pipeline
  // they're considered part of the "read" interface
  [_onError] (stream, er) {
    if (stream === this[_tail])
      this.emit('error', er)
  }
  [_onData] (stream, chunk) {
    if (stream === this[_tail])
      super.write(chunk)
  }
  [_onEnd] (stream) {
    if (stream === this[_tail])
      super.end()
  }
  pause () {
    super.pause()
    return this[_tail] && this[_tail].pause && this[_tail].pause()
  }

  // NB: Minipass calls its internal private [RESUME] method during
  // pipe drains, to avoid hazards where stream.resume() is overridden.
  // Thus, we need to listen to the resume *event*, not override the
  // resume() method, and proxy *that* to the tail.
  emit (ev, ...args) {
    if (ev === 'resume' && this[_tail] && this[_tail].resume)
      this[_tail].resume()
    return super.emit(ev, ...args)
  }

  // writable interface -> head
  [_setHead] (stream) {
    this[_head] = stream
    stream.on('drain', () => this[_onDrain](stream))
  }
  [_onDrain] (stream) {
    if (stream === this[_head])
      this.emit('drain')
  }
  write (chunk, enc, cb) {
    return this[_head].write(chunk, enc, cb) &&
      (this.flowing || this.buffer.length === 0)
  }
  end (chunk, enc, cb) {
    this[_head].end(chunk, enc, cb)
    return this
  }
}

module.exports = Pipeline
The ISC License

Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'
const proc = typeof process === 'object' && process ? process : {
  stdout: null,
  stderr: null,
}
const EE = require('events')
const Stream = require('stream')
const SD = require('string_decoder').StringDecoder

const EOF = Symbol('EOF')
const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
const EMITTED_END = Symbol('emittedEnd')
const EMITTING_END = Symbol('emittingEnd')
const EMITTED_ERROR = Symbol('emittedError')
const CLOSED = Symbol('closed')
const READ = Symbol('read')
const FLUSH = Symbol('flush')
const FLUSHCHUNK = Symbol('flushChunk')
const ENCODING = Symbol('encoding')
const DECODER = Symbol('decoder')
const FLOWING = Symbol('flowing')
const PAUSED = Symbol('paused')
const RESUME = Symbol('resume')
const BUFFERLENGTH = Symbol('bufferLength')
const BUFFERPUSH = Symbol('bufferPush')
const BUFFERSHIFT = Symbol('bufferShift')
const OBJECTMODE = Symbol('objectMode')
const DESTROYED = Symbol('destroyed')
const EMITDATA = Symbol('emitData')
const EMITEND = Symbol('emitEnd')
const EMITEND2 = Symbol('emitEnd2')
const ASYNC = Symbol('async')

const defer = fn => Promise.resolve().then(fn)

// TODO remove when Node v8 support drops
const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
const ASYNCITERATOR = doIter && Symbol.asyncIterator
  || Symbol('asyncIterator not implemented')
const ITERATOR = doIter && Symbol.iterator
  || Symbol('iterator not implemented')

// events that mean 'the stream is over'
// these are treated specially, and re-emitted
// if they are listened for after emitting.
const isEndish = ev =>
  ev === 'end' ||
  ev === 'finish' ||
  ev === 'prefinish'

const isArrayBuffer = b => b instanceof ArrayBuffer ||
  typeof b === 'object' &&
  b.constructor &&
  b.constructor.name === 'ArrayBuffer' &&
  b.byteLength >= 0

const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)

class Pipe {
  constructor (src, dest, opts) {
    this.src = src
    this.dest = dest
    this.opts = opts
    this.ondrain = () => src[RESUME]()
    dest.on('drain', this.ondrain)
  }
  unpipe () {
    this.dest.removeListener('drain', this.ondrain)
  }
  // istanbul ignore next - only here for the prototype
  proxyErrors () {}
  end () {
    this.unpipe()
    if (this.opts.end)
      this.dest.end()
  }
}

class PipeProxyErrors extends Pipe {
  unpipe () {
    this.src.removeListener('error', this.proxyErrors)
    super.unpipe()
  }
  constructor (src, dest, opts) {
    super(src, dest, opts)
    this.proxyErrors = er => dest.emit('error', er)
    src.on('error', this.proxyErrors)
  }
}

module.exports = class Minipass extends Stream {
  constructor (options) {
    super()
    this[FLOWING] = false
    // whether we're explicitly paused
    this[PAUSED] = false
    this.pipes = []
    this.buffer = []
    this[OBJECTMODE] = options && options.objectMode || false
    if (this[OBJECTMODE])
      this[ENCODING] = null
    else
      this[ENCODING] = options && options.encoding || null
    if (this[ENCODING] === 'buffer')
      this[ENCODING] = null
    this[ASYNC] = options && !!options.async || false
    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
    this[EOF] = false
    this[EMITTED_END] = false
    this[EMITTING_END] = false
    this[CLOSED] = false
    this[EMITTED_ERROR] = null
    this.writable = true
    this.readable = true
    this[BUFFERLENGTH] = 0
    this[DESTROYED] = false
  }

  get bufferLength () { return this[BUFFERLENGTH] }

  get encoding () { return this[ENCODING] }
  set encoding (enc) {
    if (this[OBJECTMODE])
      throw new Error('cannot set encoding in objectMode')

    if (this[ENCODING] && enc !== this[ENCODING] &&
        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
      throw new Error('cannot change encoding')

    if (this[ENCODING] !== enc) {
      this[DECODER] = enc ? new SD(enc) : null
      if (this.buffer.length)
        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
    }

    this[ENCODING] = enc
  }

  setEncoding (enc) {
    this.encoding = enc
  }

  get objectMode () { return this[OBJECTMODE] }
  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }

  get ['async'] () { return this[ASYNC] }
  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }

  write (chunk, encoding, cb) {
    if (this[EOF])
      throw new Error('write after end')

    if (this[DESTROYED]) {
      this.emit('error', Object.assign(
        new Error('Cannot call write after a stream was destroyed'),
        { code: 'ERR_STREAM_DESTROYED' }
      ))
      return true
    }

    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'

    if (!encoding)
      encoding = 'utf8'

    const fn = this[ASYNC] ? defer : f => f()

    // convert array buffers and typed array views into buffers
    // at some point in the future, we may want to do the opposite!
    // leave strings and buffers as-is
    // anything else switches us into object mode
    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
      if (isArrayBufferView(chunk))
        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
      else if (isArrayBuffer(chunk))
        chunk = Buffer.from(chunk)
      else if (typeof chunk !== 'string')
        // use the setter so we throw if we have encoding set
        this.objectMode = true
    }

    // handle object mode up front, since it's simpler
    // this yields better performance, fewer checks later.
    if (this[OBJECTMODE]) {
      /* istanbul ignore if - maybe impossible? */
      if (this.flowing && this[BUFFERLENGTH] !== 0)
        this[FLUSH](true)

      if (this.flowing)
        this.emit('data', chunk)
      else
        this[BUFFERPUSH](chunk)

      if (this[BUFFERLENGTH] !== 0)
        this.emit('readable')

      if (cb)
        fn(cb)

      return this.flowing
    }

    // at this point the chunk is a buffer or string
    // don't buffer it up or send it to the decoder
    if (!chunk.length) {
      if (this[BUFFERLENGTH] !== 0)
        this.emit('readable')
      if (cb)
        fn(cb)
      return this.flowing
    }

    // fast-path writing strings of same encoding to a stream with
    // an empty buffer, skipping the buffer/decoder dance
    if (typeof chunk === 'string' &&
        // unless it is a string already ready for us to use
        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
      chunk = Buffer.from(chunk, encoding)
    }

    if (Buffer.isBuffer(chunk) && this[ENCODING])
      chunk = this[DECODER].write(chunk)

    // Note: flushing CAN potentially switch us into not-flowing mode
    if (this.flowing && this[BUFFERLENGTH] !== 0)
      this[FLUSH](true)

    if (this.flowing)
      this.emit('data', chunk)
    else
      this[BUFFERPUSH](chunk)

    if (this[BUFFERLENGTH] !== 0)
      this.emit('readable')

    if (cb)
      fn(cb)

    return this.flowing
  }

  read (n) {
    if (this[DESTROYED])
      return null

    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
      this[MAYBE_EMIT_END]()
      return null
    }

    if (this[OBJECTMODE])
      n = null

    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
      if (this.encoding)
        this.buffer = [this.buffer.join('')]
      else
        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
    }

    const ret = this[READ](n || null, this.buffer[0])
    this[MAYBE_EMIT_END]()
    return ret
  }

  [READ] (n, chunk) {
    if (n === chunk.length || n === null)
      this[BUFFERSHIFT]()
    else {
      this.buffer[0] = chunk.slice(n)
      chunk = chunk.slice(0, n)
      this[BUFFERLENGTH] -= n
    }

    this.emit('data', chunk)

    if (!this.buffer.length && !this[EOF])
      this.emit('drain')

    return chunk
  }

  end (chunk, encoding, cb) {
    if (typeof chunk === 'function')
      cb = chunk, chunk = null
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'
    if (chunk)
      this.write(chunk, encoding)
    if (cb)
      this.once('end', cb)
    this[EOF] = true
    this.writable = false

    // if we haven't written anything, then go ahead and emit,
    // even if we're not reading.
    // we'll re-emit if a new 'end' listener is added anyway.
    // This makes MP more suitable to write-only use cases.
    if (this.flowing || !this[PAUSED])
      this[MAYBE_EMIT_END]()
    return this
  }

  // don't let the internal resume be overwritten
  [RESUME] () {
    if (this[DESTROYED])
      return

    this[PAUSED] = false
    this[FLOWING] = true
    this.emit('resume')
    if (this.buffer.length)
      this[FLUSH]()
    else if (this[EOF])
      this[MAYBE_EMIT_END]()
    else
      this.emit('drain')
  }

  resume () {
    return this[RESUME]()
  }

  pause () {
    this[FLOWING] = false
    this[PAUSED] = true
  }

  get destroyed () {
    return this[DESTROYED]
  }

  get flowing () {
    return this[FLOWING]
  }

  get paused () {
    return this[PAUSED]
  }

  [BUFFERPUSH] (chunk) {
    if (this[OBJECTMODE])
      this[BUFFERLENGTH] += 1
    else
      this[BUFFERLENGTH] += chunk.length
    this.buffer.push(chunk)
  }

  [BUFFERSHIFT] () {
    if (this.buffer.length) {
      if (this[OBJECTMODE])
        this[BUFFERLENGTH] -= 1
      else
        this[BUFFERLENGTH] -= this.buffer[0].length
    }
    return this.buffer.shift()
  }

  [FLUSH] (noDrain) {
    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))

    if (!noDrain && !this.buffer.length && !this[EOF])
      this.emit('drain')
  }

  [FLUSHCHUNK] (chunk) {
    return chunk ? (this.emit('data', chunk), this.flowing) : false
  }

  pipe (dest, opts) {
    if (this[DESTROYED])
      return

    const ended = this[EMITTED_END]
    opts = opts || {}
    if (dest === proc.stdout || dest === proc.stderr)
      opts.end = false
    else
      opts.end = opts.end !== false
    opts.proxyErrors = !!opts.proxyErrors

    // piping an ended stream ends immediately
    if (ended) {
      if (opts.end)
        dest.end()
    } else {
      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
        : new PipeProxyErrors(this, dest, opts))
      if (this[ASYNC])
        defer(() => this[RESUME]())
      else
        this[RESUME]()
    }

    return dest
  }

  unpipe (dest) {
    const p = this.pipes.find(p => p.dest === dest)
    if (p) {
      this.pipes.splice(this.pipes.indexOf(p), 1)
      p.unpipe()
    }
  }

  addListener (ev, fn) {
    return this.on(ev, fn)
  }

  on (ev, fn) {
    const ret = super.on(ev, fn)
    if (ev === 'data' && !this.pipes.length && !this.flowing)
      this[RESUME]()
    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
      super.emit('readable')
    else if (isEndish(ev) && this[EMITTED_END]) {
      super.emit(ev)
      this.removeAllListeners(ev)
    } else if (ev === 'error' && this[EMITTED_ERROR]) {
      if (this[ASYNC])
        defer(() => fn.call(this, this[EMITTED_ERROR]))
      else
        fn.call(this, this[EMITTED_ERROR])
    }
    return ret
  }

  get emittedEnd () {
    return this[EMITTED_END]
  }

  [MAYBE_EMIT_END] () {
    if (!this[EMITTING_END] &&
        !this[EMITTED_END] &&
        !this[DESTROYED] &&
        this.buffer.length === 0 &&
        this[EOF]) {
      this[EMITTING_END] = true
      this.emit('end')
      this.emit('prefinish')
      this.emit('finish')
      if (this[CLOSED])
        this.emit('close')
      this[EMITTING_END] = false
    }
  }

  emit (ev, data, ...extra) {
    // error and close are only events allowed after calling destroy()
    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
      return
    else if (ev === 'data') {
      return !data ? false
        : this[ASYNC] ? defer(() => this[EMITDATA](data))
        : this[EMITDATA](data)
    } else if (ev === 'end') {
      return this[EMITEND]()
    } else if (ev === 'close') {
      this[CLOSED] = true
      // don't emit close before 'end' and 'finish'
      if (!this[EMITTED_END] && !this[DESTROYED])
        return
      const ret = super.emit('close')
      this.removeAllListeners('close')
      return ret
    } else if (ev === 'error') {
      this[EMITTED_ERROR] = data
      const ret = super.emit('error', data)
      this[MAYBE_EMIT_END]()
      return ret
    } else if (ev === 'resume') {
      const ret = super.emit('resume')
      this[MAYBE_EMIT_END]()
      return ret
    } else if (ev === 'finish' || ev === 'prefinish') {
      const ret = super.emit(ev)
      this.removeAllListeners(ev)
      return ret
    }

    // Some other unknown event
    const ret = super.emit(ev, data, ...extra)
    this[MAYBE_EMIT_END]()
    return ret
  }

  [EMITDATA] (data) {
    for (const p of this.pipes) {
      if (p.dest.write(data) === false)
        this.pause()
    }
    const ret = super.emit('data', data)
    this[MAYBE_EMIT_END]()
    return ret
  }

  [EMITEND] () {
    if (this[EMITTED_END])
      return

    this[EMITTED_END] = true
    this.readable = false
    if (this[ASYNC])
      defer(() => this[EMITEND2]())
    else
      this[EMITEND2]()
  }

  [EMITEND2] () {
    if (this[DECODER]) {
      const data = this[DECODER].end()
      if (data) {
        for (const p of this.pipes) {
          p.dest.write(data)
        }
        super.emit('data', data)
      }
    }

    for (const p of this.pipes) {
      p.end()
    }
    const ret = super.emit('end')
    this.removeAllListeners('end')
    return ret
  }

  // const all = await stream.collect()
  collect () {
    const buf = []
    if (!this[OBJECTMODE])
      buf.dataLength = 0
    // set the promise first, in case an error is raised
    // by triggering the flow here.
    const p = this.promise()
    this.on('data', c => {
      buf.push(c)
      if (!this[OBJECTMODE])
        buf.dataLength += c.length
    })
    return p.then(() => buf)
  }

  // const data = await stream.concat()
  concat () {
    return this[OBJECTMODE]
      ? Promise.reject(new Error('cannot concat in objectMode'))
      : this.collect().then(buf =>
          this[OBJECTMODE]
            ? Promise.reject(new Error('cannot concat in objectMode'))
            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
  }

  // stream.promise().then(() => done, er => emitted error)
  promise () {
    return new Promise((resolve, reject) => {
      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
      this.on('error', er => reject(er))
      this.on('end', () => resolve())
    })
  }

  // for await (let chunk of stream)
  [ASYNCITERATOR] () {
    const next = () => {
      const res = this.read()
      if (res !== null)
        return Promise.resolve({ done: false, value: res })

      if (this[EOF])
        return Promise.resolve({ done: true })

      let resolve = null
      let reject = null
      const onerr = er => {
        this.removeListener('data', ondata)
        this.removeListener('end', onend)
        reject(er)
      }
      const ondata = value => {
        this.removeListener('error', onerr)
        this.removeListener('end', onend)
        this.pause()
        resolve({ value: value, done: !!this[EOF] })
      }
      const onend = () => {
        this.removeListener('error', onerr)
        this.removeListener('data', ondata)
        resolve({ done: true })
      }
      const ondestroy = () => onerr(new Error('stream destroyed'))
      return new Promise((res, rej) => {
        reject = rej
        resolve = res
        this.once(DESTROYED, ondestroy)
        this.once('error', onerr)
        this.once('end', onend)
        this.once('data', ondata)
      })
    }

    return { next }
  }

  // for (let chunk of stream)
  [ITERATOR] () {
    const next = () => {
      const value = this.read()
      const done = value === null
      return { value, done }
    }
    return { next }
  }

  destroy (er) {
    if (this[DESTROYED]) {
      if (er)
        this.emit('error', er)
      else
        this.emit(DESTROYED)
      return this
    }

    this[DESTROYED] = true

    // throw away all buffered data, it's never coming out
    this.buffer.length = 0
    this[BUFFERLENGTH] = 0

    if (typeof this.close === 'function' && !this[CLOSED])
      this.close()

    if (er)
      this.emit('error', er)
    else // if no error to emit, still reject pending promises
      this.emit(DESTROYED)

    return this
  }

  static isStream (s) {
    return !!s && (s instanceof Minipass || s instanceof Stream ||
      s instanceof EE && (
        typeof s.pipe === 'function' || // readable
        (typeof s.write === 'function' && typeof s.end === 'function') // writable
      ))
  }
}
{
  "name": "minipass",
  "version": "3.3.6",
  "description": "minimal implementation of a PassThrough stream",
  "main": "index.js",
  "types": "index.d.ts",
  "dependencies": {
    "yallist": "^4.0.0"
  },
  "devDependencies": {
    "@types/node": "^17.0.41",
    "end-of-stream": "^1.4.0",
    "prettier": "^2.6.2",
    "tap": "^16.2.0",
    "through2": "^2.0.3",
    "ts-node": "^10.8.1",
    "typescript": "^4.7.3"
  },
  "scripts": {
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --follow-tags"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minipass.git"
  },
  "keywords": [
    "passthrough",
    "stream"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "ISC",
  "files": [
    "index.d.ts",
    "index.js"
  ],
  "tap": {
    "check-coverage": true
  },
  "engines": {
    "node": ">=8"
  },
  "prettier": {
    "semi": false,
    "printWidth": 80,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  }
}
{
  "name": "minipass-pipeline",
  "version": "1.2.4",
  "description": "create a pipeline of streams using Minipass",
  "author": "Isaac Z. Schlueter  (https://izs.me)",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --follow-tags"
  },
  "tap": {
    "check-coverage": true
  },
  "devDependencies": {
    "tap": "^14.6.9"
  },
  "dependencies": {
    "minipass": "^3.0.0"
  },
  "files": [
    "index.js"
  ],
  "engines": {
    "node": ">=8"
  }
}
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const Minipass = require('minipass')

class SizeError extends Error {
  constructor (found, expect) {
    super(`Bad data size: expected ${expect} bytes, but got ${found}`)
    this.expect = expect
    this.found = found
    this.code = 'EBADSIZE'
	  Error.captureStackTrace(this, this.constructor)
  }
  get name () {
    return 'SizeError'
  }
}

class MinipassSized extends Minipass {
  constructor (options = {}) {
    super(options)

    if (options.objectMode)
      throw new TypeError(`${
        this.constructor.name
      } streams only work with string and buffer data`)

    this.found = 0
    this.expect = options.size
    if (typeof this.expect !== 'number' ||
        this.expect > Number.MAX_SAFE_INTEGER ||
        isNaN(this.expect) ||
        this.expect < 0 ||
        !isFinite(this.expect) ||
        this.expect !== Math.floor(this.expect))
      throw new Error('invalid expected size: ' + this.expect)
  }

  write (chunk, encoding, cb) {
    const buffer = Buffer.isBuffer(chunk) ? chunk
      : typeof chunk === 'string' ?
        Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8')
      : chunk

    if (!Buffer.isBuffer(buffer)) {
      this.emit('error', new TypeError(`${
        this.constructor.name
      } streams only work with string and buffer data`))
      return false
    }

    this.found += buffer.length
    if (this.found > this.expect)
      this.emit('error', new SizeError(this.found, this.expect))

    return super.write(chunk, encoding, cb)
  }

  emit (ev, ...data) {
    if (ev === 'end') {
      if (this.found !== this.expect)
        this.emit('error', new SizeError(this.found, this.expect))
    }
    return super.emit(ev, ...data)
  }
}

MinipassSized.SizeError = SizeError

module.exports = MinipassSized
The ISC License

Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'
const proc = typeof process === 'object' && process ? process : {
  stdout: null,
  stderr: null,
}
const EE = require('events')
const Stream = require('stream')
const SD = require('string_decoder').StringDecoder

const EOF = Symbol('EOF')
const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
const EMITTED_END = Symbol('emittedEnd')
const EMITTING_END = Symbol('emittingEnd')
const EMITTED_ERROR = Symbol('emittedError')
const CLOSED = Symbol('closed')
const READ = Symbol('read')
const FLUSH = Symbol('flush')
const FLUSHCHUNK = Symbol('flushChunk')
const ENCODING = Symbol('encoding')
const DECODER = Symbol('decoder')
const FLOWING = Symbol('flowing')
const PAUSED = Symbol('paused')
const RESUME = Symbol('resume')
const BUFFERLENGTH = Symbol('bufferLength')
const BUFFERPUSH = Symbol('bufferPush')
const BUFFERSHIFT = Symbol('bufferShift')
const OBJECTMODE = Symbol('objectMode')
const DESTROYED = Symbol('destroyed')
const EMITDATA = Symbol('emitData')
const EMITEND = Symbol('emitEnd')
const EMITEND2 = Symbol('emitEnd2')
const ASYNC = Symbol('async')

const defer = fn => Promise.resolve().then(fn)

// TODO remove when Node v8 support drops
const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
const ASYNCITERATOR = doIter && Symbol.asyncIterator
  || Symbol('asyncIterator not implemented')
const ITERATOR = doIter && Symbol.iterator
  || Symbol('iterator not implemented')

// events that mean 'the stream is over'
// these are treated specially, and re-emitted
// if they are listened for after emitting.
const isEndish = ev =>
  ev === 'end' ||
  ev === 'finish' ||
  ev === 'prefinish'

const isArrayBuffer = b => b instanceof ArrayBuffer ||
  typeof b === 'object' &&
  b.constructor &&
  b.constructor.name === 'ArrayBuffer' &&
  b.byteLength >= 0

const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)

class Pipe {
  constructor (src, dest, opts) {
    this.src = src
    this.dest = dest
    this.opts = opts
    this.ondrain = () => src[RESUME]()
    dest.on('drain', this.ondrain)
  }
  unpipe () {
    this.dest.removeListener('drain', this.ondrain)
  }
  // istanbul ignore next - only here for the prototype
  proxyErrors () {}
  end () {
    this.unpipe()
    if (this.opts.end)
      this.dest.end()
  }
}

class PipeProxyErrors extends Pipe {
  unpipe () {
    this.src.removeListener('error', this.proxyErrors)
    super.unpipe()
  }
  constructor (src, dest, opts) {
    super(src, dest, opts)
    this.proxyErrors = er => dest.emit('error', er)
    src.on('error', this.proxyErrors)
  }
}

module.exports = class Minipass extends Stream {
  constructor (options) {
    super()
    this[FLOWING] = false
    // whether we're explicitly paused
    this[PAUSED] = false
    this.pipes = []
    this.buffer = []
    this[OBJECTMODE] = options && options.objectMode || false
    if (this[OBJECTMODE])
      this[ENCODING] = null
    else
      this[ENCODING] = options && options.encoding || null
    if (this[ENCODING] === 'buffer')
      this[ENCODING] = null
    this[ASYNC] = options && !!options.async || false
    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
    this[EOF] = false
    this[EMITTED_END] = false
    this[EMITTING_END] = false
    this[CLOSED] = false
    this[EMITTED_ERROR] = null
    this.writable = true
    this.readable = true
    this[BUFFERLENGTH] = 0
    this[DESTROYED] = false
  }

  get bufferLength () { return this[BUFFERLENGTH] }

  get encoding () { return this[ENCODING] }
  set encoding (enc) {
    if (this[OBJECTMODE])
      throw new Error('cannot set encoding in objectMode')

    if (this[ENCODING] && enc !== this[ENCODING] &&
        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
      throw new Error('cannot change encoding')

    if (this[ENCODING] !== enc) {
      this[DECODER] = enc ? new SD(enc) : null
      if (this.buffer.length)
        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
    }

    this[ENCODING] = enc
  }

  setEncoding (enc) {
    this.encoding = enc
  }

  get objectMode () { return this[OBJECTMODE] }
  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }

  get ['async'] () { return this[ASYNC] }
  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }

  write (chunk, encoding, cb) {
    if (this[EOF])
      throw new Error('write after end')

    if (this[DESTROYED]) {
      this.emit('error', Object.assign(
        new Error('Cannot call write after a stream was destroyed'),
        { code: 'ERR_STREAM_DESTROYED' }
      ))
      return true
    }

    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'

    if (!encoding)
      encoding = 'utf8'

    const fn = this[ASYNC] ? defer : f => f()

    // convert array buffers and typed array views into buffers
    // at some point in the future, we may want to do the opposite!
    // leave strings and buffers as-is
    // anything else switches us into object mode
    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
      if (isArrayBufferView(chunk))
        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
      else if (isArrayBuffer(chunk))
        chunk = Buffer.from(chunk)
      else if (typeof chunk !== 'string')
        // use the setter so we throw if we have encoding set
        this.objectMode = true
    }

    // handle object mode up front, since it's simpler
    // this yields better performance, fewer checks later.
    if (this[OBJECTMODE]) {
      /* istanbul ignore if - maybe impossible? */
      if (this.flowing && this[BUFFERLENGTH] !== 0)
        this[FLUSH](true)

      if (this.flowing)
        this.emit('data', chunk)
      else
        this[BUFFERPUSH](chunk)

      if (this[BUFFERLENGTH] !== 0)
        this.emit('readable')

      if (cb)
        fn(cb)

      return this.flowing
    }

    // at this point the chunk is a buffer or string
    // don't buffer it up or send it to the decoder
    if (!chunk.length) {
      if (this[BUFFERLENGTH] !== 0)
        this.emit('readable')
      if (cb)
        fn(cb)
      return this.flowing
    }

    // fast-path writing strings of same encoding to a stream with
    // an empty buffer, skipping the buffer/decoder dance
    if (typeof chunk === 'string' &&
        // unless it is a string already ready for us to use
        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
      chunk = Buffer.from(chunk, encoding)
    }

    if (Buffer.isBuffer(chunk) && this[ENCODING])
      chunk = this[DECODER].write(chunk)

    // Note: flushing CAN potentially switch us into not-flowing mode
    if (this.flowing && this[BUFFERLENGTH] !== 0)
      this[FLUSH](true)

    if (this.flowing)
      this.emit('data', chunk)
    else
      this[BUFFERPUSH](chunk)

    if (this[BUFFERLENGTH] !== 0)
      this.emit('readable')

    if (cb)
      fn(cb)

    return this.flowing
  }

  read (n) {
    if (this[DESTROYED])
      return null

    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
      this[MAYBE_EMIT_END]()
      return null
    }

    if (this[OBJECTMODE])
      n = null

    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
      if (this.encoding)
        this.buffer = [this.buffer.join('')]
      else
        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
    }

    const ret = this[READ](n || null, this.buffer[0])
    this[MAYBE_EMIT_END]()
    return ret
  }

  [READ] (n, chunk) {
    if (n === chunk.length || n === null)
      this[BUFFERSHIFT]()
    else {
      this.buffer[0] = chunk.slice(n)
      chunk = chunk.slice(0, n)
      this[BUFFERLENGTH] -= n
    }

    this.emit('data', chunk)

    if (!this.buffer.length && !this[EOF])
      this.emit('drain')

    return chunk
  }

  end (chunk, encoding, cb) {
    if (typeof chunk === 'function')
      cb = chunk, chunk = null
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'
    if (chunk)
      this.write(chunk, encoding)
    if (cb)
      this.once('end', cb)
    this[EOF] = true
    this.writable = false

    // if we haven't written anything, then go ahead and emit,
    // even if we're not reading.
    // we'll re-emit if a new 'end' listener is added anyway.
    // This makes MP more suitable to write-only use cases.
    if (this.flowing || !this[PAUSED])
      this[MAYBE_EMIT_END]()
    return this
  }

  // don't let the internal resume be overwritten
  [RESUME] () {
    if (this[DESTROYED])
      return

    this[PAUSED] = false
    this[FLOWING] = true
    this.emit('resume')
    if (this.buffer.length)
      this[FLUSH]()
    else if (this[EOF])
      this[MAYBE_EMIT_END]()
    else
      this.emit('drain')
  }

  resume () {
    return this[RESUME]()
  }

  pause () {
    this[FLOWING] = false
    this[PAUSED] = true
  }

  get destroyed () {
    return this[DESTROYED]
  }

  get flowing () {
    return this[FLOWING]
  }

  get paused () {
    return this[PAUSED]
  }

  [BUFFERPUSH] (chunk) {
    if (this[OBJECTMODE])
      this[BUFFERLENGTH] += 1
    else
      this[BUFFERLENGTH] += chunk.length
    this.buffer.push(chunk)
  }

  [BUFFERSHIFT] () {
    if (this.buffer.length) {
      if (this[OBJECTMODE])
        this[BUFFERLENGTH] -= 1
      else
        this[BUFFERLENGTH] -= this.buffer[0].length
    }
    return this.buffer.shift()
  }

  [FLUSH] (noDrain) {
    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))

    if (!noDrain && !this.buffer.length && !this[EOF])
      this.emit('drain')
  }

  [FLUSHCHUNK] (chunk) {
    return chunk ? (this.emit('data', chunk), this.flowing) : false
  }

  pipe (dest, opts) {
    if (this[DESTROYED])
      return

    const ended = this[EMITTED_END]
    opts = opts || {}
    if (dest === proc.stdout || dest === proc.stderr)
      opts.end = false
    else
      opts.end = opts.end !== false
    opts.proxyErrors = !!opts.proxyErrors

    // piping an ended stream ends immediately
    if (ended) {
      if (opts.end)
        dest.end()
    } else {
      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
        : new PipeProxyErrors(this, dest, opts))
      if (this[ASYNC])
        defer(() => this[RESUME]())
      else
        this[RESUME]()
    }

    return dest
  }

  unpipe (dest) {
    const p = this.pipes.find(p => p.dest === dest)
    if (p) {
      this.pipes.splice(this.pipes.indexOf(p), 1)
      p.unpipe()
    }
  }

  addListener (ev, fn) {
    return this.on(ev, fn)
  }

  on (ev, fn) {
    const ret = super.on(ev, fn)
    if (ev === 'data' && !this.pipes.length && !this.flowing)
      this[RESUME]()
    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
      super.emit('readable')
    else if (isEndish(ev) && this[EMITTED_END]) {
      super.emit(ev)
      this.removeAllListeners(ev)
    } else if (ev === 'error' && this[EMITTED_ERROR]) {
      if (this[ASYNC])
        defer(() => fn.call(this, this[EMITTED_ERROR]))
      else
        fn.call(this, this[EMITTED_ERROR])
    }
    return ret
  }

  get emittedEnd () {
    return this[EMITTED_END]
  }

  [MAYBE_EMIT_END] () {
    if (!this[EMITTING_END] &&
        !this[EMITTED_END] &&
        !this[DESTROYED] &&
        this.buffer.length === 0 &&
        this[EOF]) {
      this[EMITTING_END] = true
      this.emit('end')
      this.emit('prefinish')
      this.emit('finish')
      if (this[CLOSED])
        this.emit('close')
      this[EMITTING_END] = false
    }
  }

  emit (ev, data, ...extra) {
    // error and close are only events allowed after calling destroy()
    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
      return
    else if (ev === 'data') {
      return !data ? false
        : this[ASYNC] ? defer(() => this[EMITDATA](data))
        : this[EMITDATA](data)
    } else if (ev === 'end') {
      return this[EMITEND]()
    } else if (ev === 'close') {
      this[CLOSED] = true
      // don't emit close before 'end' and 'finish'
      if (!this[EMITTED_END] && !this[DESTROYED])
        return
      const ret = super.emit('close')
      this.removeAllListeners('close')
      return ret
    } else if (ev === 'error') {
      this[EMITTED_ERROR] = data
      const ret = super.emit('error', data)
      this[MAYBE_EMIT_END]()
      return ret
    } else if (ev === 'resume') {
      const ret = super.emit('resume')
      this[MAYBE_EMIT_END]()
      return ret
    } else if (ev === 'finish' || ev === 'prefinish') {
      const ret = super.emit(ev)
      this.removeAllListeners(ev)
      return ret
    }

    // Some other unknown event
    const ret = super.emit(ev, data, ...extra)
    this[MAYBE_EMIT_END]()
    return ret
  }

  [EMITDATA] (data) {
    for (const p of this.pipes) {
      if (p.dest.write(data) === false)
        this.pause()
    }
    const ret = super.emit('data', data)
    this[MAYBE_EMIT_END]()
    return ret
  }

  [EMITEND] () {
    if (this[EMITTED_END])
      return

    this[EMITTED_END] = true
    this.readable = false
    if (this[ASYNC])
      defer(() => this[EMITEND2]())
    else
      this[EMITEND2]()
  }

  [EMITEND2] () {
    if (this[DECODER]) {
      const data = this[DECODER].end()
      if (data) {
        for (const p of this.pipes) {
          p.dest.write(data)
        }
        super.emit('data', data)
      }
    }

    for (const p of this.pipes) {
      p.end()
    }
    const ret = super.emit('end')
    this.removeAllListeners('end')
    return ret
  }

  // const all = await stream.collect()
  collect () {
    const buf = []
    if (!this[OBJECTMODE])
      buf.dataLength = 0
    // set the promise first, in case an error is raised
    // by triggering the flow here.
    const p = this.promise()
    this.on('data', c => {
      buf.push(c)
      if (!this[OBJECTMODE])
        buf.dataLength += c.length
    })
    return p.then(() => buf)
  }

  // const data = await stream.concat()
  concat () {
    return this[OBJECTMODE]
      ? Promise.reject(new Error('cannot concat in objectMode'))
      : this.collect().then(buf =>
          this[OBJECTMODE]
            ? Promise.reject(new Error('cannot concat in objectMode'))
            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
  }

  // stream.promise().then(() => done, er => emitted error)
  promise () {
    return new Promise((resolve, reject) => {
      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
      this.on('error', er => reject(er))
      this.on('end', () => resolve())
    })
  }

  // for await (let chunk of stream)
  [ASYNCITERATOR] () {
    const next = () => {
      const res = this.read()
      if (res !== null)
        return Promise.resolve({ done: false, value: res })

      if (this[EOF])
        return Promise.resolve({ done: true })

      let resolve = null
      let reject = null
      const onerr = er => {
        this.removeListener('data', ondata)
        this.removeListener('end', onend)
        reject(er)
      }
      const ondata = value => {
        this.removeListener('error', onerr)
        this.removeListener('end', onend)
        this.pause()
        resolve({ value: value, done: !!this[EOF] })
      }
      const onend = () => {
        this.removeListener('error', onerr)
        this.removeListener('data', ondata)
        resolve({ done: true })
      }
      const ondestroy = () => onerr(new Error('stream destroyed'))
      return new Promise((res, rej) => {
        reject = rej
        resolve = res
        this.once(DESTROYED, ondestroy)
        this.once('error', onerr)
        this.once('end', onend)
        this.once('data', ondata)
      })
    }

    return { next }
  }

  // for (let chunk of stream)
  [ITERATOR] () {
    const next = () => {
      const value = this.read()
      const done = value === null
      return { value, done }
    }
    return { next }
  }

  destroy (er) {
    if (this[DESTROYED]) {
      if (er)
        this.emit('error', er)
      else
        this.emit(DESTROYED)
      return this
    }

    this[DESTROYED] = true

    // throw away all buffered data, it's never coming out
    this.buffer.length = 0
    this[BUFFERLENGTH] = 0

    if (typeof this.close === 'function' && !this[CLOSED])
      this.close()

    if (er)
      this.emit('error', er)
    else // if no error to emit, still reject pending promises
      this.emit(DESTROYED)

    return this
  }

  static isStream (s) {
    return !!s && (s instanceof Minipass || s instanceof Stream ||
      s instanceof EE && (
        typeof s.pipe === 'function' || // readable
        (typeof s.write === 'function' && typeof s.end === 'function') // writable
      ))
  }
}
{
  "name": "minipass",
  "version": "3.3.6",
  "description": "minimal implementation of a PassThrough stream",
  "main": "index.js",
  "types": "index.d.ts",
  "dependencies": {
    "yallist": "^4.0.0"
  },
  "devDependencies": {
    "@types/node": "^17.0.41",
    "end-of-stream": "^1.4.0",
    "prettier": "^2.6.2",
    "tap": "^16.2.0",
    "through2": "^2.0.3",
    "ts-node": "^10.8.1",
    "typescript": "^4.7.3"
  },
  "scripts": {
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --follow-tags"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minipass.git"
  },
  "keywords": [
    "passthrough",
    "stream"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "ISC",
  "files": [
    "index.d.ts",
    "index.js"
  ],
  "tap": {
    "check-coverage": true
  },
  "engines": {
    "node": ">=8"
  },
  "prettier": {
    "semi": false,
    "printWidth": 80,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  }
}
{
  "name": "minipass-sized",
  "version": "1.0.3",
  "description": "A Minipass stream that raises an error if you get a different number of bytes than expected",
  "author": "Isaac Z. Schlueter  (https://izs.me)",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --follow-tags"
  },
  "tap": {
    "check-coverage": true
  },
  "devDependencies": {
    "tap": "^14.6.4"
  },
  "dependencies": {
    "minipass": "^3.0.0"
  },
  "main": "index.js",
  "keywords": [
    "minipass",
    "size",
    "length"
  ],
  "directories": {
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minipass-sized.git"
  },
  "engines": {
    "node": ">=8"
  }
}
const t = require('tap')
const MPS = require('../')

t.test('ok if size checks out', t => {
  const mps = new MPS({ size: 4 })

  mps.write(Buffer.from('a').toString('hex'), 'hex')
  mps.write(Buffer.from('sd'))
  mps.end('f')
  return mps.concat().then(data => t.equal(data.toString(), 'asdf'))
})

t.test('error if size exceeded', t => {
  const mps = new MPS({ size: 1 })
  mps.on('error', er => {
    t.match(er, {
      message: 'Bad data size: expected 1 bytes, but got 4',
      found: 4,
      expect: 1,
      code: 'EBADSIZE',
      name: 'SizeError',
    })
    t.end()
  })
  mps.write('asdf')
})

t.test('error if size is not met', t => {
  const mps = new MPS({ size: 999 })
  t.throws(() => mps.end(), {
    message: 'Bad data size: expected 999 bytes, but got 0',
    found: 0,
    name: 'SizeError',
    expect: 999,
    code: 'EBADSIZE',
  })
  t.end()
})

t.test('error if non-string/buffer is written', t => {
  const mps = new MPS({size:1})
  mps.on('error', er => {
    t.match(er, {
      message: 'MinipassSized streams only work with string and buffer data'
    })
    t.end()
  })
  mps.write({some:'object'})
})

t.test('projectiles', t => {
  t.throws(() => new MPS(), {
    message: 'invalid expected size: undefined'
  }, 'size is required')
  t.throws(() => new MPS({size: true}), {
    message: 'invalid expected size: true'
  }, 'size must be number')
  t.throws(() => new MPS({size: NaN}), {
    message: 'invalid expected size: NaN'
  }, 'size must not be NaN')
  t.throws(() => new MPS({size:1.2}), {
    message: 'invalid expected size: 1.2'
  }, 'size must be integer')
  t.throws(() => new MPS({size: Infinity}), {
    message: 'invalid expected size: Infinity'
  }, 'size must be finite')
  t.throws(() => new MPS({size: -1}), {
    message: 'invalid expected size: -1'
  }, 'size must be positive')
  t.throws(() => new MPS({objectMode: true}), {
    message: 'MinipassSized streams only work with string and buffer data'
  }, 'no objectMode')
  t.throws(() => new MPS({size: Number.MAX_SAFE_INTEGER + 1000000}), {
    message: 'invalid expected size: 9007199255740992'
  })
  t.end()
})

t.test('exports SizeError class', t => {
  t.isa(MPS.SizeError, 'function')
  t.isa(MPS.SizeError.prototype, Error)
  t.end()
})
The ISC License

Copyright (c) 2017-2023 npm, Inc., Isaac Z. Schlueter, and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Minipass = exports.isWritable = exports.isReadable = exports.isStream = void 0;
const proc = typeof process === 'object' && process
    ? process
    : {
        stdout: null,
        stderr: null,
    };
const node_events_1 = require("node:events");
const node_stream_1 = __importDefault(require("node:stream"));
const node_string_decoder_1 = require("node:string_decoder");
/**
 * Return true if the argument is a Minipass stream, Node stream, or something
 * else that Minipass can interact with.
 */
const isStream = (s) => !!s &&
    typeof s === 'object' &&
    (s instanceof Minipass ||
        s instanceof node_stream_1.default ||
        (0, exports.isReadable)(s) ||
        (0, exports.isWritable)(s));
exports.isStream = isStream;
/**
 * Return true if the argument is a valid {@link Minipass.Readable}
 */
const isReadable = (s) => !!s &&
    typeof s === 'object' &&
    s instanceof node_events_1.EventEmitter &&
    typeof s.pipe === 'function' &&
    // node core Writable streams have a pipe() method, but it throws
    s.pipe !== node_stream_1.default.Writable.prototype.pipe;
exports.isReadable = isReadable;
/**
 * Return true if the argument is a valid {@link Minipass.Writable}
 */
const isWritable = (s) => !!s &&
    typeof s === 'object' &&
    s instanceof node_events_1.EventEmitter &&
    typeof s.write === 'function' &&
    typeof s.end === 'function';
exports.isWritable = isWritable;
const EOF = Symbol('EOF');
const MAYBE_EMIT_END = Symbol('maybeEmitEnd');
const EMITTED_END = Symbol('emittedEnd');
const EMITTING_END = Symbol('emittingEnd');
const EMITTED_ERROR = Symbol('emittedError');
const CLOSED = Symbol('closed');
const READ = Symbol('read');
const FLUSH = Symbol('flush');
const FLUSHCHUNK = Symbol('flushChunk');
const ENCODING = Symbol('encoding');
const DECODER = Symbol('decoder');
const FLOWING = Symbol('flowing');
const PAUSED = Symbol('paused');
const RESUME = Symbol('resume');
const BUFFER = Symbol('buffer');
const PIPES = Symbol('pipes');
const BUFFERLENGTH = Symbol('bufferLength');
const BUFFERPUSH = Symbol('bufferPush');
const BUFFERSHIFT = Symbol('bufferShift');
const OBJECTMODE = Symbol('objectMode');
// internal event when stream is destroyed
const DESTROYED = Symbol('destroyed');
// internal event when stream has an error
const ERROR = Symbol('error');
const EMITDATA = Symbol('emitData');
const EMITEND = Symbol('emitEnd');
const EMITEND2 = Symbol('emitEnd2');
const ASYNC = Symbol('async');
const ABORT = Symbol('abort');
const ABORTED = Symbol('aborted');
const SIGNAL = Symbol('signal');
const DATALISTENERS = Symbol('dataListeners');
const DISCARDED = Symbol('discarded');
const defer = (fn) => Promise.resolve().then(fn);
const nodefer = (fn) => fn();
const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish';
const isArrayBufferLike = (b) => b instanceof ArrayBuffer ||
    (!!b &&
        typeof b === 'object' &&
        b.constructor &&
        b.constructor.name === 'ArrayBuffer' &&
        b.byteLength >= 0);
const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
/**
 * Internal class representing a pipe to a destination stream.
 *
 * @internal
 */
class Pipe {
    src;
    dest;
    opts;
    ondrain;
    constructor(src, dest, opts) {
        this.src = src;
        this.dest = dest;
        this.opts = opts;
        this.ondrain = () => src[RESUME]();
        this.dest.on('drain', this.ondrain);
    }
    unpipe() {
        this.dest.removeListener('drain', this.ondrain);
    }
    // only here for the prototype
    /* c8 ignore start */
    proxyErrors(_er) { }
    /* c8 ignore stop */
    end() {
        this.unpipe();
        if (this.opts.end)
            this.dest.end();
    }
}
/**
 * Internal class representing a pipe to a destination stream where
 * errors are proxied.
 *
 * @internal
 */
class PipeProxyErrors extends Pipe {
    unpipe() {
        this.src.removeListener('error', this.proxyErrors);
        super.unpipe();
    }
    constructor(src, dest, opts) {
        super(src, dest, opts);
        this.proxyErrors = er => dest.emit('error', er);
        src.on('error', this.proxyErrors);
    }
}
const isObjectModeOptions = (o) => !!o.objectMode;
const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer';
/**
 * Main export, the Minipass class
 *
 * `RType` is the type of data emitted, defaults to Buffer
 *
 * `WType` is the type of data to be written, if RType is buffer or string,
 * then any {@link Minipass.ContiguousData} is allowed.
 *
 * `Events` is the set of event handler signatures that this object
 * will emit, see {@link Minipass.Events}
 */
class Minipass extends node_events_1.EventEmitter {
    [FLOWING] = false;
    [PAUSED] = false;
    [PIPES] = [];
    [BUFFER] = [];
    [OBJECTMODE];
    [ENCODING];
    [ASYNC];
    [DECODER];
    [EOF] = false;
    [EMITTED_END] = false;
    [EMITTING_END] = false;
    [CLOSED] = false;
    [EMITTED_ERROR] = null;
    [BUFFERLENGTH] = 0;
    [DESTROYED] = false;
    [SIGNAL];
    [ABORTED] = false;
    [DATALISTENERS] = 0;
    [DISCARDED] = false;
    /**
     * true if the stream can be written
     */
    writable = true;
    /**
     * true if the stream can be read
     */
    readable = true;
    /**
     * If `RType` is Buffer, then options do not need to be provided.
     * Otherwise, an options object must be provided to specify either
     * {@link Minipass.SharedOptions.objectMode} or
     * {@link Minipass.SharedOptions.encoding}, as appropriate.
     */
    constructor(...args) {
        const options = (args[0] ||
            {});
        super();
        if (options.objectMode && typeof options.encoding === 'string') {
            throw new TypeError('Encoding and objectMode may not be used together');
        }
        if (isObjectModeOptions(options)) {
            this[OBJECTMODE] = true;
            this[ENCODING] = null;
        }
        else if (isEncodingOptions(options)) {
            this[ENCODING] = options.encoding;
            this[OBJECTMODE] = false;
        }
        else {
            this[OBJECTMODE] = false;
            this[ENCODING] = null;
        }
        this[ASYNC] = !!options.async;
        this[DECODER] = this[ENCODING]
            ? new node_string_decoder_1.StringDecoder(this[ENCODING])
            : null;
        //@ts-ignore - private option for debugging and testing
        if (options && options.debugExposeBuffer === true) {
            Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] });
        }
        //@ts-ignore - private option for debugging and testing
        if (options && options.debugExposePipes === true) {
            Object.defineProperty(this, 'pipes', { get: () => this[PIPES] });
        }
        const { signal } = options;
        if (signal) {
            this[SIGNAL] = signal;
            if (signal.aborted) {
                this[ABORT]();
            }
            else {
                signal.addEventListener('abort', () => this[ABORT]());
            }
        }
    }
    /**
     * The amount of data stored in the buffer waiting to be read.
     *
     * For Buffer strings, this will be the total byte length.
     * For string encoding streams, this will be the string character length,
     * according to JavaScript's `string.length` logic.
     * For objectMode streams, this is a count of the items waiting to be
     * emitted.
     */
    get bufferLength() {
        return this[BUFFERLENGTH];
    }
    /**
     * The `BufferEncoding` currently in use, or `null`
     */
    get encoding() {
        return this[ENCODING];
    }
    /**
     * @deprecated - This is a read only property
     */
    set encoding(_enc) {
        throw new Error('Encoding must be set at instantiation time');
    }
    /**
     * @deprecated - Encoding may only be set at instantiation time
     */
    setEncoding(_enc) {
        throw new Error('Encoding must be set at instantiation time');
    }
    /**
     * True if this is an objectMode stream
     */
    get objectMode() {
        return this[OBJECTMODE];
    }
    /**
     * @deprecated - This is a read-only property
     */
    set objectMode(_om) {
        throw new Error('objectMode must be set at instantiation time');
    }
    /**
     * true if this is an async stream
     */
    get ['async']() {
        return this[ASYNC];
    }
    /**
     * Set to true to make this stream async.
     *
     * Once set, it cannot be unset, as this would potentially cause incorrect
     * behavior.  Ie, a sync stream can be made async, but an async stream
     * cannot be safely made sync.
     */
    set ['async'](a) {
        this[ASYNC] = this[ASYNC] || !!a;
    }
    // drop everything and get out of the flow completely
    [ABORT]() {
        this[ABORTED] = true;
        this.emit('abort', this[SIGNAL]?.reason);
        this.destroy(this[SIGNAL]?.reason);
    }
    /**
     * True if the stream has been aborted.
     */
    get aborted() {
        return this[ABORTED];
    }
    /**
     * No-op setter. Stream aborted status is set via the AbortSignal provided
     * in the constructor options.
     */
    set aborted(_) { }
    write(chunk, encoding, cb) {
        if (this[ABORTED])
            return false;
        if (this[EOF])
            throw new Error('write after end');
        if (this[DESTROYED]) {
            this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' }));
            return true;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = 'utf8';
        }
        if (!encoding)
            encoding = 'utf8';
        const fn = this[ASYNC] ? defer : nodefer;
        // convert array buffers and typed array views into buffers
        // at some point in the future, we may want to do the opposite!
        // leave strings and buffers as-is
        // anything is only allowed if in object mode, so throw
        if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
            if (isArrayBufferView(chunk)) {
                //@ts-ignore - sinful unsafe type changing
                chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
            }
            else if (isArrayBufferLike(chunk)) {
                //@ts-ignore - sinful unsafe type changing
                chunk = Buffer.from(chunk);
            }
            else if (typeof chunk !== 'string') {
                throw new Error('Non-contiguous data written to non-objectMode stream');
            }
        }
        // handle object mode up front, since it's simpler
        // this yields better performance, fewer checks later.
        if (this[OBJECTMODE]) {
            // maybe impossible?
            /* c8 ignore start */
            if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
                this[FLUSH](true);
            /* c8 ignore stop */
            if (this[FLOWING])
                this.emit('data', chunk);
            else
                this[BUFFERPUSH](chunk);
            if (this[BUFFERLENGTH] !== 0)
                this.emit('readable');
            if (cb)
                fn(cb);
            return this[FLOWING];
        }
        // at this point the chunk is a buffer or string
        // don't buffer it up or send it to the decoder
        if (!chunk.length) {
            if (this[BUFFERLENGTH] !== 0)
                this.emit('readable');
            if (cb)
                fn(cb);
            return this[FLOWING];
        }
        // fast-path writing strings of same encoding to a stream with
        // an empty buffer, skipping the buffer/decoder dance
        if (typeof chunk === 'string' &&
            // unless it is a string already ready for us to use
            !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
            //@ts-ignore - sinful unsafe type change
            chunk = Buffer.from(chunk, encoding);
        }
        if (Buffer.isBuffer(chunk) && this[ENCODING]) {
            //@ts-ignore - sinful unsafe type change
            chunk = this[DECODER].write(chunk);
        }
        // Note: flushing CAN potentially switch us into not-flowing mode
        if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
            this[FLUSH](true);
        if (this[FLOWING])
            this.emit('data', chunk);
        else
            this[BUFFERPUSH](chunk);
        if (this[BUFFERLENGTH] !== 0)
            this.emit('readable');
        if (cb)
            fn(cb);
        return this[FLOWING];
    }
    /**
     * Low-level explicit read method.
     *
     * In objectMode, the argument is ignored, and one item is returned if
     * available.
     *
     * `n` is the number of bytes (or in the case of encoding streams,
     * characters) to consume. If `n` is not provided, then the entire buffer
     * is returned, or `null` is returned if no data is available.
     *
     * If `n` is greater that the amount of data in the internal buffer,
     * then `null` is returned.
     */
    read(n) {
        if (this[DESTROYED])
            return null;
        this[DISCARDED] = false;
        if (this[BUFFERLENGTH] === 0 ||
            n === 0 ||
            (n && n > this[BUFFERLENGTH])) {
            this[MAYBE_EMIT_END]();
            return null;
        }
        if (this[OBJECTMODE])
            n = null;
        if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
            // not object mode, so if we have an encoding, then RType is string
            // otherwise, must be Buffer
            this[BUFFER] = [
                (this[ENCODING]
                    ? this[BUFFER].join('')
                    : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])),
            ];
        }
        const ret = this[READ](n || null, this[BUFFER][0]);
        this[MAYBE_EMIT_END]();
        return ret;
    }
    [READ](n, chunk) {
        if (this[OBJECTMODE])
            this[BUFFERSHIFT]();
        else {
            const c = chunk;
            if (n === c.length || n === null)
                this[BUFFERSHIFT]();
            else if (typeof c === 'string') {
                this[BUFFER][0] = c.slice(n);
                chunk = c.slice(0, n);
                this[BUFFERLENGTH] -= n;
            }
            else {
                this[BUFFER][0] = c.subarray(n);
                chunk = c.subarray(0, n);
                this[BUFFERLENGTH] -= n;
            }
        }
        this.emit('data', chunk);
        if (!this[BUFFER].length && !this[EOF])
            this.emit('drain');
        return chunk;
    }
    end(chunk, encoding, cb) {
        if (typeof chunk === 'function') {
            cb = chunk;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = 'utf8';
        }
        if (chunk !== undefined)
            this.write(chunk, encoding);
        if (cb)
            this.once('end', cb);
        this[EOF] = true;
        this.writable = false;
        // if we haven't written anything, then go ahead and emit,
        // even if we're not reading.
        // we'll re-emit if a new 'end' listener is added anyway.
        // This makes MP more suitable to write-only use cases.
        if (this[FLOWING] || !this[PAUSED])
            this[MAYBE_EMIT_END]();
        return this;
    }
    // don't let the internal resume be overwritten
    [RESUME]() {
        if (this[DESTROYED])
            return;
        if (!this[DATALISTENERS] && !this[PIPES].length) {
            this[DISCARDED] = true;
        }
        this[PAUSED] = false;
        this[FLOWING] = true;
        this.emit('resume');
        if (this[BUFFER].length)
            this[FLUSH]();
        else if (this[EOF])
            this[MAYBE_EMIT_END]();
        else
            this.emit('drain');
    }
    /**
     * Resume the stream if it is currently in a paused state
     *
     * If called when there are no pipe destinations or `data` event listeners,
     * this will place the stream in a "discarded" state, where all data will
     * be thrown away. The discarded state is removed if a pipe destination or
     * data handler is added, if pause() is called, or if any synchronous or
     * asynchronous iteration is started.
     */
    resume() {
        return this[RESUME]();
    }
    /**
     * Pause the stream
     */
    pause() {
        this[FLOWING] = false;
        this[PAUSED] = true;
        this[DISCARDED] = false;
    }
    /**
     * true if the stream has been forcibly destroyed
     */
    get destroyed() {
        return this[DESTROYED];
    }
    /**
     * true if the stream is currently in a flowing state, meaning that
     * any writes will be immediately emitted.
     */
    get flowing() {
        return this[FLOWING];
    }
    /**
     * true if the stream is currently in a paused state
     */
    get paused() {
        return this[PAUSED];
    }
    [BUFFERPUSH](chunk) {
        if (this[OBJECTMODE])
            this[BUFFERLENGTH] += 1;
        else
            this[BUFFERLENGTH] += chunk.length;
        this[BUFFER].push(chunk);
    }
    [BUFFERSHIFT]() {
        if (this[OBJECTMODE])
            this[BUFFERLENGTH] -= 1;
        else
            this[BUFFERLENGTH] -= this[BUFFER][0].length;
        return this[BUFFER].shift();
    }
    [FLUSH](noDrain = false) {
        do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&
            this[BUFFER].length);
        if (!noDrain && !this[BUFFER].length && !this[EOF])
            this.emit('drain');
    }
    [FLUSHCHUNK](chunk) {
        this.emit('data', chunk);
        return this[FLOWING];
    }
    /**
     * Pipe all data emitted by this stream into the destination provided.
     *
     * Triggers the flow of data.
     */
    pipe(dest, opts) {
        if (this[DESTROYED])
            return dest;
        this[DISCARDED] = false;
        const ended = this[EMITTED_END];
        opts = opts || {};
        if (dest === proc.stdout || dest === proc.stderr)
            opts.end = false;
        else
            opts.end = opts.end !== false;
        opts.proxyErrors = !!opts.proxyErrors;
        // piping an ended stream ends immediately
        if (ended) {
            if (opts.end)
                dest.end();
        }
        else {
            // "as" here just ignores the WType, which pipes don't care about,
            // since they're only consuming from us, and writing to the dest
            this[PIPES].push(!opts.proxyErrors
                ? new Pipe(this, dest, opts)
                : new PipeProxyErrors(this, dest, opts));
            if (this[ASYNC])
                defer(() => this[RESUME]());
            else
                this[RESUME]();
        }
        return dest;
    }
    /**
     * Fully unhook a piped destination stream.
     *
     * If the destination stream was the only consumer of this stream (ie,
     * there are no other piped destinations or `'data'` event listeners)
     * then the flow of data will stop until there is another consumer or
     * {@link Minipass#resume} is explicitly called.
     */
    unpipe(dest) {
        const p = this[PIPES].find(p => p.dest === dest);
        if (p) {
            if (this[PIPES].length === 1) {
                if (this[FLOWING] && this[DATALISTENERS] === 0) {
                    this[FLOWING] = false;
                }
                this[PIPES] = [];
            }
            else
                this[PIPES].splice(this[PIPES].indexOf(p), 1);
            p.unpipe();
        }
    }
    /**
     * Alias for {@link Minipass#on}
     */
    addListener(ev, handler) {
        return this.on(ev, handler);
    }
    /**
     * Mostly identical to `EventEmitter.on`, with the following
     * behavior differences to prevent data loss and unnecessary hangs:
     *
     * - Adding a 'data' event handler will trigger the flow of data
     *
     * - Adding a 'readable' event handler when there is data waiting to be read
     *   will cause 'readable' to be emitted immediately.
     *
     * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
     *   already passed will cause the event to be emitted immediately and all
     *   handlers removed.
     *
     * - Adding an 'error' event handler after an error has been emitted will
     *   cause the event to be re-emitted immediately with the error previously
     *   raised.
     */
    on(ev, handler) {
        const ret = super.on(ev, handler);
        if (ev === 'data') {
            this[DISCARDED] = false;
            this[DATALISTENERS]++;
            if (!this[PIPES].length && !this[FLOWING]) {
                this[RESUME]();
            }
        }
        else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {
            super.emit('readable');
        }
        else if (isEndish(ev) && this[EMITTED_END]) {
            super.emit(ev);
            this.removeAllListeners(ev);
        }
        else if (ev === 'error' && this[EMITTED_ERROR]) {
            const h = handler;
            if (this[ASYNC])
                defer(() => h.call(this, this[EMITTED_ERROR]));
            else
                h.call(this, this[EMITTED_ERROR]);
        }
        return ret;
    }
    /**
     * Alias for {@link Minipass#off}
     */
    removeListener(ev, handler) {
        return this.off(ev, handler);
    }
    /**
     * Mostly identical to `EventEmitter.off`
     *
     * If a 'data' event handler is removed, and it was the last consumer
     * (ie, there are no pipe destinations or other 'data' event listeners),
     * then the flow of data will stop until there is another consumer or
     * {@link Minipass#resume} is explicitly called.
     */
    off(ev, handler) {
        const ret = super.off(ev, handler);
        // if we previously had listeners, and now we don't, and we don't
        // have any pipes, then stop the flow, unless it's been explicitly
        // put in a discarded flowing state via stream.resume().
        if (ev === 'data') {
            this[DATALISTENERS] = this.listeners('data').length;
            if (this[DATALISTENERS] === 0 &&
                !this[DISCARDED] &&
                !this[PIPES].length) {
                this[FLOWING] = false;
            }
        }
        return ret;
    }
    /**
     * Mostly identical to `EventEmitter.removeAllListeners`
     *
     * If all 'data' event handlers are removed, and they were the last consumer
     * (ie, there are no pipe destinations), then the flow of data will stop
     * until there is another consumer or {@link Minipass#resume} is explicitly
     * called.
     */
    removeAllListeners(ev) {
        const ret = super.removeAllListeners(ev);
        if (ev === 'data' || ev === undefined) {
            this[DATALISTENERS] = 0;
            if (!this[DISCARDED] && !this[PIPES].length) {
                this[FLOWING] = false;
            }
        }
        return ret;
    }
    /**
     * true if the 'end' event has been emitted
     */
    get emittedEnd() {
        return this[EMITTED_END];
    }
    [MAYBE_EMIT_END]() {
        if (!this[EMITTING_END] &&
            !this[EMITTED_END] &&
            !this[DESTROYED] &&
            this[BUFFER].length === 0 &&
            this[EOF]) {
            this[EMITTING_END] = true;
            this.emit('end');
            this.emit('prefinish');
            this.emit('finish');
            if (this[CLOSED])
                this.emit('close');
            this[EMITTING_END] = false;
        }
    }
    /**
     * Mostly identical to `EventEmitter.emit`, with the following
     * behavior differences to prevent data loss and unnecessary hangs:
     *
     * If the stream has been destroyed, and the event is something other
     * than 'close' or 'error', then `false` is returned and no handlers
     * are called.
     *
     * If the event is 'end', and has already been emitted, then the event
     * is ignored. If the stream is in a paused or non-flowing state, then
     * the event will be deferred until data flow resumes. If the stream is
     * async, then handlers will be called on the next tick rather than
     * immediately.
     *
     * If the event is 'close', and 'end' has not yet been emitted, then
     * the event will be deferred until after 'end' is emitted.
     *
     * If the event is 'error', and an AbortSignal was provided for the stream,
     * and there are no listeners, then the event is ignored, matching the
     * behavior of node core streams in the presense of an AbortSignal.
     *
     * If the event is 'finish' or 'prefinish', then all listeners will be
     * removed after emitting the event, to prevent double-firing.
     */
    emit(ev, ...args) {
        const data = args[0];
        // error and close are only events allowed after calling destroy()
        if (ev !== 'error' &&
            ev !== 'close' &&
            ev !== DESTROYED &&
            this[DESTROYED]) {
            return false;
        }
        else if (ev === 'data') {
            return !this[OBJECTMODE] && !data
                ? false
                : this[ASYNC]
                    ? (defer(() => this[EMITDATA](data)), true)
                    : this[EMITDATA](data);
        }
        else if (ev === 'end') {
            return this[EMITEND]();
        }
        else if (ev === 'close') {
            this[CLOSED] = true;
            // don't emit close before 'end' and 'finish'
            if (!this[EMITTED_END] && !this[DESTROYED])
                return false;
            const ret = super.emit('close');
            this.removeAllListeners('close');
            return ret;
        }
        else if (ev === 'error') {
            this[EMITTED_ERROR] = data;
            super.emit(ERROR, data);
            const ret = !this[SIGNAL] || this.listeners('error').length
                ? super.emit('error', data)
                : false;
            this[MAYBE_EMIT_END]();
            return ret;
        }
        else if (ev === 'resume') {
            const ret = super.emit('resume');
            this[MAYBE_EMIT_END]();
            return ret;
        }
        else if (ev === 'finish' || ev === 'prefinish') {
            const ret = super.emit(ev);
            this.removeAllListeners(ev);
            return ret;
        }
        // Some other unknown event
        const ret = super.emit(ev, ...args);
        this[MAYBE_EMIT_END]();
        return ret;
    }
    [EMITDATA](data) {
        for (const p of this[PIPES]) {
            if (p.dest.write(data) === false)
                this.pause();
        }
        const ret = this[DISCARDED] ? false : super.emit('data', data);
        this[MAYBE_EMIT_END]();
        return ret;
    }
    [EMITEND]() {
        if (this[EMITTED_END])
            return false;
        this[EMITTED_END] = true;
        this.readable = false;
        return this[ASYNC]
            ? (defer(() => this[EMITEND2]()), true)
            : this[EMITEND2]();
    }
    [EMITEND2]() {
        if (this[DECODER]) {
            const data = this[DECODER].end();
            if (data) {
                for (const p of this[PIPES]) {
                    p.dest.write(data);
                }
                if (!this[DISCARDED])
                    super.emit('data', data);
            }
        }
        for (const p of this[PIPES]) {
            p.end();
        }
        const ret = super.emit('end');
        this.removeAllListeners('end');
        return ret;
    }
    /**
     * Return a Promise that resolves to an array of all emitted data once
     * the stream ends.
     */
    async collect() {
        const buf = Object.assign([], {
            dataLength: 0,
        });
        if (!this[OBJECTMODE])
            buf.dataLength = 0;
        // set the promise first, in case an error is raised
        // by triggering the flow here.
        const p = this.promise();
        this.on('data', c => {
            buf.push(c);
            if (!this[OBJECTMODE])
                buf.dataLength += c.length;
        });
        await p;
        return buf;
    }
    /**
     * Return a Promise that resolves to the concatenation of all emitted data
     * once the stream ends.
     *
     * Not allowed on objectMode streams.
     */
    async concat() {
        if (this[OBJECTMODE]) {
            throw new Error('cannot concat in objectMode');
        }
        const buf = await this.collect();
        return (this[ENCODING]
            ? buf.join('')
            : Buffer.concat(buf, buf.dataLength));
    }
    /**
     * Return a void Promise that resolves once the stream ends.
     */
    async promise() {
        return new Promise((resolve, reject) => {
            this.on(DESTROYED, () => reject(new Error('stream destroyed')));
            this.on('error', er => reject(er));
            this.on('end', () => resolve());
        });
    }
    /**
     * Asynchronous `for await of` iteration.
     *
     * This will continue emitting all chunks until the stream terminates.
     */
    [Symbol.asyncIterator]() {
        // set this up front, in case the consumer doesn't call next()
        // right away.
        this[DISCARDED] = false;
        let stopped = false;
        const stop = async () => {
            this.pause();
            stopped = true;
            return { value: undefined, done: true };
        };
        const next = () => {
            if (stopped)
                return stop();
            const res = this.read();
            if (res !== null)
                return Promise.resolve({ done: false, value: res });
            if (this[EOF])
                return stop();
            let resolve;
            let reject;
            const onerr = (er) => {
                this.off('data', ondata);
                this.off('end', onend);
                this.off(DESTROYED, ondestroy);
                stop();
                reject(er);
            };
            const ondata = (value) => {
                this.off('error', onerr);
                this.off('end', onend);
                this.off(DESTROYED, ondestroy);
                this.pause();
                resolve({ value, done: !!this[EOF] });
            };
            const onend = () => {
                this.off('error', onerr);
                this.off('data', ondata);
                this.off(DESTROYED, ondestroy);
                stop();
                resolve({ done: true, value: undefined });
            };
            const ondestroy = () => onerr(new Error('stream destroyed'));
            return new Promise((res, rej) => {
                reject = rej;
                resolve = res;
                this.once(DESTROYED, ondestroy);
                this.once('error', onerr);
                this.once('end', onend);
                this.once('data', ondata);
            });
        };
        return {
            next,
            throw: stop,
            return: stop,
            [Symbol.asyncIterator]() {
                return this;
            },
        };
    }
    /**
     * Synchronous `for of` iteration.
     *
     * The iteration will terminate when the internal buffer runs out, even
     * if the stream has not yet terminated.
     */
    [Symbol.iterator]() {
        // set this up front, in case the consumer doesn't call next()
        // right away.
        this[DISCARDED] = false;
        let stopped = false;
        const stop = () => {
            this.pause();
            this.off(ERROR, stop);
            this.off(DESTROYED, stop);
            this.off('end', stop);
            stopped = true;
            return { done: true, value: undefined };
        };
        const next = () => {
            if (stopped)
                return stop();
            const value = this.read();
            return value === null ? stop() : { done: false, value };
        };
        this.once('end', stop);
        this.once(ERROR, stop);
        this.once(DESTROYED, stop);
        return {
            next,
            throw: stop,
            return: stop,
            [Symbol.iterator]() {
                return this;
            },
        };
    }
    /**
     * Destroy a stream, preventing it from being used for any further purpose.
     *
     * If the stream has a `close()` method, then it will be called on
     * destruction.
     *
     * After destruction, any attempt to write data, read data, or emit most
     * events will be ignored.
     *
     * If an error argument is provided, then it will be emitted in an
     * 'error' event.
     */
    destroy(er) {
        if (this[DESTROYED]) {
            if (er)
                this.emit('error', er);
            else
                this.emit(DESTROYED);
            return this;
        }
        this[DESTROYED] = true;
        this[DISCARDED] = true;
        // throw away all buffered data, it's never coming out
        this[BUFFER].length = 0;
        this[BUFFERLENGTH] = 0;
        const wc = this;
        if (typeof wc.close === 'function' && !this[CLOSED])
            wc.close();
        if (er)
            this.emit('error', er);
        // if no error to emit, still reject pending promises
        else
            this.emit(DESTROYED);
        return this;
    }
    /**
     * Alias for {@link isStream}
     *
     * Former export location, maintained for backwards compatibility.
     *
     * @deprecated
     */
    static get isStream() {
        return exports.isStream;
    }
}
exports.Minipass = Minipass;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
const proc = typeof process === 'object' && process
    ? process
    : {
        stdout: null,
        stderr: null,
    };
import { EventEmitter } from 'node:events';
import Stream from 'node:stream';
import { StringDecoder } from 'node:string_decoder';
/**
 * Return true if the argument is a Minipass stream, Node stream, or something
 * else that Minipass can interact with.
 */
export const isStream = (s) => !!s &&
    typeof s === 'object' &&
    (s instanceof Minipass ||
        s instanceof Stream ||
        isReadable(s) ||
        isWritable(s));
/**
 * Return true if the argument is a valid {@link Minipass.Readable}
 */
export const isReadable = (s) => !!s &&
    typeof s === 'object' &&
    s instanceof EventEmitter &&
    typeof s.pipe === 'function' &&
    // node core Writable streams have a pipe() method, but it throws
    s.pipe !== Stream.Writable.prototype.pipe;
/**
 * Return true if the argument is a valid {@link Minipass.Writable}
 */
export const isWritable = (s) => !!s &&
    typeof s === 'object' &&
    s instanceof EventEmitter &&
    typeof s.write === 'function' &&
    typeof s.end === 'function';
const EOF = Symbol('EOF');
const MAYBE_EMIT_END = Symbol('maybeEmitEnd');
const EMITTED_END = Symbol('emittedEnd');
const EMITTING_END = Symbol('emittingEnd');
const EMITTED_ERROR = Symbol('emittedError');
const CLOSED = Symbol('closed');
const READ = Symbol('read');
const FLUSH = Symbol('flush');
const FLUSHCHUNK = Symbol('flushChunk');
const ENCODING = Symbol('encoding');
const DECODER = Symbol('decoder');
const FLOWING = Symbol('flowing');
const PAUSED = Symbol('paused');
const RESUME = Symbol('resume');
const BUFFER = Symbol('buffer');
const PIPES = Symbol('pipes');
const BUFFERLENGTH = Symbol('bufferLength');
const BUFFERPUSH = Symbol('bufferPush');
const BUFFERSHIFT = Symbol('bufferShift');
const OBJECTMODE = Symbol('objectMode');
// internal event when stream is destroyed
const DESTROYED = Symbol('destroyed');
// internal event when stream has an error
const ERROR = Symbol('error');
const EMITDATA = Symbol('emitData');
const EMITEND = Symbol('emitEnd');
const EMITEND2 = Symbol('emitEnd2');
const ASYNC = Symbol('async');
const ABORT = Symbol('abort');
const ABORTED = Symbol('aborted');
const SIGNAL = Symbol('signal');
const DATALISTENERS = Symbol('dataListeners');
const DISCARDED = Symbol('discarded');
const defer = (fn) => Promise.resolve().then(fn);
const nodefer = (fn) => fn();
const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish';
const isArrayBufferLike = (b) => b instanceof ArrayBuffer ||
    (!!b &&
        typeof b === 'object' &&
        b.constructor &&
        b.constructor.name === 'ArrayBuffer' &&
        b.byteLength >= 0);
const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
/**
 * Internal class representing a pipe to a destination stream.
 *
 * @internal
 */
class Pipe {
    src;
    dest;
    opts;
    ondrain;
    constructor(src, dest, opts) {
        this.src = src;
        this.dest = dest;
        this.opts = opts;
        this.ondrain = () => src[RESUME]();
        this.dest.on('drain', this.ondrain);
    }
    unpipe() {
        this.dest.removeListener('drain', this.ondrain);
    }
    // only here for the prototype
    /* c8 ignore start */
    proxyErrors(_er) { }
    /* c8 ignore stop */
    end() {
        this.unpipe();
        if (this.opts.end)
            this.dest.end();
    }
}
/**
 * Internal class representing a pipe to a destination stream where
 * errors are proxied.
 *
 * @internal
 */
class PipeProxyErrors extends Pipe {
    unpipe() {
        this.src.removeListener('error', this.proxyErrors);
        super.unpipe();
    }
    constructor(src, dest, opts) {
        super(src, dest, opts);
        this.proxyErrors = er => dest.emit('error', er);
        src.on('error', this.proxyErrors);
    }
}
const isObjectModeOptions = (o) => !!o.objectMode;
const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer';
/**
 * Main export, the Minipass class
 *
 * `RType` is the type of data emitted, defaults to Buffer
 *
 * `WType` is the type of data to be written, if RType is buffer or string,
 * then any {@link Minipass.ContiguousData} is allowed.
 *
 * `Events` is the set of event handler signatures that this object
 * will emit, see {@link Minipass.Events}
 */
export class Minipass extends EventEmitter {
    [FLOWING] = false;
    [PAUSED] = false;
    [PIPES] = [];
    [BUFFER] = [];
    [OBJECTMODE];
    [ENCODING];
    [ASYNC];
    [DECODER];
    [EOF] = false;
    [EMITTED_END] = false;
    [EMITTING_END] = false;
    [CLOSED] = false;
    [EMITTED_ERROR] = null;
    [BUFFERLENGTH] = 0;
    [DESTROYED] = false;
    [SIGNAL];
    [ABORTED] = false;
    [DATALISTENERS] = 0;
    [DISCARDED] = false;
    /**
     * true if the stream can be written
     */
    writable = true;
    /**
     * true if the stream can be read
     */
    readable = true;
    /**
     * If `RType` is Buffer, then options do not need to be provided.
     * Otherwise, an options object must be provided to specify either
     * {@link Minipass.SharedOptions.objectMode} or
     * {@link Minipass.SharedOptions.encoding}, as appropriate.
     */
    constructor(...args) {
        const options = (args[0] ||
            {});
        super();
        if (options.objectMode && typeof options.encoding === 'string') {
            throw new TypeError('Encoding and objectMode may not be used together');
        }
        if (isObjectModeOptions(options)) {
            this[OBJECTMODE] = true;
            this[ENCODING] = null;
        }
        else if (isEncodingOptions(options)) {
            this[ENCODING] = options.encoding;
            this[OBJECTMODE] = false;
        }
        else {
            this[OBJECTMODE] = false;
            this[ENCODING] = null;
        }
        this[ASYNC] = !!options.async;
        this[DECODER] = this[ENCODING]
            ? new StringDecoder(this[ENCODING])
            : null;
        //@ts-ignore - private option for debugging and testing
        if (options && options.debugExposeBuffer === true) {
            Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] });
        }
        //@ts-ignore - private option for debugging and testing
        if (options && options.debugExposePipes === true) {
            Object.defineProperty(this, 'pipes', { get: () => this[PIPES] });
        }
        const { signal } = options;
        if (signal) {
            this[SIGNAL] = signal;
            if (signal.aborted) {
                this[ABORT]();
            }
            else {
                signal.addEventListener('abort', () => this[ABORT]());
            }
        }
    }
    /**
     * The amount of data stored in the buffer waiting to be read.
     *
     * For Buffer strings, this will be the total byte length.
     * For string encoding streams, this will be the string character length,
     * according to JavaScript's `string.length` logic.
     * For objectMode streams, this is a count of the items waiting to be
     * emitted.
     */
    get bufferLength() {
        return this[BUFFERLENGTH];
    }
    /**
     * The `BufferEncoding` currently in use, or `null`
     */
    get encoding() {
        return this[ENCODING];
    }
    /**
     * @deprecated - This is a read only property
     */
    set encoding(_enc) {
        throw new Error('Encoding must be set at instantiation time');
    }
    /**
     * @deprecated - Encoding may only be set at instantiation time
     */
    setEncoding(_enc) {
        throw new Error('Encoding must be set at instantiation time');
    }
    /**
     * True if this is an objectMode stream
     */
    get objectMode() {
        return this[OBJECTMODE];
    }
    /**
     * @deprecated - This is a read-only property
     */
    set objectMode(_om) {
        throw new Error('objectMode must be set at instantiation time');
    }
    /**
     * true if this is an async stream
     */
    get ['async']() {
        return this[ASYNC];
    }
    /**
     * Set to true to make this stream async.
     *
     * Once set, it cannot be unset, as this would potentially cause incorrect
     * behavior.  Ie, a sync stream can be made async, but an async stream
     * cannot be safely made sync.
     */
    set ['async'](a) {
        this[ASYNC] = this[ASYNC] || !!a;
    }
    // drop everything and get out of the flow completely
    [ABORT]() {
        this[ABORTED] = true;
        this.emit('abort', this[SIGNAL]?.reason);
        this.destroy(this[SIGNAL]?.reason);
    }
    /**
     * True if the stream has been aborted.
     */
    get aborted() {
        return this[ABORTED];
    }
    /**
     * No-op setter. Stream aborted status is set via the AbortSignal provided
     * in the constructor options.
     */
    set aborted(_) { }
    write(chunk, encoding, cb) {
        if (this[ABORTED])
            return false;
        if (this[EOF])
            throw new Error('write after end');
        if (this[DESTROYED]) {
            this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' }));
            return true;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = 'utf8';
        }
        if (!encoding)
            encoding = 'utf8';
        const fn = this[ASYNC] ? defer : nodefer;
        // convert array buffers and typed array views into buffers
        // at some point in the future, we may want to do the opposite!
        // leave strings and buffers as-is
        // anything is only allowed if in object mode, so throw
        if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
            if (isArrayBufferView(chunk)) {
                //@ts-ignore - sinful unsafe type changing
                chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
            }
            else if (isArrayBufferLike(chunk)) {
                //@ts-ignore - sinful unsafe type changing
                chunk = Buffer.from(chunk);
            }
            else if (typeof chunk !== 'string') {
                throw new Error('Non-contiguous data written to non-objectMode stream');
            }
        }
        // handle object mode up front, since it's simpler
        // this yields better performance, fewer checks later.
        if (this[OBJECTMODE]) {
            // maybe impossible?
            /* c8 ignore start */
            if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
                this[FLUSH](true);
            /* c8 ignore stop */
            if (this[FLOWING])
                this.emit('data', chunk);
            else
                this[BUFFERPUSH](chunk);
            if (this[BUFFERLENGTH] !== 0)
                this.emit('readable');
            if (cb)
                fn(cb);
            return this[FLOWING];
        }
        // at this point the chunk is a buffer or string
        // don't buffer it up or send it to the decoder
        if (!chunk.length) {
            if (this[BUFFERLENGTH] !== 0)
                this.emit('readable');
            if (cb)
                fn(cb);
            return this[FLOWING];
        }
        // fast-path writing strings of same encoding to a stream with
        // an empty buffer, skipping the buffer/decoder dance
        if (typeof chunk === 'string' &&
            // unless it is a string already ready for us to use
            !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
            //@ts-ignore - sinful unsafe type change
            chunk = Buffer.from(chunk, encoding);
        }
        if (Buffer.isBuffer(chunk) && this[ENCODING]) {
            //@ts-ignore - sinful unsafe type change
            chunk = this[DECODER].write(chunk);
        }
        // Note: flushing CAN potentially switch us into not-flowing mode
        if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
            this[FLUSH](true);
        if (this[FLOWING])
            this.emit('data', chunk);
        else
            this[BUFFERPUSH](chunk);
        if (this[BUFFERLENGTH] !== 0)
            this.emit('readable');
        if (cb)
            fn(cb);
        return this[FLOWING];
    }
    /**
     * Low-level explicit read method.
     *
     * In objectMode, the argument is ignored, and one item is returned if
     * available.
     *
     * `n` is the number of bytes (or in the case of encoding streams,
     * characters) to consume. If `n` is not provided, then the entire buffer
     * is returned, or `null` is returned if no data is available.
     *
     * If `n` is greater that the amount of data in the internal buffer,
     * then `null` is returned.
     */
    read(n) {
        if (this[DESTROYED])
            return null;
        this[DISCARDED] = false;
        if (this[BUFFERLENGTH] === 0 ||
            n === 0 ||
            (n && n > this[BUFFERLENGTH])) {
            this[MAYBE_EMIT_END]();
            return null;
        }
        if (this[OBJECTMODE])
            n = null;
        if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
            // not object mode, so if we have an encoding, then RType is string
            // otherwise, must be Buffer
            this[BUFFER] = [
                (this[ENCODING]
                    ? this[BUFFER].join('')
                    : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])),
            ];
        }
        const ret = this[READ](n || null, this[BUFFER][0]);
        this[MAYBE_EMIT_END]();
        return ret;
    }
    [READ](n, chunk) {
        if (this[OBJECTMODE])
            this[BUFFERSHIFT]();
        else {
            const c = chunk;
            if (n === c.length || n === null)
                this[BUFFERSHIFT]();
            else if (typeof c === 'string') {
                this[BUFFER][0] = c.slice(n);
                chunk = c.slice(0, n);
                this[BUFFERLENGTH] -= n;
            }
            else {
                this[BUFFER][0] = c.subarray(n);
                chunk = c.subarray(0, n);
                this[BUFFERLENGTH] -= n;
            }
        }
        this.emit('data', chunk);
        if (!this[BUFFER].length && !this[EOF])
            this.emit('drain');
        return chunk;
    }
    end(chunk, encoding, cb) {
        if (typeof chunk === 'function') {
            cb = chunk;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = 'utf8';
        }
        if (chunk !== undefined)
            this.write(chunk, encoding);
        if (cb)
            this.once('end', cb);
        this[EOF] = true;
        this.writable = false;
        // if we haven't written anything, then go ahead and emit,
        // even if we're not reading.
        // we'll re-emit if a new 'end' listener is added anyway.
        // This makes MP more suitable to write-only use cases.
        if (this[FLOWING] || !this[PAUSED])
            this[MAYBE_EMIT_END]();
        return this;
    }
    // don't let the internal resume be overwritten
    [RESUME]() {
        if (this[DESTROYED])
            return;
        if (!this[DATALISTENERS] && !this[PIPES].length) {
            this[DISCARDED] = true;
        }
        this[PAUSED] = false;
        this[FLOWING] = true;
        this.emit('resume');
        if (this[BUFFER].length)
            this[FLUSH]();
        else if (this[EOF])
            this[MAYBE_EMIT_END]();
        else
            this.emit('drain');
    }
    /**
     * Resume the stream if it is currently in a paused state
     *
     * If called when there are no pipe destinations or `data` event listeners,
     * this will place the stream in a "discarded" state, where all data will
     * be thrown away. The discarded state is removed if a pipe destination or
     * data handler is added, if pause() is called, or if any synchronous or
     * asynchronous iteration is started.
     */
    resume() {
        return this[RESUME]();
    }
    /**
     * Pause the stream
     */
    pause() {
        this[FLOWING] = false;
        this[PAUSED] = true;
        this[DISCARDED] = false;
    }
    /**
     * true if the stream has been forcibly destroyed
     */
    get destroyed() {
        return this[DESTROYED];
    }
    /**
     * true if the stream is currently in a flowing state, meaning that
     * any writes will be immediately emitted.
     */
    get flowing() {
        return this[FLOWING];
    }
    /**
     * true if the stream is currently in a paused state
     */
    get paused() {
        return this[PAUSED];
    }
    [BUFFERPUSH](chunk) {
        if (this[OBJECTMODE])
            this[BUFFERLENGTH] += 1;
        else
            this[BUFFERLENGTH] += chunk.length;
        this[BUFFER].push(chunk);
    }
    [BUFFERSHIFT]() {
        if (this[OBJECTMODE])
            this[BUFFERLENGTH] -= 1;
        else
            this[BUFFERLENGTH] -= this[BUFFER][0].length;
        return this[BUFFER].shift();
    }
    [FLUSH](noDrain = false) {
        do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&
            this[BUFFER].length);
        if (!noDrain && !this[BUFFER].length && !this[EOF])
            this.emit('drain');
    }
    [FLUSHCHUNK](chunk) {
        this.emit('data', chunk);
        return this[FLOWING];
    }
    /**
     * Pipe all data emitted by this stream into the destination provided.
     *
     * Triggers the flow of data.
     */
    pipe(dest, opts) {
        if (this[DESTROYED])
            return dest;
        this[DISCARDED] = false;
        const ended = this[EMITTED_END];
        opts = opts || {};
        if (dest === proc.stdout || dest === proc.stderr)
            opts.end = false;
        else
            opts.end = opts.end !== false;
        opts.proxyErrors = !!opts.proxyErrors;
        // piping an ended stream ends immediately
        if (ended) {
            if (opts.end)
                dest.end();
        }
        else {
            // "as" here just ignores the WType, which pipes don't care about,
            // since they're only consuming from us, and writing to the dest
            this[PIPES].push(!opts.proxyErrors
                ? new Pipe(this, dest, opts)
                : new PipeProxyErrors(this, dest, opts));
            if (this[ASYNC])
                defer(() => this[RESUME]());
            else
                this[RESUME]();
        }
        return dest;
    }
    /**
     * Fully unhook a piped destination stream.
     *
     * If the destination stream was the only consumer of this stream (ie,
     * there are no other piped destinations or `'data'` event listeners)
     * then the flow of data will stop until there is another consumer or
     * {@link Minipass#resume} is explicitly called.
     */
    unpipe(dest) {
        const p = this[PIPES].find(p => p.dest === dest);
        if (p) {
            if (this[PIPES].length === 1) {
                if (this[FLOWING] && this[DATALISTENERS] === 0) {
                    this[FLOWING] = false;
                }
                this[PIPES] = [];
            }
            else
                this[PIPES].splice(this[PIPES].indexOf(p), 1);
            p.unpipe();
        }
    }
    /**
     * Alias for {@link Minipass#on}
     */
    addListener(ev, handler) {
        return this.on(ev, handler);
    }
    /**
     * Mostly identical to `EventEmitter.on`, with the following
     * behavior differences to prevent data loss and unnecessary hangs:
     *
     * - Adding a 'data' event handler will trigger the flow of data
     *
     * - Adding a 'readable' event handler when there is data waiting to be read
     *   will cause 'readable' to be emitted immediately.
     *
     * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
     *   already passed will cause the event to be emitted immediately and all
     *   handlers removed.
     *
     * - Adding an 'error' event handler after an error has been emitted will
     *   cause the event to be re-emitted immediately with the error previously
     *   raised.
     */
    on(ev, handler) {
        const ret = super.on(ev, handler);
        if (ev === 'data') {
            this[DISCARDED] = false;
            this[DATALISTENERS]++;
            if (!this[PIPES].length && !this[FLOWING]) {
                this[RESUME]();
            }
        }
        else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {
            super.emit('readable');
        }
        else if (isEndish(ev) && this[EMITTED_END]) {
            super.emit(ev);
            this.removeAllListeners(ev);
        }
        else if (ev === 'error' && this[EMITTED_ERROR]) {
            const h = handler;
            if (this[ASYNC])
                defer(() => h.call(this, this[EMITTED_ERROR]));
            else
                h.call(this, this[EMITTED_ERROR]);
        }
        return ret;
    }
    /**
     * Alias for {@link Minipass#off}
     */
    removeListener(ev, handler) {
        return this.off(ev, handler);
    }
    /**
     * Mostly identical to `EventEmitter.off`
     *
     * If a 'data' event handler is removed, and it was the last consumer
     * (ie, there are no pipe destinations or other 'data' event listeners),
     * then the flow of data will stop until there is another consumer or
     * {@link Minipass#resume} is explicitly called.
     */
    off(ev, handler) {
        const ret = super.off(ev, handler);
        // if we previously had listeners, and now we don't, and we don't
        // have any pipes, then stop the flow, unless it's been explicitly
        // put in a discarded flowing state via stream.resume().
        if (ev === 'data') {
            this[DATALISTENERS] = this.listeners('data').length;
            if (this[DATALISTENERS] === 0 &&
                !this[DISCARDED] &&
                !this[PIPES].length) {
                this[FLOWING] = false;
            }
        }
        return ret;
    }
    /**
     * Mostly identical to `EventEmitter.removeAllListeners`
     *
     * If all 'data' event handlers are removed, and they were the last consumer
     * (ie, there are no pipe destinations), then the flow of data will stop
     * until there is another consumer or {@link Minipass#resume} is explicitly
     * called.
     */
    removeAllListeners(ev) {
        const ret = super.removeAllListeners(ev);
        if (ev === 'data' || ev === undefined) {
            this[DATALISTENERS] = 0;
            if (!this[DISCARDED] && !this[PIPES].length) {
                this[FLOWING] = false;
            }
        }
        return ret;
    }
    /**
     * true if the 'end' event has been emitted
     */
    get emittedEnd() {
        return this[EMITTED_END];
    }
    [MAYBE_EMIT_END]() {
        if (!this[EMITTING_END] &&
            !this[EMITTED_END] &&
            !this[DESTROYED] &&
            this[BUFFER].length === 0 &&
            this[EOF]) {
            this[EMITTING_END] = true;
            this.emit('end');
            this.emit('prefinish');
            this.emit('finish');
            if (this[CLOSED])
                this.emit('close');
            this[EMITTING_END] = false;
        }
    }
    /**
     * Mostly identical to `EventEmitter.emit`, with the following
     * behavior differences to prevent data loss and unnecessary hangs:
     *
     * If the stream has been destroyed, and the event is something other
     * than 'close' or 'error', then `false` is returned and no handlers
     * are called.
     *
     * If the event is 'end', and has already been emitted, then the event
     * is ignored. If the stream is in a paused or non-flowing state, then
     * the event will be deferred until data flow resumes. If the stream is
     * async, then handlers will be called on the next tick rather than
     * immediately.
     *
     * If the event is 'close', and 'end' has not yet been emitted, then
     * the event will be deferred until after 'end' is emitted.
     *
     * If the event is 'error', and an AbortSignal was provided for the stream,
     * and there are no listeners, then the event is ignored, matching the
     * behavior of node core streams in the presense of an AbortSignal.
     *
     * If the event is 'finish' or 'prefinish', then all listeners will be
     * removed after emitting the event, to prevent double-firing.
     */
    emit(ev, ...args) {
        const data = args[0];
        // error and close are only events allowed after calling destroy()
        if (ev !== 'error' &&
            ev !== 'close' &&
            ev !== DESTROYED &&
            this[DESTROYED]) {
            return false;
        }
        else if (ev === 'data') {
            return !this[OBJECTMODE] && !data
                ? false
                : this[ASYNC]
                    ? (defer(() => this[EMITDATA](data)), true)
                    : this[EMITDATA](data);
        }
        else if (ev === 'end') {
            return this[EMITEND]();
        }
        else if (ev === 'close') {
            this[CLOSED] = true;
            // don't emit close before 'end' and 'finish'
            if (!this[EMITTED_END] && !this[DESTROYED])
                return false;
            const ret = super.emit('close');
            this.removeAllListeners('close');
            return ret;
        }
        else if (ev === 'error') {
            this[EMITTED_ERROR] = data;
            super.emit(ERROR, data);
            const ret = !this[SIGNAL] || this.listeners('error').length
                ? super.emit('error', data)
                : false;
            this[MAYBE_EMIT_END]();
            return ret;
        }
        else if (ev === 'resume') {
            const ret = super.emit('resume');
            this[MAYBE_EMIT_END]();
            return ret;
        }
        else if (ev === 'finish' || ev === 'prefinish') {
            const ret = super.emit(ev);
            this.removeAllListeners(ev);
            return ret;
        }
        // Some other unknown event
        const ret = super.emit(ev, ...args);
        this[MAYBE_EMIT_END]();
        return ret;
    }
    [EMITDATA](data) {
        for (const p of this[PIPES]) {
            if (p.dest.write(data) === false)
                this.pause();
        }
        const ret = this[DISCARDED] ? false : super.emit('data', data);
        this[MAYBE_EMIT_END]();
        return ret;
    }
    [EMITEND]() {
        if (this[EMITTED_END])
            return false;
        this[EMITTED_END] = true;
        this.readable = false;
        return this[ASYNC]
            ? (defer(() => this[EMITEND2]()), true)
            : this[EMITEND2]();
    }
    [EMITEND2]() {
        if (this[DECODER]) {
            const data = this[DECODER].end();
            if (data) {
                for (const p of this[PIPES]) {
                    p.dest.write(data);
                }
                if (!this[DISCARDED])
                    super.emit('data', data);
            }
        }
        for (const p of this[PIPES]) {
            p.end();
        }
        const ret = super.emit('end');
        this.removeAllListeners('end');
        return ret;
    }
    /**
     * Return a Promise that resolves to an array of all emitted data once
     * the stream ends.
     */
    async collect() {
        const buf = Object.assign([], {
            dataLength: 0,
        });
        if (!this[OBJECTMODE])
            buf.dataLength = 0;
        // set the promise first, in case an error is raised
        // by triggering the flow here.
        const p = this.promise();
        this.on('data', c => {
            buf.push(c);
            if (!this[OBJECTMODE])
                buf.dataLength += c.length;
        });
        await p;
        return buf;
    }
    /**
     * Return a Promise that resolves to the concatenation of all emitted data
     * once the stream ends.
     *
     * Not allowed on objectMode streams.
     */
    async concat() {
        if (this[OBJECTMODE]) {
            throw new Error('cannot concat in objectMode');
        }
        const buf = await this.collect();
        return (this[ENCODING]
            ? buf.join('')
            : Buffer.concat(buf, buf.dataLength));
    }
    /**
     * Return a void Promise that resolves once the stream ends.
     */
    async promise() {
        return new Promise((resolve, reject) => {
            this.on(DESTROYED, () => reject(new Error('stream destroyed')));
            this.on('error', er => reject(er));
            this.on('end', () => resolve());
        });
    }
    /**
     * Asynchronous `for await of` iteration.
     *
     * This will continue emitting all chunks until the stream terminates.
     */
    [Symbol.asyncIterator]() {
        // set this up front, in case the consumer doesn't call next()
        // right away.
        this[DISCARDED] = false;
        let stopped = false;
        const stop = async () => {
            this.pause();
            stopped = true;
            return { value: undefined, done: true };
        };
        const next = () => {
            if (stopped)
                return stop();
            const res = this.read();
            if (res !== null)
                return Promise.resolve({ done: false, value: res });
            if (this[EOF])
                return stop();
            let resolve;
            let reject;
            const onerr = (er) => {
                this.off('data', ondata);
                this.off('end', onend);
                this.off(DESTROYED, ondestroy);
                stop();
                reject(er);
            };
            const ondata = (value) => {
                this.off('error', onerr);
                this.off('end', onend);
                this.off(DESTROYED, ondestroy);
                this.pause();
                resolve({ value, done: !!this[EOF] });
            };
            const onend = () => {
                this.off('error', onerr);
                this.off('data', ondata);
                this.off(DESTROYED, ondestroy);
                stop();
                resolve({ done: true, value: undefined });
            };
            const ondestroy = () => onerr(new Error('stream destroyed'));
            return new Promise((res, rej) => {
                reject = rej;
                resolve = res;
                this.once(DESTROYED, ondestroy);
                this.once('error', onerr);
                this.once('end', onend);
                this.once('data', ondata);
            });
        };
        return {
            next,
            throw: stop,
            return: stop,
            [Symbol.asyncIterator]() {
                return this;
            },
        };
    }
    /**
     * Synchronous `for of` iteration.
     *
     * The iteration will terminate when the internal buffer runs out, even
     * if the stream has not yet terminated.
     */
    [Symbol.iterator]() {
        // set this up front, in case the consumer doesn't call next()
        // right away.
        this[DISCARDED] = false;
        let stopped = false;
        const stop = () => {
            this.pause();
            this.off(ERROR, stop);
            this.off(DESTROYED, stop);
            this.off('end', stop);
            stopped = true;
            return { done: true, value: undefined };
        };
        const next = () => {
            if (stopped)
                return stop();
            const value = this.read();
            return value === null ? stop() : { done: false, value };
        };
        this.once('end', stop);
        this.once(ERROR, stop);
        this.once(DESTROYED, stop);
        return {
            next,
            throw: stop,
            return: stop,
            [Symbol.iterator]() {
                return this;
            },
        };
    }
    /**
     * Destroy a stream, preventing it from being used for any further purpose.
     *
     * If the stream has a `close()` method, then it will be called on
     * destruction.
     *
     * After destruction, any attempt to write data, read data, or emit most
     * events will be ignored.
     *
     * If an error argument is provided, then it will be emitted in an
     * 'error' event.
     */
    destroy(er) {
        if (this[DESTROYED]) {
            if (er)
                this.emit('error', er);
            else
                this.emit(DESTROYED);
            return this;
        }
        this[DESTROYED] = true;
        this[DISCARDED] = true;
        // throw away all buffered data, it's never coming out
        this[BUFFER].length = 0;
        this[BUFFERLENGTH] = 0;
        const wc = this;
        if (typeof wc.close === 'function' && !this[CLOSED])
            wc.close();
        if (er)
            this.emit('error', er);
        // if no error to emit, still reject pending promises
        else
            this.emit(DESTROYED);
        return this;
    }
    /**
     * Alias for {@link isStream}
     *
     * Former export location, maintained for backwards compatibility.
     *
     * @deprecated
     */
    static get isStream() {
        return isStream;
    }
}
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "name": "minipass",
  "version": "7.1.2",
  "description": "minimal implementation of a PassThrough stream",
  "main": "./dist/commonjs/index.js",
  "types": "./dist/commonjs/index.d.ts",
  "type": "module",
  "tshy": {
    "selfLink": false,
    "main": true,
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "presnap": "npm run prepare",
    "test": "tap",
    "snap": "tap",
    "format": "prettier --write . --loglevel warn",
    "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
  },
  "prettier": {
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "devDependencies": {
    "@types/end-of-stream": "^1.4.2",
    "@types/node": "^20.1.2",
    "end-of-stream": "^1.4.0",
    "node-abort-controller": "^3.1.1",
    "prettier": "^2.6.2",
    "tap": "^19.0.0",
    "through2": "^2.0.3",
    "tshy": "^1.14.0",
    "typedoc": "^0.25.1"
  },
  "repository": "https://github.com/isaacs/minipass",
  "keywords": [
    "passthrough",
    "stream"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "ISC",
  "engines": {
    "node": ">=16 || 14 >=14.17"
  },
  "tap": {
    "typecheck": true,
    "include": [
      "test/*.ts"
    ]
  }
}
Minizlib was created by Isaac Z. Schlueter.
It is a derivative work of the Node.js project.

"""
Copyright Isaac Z. Schlueter and Contributors
Copyright Node.js contributors. All rights reserved.
Copyright Joyent, Inc. and other Node contributors. All rights reserved.

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.
"""
// Update with any zlib constants that are added or changed in the future.
// Node v6 didn't export this, so we just hard code the version and rely
// on all the other hard-coded values from zlib v4736.  When node v6
// support drops, we can just export the realZlibConstants object.
const realZlibConstants = require('zlib').constants ||
  /* istanbul ignore next */ { ZLIB_VERNUM: 4736 }

module.exports = Object.freeze(Object.assign(Object.create(null), {
  Z_NO_FLUSH: 0,
  Z_PARTIAL_FLUSH: 1,
  Z_SYNC_FLUSH: 2,
  Z_FULL_FLUSH: 3,
  Z_FINISH: 4,
  Z_BLOCK: 5,
  Z_OK: 0,
  Z_STREAM_END: 1,
  Z_NEED_DICT: 2,
  Z_ERRNO: -1,
  Z_STREAM_ERROR: -2,
  Z_DATA_ERROR: -3,
  Z_MEM_ERROR: -4,
  Z_BUF_ERROR: -5,
  Z_VERSION_ERROR: -6,
  Z_NO_COMPRESSION: 0,
  Z_BEST_SPEED: 1,
  Z_BEST_COMPRESSION: 9,
  Z_DEFAULT_COMPRESSION: -1,
  Z_FILTERED: 1,
  Z_HUFFMAN_ONLY: 2,
  Z_RLE: 3,
  Z_FIXED: 4,
  Z_DEFAULT_STRATEGY: 0,
  DEFLATE: 1,
  INFLATE: 2,
  GZIP: 3,
  GUNZIP: 4,
  DEFLATERAW: 5,
  INFLATERAW: 6,
  UNZIP: 7,
  BROTLI_DECODE: 8,
  BROTLI_ENCODE: 9,
  Z_MIN_WINDOWBITS: 8,
  Z_MAX_WINDOWBITS: 15,
  Z_DEFAULT_WINDOWBITS: 15,
  Z_MIN_CHUNK: 64,
  Z_MAX_CHUNK: Infinity,
  Z_DEFAULT_CHUNK: 16384,
  Z_MIN_MEMLEVEL: 1,
  Z_MAX_MEMLEVEL: 9,
  Z_DEFAULT_MEMLEVEL: 8,
  Z_MIN_LEVEL: -1,
  Z_MAX_LEVEL: 9,
  Z_DEFAULT_LEVEL: -1,
  BROTLI_OPERATION_PROCESS: 0,
  BROTLI_OPERATION_FLUSH: 1,
  BROTLI_OPERATION_FINISH: 2,
  BROTLI_OPERATION_EMIT_METADATA: 3,
  BROTLI_MODE_GENERIC: 0,
  BROTLI_MODE_TEXT: 1,
  BROTLI_MODE_FONT: 2,
  BROTLI_DEFAULT_MODE: 0,
  BROTLI_MIN_QUALITY: 0,
  BROTLI_MAX_QUALITY: 11,
  BROTLI_DEFAULT_QUALITY: 11,
  BROTLI_MIN_WINDOW_BITS: 10,
  BROTLI_MAX_WINDOW_BITS: 24,
  BROTLI_LARGE_MAX_WINDOW_BITS: 30,
  BROTLI_DEFAULT_WINDOW: 22,
  BROTLI_MIN_INPUT_BLOCK_BITS: 16,
  BROTLI_MAX_INPUT_BLOCK_BITS: 24,
  BROTLI_PARAM_MODE: 0,
  BROTLI_PARAM_QUALITY: 1,
  BROTLI_PARAM_LGWIN: 2,
  BROTLI_PARAM_LGBLOCK: 3,
  BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
  BROTLI_PARAM_SIZE_HINT: 5,
  BROTLI_PARAM_LARGE_WINDOW: 6,
  BROTLI_PARAM_NPOSTFIX: 7,
  BROTLI_PARAM_NDIRECT: 8,
  BROTLI_DECODER_RESULT_ERROR: 0,
  BROTLI_DECODER_RESULT_SUCCESS: 1,
  BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
  BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
  BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
  BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
  BROTLI_DECODER_NO_ERROR: 0,
  BROTLI_DECODER_SUCCESS: 1,
  BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
  BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
  BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
  BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
  BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
  BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
  BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
  BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
  BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
  BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
  BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
  BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
  BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
  BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
  BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
  BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
  BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
  BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
  BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
  BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
  BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
  BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
  BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
  BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
  BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
  BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
  BROTLI_DECODER_ERROR_UNREACHABLE: -31,
}, realZlibConstants))
'use strict'

const assert = require('assert')
const Buffer = require('buffer').Buffer
const realZlib = require('zlib')

const constants = exports.constants = require('./constants.js')
const Minipass = require('minipass')

const OriginalBufferConcat = Buffer.concat

const _superWrite = Symbol('_superWrite')
class ZlibError extends Error {
  constructor (err) {
    super('zlib: ' + err.message)
    this.code = err.code
    this.errno = err.errno
    /* istanbul ignore if */
    if (!this.code)
      this.code = 'ZLIB_ERROR'

    this.message = 'zlib: ' + err.message
    Error.captureStackTrace(this, this.constructor)
  }

  get name () {
    return 'ZlibError'
  }
}

// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
const _opts = Symbol('opts')
const _flushFlag = Symbol('flushFlag')
const _finishFlushFlag = Symbol('finishFlushFlag')
const _fullFlushFlag = Symbol('fullFlushFlag')
const _handle = Symbol('handle')
const _onError = Symbol('onError')
const _sawError = Symbol('sawError')
const _level = Symbol('level')
const _strategy = Symbol('strategy')
const _ended = Symbol('ended')
const _defaultFullFlush = Symbol('_defaultFullFlush')

class ZlibBase extends Minipass {
  constructor (opts, mode) {
    if (!opts || typeof opts !== 'object')
      throw new TypeError('invalid options for ZlibBase constructor')

    super(opts)
    this[_sawError] = false
    this[_ended] = false
    this[_opts] = opts

    this[_flushFlag] = opts.flush
    this[_finishFlushFlag] = opts.finishFlush
    // this will throw if any options are invalid for the class selected
    try {
      this[_handle] = new realZlib[mode](opts)
    } catch (er) {
      // make sure that all errors get decorated properly
      throw new ZlibError(er)
    }

    this[_onError] = (err) => {
      // no sense raising multiple errors, since we abort on the first one.
      if (this[_sawError])
        return

      this[_sawError] = true

      // there is no way to cleanly recover.
      // continuing only obscures problems.
      this.close()
      this.emit('error', err)
    }

    this[_handle].on('error', er => this[_onError](new ZlibError(er)))
    this.once('end', () => this.close)
  }

  close () {
    if (this[_handle]) {
      this[_handle].close()
      this[_handle] = null
      this.emit('close')
    }
  }

  reset () {
    if (!this[_sawError]) {
      assert(this[_handle], 'zlib binding closed')
      return this[_handle].reset()
    }
  }

  flush (flushFlag) {
    if (this.ended)
      return

    if (typeof flushFlag !== 'number')
      flushFlag = this[_fullFlushFlag]
    this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }))
  }

  end (chunk, encoding, cb) {
    if (chunk)
      this.write(chunk, encoding)
    this.flush(this[_finishFlushFlag])
    this[_ended] = true
    return super.end(null, null, cb)
  }

  get ended () {
    return this[_ended]
  }

  write (chunk, encoding, cb) {
    // process the chunk using the sync process
    // then super.write() all the outputted chunks
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'

    if (typeof chunk === 'string')
      chunk = Buffer.from(chunk, encoding)

    if (this[_sawError])
      return
    assert(this[_handle], 'zlib binding closed')

    // _processChunk tries to .close() the native handle after it's done, so we
    // intercept that by temporarily making it a no-op.
    const nativeHandle = this[_handle]._handle
    const originalNativeClose = nativeHandle.close
    nativeHandle.close = () => {}
    const originalClose = this[_handle].close
    this[_handle].close = () => {}
    // It also calls `Buffer.concat()` at the end, which may be convenient
    // for some, but which we are not interested in as it slows us down.
    Buffer.concat = (args) => args
    let result
    try {
      const flushFlag = typeof chunk[_flushFlag] === 'number'
        ? chunk[_flushFlag] : this[_flushFlag]
      result = this[_handle]._processChunk(chunk, flushFlag)
      // if we don't throw, reset it back how it was
      Buffer.concat = OriginalBufferConcat
    } catch (err) {
      // or if we do, put Buffer.concat() back before we emit error
      // Error events call into user code, which may call Buffer.concat()
      Buffer.concat = OriginalBufferConcat
      this[_onError](new ZlibError(err))
    } finally {
      if (this[_handle]) {
        // Core zlib resets `_handle` to null after attempting to close the
        // native handle. Our no-op handler prevented actual closure, but we
        // need to restore the `._handle` property.
        this[_handle]._handle = nativeHandle
        nativeHandle.close = originalNativeClose
        this[_handle].close = originalClose
        // `_processChunk()` adds an 'error' listener. If we don't remove it
        // after each call, these handlers start piling up.
        this[_handle].removeAllListeners('error')
        // make sure OUR error listener is still attached tho
      }
    }

    if (this[_handle])
      this[_handle].on('error', er => this[_onError](new ZlibError(er)))

    let writeReturn
    if (result) {
      if (Array.isArray(result) && result.length > 0) {
        // The first buffer is always `handle._outBuffer`, which would be
        // re-used for later invocations; so, we always have to copy that one.
        // The last buffer may also be `handle._outBuffer` (if the output
        // didn't fill it completely), so copy it too.  In the WASM/ABSYNC
        // environment, subsequent writeSync() calls create a new WASM mirror
        // for the same ArrayBuffer and ABSYNC_SYNC overwrites the entire JS
        // ArrayBuffer, corrupting any un-copied views.
        // Safest: copy every chunk.
        for (let i = 0; i < result.length; i++) {
          writeReturn = this[_superWrite](Buffer.from(result[i]))
        }
      } else {
        writeReturn = this[_superWrite](Buffer.from(result))
      }
    }

    if (cb)
      cb()
    return writeReturn
  }

  [_superWrite] (data) {
    return super.write(data)
  }
}

class Zlib extends ZlibBase {
  constructor (opts, mode) {
    opts = opts || {}

    opts.flush = opts.flush || constants.Z_NO_FLUSH
    opts.finishFlush = opts.finishFlush || constants.Z_FINISH
    super(opts, mode)

    this[_fullFlushFlag] = constants.Z_FULL_FLUSH
    this[_level] = opts.level
    this[_strategy] = opts.strategy
  }

  params (level, strategy) {
    if (this[_sawError])
      return

    if (!this[_handle])
      throw new Error('cannot switch params when binding is closed')

    // no way to test this without also not supporting params at all
    /* istanbul ignore if */
    if (!this[_handle].params)
      throw new Error('not supported in this implementation')

    if (this[_level] !== level || this[_strategy] !== strategy) {
      this.flush(constants.Z_SYNC_FLUSH)
      assert(this[_handle], 'zlib binding closed')
      // .params() calls .flush(), but the latter is always async in the
      // core zlib. We override .flush() temporarily to intercept that and
      // flush synchronously.
      const origFlush = this[_handle].flush
      this[_handle].flush = (flushFlag, cb) => {
        this.flush(flushFlag)
        cb()
      }
      try {
        this[_handle].params(level, strategy)
      } finally {
        this[_handle].flush = origFlush
      }
      /* istanbul ignore else */
      if (this[_handle]) {
        this[_level] = level
        this[_strategy] = strategy
      }
    }
  }
}

// minimal 2-byte header
class Deflate extends Zlib {
  constructor (opts) {
    super(opts, 'Deflate')
  }
}

class Inflate extends Zlib {
  constructor (opts) {
    super(opts, 'Inflate')
  }
}

// gzip - bigger header, same deflate compression
const _portable = Symbol('_portable')
class Gzip extends Zlib {
  constructor (opts) {
    super(opts, 'Gzip')
    this[_portable] = opts && !!opts.portable
  }

  [_superWrite] (data) {
    if (!this[_portable])
      return super[_superWrite](data)

    // we'll always get the header emitted in one first chunk
    // overwrite the OS indicator byte with 0xFF
    this[_portable] = false
    data[9] = 255
    return super[_superWrite](data)
  }
}

class Gunzip extends Zlib {
  constructor (opts) {
    super(opts, 'Gunzip')
  }
}

// raw - no header
class DeflateRaw extends Zlib {
  constructor (opts) {
    super(opts, 'DeflateRaw')
  }
}

class InflateRaw extends Zlib {
  constructor (opts) {
    super(opts, 'InflateRaw')
  }
}

// auto-detect header.
class Unzip extends Zlib {
  constructor (opts) {
    super(opts, 'Unzip')
  }
}

class Brotli extends ZlibBase {
  constructor (opts, mode) {
    opts = opts || {}

    opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS
    opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH

    super(opts, mode)

    this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH
  }
}

class BrotliCompress extends Brotli {
  constructor (opts) {
    super(opts, 'BrotliCompress')
  }
}

class BrotliDecompress extends Brotli {
  constructor (opts) {
    super(opts, 'BrotliDecompress')
  }
}

exports.Deflate = Deflate
exports.Inflate = Inflate
exports.Gzip = Gzip
exports.Gunzip = Gunzip
exports.DeflateRaw = DeflateRaw
exports.InflateRaw = InflateRaw
exports.Unzip = Unzip
/* istanbul ignore else */
if (typeof realZlib.BrotliCompress === 'function') {
  exports.BrotliCompress = BrotliCompress
  exports.BrotliDecompress = BrotliDecompress
} else {
  exports.BrotliCompress = exports.BrotliDecompress = class {
    constructor () {
      throw new Error('Brotli is not supported in this version of Node.js')
    }
  }
}
The ISC License

Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'
const proc = typeof process === 'object' && process ? process : {
  stdout: null,
  stderr: null,
}
const EE = require('events')
const Stream = require('stream')
const SD = require('string_decoder').StringDecoder

const EOF = Symbol('EOF')
const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
const EMITTED_END = Symbol('emittedEnd')
const EMITTING_END = Symbol('emittingEnd')
const EMITTED_ERROR = Symbol('emittedError')
const CLOSED = Symbol('closed')
const READ = Symbol('read')
const FLUSH = Symbol('flush')
const FLUSHCHUNK = Symbol('flushChunk')
const ENCODING = Symbol('encoding')
const DECODER = Symbol('decoder')
const FLOWING = Symbol('flowing')
const PAUSED = Symbol('paused')
const RESUME = Symbol('resume')
const BUFFERLENGTH = Symbol('bufferLength')
const BUFFERPUSH = Symbol('bufferPush')
const BUFFERSHIFT = Symbol('bufferShift')
const OBJECTMODE = Symbol('objectMode')
const DESTROYED = Symbol('destroyed')
const EMITDATA = Symbol('emitData')
const EMITEND = Symbol('emitEnd')
const EMITEND2 = Symbol('emitEnd2')
const ASYNC = Symbol('async')

const defer = fn => Promise.resolve().then(fn)

// TODO remove when Node v8 support drops
const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
const ASYNCITERATOR = doIter && Symbol.asyncIterator
  || Symbol('asyncIterator not implemented')
const ITERATOR = doIter && Symbol.iterator
  || Symbol('iterator not implemented')

// events that mean 'the stream is over'
// these are treated specially, and re-emitted
// if they are listened for after emitting.
const isEndish = ev =>
  ev === 'end' ||
  ev === 'finish' ||
  ev === 'prefinish'

const isArrayBuffer = b => b instanceof ArrayBuffer ||
  typeof b === 'object' &&
  b.constructor &&
  b.constructor.name === 'ArrayBuffer' &&
  b.byteLength >= 0

const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)

class Pipe {
  constructor (src, dest, opts) {
    this.src = src
    this.dest = dest
    this.opts = opts
    this.ondrain = () => src[RESUME]()
    dest.on('drain', this.ondrain)
  }
  unpipe () {
    this.dest.removeListener('drain', this.ondrain)
  }
  // istanbul ignore next - only here for the prototype
  proxyErrors () {}
  end () {
    this.unpipe()
    if (this.opts.end)
      this.dest.end()
  }
}

class PipeProxyErrors extends Pipe {
  unpipe () {
    this.src.removeListener('error', this.proxyErrors)
    super.unpipe()
  }
  constructor (src, dest, opts) {
    super(src, dest, opts)
    this.proxyErrors = er => dest.emit('error', er)
    src.on('error', this.proxyErrors)
  }
}

module.exports = class Minipass extends Stream {
  constructor (options) {
    super()
    this[FLOWING] = false
    // whether we're explicitly paused
    this[PAUSED] = false
    this.pipes = []
    this.buffer = []
    this[OBJECTMODE] = options && options.objectMode || false
    if (this[OBJECTMODE])
      this[ENCODING] = null
    else
      this[ENCODING] = options && options.encoding || null
    if (this[ENCODING] === 'buffer')
      this[ENCODING] = null
    this[ASYNC] = options && !!options.async || false
    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
    this[EOF] = false
    this[EMITTED_END] = false
    this[EMITTING_END] = false
    this[CLOSED] = false
    this[EMITTED_ERROR] = null
    this.writable = true
    this.readable = true
    this[BUFFERLENGTH] = 0
    this[DESTROYED] = false
  }

  get bufferLength () { return this[BUFFERLENGTH] }

  get encoding () { return this[ENCODING] }
  set encoding (enc) {
    if (this[OBJECTMODE])
      throw new Error('cannot set encoding in objectMode')

    if (this[ENCODING] && enc !== this[ENCODING] &&
        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
      throw new Error('cannot change encoding')

    if (this[ENCODING] !== enc) {
      this[DECODER] = enc ? new SD(enc) : null
      if (this.buffer.length)
        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
    }

    this[ENCODING] = enc
  }

  setEncoding (enc) {
    this.encoding = enc
  }

  get objectMode () { return this[OBJECTMODE] }
  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }

  get ['async'] () { return this[ASYNC] }
  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }

  write (chunk, encoding, cb) {
    if (this[EOF])
      throw new Error('write after end')

    if (this[DESTROYED]) {
      this.emit('error', Object.assign(
        new Error('Cannot call write after a stream was destroyed'),
        { code: 'ERR_STREAM_DESTROYED' }
      ))
      return true
    }

    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'

    if (!encoding)
      encoding = 'utf8'

    const fn = this[ASYNC] ? defer : f => f()

    // convert array buffers and typed array views into buffers
    // at some point in the future, we may want to do the opposite!
    // leave strings and buffers as-is
    // anything else switches us into object mode
    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
      if (isArrayBufferView(chunk))
        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
      else if (isArrayBuffer(chunk))
        chunk = Buffer.from(chunk)
      else if (typeof chunk !== 'string')
        // use the setter so we throw if we have encoding set
        this.objectMode = true
    }

    // handle object mode up front, since it's simpler
    // this yields better performance, fewer checks later.
    if (this[OBJECTMODE]) {
      /* istanbul ignore if - maybe impossible? */
      if (this.flowing && this[BUFFERLENGTH] !== 0)
        this[FLUSH](true)

      if (this.flowing)
        this.emit('data', chunk)
      else
        this[BUFFERPUSH](chunk)

      if (this[BUFFERLENGTH] !== 0)
        this.emit('readable')

      if (cb)
        fn(cb)

      return this.flowing
    }

    // at this point the chunk is a buffer or string
    // don't buffer it up or send it to the decoder
    if (!chunk.length) {
      if (this[BUFFERLENGTH] !== 0)
        this.emit('readable')
      if (cb)
        fn(cb)
      return this.flowing
    }

    // fast-path writing strings of same encoding to a stream with
    // an empty buffer, skipping the buffer/decoder dance
    if (typeof chunk === 'string' &&
        // unless it is a string already ready for us to use
        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
      chunk = Buffer.from(chunk, encoding)
    }

    if (Buffer.isBuffer(chunk) && this[ENCODING])
      chunk = this[DECODER].write(chunk)

    // Note: flushing CAN potentially switch us into not-flowing mode
    if (this.flowing && this[BUFFERLENGTH] !== 0)
      this[FLUSH](true)

    if (this.flowing)
      this.emit('data', chunk)
    else
      this[BUFFERPUSH](chunk)

    if (this[BUFFERLENGTH] !== 0)
      this.emit('readable')

    if (cb)
      fn(cb)

    return this.flowing
  }

  read (n) {
    if (this[DESTROYED])
      return null

    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
      this[MAYBE_EMIT_END]()
      return null
    }

    if (this[OBJECTMODE])
      n = null

    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
      if (this.encoding)
        this.buffer = [this.buffer.join('')]
      else
        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
    }

    const ret = this[READ](n || null, this.buffer[0])
    this[MAYBE_EMIT_END]()
    return ret
  }

  [READ] (n, chunk) {
    if (n === chunk.length || n === null)
      this[BUFFERSHIFT]()
    else {
      this.buffer[0] = chunk.slice(n)
      chunk = chunk.slice(0, n)
      this[BUFFERLENGTH] -= n
    }

    this.emit('data', chunk)

    if (!this.buffer.length && !this[EOF])
      this.emit('drain')

    return chunk
  }

  end (chunk, encoding, cb) {
    if (typeof chunk === 'function')
      cb = chunk, chunk = null
    if (typeof encoding === 'function')
      cb = encoding, encoding = 'utf8'
    if (chunk)
      this.write(chunk, encoding)
    if (cb)
      this.once('end', cb)
    this[EOF] = true
    this.writable = false

    // if we haven't written anything, then go ahead and emit,
    // even if we're not reading.
    // we'll re-emit if a new 'end' listener is added anyway.
    // This makes MP more suitable to write-only use cases.
    if (this.flowing || !this[PAUSED])
      this[MAYBE_EMIT_END]()
    return this
  }

  // don't let the internal resume be overwritten
  [RESUME] () {
    if (this[DESTROYED])
      return

    this[PAUSED] = false
    this[FLOWING] = true
    this.emit('resume')
    if (this.buffer.length)
      this[FLUSH]()
    else if (this[EOF])
      this[MAYBE_EMIT_END]()
    else
      this.emit('drain')
  }

  resume () {
    return this[RESUME]()
  }

  pause () {
    this[FLOWING] = false
    this[PAUSED] = true
  }

  get destroyed () {
    return this[DESTROYED]
  }

  get flowing () {
    return this[FLOWING]
  }

  get paused () {
    return this[PAUSED]
  }

  [BUFFERPUSH] (chunk) {
    if (this[OBJECTMODE])
      this[BUFFERLENGTH] += 1
    else
      this[BUFFERLENGTH] += chunk.length
    this.buffer.push(chunk)
  }

  [BUFFERSHIFT] () {
    if (this.buffer.length) {
      if (this[OBJECTMODE])
        this[BUFFERLENGTH] -= 1
      else
        this[BUFFERLENGTH] -= this.buffer[0].length
    }
    return this.buffer.shift()
  }

  [FLUSH] (noDrain) {
    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))

    if (!noDrain && !this.buffer.length && !this[EOF])
      this.emit('drain')
  }

  [FLUSHCHUNK] (chunk) {
    return chunk ? (this.emit('data', chunk), this.flowing) : false
  }

  pipe (dest, opts) {
    if (this[DESTROYED])
      return

    const ended = this[EMITTED_END]
    opts = opts || {}
    if (dest === proc.stdout || dest === proc.stderr)
      opts.end = false
    else
      opts.end = opts.end !== false
    opts.proxyErrors = !!opts.proxyErrors

    // piping an ended stream ends immediately
    if (ended) {
      if (opts.end)
        dest.end()
    } else {
      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
        : new PipeProxyErrors(this, dest, opts))
      if (this[ASYNC])
        defer(() => this[RESUME]())
      else
        this[RESUME]()
    }

    return dest
  }

  unpipe (dest) {
    const p = this.pipes.find(p => p.dest === dest)
    if (p) {
      this.pipes.splice(this.pipes.indexOf(p), 1)
      p.unpipe()
    }
  }

  addListener (ev, fn) {
    return this.on(ev, fn)
  }

  on (ev, fn) {
    const ret = super.on(ev, fn)
    if (ev === 'data' && !this.pipes.length && !this.flowing)
      this[RESUME]()
    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
      super.emit('readable')
    else if (isEndish(ev) && this[EMITTED_END]) {
      super.emit(ev)
      this.removeAllListeners(ev)
    } else if (ev === 'error' && this[EMITTED_ERROR]) {
      if (this[ASYNC])
        defer(() => fn.call(this, this[EMITTED_ERROR]))
      else
        fn.call(this, this[EMITTED_ERROR])
    }
    return ret
  }

  get emittedEnd () {
    return this[EMITTED_END]
  }

  [MAYBE_EMIT_END] () {
    if (!this[EMITTING_END] &&
        !this[EMITTED_END] &&
        !this[DESTROYED] &&
        this.buffer.length === 0 &&
        this[EOF]) {
      this[EMITTING_END] = true
      this.emit('end')
      this.emit('prefinish')
      this.emit('finish')
      if (this[CLOSED])
        this.emit('close')
      this[EMITTING_END] = false
    }
  }

  emit (ev, data, ...extra) {
    // error and close are only events allowed after calling destroy()
    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
      return
    else if (ev === 'data') {
      return !data ? false
        : this[ASYNC] ? defer(() => this[EMITDATA](data))
        : this[EMITDATA](data)
    } else if (ev === 'end') {
      return this[EMITEND]()
    } else if (ev === 'close') {
      this[CLOSED] = true
      // don't emit close before 'end' and 'finish'
      if (!this[EMITTED_END] && !this[DESTROYED])
        return
      const ret = super.emit('close')
      this.removeAllListeners('close')
      return ret
    } else if (ev === 'error') {
      this[EMITTED_ERROR] = data
      const ret = super.emit('error', data)
      this[MAYBE_EMIT_END]()
      return ret
    } else if (ev === 'resume') {
      const ret = super.emit('resume')
      this[MAYBE_EMIT_END]()
      return ret
    } else if (ev === 'finish' || ev === 'prefinish') {
      const ret = super.emit(ev)
      this.removeAllListeners(ev)
      return ret
    }

    // Some other unknown event
    const ret = super.emit(ev, data, ...extra)
    this[MAYBE_EMIT_END]()
    return ret
  }

  [EMITDATA] (data) {
    for (const p of this.pipes) {
      if (p.dest.write(data) === false)
        this.pause()
    }
    const ret = super.emit('data', data)
    this[MAYBE_EMIT_END]()
    return ret
  }

  [EMITEND] () {
    if (this[EMITTED_END])
      return

    this[EMITTED_END] = true
    this.readable = false
    if (this[ASYNC])
      defer(() => this[EMITEND2]())
    else
      this[EMITEND2]()
  }

  [EMITEND2] () {
    if (this[DECODER]) {
      const data = this[DECODER].end()
      if (data) {
        for (const p of this.pipes) {
          p.dest.write(data)
        }
        super.emit('data', data)
      }
    }

    for (const p of this.pipes) {
      p.end()
    }
    const ret = super.emit('end')
    this.removeAllListeners('end')
    return ret
  }

  // const all = await stream.collect()
  collect () {
    const buf = []
    if (!this[OBJECTMODE])
      buf.dataLength = 0
    // set the promise first, in case an error is raised
    // by triggering the flow here.
    const p = this.promise()
    this.on('data', c => {
      buf.push(c)
      if (!this[OBJECTMODE])
        buf.dataLength += c.length
    })
    return p.then(() => buf)
  }

  // const data = await stream.concat()
  concat () {
    return this[OBJECTMODE]
      ? Promise.reject(new Error('cannot concat in objectMode'))
      : this.collect().then(buf =>
          this[OBJECTMODE]
            ? Promise.reject(new Error('cannot concat in objectMode'))
            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
  }

  // stream.promise().then(() => done, er => emitted error)
  promise () {
    return new Promise((resolve, reject) => {
      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
      this.on('error', er => reject(er))
      this.on('end', () => resolve())
    })
  }

  // for await (let chunk of stream)
  [ASYNCITERATOR] () {
    const next = () => {
      const res = this.read()
      if (res !== null)
        return Promise.resolve({ done: false, value: res })

      if (this[EOF])
        return Promise.resolve({ done: true })

      let resolve = null
      let reject = null
      const onerr = er => {
        this.removeListener('data', ondata)
        this.removeListener('end', onend)
        reject(er)
      }
      const ondata = value => {
        this.removeListener('error', onerr)
        this.removeListener('end', onend)
        this.pause()
        resolve({ value: value, done: !!this[EOF] })
      }
      const onend = () => {
        this.removeListener('error', onerr)
        this.removeListener('data', ondata)
        resolve({ done: true })
      }
      const ondestroy = () => onerr(new Error('stream destroyed'))
      return new Promise((res, rej) => {
        reject = rej
        resolve = res
        this.once(DESTROYED, ondestroy)
        this.once('error', onerr)
        this.once('end', onend)
        this.once('data', ondata)
      })
    }

    return { next }
  }

  // for (let chunk of stream)
  [ITERATOR] () {
    const next = () => {
      const value = this.read()
      const done = value === null
      return { value, done }
    }
    return { next }
  }

  destroy (er) {
    if (this[DESTROYED]) {
      if (er)
        this.emit('error', er)
      else
        this.emit(DESTROYED)
      return this
    }

    this[DESTROYED] = true

    // throw away all buffered data, it's never coming out
    this.buffer.length = 0
    this[BUFFERLENGTH] = 0

    if (typeof this.close === 'function' && !this[CLOSED])
      this.close()

    if (er)
      this.emit('error', er)
    else // if no error to emit, still reject pending promises
      this.emit(DESTROYED)

    return this
  }

  static isStream (s) {
    return !!s && (s instanceof Minipass || s instanceof Stream ||
      s instanceof EE && (
        typeof s.pipe === 'function' || // readable
        (typeof s.write === 'function' && typeof s.end === 'function') // writable
      ))
  }
}
{
  "name": "minipass",
  "version": "3.3.6",
  "description": "minimal implementation of a PassThrough stream",
  "main": "index.js",
  "types": "index.d.ts",
  "dependencies": {
    "yallist": "^4.0.0"
  },
  "devDependencies": {
    "@types/node": "^17.0.41",
    "end-of-stream": "^1.4.0",
    "prettier": "^2.6.2",
    "tap": "^16.2.0",
    "through2": "^2.0.3",
    "ts-node": "^10.8.1",
    "typescript": "^4.7.3"
  },
  "scripts": {
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --follow-tags"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minipass.git"
  },
  "keywords": [
    "passthrough",
    "stream"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "ISC",
  "files": [
    "index.d.ts",
    "index.js"
  ],
  "tap": {
    "check-coverage": true
  },
  "engines": {
    "node": ">=8"
  },
  "prettier": {
    "semi": false,
    "printWidth": 80,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  }
}
{
  "name": "minizlib",
  "version": "2.1.2",
  "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.",
  "main": "index.js",
  "dependencies": {
    "minipass": "^3.0.0",
    "yallist": "^4.0.0"
  },
  "scripts": {
    "test": "tap test/*.js --100 -J",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --all; git push origin --tags"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minizlib.git"
  },
  "keywords": [
    "zlib",
    "gzip",
    "gunzip",
    "deflate",
    "inflate",
    "compression",
    "zip",
    "unzip"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "MIT",
  "devDependencies": {
    "tap": "^14.6.9"
  },
  "files": [
    "index.js",
    "constants.js"
  ],
  "engines": {
    "node": ">= 8"
  }
}
Copyright James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me)

This project is free software released under the MIT license:

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.
#!/usr/bin/env node

const usage = () => `
usage: mkdirp [DIR1,DIR2..] {OPTIONS}

  Create each supplied directory including any necessary parent directories
  that don't yet exist.

  If the directory already exists, do nothing.

OPTIONS are:

  -m       If a directory needs to be created, set the mode as an octal
  --mode=  permission string.

  -v --version   Print the mkdirp version number

  -h --help      Print this helpful banner

  -p --print     Print the first directories created for each path provided

  --manual       Use manual implementation, even if native is available
`

const dirs = []
const opts = {}
let print = false
let dashdash = false
let manual = false
for (const arg of process.argv.slice(2)) {
  if (dashdash)
    dirs.push(arg)
  else if (arg === '--')
    dashdash = true
  else if (arg === '--manual')
    manual = true
  else if (/^-h/.test(arg) || /^--help/.test(arg)) {
    console.log(usage())
    process.exit(0)
  } else if (arg === '-v' || arg === '--version') {
    console.log(require('../package.json').version)
    process.exit(0)
  } else if (arg === '-p' || arg === '--print') {
    print = true
  } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) {
    const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8)
    if (isNaN(mode)) {
      console.error(`invalid mode argument: ${arg}\nMust be an octal number.`)
      process.exit(1)
    }
    opts.mode = mode
  } else
    dirs.push(arg)
}

const mkdirp = require('../')
const impl = manual ? mkdirp.manual : mkdirp
if (dirs.length === 0)
  console.error(usage())

Promise.all(dirs.map(dir => impl(dir, opts)))
  .then(made => print ? made.forEach(m => m && console.log(m)) : null)
  .catch(er => {
    console.error(er.message)
    if (er.code)
      console.error('  code: ' + er.code)
    process.exit(1)
  })
const optsArg = require('./lib/opts-arg.js')
const pathArg = require('./lib/path-arg.js')

const {mkdirpNative, mkdirpNativeSync} = require('./lib/mkdirp-native.js')
const {mkdirpManual, mkdirpManualSync} = require('./lib/mkdirp-manual.js')
const {useNative, useNativeSync} = require('./lib/use-native.js')


const mkdirp = (path, opts) => {
  path = pathArg(path)
  opts = optsArg(opts)
  return useNative(opts)
    ? mkdirpNative(path, opts)
    : mkdirpManual(path, opts)
}

const mkdirpSync = (path, opts) => {
  path = pathArg(path)
  opts = optsArg(opts)
  return useNativeSync(opts)
    ? mkdirpNativeSync(path, opts)
    : mkdirpManualSync(path, opts)
}

mkdirp.sync = mkdirpSync
mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts))
mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts))
mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts))
mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts))

module.exports = mkdirp
const {dirname} = require('path')

const findMade = (opts, parent, path = undefined) => {
  // we never want the 'made' return value to be a root directory
  if (path === parent)
    return Promise.resolve()

  return opts.statAsync(parent).then(
    st => st.isDirectory() ? path : undefined, // will fail later
    er => er.code === 'ENOENT'
      ? findMade(opts, dirname(parent), parent)
      : undefined
  )
}

const findMadeSync = (opts, parent, path = undefined) => {
  if (path === parent)
    return undefined

  try {
    return opts.statSync(parent).isDirectory() ? path : undefined
  } catch (er) {
    return er.code === 'ENOENT'
      ? findMadeSync(opts, dirname(parent), parent)
      : undefined
  }
}

module.exports = {findMade, findMadeSync}
const {dirname} = require('path')

const mkdirpManual = (path, opts, made) => {
  opts.recursive = false
  const parent = dirname(path)
  if (parent === path) {
    return opts.mkdirAsync(path, opts).catch(er => {
      // swallowed by recursive implementation on posix systems
      // any other error is a failure
      if (er.code !== 'EISDIR')
        throw er
    })
  }

  return opts.mkdirAsync(path, opts).then(() => made || path, er => {
    if (er.code === 'ENOENT')
      return mkdirpManual(parent, opts)
        .then(made => mkdirpManual(path, opts, made))
    if (er.code !== 'EEXIST' && er.code !== 'EROFS')
      throw er
    return opts.statAsync(path).then(st => {
      if (st.isDirectory())
        return made
      else
        throw er
    }, () => { throw er })
  })
}

const mkdirpManualSync = (path, opts, made) => {
  const parent = dirname(path)
  opts.recursive = false

  if (parent === path) {
    try {
      return opts.mkdirSync(path, opts)
    } catch (er) {
      // swallowed by recursive implementation on posix systems
      // any other error is a failure
      if (er.code !== 'EISDIR')
        throw er
      else
        return
    }
  }

  try {
    opts.mkdirSync(path, opts)
    return made || path
  } catch (er) {
    if (er.code === 'ENOENT')
      return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made))
    if (er.code !== 'EEXIST' && er.code !== 'EROFS')
      throw er
    try {
      if (!opts.statSync(path).isDirectory())
        throw er
    } catch (_) {
      throw er
    }
  }
}

module.exports = {mkdirpManual, mkdirpManualSync}
const {dirname} = require('path')
const {findMade, findMadeSync} = require('./find-made.js')
const {mkdirpManual, mkdirpManualSync} = require('./mkdirp-manual.js')

const mkdirpNative = (path, opts) => {
  opts.recursive = true
  const parent = dirname(path)
  if (parent === path)
    return opts.mkdirAsync(path, opts)

  return findMade(opts, path).then(made =>
    opts.mkdirAsync(path, opts).then(() => made)
    .catch(er => {
      if (er.code === 'ENOENT')
        return mkdirpManual(path, opts)
      else
        throw er
    }))
}

const mkdirpNativeSync = (path, opts) => {
  opts.recursive = true
  const parent = dirname(path)
  if (parent === path)
    return opts.mkdirSync(path, opts)

  const made = findMadeSync(opts, path)
  try {
    opts.mkdirSync(path, opts)
    return made
  } catch (er) {
    if (er.code === 'ENOENT')
      return mkdirpManualSync(path, opts)
    else
      throw er
  }
}

module.exports = {mkdirpNative, mkdirpNativeSync}
const { promisify } = require('util')
const fs = require('fs')
const optsArg = opts => {
  if (!opts)
    opts = { mode: 0o777, fs }
  else if (typeof opts === 'object')
    opts = { mode: 0o777, fs, ...opts }
  else if (typeof opts === 'number')
    opts = { mode: opts, fs }
  else if (typeof opts === 'string')
    opts = { mode: parseInt(opts, 8), fs }
  else
    throw new TypeError('invalid options argument')

  opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir
  opts.mkdirAsync = promisify(opts.mkdir)
  opts.stat = opts.stat || opts.fs.stat || fs.stat
  opts.statAsync = promisify(opts.stat)
  opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync
  opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync
  return opts
}
module.exports = optsArg
const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform
const { resolve, parse } = require('path')
const pathArg = path => {
  if (/\0/.test(path)) {
    // simulate same failure that node raises
    throw Object.assign(
      new TypeError('path must be a string without null bytes'),
      {
        path,
        code: 'ERR_INVALID_ARG_VALUE',
      }
    )
  }

  path = resolve(path)
  if (platform === 'win32') {
    const badWinChars = /[*|"<>?:]/
    const {root} = parse(path)
    if (badWinChars.test(path.substr(root.length))) {
      throw Object.assign(new Error('Illegal characters in path.'), {
        path,
        code: 'EINVAL',
      })
    }
  }

  return path
}
module.exports = pathArg
const fs = require('fs')

const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version
const versArr = version.replace(/^v/, '').split('.')
const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12

const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir
const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync

module.exports = {useNative, useNativeSync}
{
  "name": "mkdirp",
  "description": "Recursively mkdir, like `mkdir -p`",
  "version": "1.0.4",
  "main": "index.js",
  "keywords": [
    "mkdir",
    "directory",
    "make dir",
    "make",
    "dir",
    "recursive",
    "native"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/isaacs/node-mkdirp.git"
  },
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "postpublish": "git push origin --follow-tags"
  },
  "tap": {
    "check-coverage": true,
    "coverage-map": "map.js"
  },
  "devDependencies": {
    "require-inject": "^1.4.4",
    "tap": "^14.10.7"
  },
  "bin": "bin/cmd.js",
  "license": "MIT",
  "engines": {
    "node": ">=10"
  },
  "files": [
    "bin",
    "lib",
    "index.js"
  ]
}
# mkdirp

Like `mkdir -p`, but in Node.js!

Now with a modern API and no\* bugs!

\* may contain some bugs

# example

## pow.js

```js
const mkdirp = require('mkdirp')

// return value is a Promise resolving to the first directory created
mkdirp('/tmp/foo/bar/baz').then(made =>
  console.log(`made directories, starting with ${made}`))
```

Output (where `/tmp/foo` already exists)

```
made directories, starting with /tmp/foo/bar
```

Or, if you don't have time to wait around for promises:

```js
const mkdirp = require('mkdirp')

// return value is the first directory created
const made = mkdirp.sync('/tmp/foo/bar/baz')
console.log(`made directories, starting with ${made}`)
```

And now /tmp/foo/bar/baz exists, huzzah!

# methods

```js
const mkdirp = require('mkdirp')
```

## mkdirp(dir, [opts]) -> Promise

Create a new directory and any necessary subdirectories at `dir` with octal
permission string `opts.mode`. If `opts` is a string or number, it will be
treated as the `opts.mode`.

If `opts.mode` isn't specified, it defaults to `0o777 &
(~process.umask())`.

Promise resolves to first directory `made` that had to be created, or
`undefined` if everything already exists.  Promise rejects if any errors
are encountered.  Note that, in the case of promise rejection, some
directories _may_ have been created, as recursive directory creation is not
an atomic operation.

You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)`
and `opts.fs.stat(path, cb)`.

You can also override just one or the other of `mkdir` and `stat` by
passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that
only overrides one of these.

## mkdirp.sync(dir, opts) -> String|null

Synchronously create a new directory and any necessary subdirectories at
`dir` with octal permission string `opts.mode`. If `opts` is a string or
number, it will be treated as the `opts.mode`.

If `opts.mode` isn't specified, it defaults to `0o777 &
(~process.umask())`.

Returns the first directory that had to be created, or undefined if
everything already exists.

You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)`
and `opts.fs.statSync(path)`.

You can also override just one or the other of `mkdirSync` and `statSync`
by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs`
option that only overrides one of these.

## mkdirp.manual, mkdirp.manualSync

Use the manual implementation (not the native one).  This is the default
when the native implementation is not available or the stat/mkdir
implementation is overridden.

## mkdirp.native, mkdirp.nativeSync

Use the native implementation (not the manual one).  This is the default
when the native implementation is available and stat/mkdir are not
overridden.

# implementation

On Node.js v10.12.0 and above, use the native `fs.mkdir(p,
{recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been
overridden by an option.

## native implementation

- If the path is a root directory, then pass it to the underlying
  implementation and return the result/error.  (In this case, it'll either
  succeed or fail, but we aren't actually creating any dirs.)
- Walk up the path statting each directory, to find the first path that
  will be created, `made`.
- Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`)
- If error, raise it to the caller.
- Return `made`.

## manual implementation

- Call underlying `fs.mkdir` implementation, with `recursive: false`
- If error:
  - If path is a root directory, raise to the caller and do not handle it
  - If ENOENT, mkdirp parent dir, store result as `made`
  - stat(path)
    - If error, raise original `mkdir` error
    - If directory, return `made`
    - Else, raise original `mkdir` error
- else
  - return `undefined` if a root dir, or `made` if set, or `path`

## windows vs unix caveat

On Windows file systems, attempts to create a root directory (ie, a drive
letter or root UNC path) will fail.  If the root directory exists, then it
will fail with `EPERM`.  If the root directory does not exist, then it will
fail with `ENOENT`.

On posix file systems, attempts to create a root directory (in recursive
mode) will succeed silently, as it is treated like just another directory
that already exists.  (In non-recursive mode, of course, it fails with
`EEXIST`.)

In order to preserve this system-specific behavior (and because it's not as
if we can create the parent of a root directory anyway), attempts to create
a root directory are passed directly to the `fs` implementation, and any
errors encountered are not handled.

## native error caveat

The native implementation (as of at least Node.js v13.4.0) does not provide
appropriate errors in some cases (see
[nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and
[nodejs/node#28015](https://github.com/nodejs/node/issues/28015)).

In order to work around this issue, the native implementation will fall
back to the manual implementation if an `ENOENT` error is encountered.

# choosing a recursive mkdir implementation

There are a few to choose from!  Use the one that suits your needs best :D

## use `fs.mkdir(path, {recursive: true}, cb)` if:

- You wish to optimize performance even at the expense of other factors.
- You don't need to know the first dir created.
- You are ok with getting `ENOENT` as the error when some other problem is
  the actual cause.
- You can limit your platforms to Node.js v10.12 and above.
- You're ok with using callbacks instead of promises.
- You don't need/want a CLI.
- You don't need to override the `fs` methods in use.

## use this module (mkdirp 1.x) if:

- You need to know the first directory that was created.
- You wish to use the native implementation if available, but fall back
  when it's not.
- You prefer promise-returning APIs to callback-taking APIs.
- You want more useful error messages than the native recursive mkdir
  provides (at least as of Node.js v13.4), and are ok with re-trying on
  `ENOENT` to achieve this.
- You need (or at least, are ok with) a CLI.
- You need to override the `fs` methods in use.

## use [`make-dir`](http://npm.im/make-dir) if:

- You do not need to know the first dir created (and wish to save a few
  `stat` calls when using the native implementation for this reason).
- You wish to use the native implementation if available, but fall back
  when it's not.
- You prefer promise-returning APIs to callback-taking APIs.
- You are ok with occasionally getting `ENOENT` errors for failures that
  are actually related to something other than a missing file system entry.
- You don't need/want a CLI.
- You need to override the `fs` methods in use.

## use mkdirp 0.x if:

- You need to know the first directory that was created.
- You need (or at least, are ok with) a CLI.
- You need to override the `fs` methods in use.
- You're ok with using callbacks instead of promises.
- You are not running on Windows, where the root-level ENOENT errors can
  lead to infinite regress.
- You think vinyl just sounds warmer and richer for some weird reason.
- You are supporting truly ancient Node.js versions, before even the advent
  of a `Promise` language primitive.  (Please don't.  You deserve better.)

# cli

This package also ships with a `mkdirp` command.

```
$ mkdirp -h

usage: mkdirp [DIR1,DIR2..] {OPTIONS}

  Create each supplied directory including any necessary parent directories
  that don't yet exist.

  If the directory already exists, do nothing.

OPTIONS are:

  -m       If a directory needs to be created, set the mode as an octal
  --mode=  permission string.

  -v --version   Print the mkdirp version number

  -h --help      Print this helpful banner

  -p --print     Print the first directories created for each path provided

  --manual       Use manual implementation, even if native is available
```

# install

With [npm](http://npmjs.org) do:

```
npm install mkdirp
```

to get the library locally, or

```
npm install -g mkdirp
```

to get the command everywhere, or

```
npx mkdirp ...
```

to run the command without installing it globally.

# platform support

This module works on node v8, but only v10 and above are officially
supported, as Node v8 reached its LTS end of life 2020-01-01, which is in
the past, as of this writing.

# license

MIT
/**
 * Helpers.
 */

var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;

/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} [options]
 * @throws {Error} throw an error if val is not a non-empty string or a number
 * @return {String|Number}
 * @api public
 */

module.exports = function (val, options) {
  options = options || {};
  var type = typeof val;
  if (type === 'string' && val.length > 0) {
    return parse(val);
  } else if (type === 'number' && isFinite(val)) {
    return options.long ? fmtLong(val) : fmtShort(val);
  }
  throw new Error(
    'val is not a non-empty string or a valid number. val=' +
      JSON.stringify(val)
  );
};

/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */

function parse(str) {
  str = String(str);
  if (str.length > 100) {
    return;
  }
  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
    str
  );
  if (!match) {
    return;
  }
  var n = parseFloat(match[1]);
  var type = (match[2] || 'ms').toLowerCase();
  switch (type) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return n * y;
    case 'weeks':
    case 'week':
    case 'w':
      return n * w;
    case 'days':
    case 'day':
    case 'd':
      return n * d;
    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return n * h;
    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return n * m;
    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return n * s;
    case 'milliseconds':
    case 'millisecond':
    case 'msecs':
    case 'msec':
    case 'ms':
      return n;
    default:
      return undefined;
  }
}

/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function fmtShort(ms) {
  var msAbs = Math.abs(ms);
  if (msAbs >= d) {
    return Math.round(ms / d) + 'd';
  }
  if (msAbs >= h) {
    return Math.round(ms / h) + 'h';
  }
  if (msAbs >= m) {
    return Math.round(ms / m) + 'm';
  }
  if (msAbs >= s) {
    return Math.round(ms / s) + 's';
  }
  return ms + 'ms';
}

/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function fmtLong(ms) {
  var msAbs = Math.abs(ms);
  if (msAbs >= d) {
    return plural(ms, msAbs, d, 'day');
  }
  if (msAbs >= h) {
    return plural(ms, msAbs, h, 'hour');
  }
  if (msAbs >= m) {
    return plural(ms, msAbs, m, 'minute');
  }
  if (msAbs >= s) {
    return plural(ms, msAbs, s, 'second');
  }
  return ms + ' ms';
}

/**
 * Pluralization helper.
 */

function plural(ms, msAbs, n, name) {
  var isPlural = msAbs >= n * 1.5;
  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
The MIT License (MIT)

Copyright (c) 2020 Vercel, Inc.

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.
{
  "name": "ms",
  "version": "2.1.3",
  "description": "Tiny millisecond conversion utility",
  "repository": "vercel/ms",
  "main": "./index",
  "files": [
    "index.js"
  ],
  "scripts": {
    "precommit": "lint-staged",
    "lint": "eslint lib/* bin/*",
    "test": "mocha tests.js"
  },
  "eslintConfig": {
    "extends": "eslint:recommended",
    "env": {
      "node": true,
      "es6": true
    }
  },
  "lint-staged": {
    "*.js": [
      "npm run lint",
      "prettier --single-quote --write",
      "git add"
    ]
  },
  "license": "MIT",
  "devDependencies": {
    "eslint": "4.18.2",
    "expect.js": "0.3.1",
    "husky": "0.14.3",
    "lint-staged": "5.0.0",
    "mocha": "4.0.1",
    "prettier": "2.0.5"
  }
}
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const Stream = require('stream')

class MuteStream extends Stream {
  #isTTY = null

  constructor (opts = {}) {
    super(opts)
    this.writable = this.readable = true
    this.muted = false
    this.on('pipe', this._onpipe)
    this.replace = opts.replace

    // For readline-type situations
    // This much at the start of a line being redrawn after a ctrl char
    // is seen (such as backspace) won't be redrawn as the replacement
    this._prompt = opts.prompt || null
    this._hadControl = false
  }

  #destSrc (key, def) {
    if (this._dest) {
      return this._dest[key]
    }
    if (this._src) {
      return this._src[key]
    }
    return def
  }

  #proxy (method, ...args) {
    if (typeof this._dest?.[method] === 'function') {
      this._dest[method](...args)
    }
    if (typeof this._src?.[method] === 'function') {
      this._src[method](...args)
    }
  }

  get isTTY () {
    if (this.#isTTY !== null) {
      return this.#isTTY
    }
    return this.#destSrc('isTTY', false)
  }

  // basically just get replace the getter/setter with a regular value
  set isTTY (val) {
    this.#isTTY = val
  }

  get rows () {
    return this.#destSrc('rows')
  }

  get columns () {
    return this.#destSrc('columns')
  }

  mute () {
    this.muted = true
  }

  unmute () {
    this.muted = false
  }

  _onpipe (src) {
    this._src = src
  }

  pipe (dest, options) {
    this._dest = dest
    return super.pipe(dest, options)
  }

  pause () {
    if (this._src) {
      return this._src.pause()
    }
  }

  resume () {
    if (this._src) {
      return this._src.resume()
    }
  }

  write (c) {
    if (this.muted) {
      if (!this.replace) {
        return true
      }
      // eslint-disable-next-line no-control-regex
      if (c.match(/^\u001b/)) {
        if (c.indexOf(this._prompt) === 0) {
          c = c.slice(this._prompt.length)
          c = c.replace(/./g, this.replace)
          c = this._prompt + c
        }
        this._hadControl = true
        return this.emit('data', c)
      } else {
        if (this._prompt && this._hadControl &&
          c.indexOf(this._prompt) === 0) {
          this._hadControl = false
          this.emit('data', this._prompt)
          c = c.slice(this._prompt.length)
        }
        c = c.toString().replace(/./g, this.replace)
      }
    }
    this.emit('data', c)
  }

  end (c) {
    if (this.muted) {
      if (c && this.replace) {
        c = c.toString().replace(/./g, this.replace)
      } else {
        c = null
      }
    }
    if (c) {
      this.emit('data', c)
    }
    this.emit('end')
  }

  destroy (...args) {
    return this.#proxy('destroy', ...args)
  }

  destroySoon (...args) {
    return this.#proxy('destroySoon', ...args)
  }

  close (...args) {
    return this.#proxy('close', ...args)
  }
}

module.exports = MuteStream
{
  "name": "mute-stream",
  "version": "2.0.0",
  "main": "lib/index.js",
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.3.0"
  },
  "scripts": {
    "test": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "snap": "tap",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/mute-stream.git"
  },
  "keywords": [
    "mute",
    "stream",
    "pipe"
  ],
  "author": "GitHub Inc.",
  "license": "ISC",
  "description": "Bytes go in, but they don't come out (when muted).",
  "files": [
    "bin/",
    "lib/"
  ],
  "tap": {
    "statements": 70,
    "branches": 60,
    "functions": 81,
    "lines": 70,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  }
}
{
    ".": "11.0.0"
}
# Changelog

## [11.0.0](https://github.com/nodejs/node-gyp/compare/v10.3.1...v11.0.0) (2024-12-03)


### âš  BREAKING CHANGES

* drop node 16 support ([#3102](https://github.com/nodejs/node-gyp/issues/3102))

### Features

* drop node 16 support ([#3102](https://github.com/nodejs/node-gyp/issues/3102)) ([0e6b6f8](https://github.com/nodejs/node-gyp/commit/0e6b6f8bea615cf031d76ecff9102a38e5474c72))


### Miscellaneous

* migrate from standard to neostandard ([#3103](https://github.com/nodejs/node-gyp/issues/3103)) ([a130178](https://github.com/nodejs/node-gyp/commit/a13017807d0ae7da8fa076b0bcf23153af7c60a6))

## [10.3.1](https://github.com/nodejs/node-gyp/compare/v10.3.0...v10.3.1) (2024-12-02)


### Miscellaneous

* fix npm-publish dependencies and add provenance ([#3099](https://github.com/nodejs/node-gyp/issues/3099)) ([6dded88](https://github.com/nodejs/node-gyp/commit/6dded88065872a32f44114e60731ba4b701ec057))

## [10.3.0](https://github.com/nodejs/node-gyp/compare/v10.2.0...v10.3.0) (2024-11-29)


### Features

* prohibit compiling with ClangCL on Windows ([#3098](https://github.com/nodejs/node-gyp/issues/3098)) ([88260bf](https://github.com/nodejs/node-gyp/commit/88260bf86aeb4c39959b78104a5edc3dc88d3aef))


### Bug Fixes

* **ci:** use correct release-please-action domain after organization url was changed ([#3032](https://github.com/nodejs/node-gyp/issues/3032)) ([d1ed3d4](https://github.com/nodejs/node-gyp/commit/d1ed3d4dc3a53b8ccab4093d002e43945bbece0e))


### Miscellaneous

* add links to Code of Conduct from root file ([#2196](https://github.com/nodejs/node-gyp/issues/2196)) ([d22e2eb](https://github.com/nodejs/node-gyp/commit/d22e2eb080807c6290533a67249c343a7605a989))
* publish to npm with release-please ([#3051](https://github.com/nodejs/node-gyp/issues/3051)) ([8319847](https://github.com/nodejs/node-gyp/commit/831984736393a3ea8417efec5255f95d53a70785))

## [10.2.0](https://github.com/nodejs/node-gyp/compare/v10.1.0...v10.2.0) (2024-07-09)


### Features

* allow VCINSTALLDIR to specify a portable instance ([#3036](https://github.com/nodejs/node-gyp/issues/3036)) ([d38af2e](https://github.com/nodejs/node-gyp/commit/d38af2e0c2a81b12cd221b1f8517fb89e609d62c))
* **gyp:** update gyp to v0.18.1 ([#3039](https://github.com/nodejs/node-gyp/issues/3039)) ([ea99fea](https://github.com/nodejs/node-gyp/commit/ea99fea83485dc5be04db01df9b2fdbe05319b8e))
* support `rebuild` and `build` for cross-compiling Node-API module to wasm on Windows ([#2974](https://github.com/nodejs/node-gyp/issues/2974)) ([6318d2b](https://github.com/nodejs/node-gyp/commit/6318d2b210224415ff5932c2863e6cc14d4583dc))


### Core

* add an arch check to VS 2019 ([#3025](https://github.com/nodejs/node-gyp/issues/3025)) ([323957b](https://github.com/nodejs/node-gyp/commit/323957b74e9586fb3fbfb2acad5040379c778de6))
* **deps:** bump seanmiddleditch/gha-setup-ninja from 4 to 5 ([#3041](https://github.com/nodejs/node-gyp/issues/3041)) ([10f6730](https://github.com/nodejs/node-gyp/commit/10f6730be660e7a38be8a12111937e37fcf74834))
* proc-log@4.0.0 ([#3022](https://github.com/nodejs/node-gyp/issues/3022)) ([141aa6b](https://github.com/nodejs/node-gyp/commit/141aa6bf029e6f984be8ea98aaf985e5df894082))
* tar@6.2.1 ([#3021](https://github.com/nodejs/node-gyp/issues/3021)) ([b22d5ee](https://github.com/nodejs/node-gyp/commit/b22d5eef861892c968052ffc1c71b551f738163b))


### Doc

* `node-pre-gyp` is no longer maintained ([#3015](https://github.com/nodejs/node-gyp/issues/3015)) ([93186f1](https://github.com/nodejs/node-gyp/commit/93186f10c966b4148fc500e48f8cbffacccdfa3c))
* add the way to configuring Python dependency for Windows PowerShell ([#2996](https://github.com/nodejs/node-gyp/issues/2996)) ([9fd7936](https://github.com/nodejs/node-gyp/commit/9fd7936f0d7232a8a79e6a7b6cbfb814d9042b13))
* Installation -- Python >= v3.12 requires `node-gyp` >= v10 ([#3010](https://github.com/nodejs/node-gyp/issues/3010)) ([a6b48fc](https://github.com/nodejs/node-gyp/commit/a6b48fca9993e54d757cd110f6b41f8200d99ca4))


### Miscellaneous

* fix ruff command ([#3044](https://github.com/nodejs/node-gyp/issues/3044)) ([b3916d5](https://github.com/nodejs/node-gyp/commit/b3916d5b25704a53e89be16b500036a14bdc5060))

## [10.1.0](https://github.com/nodejs/node-gyp/compare/v10.0.1...v10.1.0) (2024-03-13)


### Features

* improve visual studio detection ([#2957](https://github.com/nodejs/node-gyp/issues/2957)) ([109e3d4](https://github.com/nodejs/node-gyp/commit/109e3d4245504a7b75c99f578e1203c0ef4b518e))


### Core

* add support for locally installed headers ([#2964](https://github.com/nodejs/node-gyp/issues/2964)) ([3298731](https://github.com/nodejs/node-gyp/commit/329873141f0d3e3787d3c006801431da04e4ed0c))
* **deps:** bump actions/setup-python from 4 to 5 ([#2960](https://github.com/nodejs/node-gyp/issues/2960)) ([3f0df7e](https://github.com/nodejs/node-gyp/commit/3f0df7e9334e49e8c7f6fdbbb9e1e6c5a8cca53b))
* **deps:** bump google-github-actions/release-please-action ([#2961](https://github.com/nodejs/node-gyp/issues/2961)) ([b1f1808](https://github.com/nodejs/node-gyp/commit/b1f1808bfff0d51e6d3eb696ab6a5b89b7b9630c))
* print Python executable path using UTF-8 ([#2995](https://github.com/nodejs/node-gyp/issues/2995)) ([c472912](https://github.com/nodejs/node-gyp/commit/c4729129daa9bb5204246b857826fb391ac961e1))
* update supported vs versions ([#2959](https://github.com/nodejs/node-gyp/issues/2959)) ([391cc5b](https://github.com/nodejs/node-gyp/commit/391cc5b9b25cffe0cb2edcba3583414a771b4a15))


### Doc

* npm is currently v10 ([#2970](https://github.com/nodejs/node-gyp/issues/2970)) ([7705a22](https://github.com/nodejs/node-gyp/commit/7705a22f31a62076e9f8429780a459f4ad71ea4c))
* remove outdated Node versions from readme ([#2955](https://github.com/nodejs/node-gyp/issues/2955)) ([ae8478e](https://github.com/nodejs/node-gyp/commit/ae8478ec32d9b2fa71b591ac22cdf867ef2e9a7d))
* remove outdated update engines.node reference in 10.0.0 changelog ([b42e796](https://github.com/nodejs/node-gyp/commit/b42e7966177f006f3d1aab1d27885d8372c8ed01))


### Miscellaneous

* only run release please on push ([cff9ac2](https://github.com/nodejs/node-gyp/commit/cff9ac2c3083769a383e00bc60b91562f03116e3))
* upgrade release please action from v2 to v4 ([#2982](https://github.com/nodejs/node-gyp/issues/2982)) ([0035d8e](https://github.com/nodejs/node-gyp/commit/0035d8e9dc98b94f0bc8cd9023a6fa635003703e))

### [10.0.1](https://www.github.com/nodejs/node-gyp/compare/v10.0.0...v10.0.1) (2023-11-02)


### Bug Fixes

* use local `util` for `findAccessibleSync()` ([b39e681](https://www.github.com/nodejs/node-gyp/commit/b39e6819aa9e2c45107d6e60a4913ca036ebfbfd))


### Miscellaneous

* add parallel test logging ([7de1f5f](https://www.github.com/nodejs/node-gyp/commit/7de1f5f32d550d26d48fe4f76aed5866744edcba))
* lint fixes ([4e0ed99](https://www.github.com/nodejs/node-gyp/commit/4e0ed992566f43abc6e988af091ad07fde04acbf))
* use platform specific timeouts in tests ([a68586a](https://www.github.com/nodejs/node-gyp/commit/a68586a67d0af238300662cc062422b42820044d))

## [10.0.0](https://www.github.com/nodejs/node-gyp/compare/v9.4.0...v10.0.0) (2023-10-28)


### âš  BREAKING CHANGES

* use .npmignore file to limit which files are published (#2921)
* the `Gyp` class exported is now created using ECMAScript classes and therefore might have small differences to classes that were previously created with `util.inherits`.
* All internal functions have been coverted to return promises and no longer accept callbacks. This is not a breaking change for users but may be breaking to consumers of `node-gyp` if you are requiring internal functions directly.
* `node-gyp` now supports node `^16.14.0 || >=18.0.0`

### Features

* convert all internal functions to async/await ([355622f](https://www.github.com/nodejs/node-gyp/commit/355622f4aac3bd3056b9e03aac5fa2f42a4b3576))
* convert internal classes from util.inherits to classes ([d52997e](https://www.github.com/nodejs/node-gyp/commit/d52997e975b9da6e0cea3d9b99873e9ddc768679))
* drop node 14 support ([#2929](https://www.github.com/nodejs/node-gyp/issues/2929)) ([1b3bd34](https://www.github.com/nodejs/node-gyp/commit/1b3bd341b40f384988d03207ce8187e93ba609bc))
* drop rimraf dependency ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* **gyp:** update gyp to v0.16.1 ([#2923](https://www.github.com/nodejs/node-gyp/issues/2923)) ([707927c](https://www.github.com/nodejs/node-gyp/commit/707927cd579205ef2b4b17e61c1cce24c056b452))
* replace npmlog with proc-log ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* update engines.node to ^14.17.0 || ^16.13.0 || >=18.0.0 ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* use .npmignore file to limit which files are published ([#2921](https://www.github.com/nodejs/node-gyp/issues/2921)) ([864a979](https://www.github.com/nodejs/node-gyp/commit/864a979930cf0ef5ad64bc887b901fa8955d058f))


### Bug Fixes

* create Python symlink only during builds, and clean it up after ([#2721](https://www.github.com/nodejs/node-gyp/issues/2721)) ([0f1f667](https://www.github.com/nodejs/node-gyp/commit/0f1f667b737d21905e283df100a2cb639993562a))
* promisify build command ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* use fs/promises in favor of fs.promises ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))


### Tests

* increase mocha timeout ([#2887](https://www.github.com/nodejs/node-gyp/issues/2887)) ([445c28f](https://www.github.com/nodejs/node-gyp/commit/445c28fabc5fbdf9c3bb3341fb70660a3530f6ad))
* update expired certs ([#2908](https://www.github.com/nodejs/node-gyp/issues/2908)) ([5746691](https://www.github.com/nodejs/node-gyp/commit/5746691a36f7b37019d4b8d4e9616aec43d20410))


### Doc

* Add note about Python symlinks (PR 2362) to CHANGELOG.md for 9.1.0 ([#2783](https://www.github.com/nodejs/node-gyp/issues/2783)) ([b3d41ae](https://www.github.com/nodejs/node-gyp/commit/b3d41aeb737ddd54cc292f363abc561dcc0a614e))
* README.md Do not hardcode the supported versions of Python ([#2880](https://www.github.com/nodejs/node-gyp/issues/2880)) ([bb93b94](https://www.github.com/nodejs/node-gyp/commit/bb93b946a9c74934b59164deb52128cf913c97d5))
* update applicable GitHub links from master to main ([#2843](https://www.github.com/nodejs/node-gyp/issues/2843)) ([d644ce4](https://www.github.com/nodejs/node-gyp/commit/d644ce48311edf090d0e920ad449e5766c757933))
* Update windows installation instructions in README.md ([#2882](https://www.github.com/nodejs/node-gyp/issues/2882)) ([c9caa2e](https://www.github.com/nodejs/node-gyp/commit/c9caa2ecf3c7deae68444ce8fabb32d2dca651cd))


### Core

* find python checks order changed on windows ([#2872](https://www.github.com/nodejs/node-gyp/issues/2872)) ([b030555](https://www.github.com/nodejs/node-gyp/commit/b030555cdb754d9c23906e7e707115cd077bbf76))
* glob@10.3.10 ([#2926](https://www.github.com/nodejs/node-gyp/issues/2926)) ([4bef1ec](https://www.github.com/nodejs/node-gyp/commit/4bef1ecc7554097d92beb397fbe1a546c5227545))
* glob@8.0.3 ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* make-fetch-happen@13.0.0 ([#2927](https://www.github.com/nodejs/node-gyp/issues/2927)) ([059bb6f](https://www.github.com/nodejs/node-gyp/commit/059bb6fd41bb50955a9efbd97887773d60d53221))
* nopt@^7.0.0 ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* standard@17.0.0 and fix linting errors ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* which@3.0.0 ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* which@4.0.0 ([#2928](https://www.github.com/nodejs/node-gyp/issues/2928)) ([e388255](https://www.github.com/nodejs/node-gyp/commit/e38825531403aabeae7abe58e76867f31b832f36))


### Miscellaneous

* add check engines script to CI ([#2922](https://www.github.com/nodejs/node-gyp/issues/2922)) ([21a7249](https://www.github.com/nodejs/node-gyp/commit/21a7249b40d8f95e7721e450fd18764adb1648a7))
* empty commit to add changelog entries from [#2770](https://www.github.com/nodejs/node-gyp/issues/2770) ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* GitHub Workflows security hardening ([#2740](https://www.github.com/nodejs/node-gyp/issues/2740)) ([26683e9](https://www.github.com/nodejs/node-gyp/commit/26683e993df038fb94d89f2276f3535e4522d79a))
* misc testing fixes ([#2930](https://www.github.com/nodejs/node-gyp/issues/2930)) ([4e493d4](https://www.github.com/nodejs/node-gyp/commit/4e493d4fb262d12ac52c84979071ccc79e666a1a))
* run tests after release please PR ([3032e10](https://www.github.com/nodejs/node-gyp/commit/3032e1061cc2b7b49f83c397d385bafddc6b0214))

## [9.4.0](https://www.github.com/nodejs/node-gyp/compare/v9.3.1...v9.4.0) (2023-06-12)


### Features

* add support for native windows arm64 build tools ([bb76021](https://www.github.com/nodejs/node-gyp/commit/bb76021d35964d2bb125bc6214286f35ae4e6cad))
* Upgrade Python linting from flake8 to ruff ([#2815](https://www.github.com/nodejs/node-gyp/issues/2815)) ([fc0ddc6](https://www.github.com/nodejs/node-gyp/commit/fc0ddc6523c62b10e5ca1257500b3ceac01450a7))


### Bug Fixes

* extract tarball to temp directory on Windows ([#2846](https://www.github.com/nodejs/node-gyp/issues/2846)) ([aaa117c](https://www.github.com/nodejs/node-gyp/commit/aaa117c514430aa2c1e568b95df1b6ed1c1fd3b6))
* log statement is for devDir not nodedir ([#2840](https://www.github.com/nodejs/node-gyp/issues/2840)) ([55048f8](https://www.github.com/nodejs/node-gyp/commit/55048f8be5707c295fb0876306aded75638a8b63))


### Miscellaneous

* get update-gyp.py to work with Python >= v3.5 ([#2826](https://www.github.com/nodejs/node-gyp/issues/2826)) ([337e8e6](https://www.github.com/nodejs/node-gyp/commit/337e8e68209bd2481cbb11dacce61234dc5c9419))


### Doc

* docs/README.md add advise about deprecated node-sass ([#2828](https://www.github.com/nodejs/node-gyp/issues/2828)) ([6f3c2d3](https://www.github.com/nodejs/node-gyp/commit/6f3c2d3c6c0de0dbf8c7245f34c2e0b3eea53812))
* Update README.md ([#2822](https://www.github.com/nodejs/node-gyp/issues/2822)) ([c7927e2](https://www.github.com/nodejs/node-gyp/commit/c7927e228dfde059c93e08c26b54dd8026144583))


### Tests

* remove deprecated Node.js and Python ([#2868](https://www.github.com/nodejs/node-gyp/issues/2868)) ([a0b3d1c](https://www.github.com/nodejs/node-gyp/commit/a0b3d1c3afed71a74501476fcbc6ee3fface4d13))

### [9.3.1](https://www.github.com/nodejs/node-gyp/compare/v9.3.0...v9.3.1) (2022-12-16)


### Bug Fixes

* increase node 12 support to ^12.13 ([#2771](https://www.github.com/nodejs/node-gyp/issues/2771)) ([888efb9](https://www.github.com/nodejs/node-gyp/commit/888efb9055857afee6a6b54550722cf9ae3ee323))


### Miscellaneous

* update python test matrix ([#2774](https://www.github.com/nodejs/node-gyp/issues/2774)) ([38f01fa](https://www.github.com/nodejs/node-gyp/commit/38f01fa57d10fdb3db7697121d957bc2e0e96508))

## [9.3.0](https://www.github.com/nodejs/node-gyp/compare/v9.2.0...v9.3.0) (2022-10-10)


### Features

* **gyp:** update gyp to v0.14.0 ([#2749](https://www.github.com/nodejs/node-gyp/issues/2749)) ([713b8dc](https://www.github.com/nodejs/node-gyp/commit/713b8dcdbf44532ca9453a127da266386cc737f8))
* remove support for VS2015 in Node.js >=19 ([#2746](https://www.github.com/nodejs/node-gyp/issues/2746)) ([131d1a4](https://www.github.com/nodejs/node-gyp/commit/131d1a463baf034a04154bcda753a8295f112a34))
* support IBM Open XL C/C++ on z/OS ([#2743](https://www.github.com/nodejs/node-gyp/issues/2743)) ([7d0c83d](https://www.github.com/nodejs/node-gyp/commit/7d0c83d2a95aca743dff972826d0da26203acfc4))

## [9.2.0](https://www.github.com/nodejs/node-gyp/compare/v9.1.0...v9.2.0) (2022-10-02)


### Features

* Add proper support for IBM i ([a26494f](https://www.github.com/nodejs/node-gyp/commit/a26494fbb8883d9ef784503979e115dec3e2791e))
* **gyp:** update gyp to v0.13.0 ([3e2a532](https://www.github.com/nodejs/node-gyp/commit/3e2a5324f1c24f3a04bca04cf54fe23d5c4d5e50))


### Bug Fixes

* node.js debugger adds stderr (but exit code is 0) -> shouldn't throw ([#2719](https://www.github.com/nodejs/node-gyp/issues/2719)) ([c379a74](https://www.github.com/nodejs/node-gyp/commit/c379a744c65c7ab07c2c3193d9c7e8f25ae1b05e))


### Core

* enable support for zoslib on z/OS ([#2600](https://www.github.com/nodejs/node-gyp/issues/2600)) ([83c0a12](https://www.github.com/nodejs/node-gyp/commit/83c0a12bf23b4cbf3125d41f9e2d4201db76c9ae))


### Miscellaneous

* update dependency - nopt@6.0.0 ([#2707](https://www.github.com/nodejs/node-gyp/issues/2707)) ([8958ecf](https://www.github.com/nodejs/node-gyp/commit/8958ecf2bb719227bbcbf155891c3186ee219a2e))

## [9.1.0](https://www.github.com/nodejs/node-gyp/compare/v9.0.0...v9.1.0) (2022-07-13)


### Features

* Update function getSDK() to support Windows 11 SDK ([#2565](https://www.github.com/nodejs/node-gyp/issues/2565)) ([ea8520e](https://www.github.com/nodejs/node-gyp/commit/ea8520e3855374bd15b6d001fe112d58a8d7d737))


### Bug Fixes

* extend tap timeout length to allow for slow CI ([6f74c76](https://www.github.com/nodejs/node-gyp/commit/6f74c762fe3c19bdd20245cb5c02e2dfa65d9451))
* new ca & server certs, bundle in .js file and unpack for testing ([147e3d3](https://www.github.com/nodejs/node-gyp/commit/147e3d34f44a97deb7aa507207680cf0f4e662a2))
* re-label ([#2689](https://www.github.com/nodejs/node-gyp/issues/2689)) ([f0b7863](https://www.github.com/nodejs/node-gyp/commit/f0b7863dadfa365afc173025ae95351aec79abd9))
* typo on readme ([bf81cd4](https://www.github.com/nodejs/node-gyp/commit/bf81cd452b931dd4dfa82762c23dd530a075d992))


### Doc

* update docs/README.md with latest version number ([62d2815](https://www.github.com/nodejs/node-gyp/commit/62d28151bf8266a34e1bcceeb25b4e6e2ae5ca5d))


### Core

* update due to rename of primary branch ([ca1f068](https://www.github.com/nodejs/node-gyp/commit/ca1f0681a5567ca8cd51acebccd37a633f19bc6a))
* Add Python symlink to path (for non-Windows OSes only) ([#2362](https://github.com/nodejs/node-gyp/pull/2362)) ([b9ddcd5](https://github.com/nodejs/node-gyp/commit/b9ddcd5bbd93b05b03674836b6ebdae2c2e74c8c))


### Tests

* Try msvs-version: [2016, 2019, 2022] ([#2700](https://www.github.com/nodejs/node-gyp/issues/2700)) ([68b5b5b](https://www.github.com/nodejs/node-gyp/commit/68b5b5be9c94ac20c55e88654ff6f55234d7130a))
* Upgrade GitHub Actions ([#2623](https://www.github.com/nodejs/node-gyp/issues/2623)) ([245cd5b](https://www.github.com/nodejs/node-gyp/commit/245cd5bbe4441d4f05e88f2fa20a86425419b6af))
* Upgrade GitHub Actions ([#2701](https://www.github.com/nodejs/node-gyp/issues/2701)) ([1c64ca7](https://www.github.com/nodejs/node-gyp/commit/1c64ca7f4702c6eb43ecd16fbd67b5d939041621))

## [9.0.0](https://www.github.com/nodejs/node-gyp/compare/v8.4.1...v9.0.0) (2022-02-24)


### âš  BREAKING CHANGES

* increase "engines" to "node" : "^12.22 || ^14.13 || >=16" (#2601)

### Bug Fixes

* _ in npm_config_ env variables ([eef4eef](https://www.github.com/nodejs/node-gyp/commit/eef4eefccb13ff6a32db862709ee5b2d4edf7e95))
* update make-fetch-happen to a minimum of 10.0.3 ([839e414](https://www.github.com/nodejs/node-gyp/commit/839e414b63790c815a4a370d0feee8f24a94d40f))


### Miscellaneous

* add minimal SECURITY.md ([#2560](https://www.github.com/nodejs/node-gyp/issues/2560)) ([c2a1850](https://www.github.com/nodejs/node-gyp/commit/c2a185056e2e589b520fbc0bcc59c2935cd07ede))


### Doc

* Add notes/disclaimers for upgrading the copy of node-gyp that npm uses ([#2585](https://www.github.com/nodejs/node-gyp/issues/2585)) ([faf6d48](https://www.github.com/nodejs/node-gyp/commit/faf6d48f8a77c08a313baf9332358c4b1231c73c))
* Rename and update Common-issues.md --> docs/README.md ([#2567](https://www.github.com/nodejs/node-gyp/issues/2567)) ([2ef5fb8](https://www.github.com/nodejs/node-gyp/commit/2ef5fb86277c4d81baffc0b9f642a8d86be1bfa5))
* rephrase explanation of which node-gyp is used by npm ([#2587](https://www.github.com/nodejs/node-gyp/issues/2587)) ([a2f2988](https://www.github.com/nodejs/node-gyp/commit/a2f298870692022302fa27a1d42363c4a72df407))
* title match content ([#2574](https://www.github.com/nodejs/node-gyp/issues/2574)) ([6e8f93b](https://www.github.com/nodejs/node-gyp/commit/6e8f93be0443f2649d4effa7bc773a9da06a33b4))
* Update Python versions ([#2571](https://www.github.com/nodejs/node-gyp/issues/2571)) ([e069f13](https://www.github.com/nodejs/node-gyp/commit/e069f13658a8bfb5fd60f74708cf8be0856d92e3))


### Core

* add lib.target as path for searching libnode on z/OS ([1d499dd](https://www.github.com/nodejs/node-gyp/commit/1d499dd5606f39de2d34fa822fd0fa5ce17fbd06))
* increase "engines" to "node" : "^12.22 || ^14.13 || >=16" ([#2601](https://www.github.com/nodejs/node-gyp/issues/2601)) ([6562f92](https://www.github.com/nodejs/node-gyp/commit/6562f92a6f2e67aeae081ddf5272ff117f1fab07))
* make-fetch-happen@10.0.1 ([78f6660](https://www.github.com/nodejs/node-gyp/commit/78f66604e0df480d4f36a8fa4f3618c046a6fbdc))

### [8.4.1](https://www.github.com/nodejs/node-gyp/compare/v8.4.0...v8.4.1) (2021-11-19)


### Bug Fixes

* windows command missing space ([#2553](https://www.github.com/nodejs/node-gyp/issues/2553)) ([cc37b88](https://www.github.com/nodejs/node-gyp/commit/cc37b880690706d3c5d04d5a68c76c392a0a23ed))


### Doc

* fix typo in powershell node-gyp update ([787cf7f](https://www.github.com/nodejs/node-gyp/commit/787cf7f8e5ddd5039e02b64ace6b7b15e06fe0a4))


### Core

* npmlog@6.0.0 ([8083f6b](https://www.github.com/nodejs/node-gyp/commit/8083f6b855bd7f3326af04c5f5269fc28d7f2508))

## [8.4.0](https://www.github.com/nodejs/node-gyp/compare/v8.3.0...v8.4.0) (2021-11-05)


### Features

* build with config.gypi from node headers ([a27dc08](https://www.github.com/nodejs/node-gyp/commit/a27dc08696911c6d81e76cc228697243069103c1))
* support vs2022 ([#2533](https://www.github.com/nodejs/node-gyp/issues/2533)) ([5a00387](https://www.github.com/nodejs/node-gyp/commit/5a00387e5f8018264a1822f6c4d5dbf425f21cf6))

## [8.3.0](https://www.github.com/nodejs/node-gyp/compare/v8.2.0...v8.3.0) (2021-10-11)


### Features

* **gyp:** update gyp to v0.10.0 ([#2521](https://www.github.com/nodejs/node-gyp/issues/2521)) ([5585792](https://www.github.com/nodejs/node-gyp/commit/5585792922a97f0629f143c560efd74470eae87f))


### Tests

* Python 3.10 was release on Oct. 4th ([#2504](https://www.github.com/nodejs/node-gyp/issues/2504)) ([0a67dcd](https://www.github.com/nodejs/node-gyp/commit/0a67dcd1307f3560495219253241eafcbf4e2a69))


### Miscellaneous

* **deps:** bump make-fetch-happen from 8.0.14 to 9.1.0 ([b05b4fe](https://www.github.com/nodejs/node-gyp/commit/b05b4fe9891f718f40edf547e9b50e982826d48a))
* refactor the creation of config.gypi file ([f2ad87f](https://www.github.com/nodejs/node-gyp/commit/f2ad87ff65f98ad66daa7225ad59d99b759a2b07))

## [8.2.0](https://www.github.com/nodejs/node-gyp/compare/v8.1.0...v8.2.0) (2021-08-23)


### Features

* **gyp:** update gyp to v0.9.6 ([#2481](https://www.github.com/nodejs/node-gyp/issues/2481)) ([ed9a9ed](https://www.github.com/nodejs/node-gyp/commit/ed9a9ed653a17c84afa3c327161992d0da7d0cea))


### Bug Fixes

* add error arg back into catch block for older Node.js users ([5cde818](https://www.github.com/nodejs/node-gyp/commit/5cde818aac715477e9e9747966bb6b4c4ed070a8))
* change default gyp update message ([#2420](https://www.github.com/nodejs/node-gyp/issues/2420)) ([cfd12ff](https://www.github.com/nodejs/node-gyp/commit/cfd12ff3bb0eb4525173413ef6a94b3cd8398cad))
* doc how to update node-gyp independently from npm ([c8c0af7](https://www.github.com/nodejs/node-gyp/commit/c8c0af72e78141a02b5da4cd4d704838333a90bd))
* missing spaces ([f0882b1](https://www.github.com/nodejs/node-gyp/commit/f0882b1264b2fa701adbc81a3be0b3cba80e333d))


### Core

* deep-copy process.config during configure ([#2368](https://www.github.com/nodejs/node-gyp/issues/2368)) ([5f1a06c](https://www.github.com/nodejs/node-gyp/commit/5f1a06c50f3b0c3d292f64948f85a004cfcc5c87))


### Miscellaneous

* **deps:** bump tar from 6.1.0 to 6.1.2 ([#2474](https://www.github.com/nodejs/node-gyp/issues/2474)) ([ec15a3e](https://www.github.com/nodejs/node-gyp/commit/ec15a3e5012004172713c11eebcc9d852d32d380))
* fix typos discovered by codespell ([#2442](https://www.github.com/nodejs/node-gyp/issues/2442)) ([2d0ce55](https://www.github.com/nodejs/node-gyp/commit/2d0ce5595e232a3fc7c562cdf39efb77e2312cc1))
* GitHub Actions Test on node: [12.x, 14.x, 16.x] ([#2439](https://www.github.com/nodejs/node-gyp/issues/2439)) ([b7bccdb](https://www.github.com/nodejs/node-gyp/commit/b7bccdb527d93b0bb0ce99713f083ce2985fe85c))


### Doc

* correct link to "binding.gyp files out in the wild" ([#2483](https://www.github.com/nodejs/node-gyp/issues/2483)) ([660dd7b](https://www.github.com/nodejs/node-gyp/commit/660dd7b2a822c184be8027b300e68be67b366772))
* **wiki:** Add a link to the node-midi binding.gyp file. ([b354711](https://www.github.com/nodejs/node-gyp/commit/b3547115f6e356358138310e857c7f1ec627a8a7))
* **wiki:** add bcrypt ([e199cfa](https://www.github.com/nodejs/node-gyp/commit/e199cfa8fc6161492d2a6ade2190510d0ebf7c0f))
* **wiki:** Add helpful information ([4eda827](https://www.github.com/nodejs/node-gyp/commit/4eda8275c03dae6d2f5c40f3c1dbe930d84b0f2b))
* **wiki:** Add node-canvas ([13a9553](https://www.github.com/nodejs/node-gyp/commit/13a955317b39caf98fd1f412d8d3f41599e979fd))
* **wiki:** Add node-openvg-canvas and node-openvg. ([61f709e](https://www.github.com/nodejs/node-gyp/commit/61f709ec4d9f256a6467e9ff84430a48eeb629d1))
* **wiki:** add one more example ([77f3632](https://www.github.com/nodejs/node-gyp/commit/77f363272930d3d4d24fd3973be22e6237128fcc))
* **wiki:** add topcube, node-osmium, and node-osrm ([1a75d2b](https://www.github.com/nodejs/node-gyp/commit/1a75d2bf2f562ba50846893a516e111cfbb50885))
* **wiki:** Added details for properly fixing ([3d4d9d5](https://www.github.com/nodejs/node-gyp/commit/3d4d9d52d6b5b49de06bb0bb5b68e2686d2b7ebd))
* **wiki:** Added Ghostscript4JS ([bf4bed1](https://www.github.com/nodejs/node-gyp/commit/bf4bed1b96a7d22fba6f97f4552ad09f32ac3737))
* **wiki:** added levelup ([1575bce](https://www.github.com/nodejs/node-gyp/commit/1575bce3a53db628bfb023fd6f3258fdf98c3195))
* **wiki:** Added nk-mysql (nodamysql) ([5b4f2d0](https://www.github.com/nodejs/node-gyp/commit/5b4f2d0e1d5d3eadfd03aaf9c1668340f76c4bea))
* **wiki:** Added nk-xrm-installer .gyp references, including .py scripts for providing complete reference to examples of fetching source via http, extracting, and moving files (as opposed to copying) ([ceb3088](https://www.github.com/nodejs/node-gyp/commit/ceb30885b74f6789374ef52267b84767be93ebe4))
* **wiki:** Added tip about resolving frustrating LNK1181 error ([e64798d](https://www.github.com/nodejs/node-gyp/commit/e64798de8cac6031ad598a86d7599e81b4d20b17))
* **wiki:** ADDED: Node.js binding to OpenCV ([e2dc777](https://www.github.com/nodejs/node-gyp/commit/e2dc77730b09d7ee8682d7713a7603a2d7aacabd))
* **wiki:** Adding link to node-cryptopp's gyp file ([875adbe](https://www.github.com/nodejs/node-gyp/commit/875adbe2a4669fa5f2be0250ffbf98fb55e800fd))
* **wiki:** Adding the sharp library to the list ([9dce0e4](https://www.github.com/nodejs/node-gyp/commit/9dce0e41650c3fa973e6135a79632d022c662a1d))
* **wiki:** Adds node-fann ([23e3d48](https://www.github.com/nodejs/node-gyp/commit/23e3d485ed894ba7c631e9c062f5e366b50c416c))
* **wiki:** Adds node-inotify and v8-profiler ([b6e542f](https://www.github.com/nodejs/node-gyp/commit/b6e542f644dbbfe22b88524ec500696e06ee4af7))
* **wiki:** Bumping Python version from 2.3 to 2.7 as per the node-gyp readme ([55ebd6e](https://www.github.com/nodejs/node-gyp/commit/55ebd6ebacde975bf84f7bf4d8c66e64cc7cd0da))
* **wiki:** C++ build tools version upgraded ([5b899b7](https://www.github.com/nodejs/node-gyp/commit/5b899b70db729c392ced7c98e8e17590c6499fc3))
* **wiki:** change bcrypt url to binding.gyp file ([e11bdd8](https://www.github.com/nodejs/node-gyp/commit/e11bdd84de6144492d3eb327d67cbf2d62da1a76))
* **wiki:** Clarification + direct link to VS2010 ([531c724](https://www.github.com/nodejs/node-gyp/commit/531c724561d947b5d870de8d52dd8c3c51c5ec2d))
* **wiki:** Correcting the link to node-osmium ([fae7516](https://www.github.com/nodejs/node-gyp/commit/fae7516a1d2829b6e234eaded74fb112ebd79a05))
* **wiki:** Created "binding.gyp" files out in the wild (markdown) ([d4fd143](https://www.github.com/nodejs/node-gyp/commit/d4fd14355bbe57f229f082f47bb2b3670868203f))
* **wiki:** Created Common issues (markdown) ([a38299e](https://www.github.com/nodejs/node-gyp/commit/a38299ea340ceb0e732c6dc6a1b4760257644839))
* **wiki:** Created Error: "pre" versions of node cannot be installed (markdown) ([98bc80d](https://www.github.com/nodejs/node-gyp/commit/98bc80d7a62ba70c881f3c39d94f804322e57852))
* **wiki:** Created Linking to OpenSSL (markdown) ([c46d00d](https://www.github.com/nodejs/node-gyp/commit/c46d00d83bac5173dea8bbbb175a1a7de74fdaca))
* **wiki:** Created Updating npm's bundled node gyp (markdown) ([e0ac8d1](https://www.github.com/nodejs/node-gyp/commit/e0ac8d15af46aadd1c220599e63199b154a514e6))
* **wiki:** Created use of undeclared identifier 'TypedArray' (markdown) ([65ba711](https://www.github.com/nodejs/node-gyp/commit/65ba71139e9b7f64ac823e575ee9dbf17d937ce4))
* **wiki:** Created Visual Studio 2010 Setup (markdown) ([5b80e83](https://www.github.com/nodejs/node-gyp/commit/5b80e834c8f79dda9fb2770a876ff3cf649c06f3))
* **wiki:** Created Visual studio 2012 setup (markdown) ([becef31](https://www.github.com/nodejs/node-gyp/commit/becef316b6c46a33e783667720ee074a0141d1a5))
* **wiki:** Destroyed Visual Studio 2010 Setup (markdown) ([93423b4](https://www.github.com/nodejs/node-gyp/commit/93423b43606de9664aeb79635825f5e9941ec9bc))
* **wiki:** Destroyed Visual studio 2012 setup (markdown) ([3601508](https://www.github.com/nodejs/node-gyp/commit/3601508bb10fa05da0ddc7e70d57e4b4dd679657))
* **wiki:** Different commands for Windows npm v6 vs. v7 ([0fce46b](https://www.github.com/nodejs/node-gyp/commit/0fce46b53340c85e8091cde347d5ed23a443c82f))
* **wiki:** Drop  in favor of ([9285ff6](https://www.github.com/nodejs/node-gyp/commit/9285ff6e451c52c070a05f05f0a9602621d91d53))
* **wiki:** Explicit link to Visual C++ 2010 Express ([378c363](https://www.github.com/nodejs/node-gyp/commit/378c3632f02c096ed819ec8f2611c65bef0c0554))
* **wiki:** fix link to gyp file used to build libsqlite3 ([54db8d7](https://www.github.com/nodejs/node-gyp/commit/54db8d7ac33e3f98220960b5d86cfa18a75b53cb))
* **wiki:** Fix link to node-zipfile ([92e49a8](https://www.github.com/nodejs/node-gyp/commit/92e49a858ed69cb4847a26a5676ab56ef5e2de33))
* **wiki:** fixed node-serialport link ([954ee53](https://www.github.com/nodejs/node-gyp/commit/954ee530b3972d1db591fce32368e4e31b5a25d8))
* **wiki:** I highly missing it in common issue as every windows biggner face that issue ([d617fae](https://www.github.com/nodejs/node-gyp/commit/d617faee29c40871ca5c8f93efd0ce929a40d541))
* **wiki:** if ouns that the -h did not help. I founs on github that there was support for visual studio 2015, while i couldn't install node-red beacuse it kept telling me the key 2015 was missing. looking in he gyp python code i found the local file was bot up t dat with the github repo. updating took several efforts before i tried to drop the -g option. ([408b72f](https://www.github.com/nodejs/node-gyp/commit/408b72f561329408daeb17834436e381406efcc8))
* **wiki:** If permissions error, please try  and then the command. ([ee8e1c1](https://www.github.com/nodejs/node-gyp/commit/ee8e1c1e5334096d58e0d6bca6c006f2ee9c88cb))
* **wiki:** Improve Unix instructions ([c3e5487](https://www.github.com/nodejs/node-gyp/commit/c3e548736645b535ea5bce613d74ca3e98598243))
* **wiki:** link to docs/ from README ([b52e487](https://www.github.com/nodejs/node-gyp/commit/b52e487eac1eb421573d1e67114a242eeff45a00))
* **wiki:** Lower case L ([3aa2c6b](https://www.github.com/nodejs/node-gyp/commit/3aa2c6bdb07971b87505e32e32548d75264bd19f))
* **wiki:** Make changes discussed in https://github.com/nodejs/node-gyp/issues/2416 ([1dcad87](https://www.github.com/nodejs/node-gyp/commit/1dcad873539027511a5f0243baf770ea90f6f4e2))
* **wiki:** move wiki docs into doc/ ([f0a4835](https://www.github.com/nodejs/node-gyp/commit/f0a48355d86534ec3bdabcdb3ce3340fa2e17f39))
* **wiki:** node-sass in the wild ([d310a73](https://www.github.com/nodejs/node-gyp/commit/d310a73d64d0065050377baac7047472f7424a1b))
* **wiki:** node-srs was a 404 ([bbca21a](https://www.github.com/nodejs/node-gyp/commit/bbca21a1e1ede4c473aff365ca71989a5bda7b57))
* **wiki:** Note: VS2010 seems to be no longer available!  VS2013 or nothing! ([7b5dcaf](https://www.github.com/nodejs/node-gyp/commit/7b5dcafafccdceae4b8f2b53ac9081a694b6ade8))
* **wiki:** safer doc names, remove unnecessary TypedArray doc ([161c235](https://www.github.com/nodejs/node-gyp/commit/161c2353ef5b562f4acfb2fd77608fcbd0800fc0))
* **wiki:** sorry, forgot to mention a specific windows version. ([d69dffc](https://www.github.com/nodejs/node-gyp/commit/d69dffc16c2b1e3c60dcb5d1c35a49270ba22a35))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([7444b47](https://www.github.com/nodejs/node-gyp/commit/7444b47a7caac1e14d1da474a7fcfcf88d328017))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([d766b74](https://www.github.com/nodejs/node-gyp/commit/d766b7427851e6c2edc02e2504a7be9be7e330c0))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([d319b0e](https://www.github.com/nodejs/node-gyp/commit/d319b0e98c7085de8e51bc5595eba4264b99a7d5))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([3c6692d](https://www.github.com/nodejs/node-gyp/commit/3c6692d538f0ce973869aa237118b7d2483feccd))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([93392d5](https://www.github.com/nodejs/node-gyp/commit/93392d559ce6f250b9c7fe8177e6c88603809dc1))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([8841158](https://www.github.com/nodejs/node-gyp/commit/88411588f300e9b7c00fe516ecd977a1feeeb15c))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([81bfa1f](https://www.github.com/nodejs/node-gyp/commit/81bfa1f1b63d522a9f8a9ae9ca0c7ae90fe75140))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([d1cd237](https://www.github.com/nodejs/node-gyp/commit/d1cd237bad06fa507adb354b9e2181a14dc63d24))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([3de9e17](https://www.github.com/nodejs/node-gyp/commit/3de9e17e0b8a387eafe7bd18d0ec1e3191d118e8))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([a9b7096](https://www.github.com/nodejs/node-gyp/commit/a9b70968fb956eab3b95672048b94350e1565ca3))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([3236069](https://www.github.com/nodejs/node-gyp/commit/3236069689e7e0eb15b324fce74ab58158956f98))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([1462755](https://www.github.com/nodejs/node-gyp/commit/14627556966e5d513bdb8e5208f0e1300f68991f))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([7ab1337](https://www.github.com/nodejs/node-gyp/commit/7ab133752a6c402bb96dcd3d671d73e03e9487ad))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([640895d](https://www.github.com/nodejs/node-gyp/commit/640895d36b7448c646a3b850c1e159106f83c724))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([ced8c96](https://www.github.com/nodejs/node-gyp/commit/ced8c968457f285ab8989c291d28173d7730833c))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([27b883a](https://www.github.com/nodejs/node-gyp/commit/27b883a350ad0db6b9130d7b996f35855ec34c7a))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([d29fb13](https://www.github.com/nodejs/node-gyp/commit/d29fb134f1c4b9dd729ba95f2979e69e0934809f))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([2765891](https://www.github.com/nodejs/node-gyp/commit/27658913e6220cf0371b4b73e25a0e4ab11108a1))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([dc97766](https://www.github.com/nodejs/node-gyp/commit/dc9776648d432bca6775c176641f16da14522d4c))
* **wiki:** Updated Error: "pre" versions of node cannot be installed (markdown) ([e9f8b33](https://www.github.com/nodejs/node-gyp/commit/e9f8b33d1f87d04f22cb09a814d7c55d0fa38446))
* **wiki:** Updated Home (markdown) ([3407109](https://www.github.com/nodejs/node-gyp/commit/3407109325cf7ba1e925656b9eb75feffab0557c))
* **wiki:** Updated Home (markdown) ([6e392bc](https://www.github.com/nodejs/node-gyp/commit/6e392bcdd3dd1691773e6e16e1dffc35931b81e0))
* **wiki:** Updated Home (markdown) ([65efe32](https://www.github.com/nodejs/node-gyp/commit/65efe32ccb8d446ce569453364f922dd9d27c945))
* **wiki:** Updated Home (markdown) ([ea28f09](https://www.github.com/nodejs/node-gyp/commit/ea28f0947af91fa638be355143f5df89d2e431c8))
* **wiki:** Updated Home (markdown) ([0e37ff4](https://www.github.com/nodejs/node-gyp/commit/0e37ff48b306c12149661b375895741d3d710da7))
* **wiki:** Updated Home (markdown) ([b398ef4](https://www.github.com/nodejs/node-gyp/commit/b398ef46f660d2b1506508550dadfb4c35639e4b))
* **wiki:** Updated Linking to OpenSSL (markdown) ([8919028](https://www.github.com/nodejs/node-gyp/commit/8919028921fd304f08044098434f0dc6071fb7cf))
* **wiki:** Updated Linking to OpenSSL (markdown) ([c00eb77](https://www.github.com/nodejs/node-gyp/commit/c00eb778fc7dc27e4dab3a9219035ea20458b33b))
* **wiki:** Updated node-levelup to node-leveldown (broken links) ([59668bb](https://www.github.com/nodejs/node-gyp/commit/59668bb0b904feccf3c09afa2fd37378c77af967))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([d314854](https://www.github.com/nodejs/node-gyp/commit/d31485415ef69d46effa6090c95698341965de1b))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([11858b0](https://www.github.com/nodejs/node-gyp/commit/11858b0655d1eee00c62ad628e719d4378803d14))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([33561e9](https://www.github.com/nodejs/node-gyp/commit/33561e9cbf5f4eb46111318503c77df2c6eb484a))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([4a7f2d0](https://www.github.com/nodejs/node-gyp/commit/4a7f2d0d869a65c99a78504976567017edadf657))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([979a706](https://www.github.com/nodejs/node-gyp/commit/979a7063b950c088a7f4896fc3a48e1d00dfd231))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([e50e04d](https://www.github.com/nodejs/node-gyp/commit/e50e04d7b6a3754ea0aa11fe8cef491b3bc5bdd4))

## [8.1.0](https://www.github.com/nodejs/node-gyp/compare/v8.0.0...v8.1.0) (2021-05-28)


### Features

* **gyp:** update gyp to v0.9.1 ([#2402](https://www.github.com/nodejs/node-gyp/issues/2402)) ([814b1b0](https://www.github.com/nodejs/node-gyp/commit/814b1b0eda102afb9fc87e81638a9cf5b650bb10))


### Miscellaneous

* add `release-please-action` for automated releases ([#2395](https://www.github.com/nodejs/node-gyp/issues/2395)) ([07e9d7c](https://www.github.com/nodejs/node-gyp/commit/07e9d7c7ee80ba119ea760c635f72fd8e7efe198))


### Core

* fail gracefully if we can't find the username ([#2375](https://www.github.com/nodejs/node-gyp/issues/2375)) ([fca4795](https://www.github.com/nodejs/node-gyp/commit/fca4795512c67dc8420aaa0d913b5b89a4b147f3))
* log as yes/no whether build dir was created ([#2370](https://www.github.com/nodejs/node-gyp/issues/2370)) ([245dee5](https://www.github.com/nodejs/node-gyp/commit/245dee5b62581309946872ae253226ea3a42c0e3))


### Doc

* fix v8.0.0 release date ([4b83c3d](https://www.github.com/nodejs/node-gyp/commit/4b83c3de7300457919d53f26d96ea9ad6f6bedd8))
* remove redundant version info ([#2403](https://www.github.com/nodejs/node-gyp/issues/2403)) ([1423670](https://www.github.com/nodejs/node-gyp/commit/14236709de64b100a424396b91a5115639daa0ef))
* Update README.md Visual Studio Community page polski to auto ([#2371](https://www.github.com/nodejs/node-gyp/issues/2371)) ([1b4697a](https://www.github.com/nodejs/node-gyp/commit/1b4697abf69ef574a48faf832a7098f4c6c224a5))

## v8.0.0 2021-04-03

* [[`0d8a6f1b19`](https://github.com/nodejs/node-gyp/commit/0d8a6f1b19)] - **ci**: update actions/setup-node to v2 (#2302) (Sora Morimoto) [#2302](https://github.com/nodejs/node-gyp/pull/2302)
* [[`15a5c7d45b`](https://github.com/nodejs/node-gyp/commit/15a5c7d45b)] - **ci**: migrate deprecated grammar (#2285) (Jiawen Geng) [#2285](https://github.com/nodejs/node-gyp/pull/2285)
* [[`06ddde27f9`](https://github.com/nodejs/node-gyp/commit/06ddde27f9)] - **deps**: sync mutual dependencies with npm (DeeDeeG) [#2348](https://github.com/nodejs/node-gyp/pull/2348)
* [[`a5fd1f41e3`](https://github.com/nodejs/node-gyp/commit/a5fd1f41e3)] - **doc**: add downloads badge (#2352) (Jiawen Geng) [#2352](https://github.com/nodejs/node-gyp/pull/2352)
* [[`cc1cbce056`](https://github.com/nodejs/node-gyp/commit/cc1cbce056)] - **doc**: update macOS\_Catalina.md (#2293) (iMrLopez) [#2293](https://github.com/nodejs/node-gyp/pull/2293)
* [[`6287118fc4`](https://github.com/nodejs/node-gyp/commit/6287118fc4)] - **doc**: updated README.md to copy easily (#2281) (மனோஜà¯à®•à¯à®®à®¾à®°à¯ பழனிசà¯à®šà®¾à®®à®¿) [#2281](https://github.com/nodejs/node-gyp/pull/2281)
* [[`66c0f04467`](https://github.com/nodejs/node-gyp/commit/66c0f04467)] - **doc**: add missing `sudo` to Catalina doc (Karl Horky) [#2244](https://github.com/nodejs/node-gyp/pull/2244)
* [[`0da2e0140d`](https://github.com/nodejs/node-gyp/commit/0da2e0140d)] - **gyp**: update gyp to v0.8.1 (#2355) (DeeDeeG) [#2355](https://github.com/nodejs/node-gyp/pull/2355)
* [[`0093ec8646`](https://github.com/nodejs/node-gyp/commit/0093ec8646)] - **gyp**: Improve our flake8 linting tests (Christian Clauss) [#2356](https://github.com/nodejs/node-gyp/pull/2356)
* [[`a78b584236`](https://github.com/nodejs/node-gyp/commit/a78b584236)] - **(SEMVER-MAJOR)** **gyp**: remove support for Python 2 (#2300) (Christian Clauss) [#2300](https://github.com/nodejs/node-gyp/pull/2300)
* [[`c3c510d89e`](https://github.com/nodejs/node-gyp/commit/c3c510d89e)] - **gyp**: update gyp to v0.8.0 (#2318) (Christian Clauss) [#2318](https://github.com/nodejs/node-gyp/pull/2318)
* [[`9e1397c52e`](https://github.com/nodejs/node-gyp/commit/9e1397c52e)] - **(SEMVER-MAJOR)** **gyp**: update gyp to v0.7.0 (#2284) (Jiawen Geng) [#2284](https://github.com/nodejs/node-gyp/pull/2284)
* [[`1bd18f3e77`](https://github.com/nodejs/node-gyp/commit/1bd18f3e77)] - **(SEMVER-MAJOR)** **lib**: drop Python 2 support in find-python.js (#2333) (DeeDeeG) [#2333](https://github.com/nodejs/node-gyp/pull/2333)
* [[`e81602ef55`](https://github.com/nodejs/node-gyp/commit/e81602ef55)] - **(SEMVER-MAJOR)** **lib**: migrate requests to fetch (#2220) (Matias Lopez) [#2220](https://github.com/nodejs/node-gyp/pull/2220)
* [[`392b7760b4`](https://github.com/nodejs/node-gyp/commit/392b7760b4)] - **lib**: avoid changing process.config (#2322) (Michaël Zasso) [#2322](https://github.com/nodejs/node-gyp/pull/2322)

## v7.1.2 2020-10-17

* [[`096e3aded5`](https://github.com/nodejs/node-gyp/commit/096e3aded5)] - **gyp**: update gyp to 0.6.2 (Myles Borins) [#2241](https://github.com/nodejs/node-gyp/pull/2241)
* [[`54f97cd243`](https://github.com/nodejs/node-gyp/commit/54f97cd243)] - **doc**: add cmd to reset `xcode-select` to initial state (Valera Rozuvan) [#2235](https://github.com/nodejs/node-gyp/pull/2235)

## v7.1.1 2020-10-15

This release restores the location of shared library builds to the pre-v7
location. In v7.0.0 until this release, shared library outputs were placed
in a lib.target subdirectory inside the build/{Release,Debug} directory for
builds using `make` (Linux, etc.). This is inconsistent with macOS (Xcode)
behavior and previous node-gyp behavior so has been reverted.
We consider this a bug-fix rather than semver-major change.

* [[`18bf2d1d38`](https://github.com/nodejs/node-gyp/commit/18bf2d1d38)] - **deps**: update deps to match npm@7 (Rod Vagg) [#2240](https://github.com/nodejs/node-gyp/pull/2240)
* [[`ee6a837cb7`](https://github.com/nodejs/node-gyp/commit/ee6a837cb7)] - **gyp**: update gyp to 0.6.1 (Rod Vagg) [#2238](https://github.com/nodejs/node-gyp/pull/2238)
* [[`3e7f8ccafc`](https://github.com/nodejs/node-gyp/commit/3e7f8ccafc)] - **lib**: better log message when ps fails (Martin Midtgaard) [#2229](https://github.com/nodejs/node-gyp/pull/2229)
* [[`7fb314339f`](https://github.com/nodejs/node-gyp/commit/7fb314339f)] - **test**: GitHub Actions: Test on Python 3.9 (Christian Clauss) [#2230](https://github.com/nodejs/node-gyp/pull/2230)
* [[`754996b9ec`](https://github.com/nodejs/node-gyp/commit/754996b9ec)] - **doc**: replace status badges with new Actions badge (Rod Vagg) [#2218](https://github.com/nodejs/node-gyp/pull/2218)
* [[`2317dc400c`](https://github.com/nodejs/node-gyp/commit/2317dc400c)] - **ci**: switch to GitHub Actions (Shelley Vohr) [#2210](https://github.com/nodejs/node-gyp/pull/2210)
* [[`2cca9b74f7`](https://github.com/nodejs/node-gyp/commit/2cca9b74f7)] - **doc**: drop the --production flag for installing windows-build-tools (DeeDeeG) [#2206](https://github.com/nodejs/node-gyp/pull/2206)

## v7.1.0 2020-08-12

* [[`aaf33c3029`](https://github.com/nodejs/node-gyp/commit/aaf33c3029)] - **build**: add update-gyp script (Samuel Attard) [#2167](https://github.com/nodejs/node-gyp/pull/2167)
* * [[`3baa4e4172`](https://github.com/nodejs/node-gyp/commit/3baa4e4172)] - **(SEMVER-MINOR)** **gyp**: update gyp to 0.4.0 (Samuel Attard) [#2165](https://github.com/nodejs/node-gyp/pull/2165)
* * [[`f461d56c53`](https://github.com/nodejs/node-gyp/commit/f461d56c53)] - **(SEMVER-MINOR)** **build**: support apple silicon (arm64 darwin) builds (Samuel Attard) [#2165](https://github.com/nodejs/node-gyp/pull/2165)
* * [[`ee6fa7d3bc`](https://github.com/nodejs/node-gyp/commit/ee6fa7d3bc)] - **docs**: note that node-gyp@7 should solve Catalina CLT issues (Rod Vagg) [#2156](https://github.com/nodejs/node-gyp/pull/2156)
* * [[`4fc8ff179d`](https://github.com/nodejs/node-gyp/commit/4fc8ff179d)] - **doc**: silence curl for macOS Catalina acid test (Chia Wei Ong) [#2150](https://github.com/nodejs/node-gyp/pull/2150)
* * [[`7857cb2eb1`](https://github.com/nodejs/node-gyp/commit/7857cb2eb1)] - **deps**: increase "engines" to "node" : "\>= 10.12.0" (DeeDeeG) [#2153](https://github.com/nodejs/node-gyp/pull/2153)

## v7.0.0 2020-06-03

* [[`e18a61afc1`](https://github.com/nodejs/node-gyp/commit/e18a61afc1)] - **build**: shrink bloated addon binaries on windows (Shelley Vohr) [#2060](https://github.com/nodejs/node-gyp/pull/2060)
* [[`4937722cf5`](https://github.com/nodejs/node-gyp/commit/4937722cf5)] - **(SEMVER-MAJOR)** **deps**: replace mkdirp with {recursive} mkdir (Rod Vagg) [#2123](https://github.com/nodejs/node-gyp/pull/2123)
* [[`d45438a047`](https://github.com/nodejs/node-gyp/commit/d45438a047)] - **(SEMVER-MAJOR)** **deps**: update deps, match to npm@7 (Rod Vagg) [#2126](https://github.com/nodejs/node-gyp/pull/2126)
* [[`ba4f34b7d6`](https://github.com/nodejs/node-gyp/commit/ba4f34b7d6)] - **doc**: update catalina xcode clt download link (Dario Vladovic) [#2133](https://github.com/nodejs/node-gyp/pull/2133)
* [[`f7bfce96ed`](https://github.com/nodejs/node-gyp/commit/f7bfce96ed)] - **doc**: update acid test and introduce curl|bash test script (Dario Vladovic) [#2105](https://github.com/nodejs/node-gyp/pull/2105)
* [[`e529f3309d`](https://github.com/nodejs/node-gyp/commit/e529f3309d)] - **doc**: update README to reflect upgrade to gyp-next (Ujjwal Sharma) [#2092](https://github.com/nodejs/node-gyp/pull/2092)
* [[`9aed6286a3`](https://github.com/nodejs/node-gyp/commit/9aed6286a3)] - **doc**: give more attention to Catalina issues doc (Matheus Marchini) [#2134](https://github.com/nodejs/node-gyp/pull/2134)
* [[`963f2a7b48`](https://github.com/nodejs/node-gyp/commit/963f2a7b48)] - **doc**: improve Catalina discoverability for search engines (Matheus Marchini) [#2135](https://github.com/nodejs/node-gyp/pull/2135)
* [[`7b75af349b`](https://github.com/nodejs/node-gyp/commit/7b75af349b)] - **doc**: add macOS Catalina software update info (Karl Horky) [#2078](https://github.com/nodejs/node-gyp/pull/2078)
* [[`4f23c7bee2`](https://github.com/nodejs/node-gyp/commit/4f23c7bee2)] - **doc**: update link to the code of conduct (#2073) (Michaël Zasso) [#2073](https://github.com/nodejs/node-gyp/pull/2073)
* [[`473cfa283f`](https://github.com/nodejs/node-gyp/commit/473cfa283f)] - **doc**: note in README that Python 3.8 is supported (#2072) (Michaël Zasso) [#2072](https://github.com/nodejs/node-gyp/pull/2072)
* [[`e7402b4a7c`](https://github.com/nodejs/node-gyp/commit/e7402b4a7c)] - **doc**: update catalina xcode cli tools download link (#2044) (Dario Vladović) [#2044](https://github.com/nodejs/node-gyp/pull/2044)
* [[`35de45984f`](https://github.com/nodejs/node-gyp/commit/35de45984f)] - **doc**: update catalina xcode cli tools download link; formatting (Jonathan Hult) [#2034](https://github.com/nodejs/node-gyp/pull/2034)
* [[`48642191f5`](https://github.com/nodejs/node-gyp/commit/48642191f5)] - **doc**: add download link for Command Line Tools for Xcode (Przemysław Bitkowski) [#2029](https://github.com/nodejs/node-gyp/pull/2029)
* [[`ae5b150051`](https://github.com/nodejs/node-gyp/commit/ae5b150051)] - **doc**: Catalina suggestion: remove /Library/Developer/CommandLineTools (Christian Clauss) [#2022](https://github.com/nodejs/node-gyp/pull/2022)
* [[`d1dea13fe4`](https://github.com/nodejs/node-gyp/commit/d1dea13fe4)] - **doc**: fix changelog 6.1.0 release year to be 2020 (Quentin Vernot) [#2021](https://github.com/nodejs/node-gyp/pull/2021)
* [[`6356117b08`](https://github.com/nodejs/node-gyp/commit/6356117b08)] - **doc, bin**: stop suggesting opening  node-gyp issues (Bartosz Sosnowski) [#2096](https://github.com/nodejs/node-gyp/pull/2096)
* [[`a6b76a8b48`](https://github.com/nodejs/node-gyp/commit/a6b76a8b48)] - **gyp**: update gyp to 0.2.1 (Ujjwal Sharma) [#2092](https://github.com/nodejs/node-gyp/pull/2092)
* [[`ebc34ec823`](https://github.com/nodejs/node-gyp/commit/ebc34ec823)] - **gyp**: update gyp to 0.2.0 (Ujjwal Sharma) [#2092](https://github.com/nodejs/node-gyp/pull/2092)
* [[`972780bde7`](https://github.com/nodejs/node-gyp/commit/972780bde7)] - **(SEMVER-MAJOR)** **gyp**: sync code base with nodejs repo (#1975) (Michaël Zasso) [#1975](https://github.com/nodejs/node-gyp/pull/1975)
* [[`c255ffbf6a`](https://github.com/nodejs/node-gyp/commit/c255ffbf6a)] - **lib**: drop "-2" flag for "py.exe" launcher (DeeDeeG) [#2131](https://github.com/nodejs/node-gyp/pull/2131)
* [[`1f7e1e93b5`](https://github.com/nodejs/node-gyp/commit/1f7e1e93b5)] - **lib**: ignore VS instances that cause COMExceptions (Andrew Casey) [#2018](https://github.com/nodejs/node-gyp/pull/2018)
* [[`741ab096d5`](https://github.com/nodejs/node-gyp/commit/741ab096d5)] - **test**: remove support for EOL versions of Node.js (Shelley Vohr)
* [[`ca86ef2539`](https://github.com/nodejs/node-gyp/commit/ca86ef2539)] - **test**: bump actions/checkout from v1 to v2 (BSKY) [#2063](https://github.com/nodejs/node-gyp/pull/2063)

## v6.1.0 2020-01-08

* [[`9a7dd16b76`](https://github.com/nodejs/node-gyp/commit/9a7dd16b76)] - **doc**: remove backticks from Python version list (Rod Vagg) [#2011](https://github.com/nodejs/node-gyp/pull/2011)
* [[`26cd6eaea6`](https://github.com/nodejs/node-gyp/commit/26cd6eaea6)] - **doc**: add GitHub Actions badge (#1994) (Rod Vagg) [#1994](https://github.com/nodejs/node-gyp/pull/1994)
* [[`312c12ef4f`](https://github.com/nodejs/node-gyp/commit/312c12ef4f)] - **doc**: update macOS\_Catalina.md (#1992) (James Home) [#1992](https://github.com/nodejs/node-gyp/pull/1992)
* [[`f7b6b6b77b`](https://github.com/nodejs/node-gyp/commit/f7b6b6b77b)] - **doc**: fix typo in README.md (#1985) (Suraneti Rodsuwan) [#1985](https://github.com/nodejs/node-gyp/pull/1985)
* [[`6b8f2652dd`](https://github.com/nodejs/node-gyp/commit/6b8f2652dd)] - **doc**: add travis badge (Rod Vagg) [#1971](https://github.com/nodejs/node-gyp/pull/1971)
* [[`20aa0b44f7`](https://github.com/nodejs/node-gyp/commit/20aa0b44f7)] - **doc**: macOS Catalina add two commands (Christian Clauss) [#1962](https://github.com/nodejs/node-gyp/pull/1962)
* [[`14f2a07a39`](https://github.com/nodejs/node-gyp/commit/14f2a07a39)] - **gyp**: list(dict) so we can del dict(key) while iterating (Christian Clauss) [#2009](https://github.com/nodejs/node-gyp/pull/2009)
* [[`f242ce4d2c`](https://github.com/nodejs/node-gyp/commit/f242ce4d2c)] - **lib**: compatibility with semver ≥ 7 (`new` for semver.Range) (Xavier Guimard) [#2006](https://github.com/nodejs/node-gyp/pull/2006)
* [[`3bcba2a01a`](https://github.com/nodejs/node-gyp/commit/3bcba2a01a)] - **(SEMVER-MINOR)** **lib**: noproxy support, match proxy detection to `request` (Matias Lopez) [#1978](https://github.com/nodejs/node-gyp/pull/1978)
* [[`470cc2178e`](https://github.com/nodejs/node-gyp/commit/470cc2178e)] - **test**: remove old docker test harness (#1993) (Rod Vagg) [#1993](https://github.com/nodejs/node-gyp/pull/1993)
* [[`31ecc8421d`](https://github.com/nodejs/node-gyp/commit/31ecc8421d)] - **test**: add Windows to GitHub Actions testing (#1996) (Christian Clauss) [#1996](https://github.com/nodejs/node-gyp/pull/1996)
* [[`5a729e86ee`](https://github.com/nodejs/node-gyp/commit/5a729e86ee)] - **test**: fix typo in header download test (#2001) (Richard Lau) [#2001](https://github.com/nodejs/node-gyp/pull/2001)
* [[`345c70e56d`](https://github.com/nodejs/node-gyp/commit/345c70e56d)] - **test**: direct python invocation & simpler pyenv (Matias Lopez) [#1979](https://github.com/nodejs/node-gyp/pull/1979)
* [[`d6a7e0e1fb`](https://github.com/nodejs/node-gyp/commit/d6a7e0e1fb)] - **test**: fix macOS Travis on Python 2.7 & 3.7 (Christian Clauss) [#1979](https://github.com/nodejs/node-gyp/pull/1979)
* [[`5a64e9bd32`](https://github.com/nodejs/node-gyp/commit/5a64e9bd32)] - **test**: initial Github Actions with Ubuntu & macOS (Christian Clauss) [#1985](https://github.com/nodejs/node-gyp/pull/1985)
* [[`04da736d38`](https://github.com/nodejs/node-gyp/commit/04da736d38)] - **test**: fix Python unittests (cclauss) [#1961](https://github.com/nodejs/node-gyp/pull/1961)
* [[`0670e5189d`](https://github.com/nodejs/node-gyp/commit/0670e5189d)] - **test**: add header download test (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796)
* [[`c506a6a150`](https://github.com/nodejs/node-gyp/commit/c506a6a150)] - **test**: configure proper devDir for invoking configure() (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796)

## v6.0.1 2019-11-01

* [[`8ec2e681d5`](https://github.com/nodejs/node-gyp/commit/8ec2e681d5)] - **doc**: add macOS\_Catalina.md document (cclauss) [#1940](https://github.com/nodejs/node-gyp/pull/1940)
* [[`1b11be63cc`](https://github.com/nodejs/node-gyp/commit/1b11be63cc)] - **gyp**: python3 fixes: utf8 decode, use of 'None' in eval (Wilfried Goesgens) [#1925](https://github.com/nodejs/node-gyp/pull/1925)
* [[`c0282daa48`](https://github.com/nodejs/node-gyp/commit/c0282daa48)] - **gyp**: iteritems() -\> items() in compile\_commands\_json.py (cclauss) [#1947](https://github.com/nodejs/node-gyp/pull/1947)
* [[`d8e09a1b6a`](https://github.com/nodejs/node-gyp/commit/d8e09a1b6a)] - **gyp**: make cmake python3 compatible (gengjiawen) [#1944](https://github.com/nodejs/node-gyp/pull/1944)
* [[`9c0f3404f0`](https://github.com/nodejs/node-gyp/commit/9c0f3404f0)] - **gyp**: fix TypeError in XcodeVersion() (Christian Clauss) [#1939](https://github.com/nodejs/node-gyp/pull/1939)
* [[`bb2eb72a3f`](https://github.com/nodejs/node-gyp/commit/bb2eb72a3f)] - **gyp**: finish decode stdout on Python 3 (Christian Clauss) [#1937](https://github.com/nodejs/node-gyp/pull/1937)
* [[`f0693413d9`](https://github.com/nodejs/node-gyp/commit/f0693413d9)] - **src,win**: allow 403 errors for arm64 node.lib (Richard Lau) [#1934](https://github.com/nodejs/node-gyp/pull/1934)
* [[`c60c22de58`](https://github.com/nodejs/node-gyp/commit/c60c22de58)] - **deps**: update deps to roughly match current npm@6 (Rod Vagg) [#1920](https://github.com/nodejs/node-gyp/pull/1920)
* [[`b91718eefc`](https://github.com/nodejs/node-gyp/commit/b91718eefc)] - **test**: upgrade Linux Travis CI to Python 3.8 (Christian Clauss) [#1923](https://github.com/nodejs/node-gyp/pull/1923)
* [[`3538a317b6`](https://github.com/nodejs/node-gyp/commit/3538a317b6)] - **doc**: adjustments to the README.md for new users (Dan Pike) [#1919](https://github.com/nodejs/node-gyp/pull/1919)
* [[`4fff8458c0`](https://github.com/nodejs/node-gyp/commit/4fff8458c0)] - **travis**: ignore failed `brew upgrade npm`, update xcode (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932)
* [[`60e4488f08`](https://github.com/nodejs/node-gyp/commit/60e4488f08)] - **build**: avoid bare exceptions in xcode\_emulation.py (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932)
* [[`032db2a2d0`](https://github.com/nodejs/node-gyp/commit/032db2a2d0)] - **lib,install**: always download SHA sums on Windows (Sam Hughes) [#1926](https://github.com/nodejs/node-gyp/pull/1926)
* [[`5a83630c33`](https://github.com/nodejs/node-gyp/commit/5a83630c33)] - **travis**: add Windows + Python 3.8 to the mix (Rod Vagg) [#1921](https://github.com/nodejs/node-gyp/pull/1921)

## v6.0.0 2019-10-04

* [[`dd0e97ef0b`](https://github.com/nodejs/node-gyp/commit/dd0e97ef0b)] - **(SEMVER-MAJOR)** **lib**: try to find `python` after `python3` (Sam Roberts) [#1907](https://github.com/nodejs/node-gyp/pull/1907)
* [[`f60ed47d14`](https://github.com/nodejs/node-gyp/commit/f60ed47d14)] - **travis**: add Python 3.5 and 3.6 tests on Linux (Christian Clauss) [#1903](https://github.com/nodejs/node-gyp/pull/1903)
* [[`c763ca1838`](https://github.com/nodejs/node-gyp/commit/c763ca1838)] - **(SEMVER-MAJOR)** **doc**: Declare that node-gyp is Python 3 compatible (cclauss) [#1811](https://github.com/nodejs/node-gyp/pull/1811)
* [[`3d1c60ab81`](https://github.com/nodejs/node-gyp/commit/3d1c60ab81)] - **(SEMVER-MAJOR)** **lib**: accept Python 3 by default (João Reis) [#1844](https://github.com/nodejs/node-gyp/pull/1844)
* [[`c6e3b65a23`](https://github.com/nodejs/node-gyp/commit/c6e3b65a23)] - **(SEMVER-MAJOR)** **lib**: raise the minimum Python version from 2.6 to 2.7 (cclauss) [#1818](https://github.com/nodejs/node-gyp/pull/1818)

## v5.1.1 2020-05-25

* [[`bdd3a79abe`](https://github.com/nodejs/node-gyp/commit/bdd3a79abe)] - **build**: shrink bloated addon binaries on windows (Shelley Vohr) [#2060](https://github.com/nodejs/node-gyp/pull/2060)
* [[`1f2ba75bc0`](https://github.com/nodejs/node-gyp/commit/1f2ba75bc0)] - **doc**: add macOS Catalina software update info (Karl Horky) [#2078](https://github.com/nodejs/node-gyp/pull/2078)
* [[`c106d915f5`](https://github.com/nodejs/node-gyp/commit/c106d915f5)] - **doc**: update catalina xcode cli tools download link (#2044) (Dario Vladović) [#2044](https://github.com/nodejs/node-gyp/pull/2044)
* [[`9a6fea92e2`](https://github.com/nodejs/node-gyp/commit/9a6fea92e2)] - **doc**: update catalina xcode cli tools download link; formatting (Jonathan Hult) [#2034](https://github.com/nodejs/node-gyp/pull/2034)
* [[`59b0b1add8`](https://github.com/nodejs/node-gyp/commit/59b0b1add8)] - **doc**: add download link for Command Line Tools for Xcode (Przemysław Bitkowski) [#2029](https://github.com/nodejs/node-gyp/pull/2029)
* [[`bb8d0e7b10`](https://github.com/nodejs/node-gyp/commit/bb8d0e7b10)] - **doc**: Catalina suggestion: remove /Library/Developer/CommandLineTools (Christian Clauss) [#2022](https://github.com/nodejs/node-gyp/pull/2022)
* [[`fb2e80d4e3`](https://github.com/nodejs/node-gyp/commit/fb2e80d4e3)] - **doc**: update link to the code of conduct (#2073) (Michaël Zasso) [#2073](https://github.com/nodejs/node-gyp/pull/2073)
* [[`251d9c885c`](https://github.com/nodejs/node-gyp/commit/251d9c885c)] - **doc**: note in README that Python 3.8 is supported (#2072) (Michaël Zasso) [#2072](https://github.com/nodejs/node-gyp/pull/2072)
* [[`2b6fc3c8d6`](https://github.com/nodejs/node-gyp/commit/2b6fc3c8d6)] - **doc, bin**: stop suggesting opening  node-gyp issues (Bartosz Sosnowski) [#2096](https://github.com/nodejs/node-gyp/pull/2096)
* [[`a876ae58ad`](https://github.com/nodejs/node-gyp/commit/a876ae58ad)] - **test**: bump actions/checkout from v1 to v2 (BSKY) [#2063](https://github.com/nodejs/node-gyp/pull/2063)

## v5.1.0 2020-02-05

* [[`f37a8b40d0`](https://github.com/nodejs/node-gyp/commit/f37a8b40d0)] - **doc**: add GitHub Actions badge (#1994) (Rod Vagg) [#1994](https://github.com/nodejs/node-gyp/pull/1994)
* [[`cb3f6aae5e`](https://github.com/nodejs/node-gyp/commit/cb3f6aae5e)] - **doc**: update macOS\_Catalina.md (#1992) (James Home) [#1992](https://github.com/nodejs/node-gyp/pull/1992)
* [[`0607596a4c`](https://github.com/nodejs/node-gyp/commit/0607596a4c)] - **doc**: fix typo in README.md (#1985) (Suraneti Rodsuwan) [#1985](https://github.com/nodejs/node-gyp/pull/1985)
* [[`0d5a415a14`](https://github.com/nodejs/node-gyp/commit/0d5a415a14)] - **doc**: add travis badge (Rod Vagg) [#1971](https://github.com/nodejs/node-gyp/pull/1971)
* [[`103740cd95`](https://github.com/nodejs/node-gyp/commit/103740cd95)] - **gyp**: list(dict) so we can del dict(key) while iterating (Christian Clauss) [#2009](https://github.com/nodejs/node-gyp/pull/2009)
* [[`278dcddbdd`](https://github.com/nodejs/node-gyp/commit/278dcddbdd)] - **lib**: ignore VS instances that cause COMExceptions (Andrew Casey) [#2018](https://github.com/nodejs/node-gyp/pull/2018)
* [[`1694907bbf`](https://github.com/nodejs/node-gyp/commit/1694907bbf)] - **lib**: compatibility with semver ≥ 7 (`new` for semver.Range) (Xavier Guimard) [#2006](https://github.com/nodejs/node-gyp/pull/2006)
* [[`a3f1143514`](https://github.com/nodejs/node-gyp/commit/a3f1143514)] - **(SEMVER-MINOR)** **lib**: noproxy support, match proxy detection to `request` (Matias Lopez) [#1978](https://github.com/nodejs/node-gyp/pull/1978)
* [[`52365819c7`](https://github.com/nodejs/node-gyp/commit/52365819c7)] - **test**: remove old docker test harness (#1993) (Rod Vagg) [#1993](https://github.com/nodejs/node-gyp/pull/1993)
* [[`bc509c511d`](https://github.com/nodejs/node-gyp/commit/bc509c511d)] - **test**: add Windows to GitHub Actions testing (#1996) (Christian Clauss) [#1996](https://github.com/nodejs/node-gyp/pull/1996)
* [[`91ee26dd48`](https://github.com/nodejs/node-gyp/commit/91ee26dd48)] - **test**: fix typo in header download test (#2001) (Richard Lau) [#2001](https://github.com/nodejs/node-gyp/pull/2001)
* [[`0923f344c9`](https://github.com/nodejs/node-gyp/commit/0923f344c9)] - **test**: direct python invocation & simpler pyenv (Matias Lopez) [#1979](https://github.com/nodejs/node-gyp/pull/1979)
* [[`32c8744b34`](https://github.com/nodejs/node-gyp/commit/32c8744b34)] - **test**: fix macOS Travis on Python 2.7 & 3.7 (Christian Clauss) [#1979](https://github.com/nodejs/node-gyp/pull/1979)
* [[`fd4b1351e4`](https://github.com/nodejs/node-gyp/commit/fd4b1351e4)] - **test**: initial Github Actions with Ubuntu & macOS (Christian Clauss) [#1985](https://github.com/nodejs/node-gyp/pull/1985)

## v5.0.7 2019-12-16

Republish of v5.0.6 with unnecessary tarball removed from pack file.

## v5.0.6 2019-12-16

* [[`cdec00286f`](https://github.com/nodejs/node-gyp/commit/cdec00286f)] - **doc**: adjustments to the README.md for new users (Dan Pike) [#1919](https://github.com/nodejs/node-gyp/pull/1919)
* [[`b7c8233ef2`](https://github.com/nodejs/node-gyp/commit/b7c8233ef2)] - **test**: fix Python unittests (cclauss) [#1961](https://github.com/nodejs/node-gyp/pull/1961)
* [[`e12b00ab0a`](https://github.com/nodejs/node-gyp/commit/e12b00ab0a)] - **doc**: macOS Catalina add two commands (Christian Clauss) [#1962](https://github.com/nodejs/node-gyp/pull/1962)
* [[`70b9890c0d`](https://github.com/nodejs/node-gyp/commit/70b9890c0d)] - **test**: add header download test (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796)
* [[`4029fa8629`](https://github.com/nodejs/node-gyp/commit/4029fa8629)] - **test**: configure proper devDir for invoking configure() (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796)
* [[`fe8b02cc8b`](https://github.com/nodejs/node-gyp/commit/fe8b02cc8b)] - **doc**: add macOS\_Catalina.md document (cclauss) [#1940](https://github.com/nodejs/node-gyp/pull/1940)
* [[`8ea47ce365`](https://github.com/nodejs/node-gyp/commit/8ea47ce365)] - **gyp**: python3 fixes: utf8 decode, use of 'None' in eval (Wilfried Goesgens) [#1925](https://github.com/nodejs/node-gyp/pull/1925)
* [[`c7229716ba`](https://github.com/nodejs/node-gyp/commit/c7229716ba)] - **gyp**: iteritems() -\> items() in compile\_commands\_json.py (cclauss) [#1947](https://github.com/nodejs/node-gyp/pull/1947)
* [[`2a18b2a0f8`](https://github.com/nodejs/node-gyp/commit/2a18b2a0f8)] - **gyp**: make cmake python3 compatible (gengjiawen) [#1944](https://github.com/nodejs/node-gyp/pull/1944)
* [[`70f391e844`](https://github.com/nodejs/node-gyp/commit/70f391e844)] - **gyp**: fix TypeError in XcodeVersion() (Christian Clauss) [#1939](https://github.com/nodejs/node-gyp/pull/1939)
* [[`9f4f0fa34e`](https://github.com/nodejs/node-gyp/commit/9f4f0fa34e)] - **gyp**: finish decode stdout on Python 3 (Christian Clauss) [#1937](https://github.com/nodejs/node-gyp/pull/1937)
* [[`7cf507906d`](https://github.com/nodejs/node-gyp/commit/7cf507906d)] - **src,win**: allow 403 errors for arm64 node.lib (Richard Lau) [#1934](https://github.com/nodejs/node-gyp/pull/1934)
* [[`ad0d182c01`](https://github.com/nodejs/node-gyp/commit/ad0d182c01)] - **deps**: update deps to roughly match current npm@6 (Rod Vagg) [#1920](https://github.com/nodejs/node-gyp/pull/1920)
* [[`1553081ed6`](https://github.com/nodejs/node-gyp/commit/1553081ed6)] - **test**: upgrade Linux Travis CI to Python 3.8 (Christian Clauss) [#1923](https://github.com/nodejs/node-gyp/pull/1923)
* [[`0705cae9aa`](https://github.com/nodejs/node-gyp/commit/0705cae9aa)] - **travis**: ignore failed `brew upgrade npm`, update xcode (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932)
* [[`7bfdb6f5bf`](https://github.com/nodejs/node-gyp/commit/7bfdb6f5bf)] - **build**: avoid bare exceptions in xcode\_emulation.py (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932)
* [[`7edf7658fa`](https://github.com/nodejs/node-gyp/commit/7edf7658fa)] - **lib,install**: always download SHA sums on Windows (Sam Hughes) [#1926](https://github.com/nodejs/node-gyp/pull/1926)
* [[`69056d04fe`](https://github.com/nodejs/node-gyp/commit/69056d04fe)] - **travis**: add Windows + Python 3.8 to the mix (Rod Vagg) [#1921](https://github.com/nodejs/node-gyp/pull/1921)

## v5.0.5 2019-10-04

* [[`3891391746`](https://github.com/nodejs/node-gyp/commit/3891391746)] - **doc**: reconcile README with Python 3 compat changes (Rod Vagg) [#1911](https://github.com/nodejs/node-gyp/pull/1911)
* [[`07f81f1920`](https://github.com/nodejs/node-gyp/commit/07f81f1920)] - **lib**: accept Python 3 after Python 2 (Sam Roberts) [#1910](https://github.com/nodejs/node-gyp/pull/1910)
* [[`04ce59f4a2`](https://github.com/nodejs/node-gyp/commit/04ce59f4a2)] - **doc**: clarify Python configuration, etc (Sam Roberts) [#1908](https://github.com/nodejs/node-gyp/pull/1908)
* [[`01c46ee3df`](https://github.com/nodejs/node-gyp/commit/01c46ee3df)] - **gyp**: add \_\_lt\_\_ to MSVSSolutionEntry (João Reis) [#1904](https://github.com/nodejs/node-gyp/pull/1904)
* [[`735d961b99`](https://github.com/nodejs/node-gyp/commit/735d961b99)] - **win**: support VS 2017 Desktop Express (João Reis) [#1902](https://github.com/nodejs/node-gyp/pull/1902)
* [[`3834156a92`](https://github.com/nodejs/node-gyp/commit/3834156a92)] - **test**: add Python 3.5 and 3.6 tests on Linux (cclauss) [#1909](https://github.com/nodejs/node-gyp/pull/1909)
* [[`1196e990d8`](https://github.com/nodejs/node-gyp/commit/1196e990d8)] - **src**: update to standard@14 (Rod Vagg) [#1899](https://github.com/nodejs/node-gyp/pull/1899)
* [[`53ee7dfe89`](https://github.com/nodejs/node-gyp/commit/53ee7dfe89)] - **gyp**: fix undefined name: cflags --\> ldflags (Christian Clauss) [#1901](https://github.com/nodejs/node-gyp/pull/1901)
* [[`5871dcf6c9`](https://github.com/nodejs/node-gyp/commit/5871dcf6c9)] - **src,win**: add support for fetching arm64 node.lib (Richard Townsend) [#1875](https://github.com/nodejs/node-gyp/pull/1875)

## v5.0.4 2019-09-27

* [[`1236869ffc`](https://github.com/nodejs/node-gyp/commit/1236869ffc)] - **gyp**: modify XcodeVersion() to convert "4.2" to "0420" and "10.0" to "1000" (Christian Clauss) [#1895](https://github.com/nodejs/node-gyp/pull/1895)
* [[`36638afe48`](https://github.com/nodejs/node-gyp/commit/36638afe48)] - **gyp**: more decode stdout on Python 3 (cclauss) [#1894](https://github.com/nodejs/node-gyp/pull/1894)
* [[`f753c167c5`](https://github.com/nodejs/node-gyp/commit/f753c167c5)] - **gyp**: decode stdout on Python 3 (cclauss) [#1890](https://github.com/nodejs/node-gyp/pull/1890)
* [[`60a4083523`](https://github.com/nodejs/node-gyp/commit/60a4083523)] - **doc**: update xcode install instructions to match Node's BUILDING (Nhan Khong) [#1884](https://github.com/nodejs/node-gyp/pull/1884)
* [[`19dbc9ac32`](https://github.com/nodejs/node-gyp/commit/19dbc9ac32)] - **deps**: update tar to 4.4.12 (Matheus Marchini) [#1889](https://github.com/nodejs/node-gyp/pull/1889)
* [[`5f3ed92181`](https://github.com/nodejs/node-gyp/commit/5f3ed92181)] - **bin**: fix the usage instructions (Halit Ogunc) [#1888](https://github.com/nodejs/node-gyp/pull/1888)
* [[`aab118edf1`](https://github.com/nodejs/node-gyp/commit/aab118edf1)] - **lib**: adding keep-alive header to download requests (Milad Farazmand) [#1863](https://github.com/nodejs/node-gyp/pull/1863)
* [[`1186e89326`](https://github.com/nodejs/node-gyp/commit/1186e89326)] - **lib**: ignore non-critical os.userInfo() failures (Rod Vagg) [#1835](https://github.com/nodejs/node-gyp/pull/1835)
* [[`785e527c3d`](https://github.com/nodejs/node-gyp/commit/785e527c3d)] - **doc**: fix missing argument for setting python path (lagorsse) [#1802](https://github.com/nodejs/node-gyp/pull/1802)
* [[`a97615196c`](https://github.com/nodejs/node-gyp/commit/a97615196c)] - **gyp**: rm semicolons (Python != JavaScript) (MattIPv4) [#1858](https://github.com/nodejs/node-gyp/pull/1858)
* [[`06019bac24`](https://github.com/nodejs/node-gyp/commit/06019bac24)] - **gyp**: assorted typo fixes (XhmikosR) [#1853](https://github.com/nodejs/node-gyp/pull/1853)
* [[`3f4972c1ca`](https://github.com/nodejs/node-gyp/commit/3f4972c1ca)] - **gyp**: use "is" when comparing to None (Vladyslav Burzakovskyy) [#1860](https://github.com/nodejs/node-gyp/pull/1860)
* [[`1cb4708073`](https://github.com/nodejs/node-gyp/commit/1cb4708073)] - **src,win**: improve unmanaged handling (Peter Sabath) [#1852](https://github.com/nodejs/node-gyp/pull/1852)
* [[`5553cd910e`](https://github.com/nodejs/node-gyp/commit/5553cd910e)] - **gyp**: improve Windows+Cygwin compatibility (Jose Quijada) [#1817](https://github.com/nodejs/node-gyp/pull/1817)
* [[`8bcb1fbb43`](https://github.com/nodejs/node-gyp/commit/8bcb1fbb43)] - **gyp**: Python 3 Windows fixes (João Reis) [#1843](https://github.com/nodejs/node-gyp/pull/1843)
* [[`2e24d0a326`](https://github.com/nodejs/node-gyp/commit/2e24d0a326)] - **test**: accept Python 3 in test-find-python.js (João Reis) [#1843](https://github.com/nodejs/node-gyp/pull/1843)
* [[`1267b4dc1c`](https://github.com/nodejs/node-gyp/commit/1267b4dc1c)] - **build**: add test run Python 3.7 on macOS (Christian Clauss) [#1843](https://github.com/nodejs/node-gyp/pull/1843)
* [[`da1b031aa3`](https://github.com/nodejs/node-gyp/commit/da1b031aa3)] - **build**: import StringIO on Python 2 and Python 3 (Christian Clauss) [#1836](https://github.com/nodejs/node-gyp/pull/1836)
* [[`fa0ed4aa42`](https://github.com/nodejs/node-gyp/commit/fa0ed4aa42)] - **build**: more Python 3 compat, replace compile with ast (cclauss) [#1820](https://github.com/nodejs/node-gyp/pull/1820)
* [[`18d5c7c9d0`](https://github.com/nodejs/node-gyp/commit/18d5c7c9d0)] - **win,src**: update win\_delay\_load\_hook.cc to work with /clr (Ivan Petrovic) [#1819](https://github.com/nodejs/node-gyp/pull/1819)

## v5.0.3 2019-07-17

* [[`66ad305775`](https://github.com/nodejs/node-gyp/commit/66ad305775)] - **python**: accept Python 3 conditionally (João Reis) [#1815](https://github.com/nodejs/node-gyp/pull/1815)
* [[`7e7fce3fed`](https://github.com/nodejs/node-gyp/commit/7e7fce3fed)] - **python**: move Python detection to its own file (João Reis) [#1815](https://github.com/nodejs/node-gyp/pull/1815)
* [[`e40c99e283`](https://github.com/nodejs/node-gyp/commit/e40c99e283)] - **src**: implement standard.js linting (Rod Vagg) [#1794](https://github.com/nodejs/node-gyp/pull/1794)
* [[`bb92c761a9`](https://github.com/nodejs/node-gyp/commit/bb92c761a9)] - **test**: add Node.js 6 on Windows to Travis CI (João Reis) [#1812](https://github.com/nodejs/node-gyp/pull/1812)
* [[`7fd924079f`](https://github.com/nodejs/node-gyp/commit/7fd924079f)] - **test**: increase tap timeout (João Reis) [#1812](https://github.com/nodejs/node-gyp/pull/1812)
* [[`7e8127068f`](https://github.com/nodejs/node-gyp/commit/7e8127068f)] - **test**: cover supported node versions with travis (Rod Vagg) [#1809](https://github.com/nodejs/node-gyp/pull/1809)
* [[`24109148df`](https://github.com/nodejs/node-gyp/commit/24109148df)] - **test**: downgrade to tap@^12 for continued Node 6 support (Rod Vagg) [#1808](https://github.com/nodejs/node-gyp/pull/1808)
* [[`656117cc4a`](https://github.com/nodejs/node-gyp/commit/656117cc4a)] - **win**: make VS path match case-insensitive (João Reis) [#1806](https://github.com/nodejs/node-gyp/pull/1806)

## v5.0.2 2019-06-27

* [[`2761afbf73`](https://github.com/nodejs/node-gyp/commit/2761afbf73)] - **build,test**: add duplicate symbol test (Gabriel Schulhof) [#1689](https://github.com/nodejs/node-gyp/pull/1689)
* [[`82f129d6de`](https://github.com/nodejs/node-gyp/commit/82f129d6de)] - **gyp**: replace optparse to argparse (KiYugadgeter) [#1591](https://github.com/nodejs/node-gyp/pull/1591)
* [[`afaaa29c61`](https://github.com/nodejs/node-gyp/commit/afaaa29c61)] - **gyp**: remove from \_\_future\_\_ import with\_statement (cclauss) [#1799](https://github.com/nodejs/node-gyp/pull/1799)
* [[`a991f633d6`](https://github.com/nodejs/node-gyp/commit/a991f633d6)] - **gyp**: fix the remaining Python 3 issues (cclauss) [#1793](https://github.com/nodejs/node-gyp/pull/1793)
* [[`f952b08f84`](https://github.com/nodejs/node-gyp/commit/f952b08f84)] - **gyp**: move from \_\_future\_\_ import to the top of the file (cclauss) [#1789](https://github.com/nodejs/node-gyp/pull/1789)
* [[`4f4a677dfa`](https://github.com/nodejs/node-gyp/commit/4f4a677dfa)] - **gyp**: use different default compiler for z/OS (Shuowang (Wayne) Zhang) [#1768](https://github.com/nodejs/node-gyp/pull/1768)
* [[`03683f09d6`](https://github.com/nodejs/node-gyp/commit/03683f09d6)] - **lib**: code de-duplication (Pavel Medvedev) [#965](https://github.com/nodejs/node-gyp/pull/965)
* [[`611bc3c89f`](https://github.com/nodejs/node-gyp/commit/611bc3c89f)] - **lib**: add .json suffix for explicit require (Rod Vagg) [#1787](https://github.com/nodejs/node-gyp/pull/1787)
* [[`d3478d7b0b`](https://github.com/nodejs/node-gyp/commit/d3478d7b0b)] - **meta**: add to .gitignore (Refael Ackermann) [#1573](https://github.com/nodejs/node-gyp/pull/1573)
* [[`7a9a038e9e`](https://github.com/nodejs/node-gyp/commit/7a9a038e9e)] - **test**: add parallel test runs on macOS and Windows (cclauss) [#1800](https://github.com/nodejs/node-gyp/pull/1800)
* [[`7dd7f2b2a2`](https://github.com/nodejs/node-gyp/commit/7dd7f2b2a2)] - **test**: fix Python syntax error in test-adding.js (cclauss) [#1793](https://github.com/nodejs/node-gyp/pull/1793)
* [[`395f843de0`](https://github.com/nodejs/node-gyp/commit/395f843de0)] - **test**: replace self-signed cert with 'localhost' (Rod Vagg) [#1795](https://github.com/nodejs/node-gyp/pull/1795)
* [[`a52c6eb9e8`](https://github.com/nodejs/node-gyp/commit/a52c6eb9e8)] - **test**: migrate from tape to tap (Rod Vagg) [#1795](https://github.com/nodejs/node-gyp/pull/1795)
* [[`ec2eb44a30`](https://github.com/nodejs/node-gyp/commit/ec2eb44a30)] - **test**: use Nan in duplicate\_symbols (Gabriel Schulhof) [#1689](https://github.com/nodejs/node-gyp/pull/1689)
* [[`1597c84aad`](https://github.com/nodejs/node-gyp/commit/1597c84aad)] - **test**: use Travis CI to run tests on every pull request (cclauss) [#1752](https://github.com/nodejs/node-gyp/pull/1752)
* [[`dd9bf929ac`](https://github.com/nodejs/node-gyp/commit/dd9bf929ac)] - **zos**: update compiler options (Shuowang (Wayne) Zhang) [#1768](https://github.com/nodejs/node-gyp/pull/1768)

## v5.0.1 2019-06-20

* [[`e3861722ed`](https://github.com/nodejs/node-gyp/commit/e3861722ed)] - **doc**: document --jobs max (David Sanders) [#1770](https://github.com/nodejs/node-gyp/pull/1770)
* [[`1cfdb28886`](https://github.com/nodejs/node-gyp/commit/1cfdb28886)] - **lib**: reintroduce support for iojs file naming for releases \>= 1 && \< 4 (Samuel Attard) [#1777](https://github.com/nodejs/node-gyp/pull/1777)

## v5.0.0 2019-06-13

* [[`8a83972743`](https://github.com/nodejs/node-gyp/commit/8a83972743)] - **(SEMVER-MAJOR)** **bin**: follow XDG OS conventions for storing data (Selwyn) [#1570](https://github.com/nodejs/node-gyp/pull/1570)
* [[`9e46872ea3`](https://github.com/nodejs/node-gyp/commit/9e46872ea3)] - **bin,lib**: remove extra comments/lines/spaces (Jon Moss) [#1508](https://github.com/nodejs/node-gyp/pull/1508)
* [[`8098ebdeb4`](https://github.com/nodejs/node-gyp/commit/8098ebdeb4)] - **deps**: replace `osenv` dependency with native `os` (Selwyn)
* [[`f83b457e03`](https://github.com/nodejs/node-gyp/commit/f83b457e03)] - **deps**: bump request to 2.8.7, fixes heok/hawk issues (Rohit Hazra) [#1492](https://github.com/nodejs/node-gyp/pull/1492)
* [[`323cee7323`](https://github.com/nodejs/node-gyp/commit/323cee7323)] - **deps**: pin `request` version range (Refael Ackermann) [#1300](https://github.com/nodejs/node-gyp/pull/1300)
* [[`c515912d08`](https://github.com/nodejs/node-gyp/commit/c515912d08)] - **doc**: improve issue template (Bartosz Sosnowski) [#1618](https://github.com/nodejs/node-gyp/pull/1618)
* [[`cca2d66727`](https://github.com/nodejs/node-gyp/commit/cca2d66727)] - **doc**: python info needs own header (Taylor D. Lee) [#1245](https://github.com/nodejs/node-gyp/pull/1245)
* [[`3e64c780f5`](https://github.com/nodejs/node-gyp/commit/3e64c780f5)] - **doc**: lint README.md (Jon Moss) [#1498](https://github.com/nodejs/node-gyp/pull/1498)
* [[`a20faedc91`](https://github.com/nodejs/node-gyp/commit/a20faedc91)] - **(SEMVER-MAJOR)** **gyp**: enable MARMASM items only on new VS versions (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`721eb691cf`](https://github.com/nodejs/node-gyp/commit/721eb691cf)] - **gyp**: teach MSVS generator about MARMASM Items (Jon Kunkee) [#1679](https://github.com/nodejs/node-gyp/pull/1679)
* [[`91744bfecc`](https://github.com/nodejs/node-gyp/commit/91744bfecc)] - **gyp**: add support for Windows on Arm (Richard Townsend) [#1739](https://github.com/nodejs/node-gyp/pull/1739)
* [[`a6e0a6c7ed`](https://github.com/nodejs/node-gyp/commit/a6e0a6c7ed)] - **gyp**: move compile\_commands\_json (Paul Maréchal) [#1661](https://github.com/nodejs/node-gyp/pull/1661)
* [[`92e8b52cee`](https://github.com/nodejs/node-gyp/commit/92e8b52cee)] - **gyp**: fix target --\> self.target (cclauss)
* [[`febdfa2137`](https://github.com/nodejs/node-gyp/commit/febdfa2137)] - **gyp**: fix sntex error (cclauss) [#1333](https://github.com/nodejs/node-gyp/pull/1333)
* [[`588d333c14`](https://github.com/nodejs/node-gyp/commit/588d333c14)] - **gyp**: \_winreg module was renamed to winreg in Python 3. (Craig Rodrigues)
* [[`98226d198c`](https://github.com/nodejs/node-gyp/commit/98226d198c)] - **gyp**: replace basestring with str, but only on Python 3. (Craig Rodrigues)
* [[`7535e4478e`](https://github.com/nodejs/node-gyp/commit/7535e4478e)] - **gyp**: replace deprecated functions (Craig Rodrigues)
* [[`2040cd21cc`](https://github.com/nodejs/node-gyp/commit/2040cd21cc)] - **gyp**: use print as a function, as specified in PEP 3105. (Craig Rodrigues)
* [[`abef93ded5`](https://github.com/nodejs/node-gyp/commit/abef93ded5)] - **gyp**: get ready for python 3 (cclauss)
* [[`43031fadcb`](https://github.com/nodejs/node-gyp/commit/43031fadcb)] - **python**: clean-up detection (João Reis) [#1582](https://github.com/nodejs/node-gyp/pull/1582)
* [[`49ab79d221`](https://github.com/nodejs/node-gyp/commit/49ab79d221)] - **python**: more informative error (Refael Ackermann) [#1269](https://github.com/nodejs/node-gyp/pull/1269)
* [[`997bc3c748`](https://github.com/nodejs/node-gyp/commit/997bc3c748)] - **readme**: add ARM64 info to MSVC setup instructions (Jon Kunkee) [#1655](https://github.com/nodejs/node-gyp/pull/1655)
* [[`788e767179`](https://github.com/nodejs/node-gyp/commit/788e767179)] - **test**: remove unused variable (João Reis)
* [[`6f5a408934`](https://github.com/nodejs/node-gyp/commit/6f5a408934)] - **tools**: fix usage of inherited -fPIC and -fPIE (Jens) [#1340](https://github.com/nodejs/node-gyp/pull/1340)
* [[`0efb8fb34b`](https://github.com/nodejs/node-gyp/commit/0efb8fb34b)] - **(SEMVER-MAJOR)** **win**: support running in VS Command Prompt (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`360ddbdf3a`](https://github.com/nodejs/node-gyp/commit/360ddbdf3a)] - **(SEMVER-MAJOR)** **win**: add support for Visual Studio 2019 (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`8f43f68275`](https://github.com/nodejs/node-gyp/commit/8f43f68275)] - **(SEMVER-MAJOR)** **win**: detect all VS versions in node-gyp (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`7fe4095974`](https://github.com/nodejs/node-gyp/commit/7fe4095974)] - **(SEMVER-MAJOR)** **win**: generic Visual Studio 2017 detection (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`7a71d68bce`](https://github.com/nodejs/node-gyp/commit/7a71d68bce)] - **win**: use msbuild from the configure stage (Bartosz Sosnowski) [#1654](https://github.com/nodejs/node-gyp/pull/1654)
* [[`d3b21220a0`](https://github.com/nodejs/node-gyp/commit/d3b21220a0)] - **win**: fix delay-load hook for electron 4 (Andy Dill)
* [[`81f3a92338`](https://github.com/nodejs/node-gyp/commit/81f3a92338)] - Update list of Node.js versions to test against. (Ben Noordhuis) [#1670](https://github.com/nodejs/node-gyp/pull/1670)
* [[`4748f6ab75`](https://github.com/nodejs/node-gyp/commit/4748f6ab75)] - Remove deprecated compatibility code. (Ben Noordhuis) [#1670](https://github.com/nodejs/node-gyp/pull/1670)
* [[`45e3221fd4`](https://github.com/nodejs/node-gyp/commit/45e3221fd4)] - Remove an outdated workaround for Python 2.4 (cclauss) [#1650](https://github.com/nodejs/node-gyp/pull/1650)
* [[`721dc7d314`](https://github.com/nodejs/node-gyp/commit/721dc7d314)] - Add ARM64 to MSBuild /Platform logic (Jon Kunkee) [#1655](https://github.com/nodejs/node-gyp/pull/1655)
* [[`a5b7410497`](https://github.com/nodejs/node-gyp/commit/a5b7410497)] - Add ESLint no-unused-vars rule (Jon Moss) [#1497](https://github.com/nodejs/node-gyp/pull/1497)

## v4.0.0 2019-04-24

* [[`ceed5cbe10`](https://github.com/nodejs/node-gyp/commit/ceed5cbe10)] - **deps**: updated tar package version to 4.4.8 (Pobegaylo Maksim) [#1713](https://github.com/nodejs/node-gyp/pull/1713)
* [[`374519e066`](https://github.com/nodejs/node-gyp/commit/374519e066)] - **(SEMVER-MAJOR)** Upgrade to tar v3 (isaacs) [#1212](https://github.com/nodejs/node-gyp/pull/1212)
* [[`e6699d13cd`](https://github.com/nodejs/node-gyp/commit/e6699d13cd)] - **test**: fix addon test for Node.js 12 and V8 7.4 (Richard Lau) [#1705](https://github.com/nodejs/node-gyp/pull/1705)
* [[`0c6bf530a0`](https://github.com/nodejs/node-gyp/commit/0c6bf530a0)] - **lib**: use print() for python version detection (GreenAddress) [#1534](https://github.com/nodejs/node-gyp/pull/1534)

## v3.8.0 2018-08-09

* [[`c5929cb4fe`](https://github.com/nodejs/node-gyp/commit/c5929cb4fe)] - **doc**: update Xcode preferences tab name. (Ivan Daniluk) [#1330](https://github.com/nodejs/node-gyp/pull/1330)
* [[`8b488da8b9`](https://github.com/nodejs/node-gyp/commit/8b488da8b9)] - **doc**: update link to commit guidelines (Jonas Hermsmeier) [#1456](https://github.com/nodejs/node-gyp/pull/1456)
* [[`b4fe8c16f9`](https://github.com/nodejs/node-gyp/commit/b4fe8c16f9)] - **doc**: fix visual studio links (Bartosz Sosnowski) [#1490](https://github.com/nodejs/node-gyp/pull/1490)
* [[`536759c7e9`](https://github.com/nodejs/node-gyp/commit/536759c7e9)] - **configure**: use sys.version\_info to get python version (Yang Guo) [#1504](https://github.com/nodejs/node-gyp/pull/1504)
* [[`94c39c604e`](https://github.com/nodejs/node-gyp/commit/94c39c604e)] - **gyp**: fix ninja build failure (GYP patch) (Daniel Bevenius) [nodejs/node#12484](https://github.com/nodejs/node/pull/12484)
* [[`e8ea74e0fa`](https://github.com/nodejs/node-gyp/commit/e8ea74e0fa)] - **tools**: patch gyp to avoid xcrun errors (Ujjwal Sharma) [nodejs/node#21520](https://github.com/nodejs/node/pull/21520)
* [[`ea9aff44f2`](https://github.com/nodejs/node-gyp/commit/ea9aff44f2)] - **tools**: fix "the the" typos in comments (Masashi Hirano) [nodejs/node#20716](https://github.com/nodejs/node/pull/20716)
* [[`207e5aa4fd`](https://github.com/nodejs/node-gyp/commit/207e5aa4fd)] - **gyp**: implement LD/LDXX for ninja and FIPS (Sam Roberts)
* [[`b416c5f4b7`](https://github.com/nodejs/node-gyp/commit/b416c5f4b7)] - **gyp**: enable cctest to use objects (gyp part) (Daniel Bevenius) [nodejs/node#12450](https://github.com/nodejs/node/pull/12450)
* [[`40692d016b`](https://github.com/nodejs/node-gyp/commit/40692d016b)] - **gyp**: add compile\_commands.json gyp generator (Ben Noordhuis) [nodejs/node#12450](https://github.com/nodejs/node/pull/12450)
* [[`fc3c4e2b10`](https://github.com/nodejs/node-gyp/commit/fc3c4e2b10)] - **gyp**: float gyp patch for long filenames (Anna Henningsen) [nodejs/node#7963](https://github.com/nodejs/node/pull/7963)
* [[`8aedbfdef6`](https://github.com/nodejs/node-gyp/commit/8aedbfdef6)] - **gyp**: backport GYP fix to fix AIX shared suffix (Stewart Addison)
* [[`6cd84b84fc`](https://github.com/nodejs/node-gyp/commit/6cd84b84fc)] - **test**: formatting and minor fixes for execFileSync replacement (Rod Vagg) [#1521](https://github.com/nodejs/node-gyp/pull/1521)
* [[`60e421363f`](https://github.com/nodejs/node-gyp/commit/60e421363f)] - **test**: added test/processExecSync.js for when execFileSync is not available. (Rohit Hazra) [#1492](https://github.com/nodejs/node-gyp/pull/1492)
* [[`969447c5bd`](https://github.com/nodejs/node-gyp/commit/969447c5bd)] - **deps**: bump request to 2.8.7, fixes heok/hawk issues (Rohit Hazra) [#1492](https://github.com/nodejs/node-gyp/pull/1492)
* [[`340403ccfe`](https://github.com/nodejs/node-gyp/commit/340403ccfe)] - **win**: improve parsing of SDK version (Alessandro Vergani) [#1516](https://github.com/nodejs/node-gyp/pull/1516)

## v3.7.0 2018-06-08

* [[`84cea7b30d`](https://github.com/nodejs/node-gyp/commit/84cea7b30d)] - Remove unused gyp test scripts. (Ben Noordhuis) [#1458](https://github.com/nodejs/node-gyp/pull/1458)
* [[`0540e4ec63`](https://github.com/nodejs/node-gyp/commit/0540e4ec63)] - **gyp**: escape spaces in filenames in make generator (Jeff Senn) [#1436](https://github.com/nodejs/node-gyp/pull/1436)
* [[`88fc6fa0ec`](https://github.com/nodejs/node-gyp/commit/88fc6fa0ec)] - Drop dependency on minimatch. (Brian Woodward) [#1158](https://github.com/nodejs/node-gyp/pull/1158)
* [[`1e203c5148`](https://github.com/nodejs/node-gyp/commit/1e203c5148)] - Fix include path when pointing to Node.js source (Richard Lau) [#1055](https://github.com/nodejs/node-gyp/pull/1055)
* [[`53d8cb967c`](https://github.com/nodejs/node-gyp/commit/53d8cb967c)] - Prefix build targets with /t: on Windows (Natalie Wolfe) [#1164](https://github.com/nodejs/node-gyp/pull/1164)
* [[`53a5f8ff38`](https://github.com/nodejs/node-gyp/commit/53a5f8ff38)] - **gyp**: add support for .mm files to msvs generator (Julien Racle) [#1167](https://github.com/nodejs/node-gyp/pull/1167)
* [[`dd8561e528`](https://github.com/nodejs/node-gyp/commit/dd8561e528)] - **zos**: don't use universal-new-lines mode (John Barboza) [#1451](https://github.com/nodejs/node-gyp/pull/1451)
* [[`e5a69010ed`](https://github.com/nodejs/node-gyp/commit/e5a69010ed)] - **zos**: add search locations for libnode.x (John Barboza) [#1451](https://github.com/nodejs/node-gyp/pull/1451)
* [[`79febace53`](https://github.com/nodejs/node-gyp/commit/79febace53)] - **doc**: update macOS information in README (Josh Parnham) [#1323](https://github.com/nodejs/node-gyp/pull/1323)
* [[`9425448945`](https://github.com/nodejs/node-gyp/commit/9425448945)] - **gyp**: don't print xcodebuild not found errors (Gibson Fahnestock) [#1370](https://github.com/nodejs/node-gyp/pull/1370)
* [[`6f1286f5b2`](https://github.com/nodejs/node-gyp/commit/6f1286f5b2)] - Fix infinite install loop. (Ben Noordhuis) [#1384](https://github.com/nodejs/node-gyp/pull/1384)
* [[`2580b9139e`](https://github.com/nodejs/node-gyp/commit/2580b9139e)] - Update `--nodedir` description in README. (Ben Noordhuis) [#1372](https://github.com/nodejs/node-gyp/pull/1372)
* [[`a61360391a`](https://github.com/nodejs/node-gyp/commit/a61360391a)] - Update README with another way to install on windows (JeffAtDeere) [#1352](https://github.com/nodejs/node-gyp/pull/1352)
* [[`47496bf6dc`](https://github.com/nodejs/node-gyp/commit/47496bf6dc)] - Fix IndexError when parsing GYP files. (Ben Noordhuis) [#1267](https://github.com/nodejs/node-gyp/pull/1267)
* [[`b2024dee7b`](https://github.com/nodejs/node-gyp/commit/b2024dee7b)] - **zos**: support platform (John Barboza) [#1276](https://github.com/nodejs/node-gyp/pull/1276)
* [[`90d86512f4`](https://github.com/nodejs/node-gyp/commit/90d86512f4)] - **win**: run PS with `-NoProfile` (Refael Ackermann) [#1292](https://github.com/nodejs/node-gyp/pull/1292)
* [[`2da5f86ef7`](https://github.com/nodejs/node-gyp/commit/2da5f86ef7)] - **doc**: add github PR and Issue templates (Gibson Fahnestock) [#1228](https://github.com/nodejs/node-gyp/pull/1228)
* [[`a46a770d68`](https://github.com/nodejs/node-gyp/commit/a46a770d68)] - **doc**: update proposed DCO and CoC (Mikeal Rogers) [#1229](https://github.com/nodejs/node-gyp/pull/1229)
* [[`7e803d58e0`](https://github.com/nodejs/node-gyp/commit/7e803d58e0)] - **doc**: headerify the Install instructions (Nick Schonning) [#1225](https://github.com/nodejs/node-gyp/pull/1225)
* [[`f27599193a`](https://github.com/nodejs/node-gyp/commit/f27599193a)] - **gyp**: update xml string encoding conversion (Liu Chao) [#1203](https://github.com/nodejs/node-gyp/pull/1203)
* [[`0a07e481f7`](https://github.com/nodejs/node-gyp/commit/0a07e481f7)] - **configure**: don't set ensure if tarball is set (Gibson Fahnestock) [#1220](https://github.com/nodejs/node-gyp/pull/1220)

## v3.6.3 2018-06-08

* [[`90cd2e8da9`](https://github.com/nodejs/node-gyp/commit/90cd2e8da9)] - **gyp**: fix regex to match multi-digit versions (Jonas Hermsmeier) [#1455](https://github.com/nodejs/node-gyp/pull/1455)
* [[`7900122337`](https://github.com/nodejs/node-gyp/commit/7900122337)] - deps: pin `request` version range (Refael Ackerman) [#1300](https://github.com/nodejs/node-gyp/pull/1300)

## v3.6.2 2017-06-01

* [[`72afdd62cd`](https://github.com/nodejs/node-gyp/commit/72afdd62cd)] - **build**: rename copyNodeLib() to doBuild() (Liu Chao) [#1206](https://github.com/nodejs/node-gyp/pull/1206)
* [[`bad903ac70`](https://github.com/nodejs/node-gyp/commit/bad903ac70)] - **win**: more robust parsing of SDK version (Refael Ackermann) [#1198](https://github.com/nodejs/node-gyp/pull/1198)
* [[`241752f381`](https://github.com/nodejs/node-gyp/commit/241752f381)] - Log dist-url. (Ben Noordhuis) [#1170](https://github.com/nodejs/node-gyp/pull/1170)
* [[`386746c7d1`](https://github.com/nodejs/node-gyp/commit/386746c7d1)] - **configure**: use full path in node_lib_file GYP var (Pavel Medvedev) [#964](https://github.com/nodejs/node-gyp/pull/964)
* [[`0913b2dd99`](https://github.com/nodejs/node-gyp/commit/0913b2dd99)] - **build, win**: use target_arch to link with node.lib (Pavel Medvedev) [#964](https://github.com/nodejs/node-gyp/pull/964)
* [[`c307b302f7`](https://github.com/nodejs/node-gyp/commit/c307b302f7)] - **doc**: blorb about setting `npm_config_OPTION_NAME` (Refael Ackermann) [#1185](https://github.com/nodejs/node-gyp/pull/1185)

## v3.6.1 2017-04-30

* [[`49801716c2`](https://github.com/nodejs/node-gyp/commit/49801716c2)] - **test**: fix test-find-python on v0.10.x buildbot. (Ben Noordhuis) [#1172](https://github.com/nodejs/node-gyp/pull/1172)
* [[`a83a3801fc`](https://github.com/nodejs/node-gyp/commit/a83a3801fc)] - **test**: fix test/test-configure-python on AIX (Richard Lau) [#1131](https://github.com/nodejs/node-gyp/pull/1131)
* [[`8a767145c9`](https://github.com/nodejs/node-gyp/commit/8a767145c9)] - **gyp**: Revert quote_cmd workaround (Kunal Pathak) [#1153](https://github.com/nodejs/node-gyp/pull/1153)
* [[`c09cf7671e`](https://github.com/nodejs/node-gyp/commit/c09cf7671e)] - **doc**: add a note for using `configure` on Windows (Vse Mozhet Byt) [#1152](https://github.com/nodejs/node-gyp/pull/1152)
* [[`da9cb5f411`](https://github.com/nodejs/node-gyp/commit/da9cb5f411)] - Delete superfluous .patch files. (Ben Noordhuis) [#1122](https://github.com/nodejs/node-gyp/pull/1122)

## v3.6.0 2017-03-16

* [[`ae141e1906`](https://github.com/nodejs/node-gyp/commit/ae141e1906)] - **win**: find and setup for VS2017 (Refael Ackermann) [#1130](https://github.com/nodejs/node-gyp/pull/1130)
* [[`ec5fc36a80`](https://github.com/nodejs/node-gyp/commit/ec5fc36a80)] - Add support to build node.js with chakracore for ARM. (Kunal Pathak) [#873](https://github.com/nodejs/node-gyp/pull/873)
* [[`a04ea3051a`](https://github.com/nodejs/node-gyp/commit/a04ea3051a)] - Add support to build node.js with chakracore. (Kunal Pathak) [#873](https://github.com/nodejs/node-gyp/pull/873)
* [[`93d7fa83c8`](https://github.com/nodejs/node-gyp/commit/93d7fa83c8)] - Upgrade semver dependency. (Ben Noordhuis) [#1107](https://github.com/nodejs/node-gyp/pull/1107)
* [[`ff9a6fadfd`](https://github.com/nodejs/node-gyp/commit/ff9a6fadfd)] - Update link of gyp as Google code is shutting down (Peter Dave Hello) [#1061](https://github.com/nodejs/node-gyp/pull/1061)

## v3.5.0 2017-01-10

* [[`762d19a39e`](https://github.com/nodejs/node-gyp/commit/762d19a39e)] - \[doc\] merge History.md and CHANGELOG.md (Rod Vagg)
* [[`80fc5c3d31`](https://github.com/nodejs/node-gyp/commit/80fc5c3d31)] - Fix deprecated dependency warning (Simone Primarosa) [#1069](https://github.com/nodejs/node-gyp/pull/1069)
* [[`05c44944fd`](https://github.com/nodejs/node-gyp/commit/05c44944fd)] - Open the build file with universal-newlines mode (Guy Margalit) [#1053](https://github.com/nodejs/node-gyp/pull/1053)
* [[`37ae7be114`](https://github.com/nodejs/node-gyp/commit/37ae7be114)] - Try python launcher when stock python is python 3. (Ben Noordhuis) [#992](https://github.com/nodejs/node-gyp/pull/992)
* [[`e3778d9907`](https://github.com/nodejs/node-gyp/commit/e3778d9907)] - Add lots of findPython() tests. (Ben Noordhuis) [#992](https://github.com/nodejs/node-gyp/pull/992)
* [[`afc766adf6`](https://github.com/nodejs/node-gyp/commit/afc766adf6)] - Unset executable bit for .bat files (Pavel Medvedev) [#969](https://github.com/nodejs/node-gyp/pull/969)
* [[`ddac348991`](https://github.com/nodejs/node-gyp/commit/ddac348991)] - Use push on PYTHONPATH and add tests (Michael Hart) [#990](https://github.com/nodejs/node-gyp/pull/990)
* [[`b182a19042`](https://github.com/nodejs/node-gyp/commit/b182a19042)] - ***Revert*** "add "path-array" dep" (Michael Hart) [#990](https://github.com/nodejs/node-gyp/pull/990)
* [[`7c08b85c5a`](https://github.com/nodejs/node-gyp/commit/7c08b85c5a)] - ***Revert*** "**configure**: use "path-array" for PYTHONPATH" (Michael Hart) [#990](https://github.com/nodejs/node-gyp/pull/990)
* [[`9c8d275526`](https://github.com/nodejs/node-gyp/commit/9c8d275526)] - Add --devdir flag. (Ben Noordhuis) [#916](https://github.com/nodejs/node-gyp/pull/916)
* [[`f6eab1f9e4`](https://github.com/nodejs/node-gyp/commit/f6eab1f9e4)] - **doc**: add windows-build-tools to readme (Felix Rieseberg) [#970](https://github.com/nodejs/node-gyp/pull/970)

## v3.4.0 2016-06-28

* [[`ce5fd04e94`](https://github.com/nodejs/node-gyp/commit/ce5fd04e94)] - **deps**: update minimatch version (delphiactual) [#961](https://github.com/nodejs/node-gyp/pull/961)
* [[`77383ddd85`](https://github.com/nodejs/node-gyp/commit/77383ddd85)] - Replace fs.accessSync call to fs.statSync (Richard Lau) [#955](https://github.com/nodejs/node-gyp/pull/955)
* [[`0dba4bda57`](https://github.com/nodejs/node-gyp/commit/0dba4bda57)] - **test**: add simple addon test (Richard Lau) [#955](https://github.com/nodejs/node-gyp/pull/955)
* [[`c4344b3889`](https://github.com/nodejs/node-gyp/commit/c4344b3889)] - **doc**: add --target option to README (Gibson Fahnestock) [#958](https://github.com/nodejs/node-gyp/pull/958)
* [[`cc778e9215`](https://github.com/nodejs/node-gyp/commit/cc778e9215)] - Override BUILDING_UV_SHARED, BUILDING_V8_SHARED. (Ben Noordhuis) [#915](https://github.com/nodejs/node-gyp/pull/915)
* [[`af35b2ad32`](https://github.com/nodejs/node-gyp/commit/af35b2ad32)] - Move VC++ Build Tools to Build Tools landing page. (Andrew Pardoe) [#953](https://github.com/nodejs/node-gyp/pull/953)
* [[`f31482e226`](https://github.com/nodejs/node-gyp/commit/f31482e226)] - **win**: work around __pfnDliNotifyHook2 type change (Alexis Campailla) [#952](https://github.com/nodejs/node-gyp/pull/952)
* [[`3df8222fa5`](https://github.com/nodejs/node-gyp/commit/3df8222fa5)] - Allow for npmlog@3.x (Rebecca Turner) [#950](https://github.com/nodejs/node-gyp/pull/950)
* [[`a4fa07b390`](https://github.com/nodejs/node-gyp/commit/a4fa07b390)] - More verbose error on locating msbuild.exe failure. (Mateusz Jaworski) [#930](https://github.com/nodejs/node-gyp/pull/930)
* [[`4ee31329e0`](https://github.com/nodejs/node-gyp/commit/4ee31329e0)] - **doc**: add command options to README.md (Gibson Fahnestock) [#937](https://github.com/nodejs/node-gyp/pull/937)
* [[`c8c7ca86b9`](https://github.com/nodejs/node-gyp/commit/c8c7ca86b9)] - Add --silent option for zero output. (Gibson Fahnestock) [#937](https://github.com/nodejs/node-gyp/pull/937)
* [[`ac29d23a7c`](https://github.com/nodejs/node-gyp/commit/ac29d23a7c)] - Upgrade to glob@7.0.3. (Ben Noordhuis) [#943](https://github.com/nodejs/node-gyp/pull/943)
* [[`15fd56be3d`](https://github.com/nodejs/node-gyp/commit/15fd56be3d)] - Enable V8 deprecation warnings for native modules (Matt Loring) [#920](https://github.com/nodejs/node-gyp/pull/920)
* [[`7f1c1b960c`](https://github.com/nodejs/node-gyp/commit/7f1c1b960c)] - **gyp**: improvements for android generator (Robert Chiras) [#935](https://github.com/nodejs/node-gyp/pull/935)
* [[`088082766c`](https://github.com/nodejs/node-gyp/commit/088082766c)] - Update Windows install instructions (Sara Itani) [#867](https://github.com/nodejs/node-gyp/pull/867)
* [[`625c1515f9`](https://github.com/nodejs/node-gyp/commit/625c1515f9)] - **gyp**: inherit CC/CXX for CC/CXX.host (Johan Bergström) [#908](https://github.com/nodejs/node-gyp/pull/908)
* [[`3bcb1720e4`](https://github.com/nodejs/node-gyp/commit/3bcb1720e4)] - Add support for the Python launcher on Windows (Patrick Westerhoff) [#894](https://github.com/nodejs/node-gyp/pull/894

## v3.3.1 2016-03-04

* [[`a981ef847a`](https://github.com/nodejs/node-gyp/commit/a981ef847a)] - **gyp**: fix android generator (Robert Chiras) [#889](https://github.com/nodejs/node-gyp/pull/889)

## v3.3.0 2016-02-16

* [[`818d854a4d`](https://github.com/nodejs/node-gyp/commit/818d854a4d)] - Introduce NODEJS_ORG_MIRROR and IOJS_ORG_MIRROR (Rod Vagg) [#878](https://github.com/nodejs/node-gyp/pull/878)
* [[`d1e4cc4b62`](https://github.com/nodejs/node-gyp/commit/d1e4cc4b62)] - **(SEMVER-MINOR)** Download headers tarball for ~0.12.10 || ~0.10.42 (Rod Vagg) [#877](https://github.com/nodejs/node-gyp/pull/877)
* [[`6e28ad1bea`](https://github.com/nodejs/node-gyp/commit/6e28ad1bea)] - Allow for npmlog@2.x (Rebecca Turner) [#861](https://github.com/nodejs/node-gyp/pull/861)
* [[`07371e5812`](https://github.com/nodejs/node-gyp/commit/07371e5812)] - Use -fPIC for NetBSD. (Marcin Cieślak) [#856](https://github.com/nodejs/node-gyp/pull/856)
* [[`8c4b0ffa50`](https://github.com/nodejs/node-gyp/commit/8c4b0ffa50)] - **(SEMVER-MINOR)** Add --cafile command line option. (Ben Noordhuis) [#837](https://github.com/nodejs/node-gyp/pull/837)
* [[`b3ad43498e`](https://github.com/nodejs/node-gyp/commit/b3ad43498e)] - **(SEMVER-MINOR)** Make download() function testable. (Ben Noordhuis) [#837](https://github.com/nodejs/node-gyp/pull/837)

## v3.2.1 2015-12-03

* [[`ab89b477c4`](https://github.com/nodejs/node-gyp/commit/ab89b477c4)] - Upgrade gyp to b3cef02. (Ben Noordhuis) [#831](https://github.com/nodejs/node-gyp/pull/831)
* [[`90078ecb17`](https://github.com/nodejs/node-gyp/commit/90078ecb17)] - Define WIN32_LEAN_AND_MEAN conditionally. (Ben Noordhuis) [#824](https://github.com/nodejs/node-gyp/pull/824)

## v3.2.0 2015-11-25

* [[`268f1ca4c7`](https://github.com/nodejs/node-gyp/commit/268f1ca4c7)] - Use result of `which` when searching for python. (Refael Ackermann) [#668](https://github.com/nodejs/node-gyp/pull/668)
* [[`817ed9bd78`](https://github.com/nodejs/node-gyp/commit/817ed9bd78)] - Add test for python executable search logic. (Ben Noordhuis) [#756](https://github.com/nodejs/node-gyp/pull/756)
* [[`0e2dfda1f3`](https://github.com/nodejs/node-gyp/commit/0e2dfda1f3)] - Fix test/test-options when run through `npm test`. (Ben Noordhuis) [#755](https://github.com/nodejs/node-gyp/pull/755)
* [[`9bfa0876b4`](https://github.com/nodejs/node-gyp/commit/9bfa0876b4)] - Add support for AIX (Michael Dawson) [#753](https://github.com/nodejs/node-gyp/pull/753)
* [[`a8d441a0a2`](https://github.com/nodejs/node-gyp/commit/a8d441a0a2)] - Update README for Windows 10 support. (Jason Williams) [#766](https://github.com/nodejs/node-gyp/pull/766)
* [[`d1d6015276`](https://github.com/nodejs/node-gyp/commit/d1d6015276)] - Update broken links and switch to HTTPS. (andrew morton)

## v3.1.0 2015-11-14

* [[`9049241f91`](https://github.com/nodejs/node-gyp/commit/9049241f91)] - **gyp**: don't use links at all, just copy the files instead (Nathan Zadoks)
* [[`8ef90348d1`](https://github.com/nodejs/node-gyp/commit/8ef90348d1)] - **gyp**: apply https://codereview.chromium.org/11361103/ (Nathan Rajlich)
* [[`a2ed0df84e`](https://github.com/nodejs/node-gyp/commit/a2ed0df84e)] - **gyp**: always install into $PRODUCT_DIR (Nathan Rajlich)
* [[`cc8b2fa83e`](https://github.com/nodejs/node-gyp/commit/cc8b2fa83e)] - Update gyp to b3cef02. (Imran Iqbal) [#781](https://github.com/nodejs/node-gyp/pull/781)
* [[`f5d86eb84e`](https://github.com/nodejs/node-gyp/commit/f5d86eb84e)] - Update to tar@2.0.0. (Edgar Muentes) [#797](https://github.com/nodejs/node-gyp/pull/797)
* [[`2ac7de02c4`](https://github.com/nodejs/node-gyp/commit/2ac7de02c4)] - Fix infinite loop with zero-length options. (Ben Noordhuis) [#745](https://github.com/nodejs/node-gyp/pull/745)
* [[`101bed639b`](https://github.com/nodejs/node-gyp/commit/101bed639b)] - This platform value came from debian package, and now the value (Jérémy Lal) [#738](https://github.com/nodejs/node-gyp/pull/738)

## v3.0.3 2015-09-14

* [[`ad827cda30`](https://github.com/nodejs/node-gyp/commit/ad827cda30)] - tarballUrl global and && when checking for iojs (Lars-Magnus Skog) [#729](https://github.com/nodejs/node-gyp/pull/729)

## v3.0.2 2015-09-12

* [[`6e8c3bf3c6`](https://github.com/nodejs/node-gyp/commit/6e8c3bf3c6)] - add back support for passing additional cmdline args (Rod Vagg) [#723](https://github.com/nodejs/node-gyp/pull/723)
* [[`ff82f2f3b9`](https://github.com/nodejs/node-gyp/commit/ff82f2f3b9)] - fixed broken link in docs to Visual Studio 2013 download (simon-p-r) [#722](https://github.com/nodejs/node-gyp/pull/722)

## v3.0.1 2015-09-08

* [[`846337e36b`](https://github.com/nodejs/node-gyp/commit/846337e36b)] - normalise versions for target == this comparison (Rod Vagg) [#716](https://github.com/nodejs/node-gyp/pull/716)

## v3.0.0 2015-09-08

* [[`9720d0373c`](https://github.com/nodejs/node-gyp/commit/9720d0373c)] - remove node_modules from tree (Rod Vagg) [#711](https://github.com/nodejs/node-gyp/pull/711)
* [[`6dcf220db7`](https://github.com/nodejs/node-gyp/commit/6dcf220db7)] - test version major directly, don't use semver.satisfies() (Rod Vagg) [#711](https://github.com/nodejs/node-gyp/pull/711)
* [[`938dd18d1c`](https://github.com/nodejs/node-gyp/commit/938dd18d1c)] - refactor for clarity, fix dist-url, add env var dist-url functionality (Rod Vagg) [#711](https://github.com/nodejs/node-gyp/pull/711)
* [[`9e9df66a06`](https://github.com/nodejs/node-gyp/commit/9e9df66a06)] - use process.release, make aware of io.js & node v4 differences (Rod Vagg) [#711](https://github.com/nodejs/node-gyp/pull/711)
* [[`1ea7ed01f4`](https://github.com/nodejs/node-gyp/commit/1ea7ed01f4)] - **deps**: update graceful-fs dependency to the latest (Sakthipriyan Vairamani) [#714](https://github.com/nodejs/node-gyp/pull/714)
* [[`0fbc387b35`](https://github.com/nodejs/node-gyp/commit/0fbc387b35)] - Update repository URLs. (Ben Noordhuis) [#715](https://github.com/nodejs/node-gyp/pull/715)
* [[`bbedb8868b`](https://github.com/nodejs/node-gyp/commit/bbedb8868b)] - **(SEMVER-MAJOR)** **win**: enable delay-load hook by default (Jeremiah Senkpiel) [#708](https://github.com/nodejs/node-gyp/pull/708)
* [[`85ed107565`](https://github.com/nodejs/node-gyp/commit/85ed107565)] - Merge pull request #664 from othiym23/othiym23/allow-semver-5 (Nathan Rajlich)
* [[`0c720d234c`](https://github.com/nodejs/node-gyp/commit/0c720d234c)] - allow semver@5 (Forrest L Norvell)

## 2.0.2 / 2015-07-14

  * Use HTTPS for dist url (#656, @SonicHedgehog)
  * Merge pull request #648 from nevosegal/master
  * Merge pull request #650 from magic890/patch-1
  * Updated Installation section on README
  * Updated link to gyp user documentation
  * Fix download error message spelling (#643, @tomxtobin)
  * Merge pull request #637 from lygstate/master
  * Set NODE_GYP_DIR for addon.gypi to setting absolute path for
    src/win_delay_load_hook.c, and fixes of the long relative path issue on Win32.
    Fixes #636 (#637, @lygstate).

## 2.0.1 / 2015-05-28

  * configure: try/catch the semver range.test() call
  * README: update for visual studio 2013 (#510, @samccone)

## 2.0.0 / 2015-05-24

  * configure: check for python2 executable by default, fallback to python
  * configure: don't clobber existing $PYTHONPATH
  * configure: use "path-array" for PYTHONPATH
  * gyp: fix for non-acsii userprofile name on Windows
  * gyp: always install into $PRODUCT_DIR
  * gyp: apply https://codereview.chromium.org/11361103/
  * gyp: don't use links at all, just copy the files instead
  * gyp: update gyp to e1c8fcf7
  * Updated README.md with updated Windows build info
  * Show URL when a download fails
  * package: add a "license" field
  * move HMODULE m declaration to top
  * Only add "-undefined dynamic_lookup" to loadable_module targets
  * win: optionally allow node.exe/iojs.exe to be renamed
  * Avoid downloading shasums if using tarPath
  * Add target name preprocessor define: `NODE_GYP_MODULE_NAME`
  * Show better error message in case of bad network settings
# Code of Conduct

* [Node.js Code of Conduct](https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md)
* [Node.js Moderation Policy](https://github.com/nodejs/admin/blob/master/Moderation-Policy.md)
# Contributing to node-gyp

## Code of Conduct

Please read the
[Code of Conduct](https://github.com/nodejs/admin/blob/main/CODE_OF_CONDUCT.md)
which explains the minimum behavior expectations for node-gyp contributors.


## Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

* (a) The contribution was created in whole or in part by me and I
  have the right to submit it under the open source license
  indicated in the file; or

* (b) The contribution is based upon previous work that, to the best
  of my knowledge, is covered under an appropriate open source
  license and I have the right under that license to submit that
  work with modifications, whether created in whole or in part
  by me, under the same open source license (unless I am
  permitted to submit under a different license), as indicated
  in the file; or

* (c) The contribution was provided directly to me by some other
  person who certified (a), (b) or (c) and I have not modified
  it.

* (d) I understand and agree that this project and the contribution
  are public and that a record of the contribution (including all
  personal information I submit with it, including my sign-off) is
  maintained indefinitely and may be redistributed consistent with
  this project or the open source license(s) involved.
(The MIT License)

Copyright (c) 2012 Nathan Rajlich 

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.
# `node-gyp` - Node.js native addon build tool

[![Build Status](https://github.com/nodejs/node-gyp/workflows/Tests/badge.svg?branch=main)](https://github.com/nodejs/node-gyp/actions?query=workflow%3ATests+branch%3Amain)
![npm](https://img.shields.io/npm/dm/node-gyp)

`node-gyp` is a cross-platform command-line tool written in Node.js for
compiling native addon modules for Node.js. It contains a vendored copy of the
[gyp-next](https://github.com/nodejs/gyp-next) project that was previously used
by the Chromium team and extended to support the development of Node.js native
addons.

Note that `node-gyp` is _not_ used to build Node.js itself.

All current and LTS target versions of Node.js are supported. Depending on what version of Node.js is actually installed on your system
`node-gyp` downloads the necessary development files or headers for the target version. List of stable Node.js versions can be found on [Node.js website](https://nodejs.org/en/about/previous-releases).

## Features

 * The same build commands work on any of the supported platforms
 * Supports the targeting of different versions of Node.js

## Installation

> [!Important]
> Python >= v3.12 requires `node-gyp` >= v10

You can install `node-gyp` using `npm`:

``` bash
npm install -g node-gyp
```

Depending on your operating system, you will need to install:

### On Unix

   * [A supported version of Python](https://devguide.python.org/versions/)
   * `make`
   * A proper C/C++ compiler toolchain, like [GCC](https://gcc.gnu.org)

### On macOS

   * [A supported version of Python](https://devguide.python.org/versions/)
   * `Xcode Command Line Tools` which will install `clang`, `clang++`, and `make`.
     * Install the `Xcode Command Line Tools` standalone by running `xcode-select --install`. -- OR --
     * Alternatively, if you already have the [full Xcode installed](https://developer.apple.com/xcode/download/), you can install the Command Line Tools under the menu `Xcode -> Open Developer Tool -> More Developer Tools...`.


### On Windows

Install tools with [Chocolatey](https://chocolatey.org):
``` bash
choco install python visualstudio2022-workload-vctools -y
```

Or install and configure Python and Visual Studio tools manually:

  * Install the current [version of Python](https://devguide.python.org/versions/) from the
  [Microsoft Store](https://apps.microsoft.com/store/search?publisher=Python+Software+Foundation).

   * Install Visual C++ Build Environment: For Visual Studio 2019 or later, use the `Desktop development with C++` workload from [Visual Studio Community](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=Community).  For a version older than Visual Studio 2019, install [Visual Studio Build Tools](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools) with the `Visual C++ build tools` option.

   If the above steps didn't work for you, please visit [Microsoft's Node.js Guidelines for Windows](https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#compiling-native-addon-modules) for additional tips.

   To target native ARM64 Node.js on Windows on ARM, add the components "Visual C++ compilers and libraries for ARM64" and "Visual C++ ATL for ARM64".

   To use the native ARM64 C++ compiler on Windows on ARM, ensure that you have Visual Studio 2022 [17.4 or later](https://devblogs.microsoft.com/visualstudio/arm64-visual-studio-is-officially-here/) installed.

It's advised to install following Powershell module: [VSSetup](https://github.com/microsoft/vssetup.powershell) using `Install-Module VSSetup -Scope CurrentUser`.
This will make Visual Studio detection logic to use more flexible and accessible method, avoiding Powershell's `ConstrainedLanguage` mode.

### Configuring Python Dependency

`node-gyp` requires that you have installed a [supported version of Python](https://devguide.python.org/versions/).
If you have multiple versions of Python installed, you can identify which version
`node-gyp` should use in one of the following ways:

1. by setting the `--python` command-line option, e.g.:

``` bash
node-gyp  --python /path/to/executable/python
```

2. If `node-gyp` is called by way of `npm`, *and* you have multiple versions of
Python installed, then you can set the `npm_config_python` environment variable
to the appropriate path:
``` bash
export npm_config_python=/path/to/executable/python
```
    Or on Windows:
```console
py --list-paths  # To see the installed Python versions
set npm_config_python=C:\path\to\python.exe  # CMD
$Env:npm_config_python="C:\path\to\python.exe"  # PowerShell
```

3. If the `PYTHON` environment variable is set to the path of a Python executable,
then that version will be used if it is a supported version.

4. If the `NODE_GYP_FORCE_PYTHON` environment variable is set to the path of a
Python executable, it will be used instead of any of the other configured or
built-in Python search paths. If it's not a compatible version, no further
searching will be done.

### Build for Third Party Node.js Runtimes

When building modules for third-party Node.js runtimes like Electron, which have
different build configurations from the official Node.js distribution, you
should use `--dist-url` or `--nodedir` flags to specify the headers of the
runtime to build for.

Also when `--dist-url` or `--nodedir` flags are passed, node-gyp will use the
`config.gypi` shipped in the headers distribution to generate build
configurations, which is different from the default mode that would use the
`process.config` object of the running Node.js instance.

Some old versions of Electron shipped malformed `config.gypi` in their headers
distributions, and you might need to pass `--force-process-config` to node-gyp
to work around configuration errors.

## How to Use

To compile your native addon first go to its root directory:

``` bash
cd my_node_addon
```

The next step is to generate the appropriate project build files for the current
platform. Use `configure` for that:

``` bash
node-gyp configure
```

Auto-detection fails for Visual C++ Build Tools 2015, so `--msvs_version=2015`
needs to be added (not needed when run by npm as configured above):
``` bash
node-gyp configure --msvs_version=2015
```

__Note__: The `configure` step looks for a `binding.gyp` file in the current
directory to process. See below for instructions on creating a `binding.gyp` file.

Now you will have either a `Makefile` (on Unix platforms) or a `vcxproj` file
(on Windows) in the `build/` directory. Next, invoke the `build` command:

``` bash
node-gyp build
```

Now you have your compiled `.node` bindings file! The compiled bindings end up
in `build/Debug/` or `build/Release/`, depending on the build mode. At this point,
you can require the `.node` file with Node.js and run your tests!

__Note:__ To create a _Debug_ build of the bindings file, pass the `--debug` (or
`-d`) switch when running either the `configure`, `build` or `rebuild` commands.

## The `binding.gyp` file

A `binding.gyp` file describes the configuration to build your module, in a
JSON-like format. This file gets placed in the root of your package, alongside
`package.json`.

A barebones `gyp` file appropriate for building a Node.js addon could look like:

```python
{
  "targets": [
    {
      "target_name": "binding",
      "sources": [ "src/binding.cc" ]
    }
  ]
}
```

## Further reading

The **[docs](./docs/)** directory contains additional documentation on specific node-gyp topics that may be useful if you are experiencing problems installing or building addons using node-gyp.

Some additional resources for Node.js native addons and writing `gyp` configuration files:

 * ["Going Native" a nodeschool.io tutorial](http://nodeschool.io/#goingnative)
 * ["Hello World" node addon example](https://github.com/nodejs/node/tree/main/test/addons/hello-world)
 * [gyp user documentation](https://gyp.gsrc.io/docs/UserDocumentation.md)
 * [gyp input format reference](https://gyp.gsrc.io/docs/InputFormatReference.md)
 * [*"binding.gyp" files out in the wild* wiki page](./docs/binding.gyp-files-in-the-wild.md)

## Commands

`node-gyp` responds to the following commands:

| **Command**   | **Description**
|:--------------|:---------------------------------------------------------------
| `help`        | Shows the help dialog
| `build`       | Invokes `make`/`msbuild.exe` and builds the native addon
| `clean`       | Removes the `build` directory if it exists
| `configure`   | Generates project build files for the current platform
| `rebuild`     | Runs `clean`, `configure` and `build` all in a row
| `install`     | Installs Node.js header files for the given version
| `list`        | Lists the currently installed Node.js header versions
| `remove`      | Removes the Node.js header files for the given version


## Command Options

`node-gyp` accepts the following command options:

| **Command**                       | **Description**
|:----------------------------------|:------------------------------------------
| `-j n`, `--jobs n`                | Run `make` in parallel. The value `max` will use all available CPU cores
| `--target=v6.2.1`                 | Node.js version to build for (default is `process.version`)
| `--silly`, `--loglevel=silly`     | Log all progress to console
| `--verbose`, `--loglevel=verbose` | Log most progress to console
| `--silent`, `--loglevel=silent`   | Don't log anything to console
| `debug`, `--debug`                | Make Debug build (default is `Release`)
| `--release`, `--no-debug`         | Make Release build
| `-C $dir`, `--directory=$dir`     | Run command in different directory
| `--make=$make`                    | Override `make` command (e.g. `gmake`)
| `--thin=yes`                      | Enable thin static libraries
| `--arch=$arch`                    | Set target architecture (e.g. ia32)
| `--tarball=$path`                 | Get headers from a local tarball
| `--devdir=$path`                  | SDK download directory (default is OS cache directory)
| `--ensure`                        | Don't reinstall headers if already present
| `--dist-url=$url`                 | Download header tarball from custom URL
| `--proxy=$url`                    | Set HTTP(S) proxy for downloading header tarball
| `--noproxy=$urls`                 | Set urls to ignore proxies when downloading header tarball
| `--cafile=$cafile`                | Override default CA chain (to download tarball)
| `--nodedir=$path`                 | Set the path to the node source code
| `--python=$path`                  | Set path to the Python binary
| `--msvs_version=$version`         | Set Visual Studio version (Windows only)
| `--solution=$solution`            | Set Visual Studio Solution version (Windows only)
| `--force-process-config`          | Force using runtime's `process.config` object to generate `config.gypi` file

## Configuration

### Environment variables

Use the form `npm_config_OPTION_NAME` for any of the command options listed
above (dashes in option names should be replaced by underscores).

For example, to set `devdir` equal to `/tmp/.gyp`, you would:

Run this on Unix:

```bash
export npm_config_devdir=/tmp/.gyp
```

Or this on Windows:

```console
set npm_config_devdir=c:\temp\.gyp
```

### `npm` configuration for npm versions before v9

Use the form `OPTION_NAME` for any of the command options listed above.

For example, to set `devdir` equal to `/tmp/.gyp`, you would run:

```bash
npm config set [--global] devdir /tmp/.gyp
```

**Note:** Configuration set via `npm` will only be used when `node-gyp`
is run via `npm`, not when `node-gyp` is run directly.

## License

`node-gyp` is available under the MIT license. See the [LICENSE
file](LICENSE) for details.
If you believe you have found a security issue in the software in this
repository, please consult https://github.com/nodejs/node/blob/HEAD/SECURITY.md.{
  'variables' : {
    'node_engine_include_dir%': 'deps/v8/include',
    'node_host_binary%': 'node',
    'node_with_ltcg%': 'true',
  },
  'target_defaults': {
    'type': 'loadable_module',
    'win_delay_load_hook': 'true',
    'product_prefix': '',

    'conditions': [
      [ 'node_engine=="chakracore"', {
        'variables': {
          'node_engine_include_dir%': 'deps/chakrashim/include'
        },
      }]
    ],

    'include_dirs': [
      '<(node_root_dir)/include/node',
      '<(node_root_dir)/src',
      '<(node_root_dir)/deps/openssl/config',
      '<(node_root_dir)/deps/openssl/openssl/include',
      '<(node_root_dir)/deps/uv/include',
      '<(node_root_dir)/deps/zlib',
      '<(node_root_dir)/<(node_engine_include_dir)'
    ],
    'defines!': [
      'BUILDING_UV_SHARED=1',  # Inherited from common.gypi.
      'BUILDING_V8_SHARED=1',  # Inherited from common.gypi.
    ],
    'defines': [
      'NODE_GYP_MODULE_NAME=>(_target_name)',
      'USING_UV_SHARED=1',
      'USING_V8_SHARED=1',
      # Warn when using deprecated V8 APIs.
      'V8_DEPRECATION_WARNINGS=1'
    ],

    'target_conditions': [
      ['_type=="loadable_module"', {
        'product_extension': 'node',
        'defines': [
          'BUILDING_NODE_EXTENSION'
        ],
        'xcode_settings': {
          'OTHER_LDFLAGS': [
            '-undefined dynamic_lookup'
          ],
        },
      }],

      ['_type=="static_library"', {
        # set to `1` to *disable* the -T thin archive 'ld' flag.
        # older linkers don't support this flag.
        'standalone_static_library': '<(standalone_static_library)'
      }],

      ['_type!="executable"', {
        'conditions': [
          [ 'OS=="android"', {
            'cflags!': [ '-fPIE' ],
          }]
        ]
      }],

      ['_win_delay_load_hook=="true"', {
        # If the addon specifies `'win_delay_load_hook': 'true'` in its
        # binding.gyp, link a delay-load hook into the DLL. This hook ensures
        # that the addon will work regardless of whether the node/iojs binary
        # is named node.exe, iojs.exe, or something else.
        'conditions': [
          [ 'OS=="win"', {
            'defines': [ 'HOST_BINARY=\"<(node_host_binary)<(EXECUTABLE_SUFFIX)\"', ],
            'sources': [
              '<(node_gyp_dir)/src/win_delay_load_hook.cc',
            ],
            'msvs_settings': {
              'VCLinkerTool': {
                'DelayLoadDLLs': [ '<(node_host_binary)<(EXECUTABLE_SUFFIX)' ],
                # Don't print a linker warning when no imports from either .exe
                # are used.
                'AdditionalOptions': [ '/ignore:4199' ],
              },
            },
          }],
        ],
      }],
    ],

    'conditions': [
      [ 'OS=="mac"', {
        'defines': [
          '_DARWIN_USE_64_BIT_INODE=1'
        ],
        'xcode_settings': {
          'DYLIB_INSTALL_NAME_BASE': '@rpath'
        },
      }],
      [ 'OS=="aix"', {
        'ldflags': [
          '-Wl,-bimport:<(node_exp_file)'
        ],
      }],
      [ 'OS=="os400"', {
        'ldflags': [
          '-Wl,-bimport:<(node_exp_file)'
        ],
      }],
      [ 'OS=="zos"', {
        'conditions': [
          [ '"'
          # needs to have dll-interface to be used by
          # clients of class 'node::ObjectWrap'
          4251
        ],
      }, {
        # OS!="win"
        'defines': [
          '_LARGEFILE_SOURCE',
          '_FILE_OFFSET_BITS=64'
        ],
      }],
      [ 'OS in "freebsd openbsd netbsd solaris android" or \
         (OS=="linux" and target_arch!="ia32")', {
        'cflags': [ '-fPIC' ],
      }],
    ]
  }
}
#!/usr/bin/env node

'use strict'

process.title = 'node-gyp'

const envPaths = require('env-paths')
const gyp = require('../')
const log = require('../lib/log')
const os = require('os')

/**
 * Process and execute the selected commands.
 */

const prog = gyp()
let completed = false
prog.parseArgv(process.argv)
prog.devDir = prog.opts.devdir

const homeDir = os.homedir()
if (prog.devDir) {
  prog.devDir = prog.devDir.replace(/^~/, homeDir)
} else if (homeDir) {
  prog.devDir = envPaths('node-gyp', { suffix: '' }).cache
} else {
  throw new Error(
    "node-gyp requires that the user's home directory is specified " +
    'in either of the environmental variables HOME or USERPROFILE. ' +
    'Overide with: --devdir /path/to/.node-gyp')
}

if (prog.todo.length === 0) {
  if (~process.argv.indexOf('-v') || ~process.argv.indexOf('--version')) {
    log.stdout('v%s', prog.version)
  } else {
    log.stdout('%s', prog.usage())
  }
  process.exit(0)
}

log.info('it worked if it ends with', 'ok')
log.verbose('cli', process.argv)
log.info('using', 'node-gyp@%s', prog.version)
log.info('using', 'node@%s | %s | %s', process.versions.node, process.platform, process.arch)

/**
 * Change dir if -C/--directory was passed.
 */

const dir = prog.opts.directory
if (dir) {
  const fs = require('fs')
  try {
    const stat = fs.statSync(dir)
    if (stat.isDirectory()) {
      log.info('chdir', dir)
      process.chdir(dir)
    } else {
      log.warn('chdir', dir + ' is not a directory')
    }
  } catch (e) {
    if (e.code === 'ENOENT') {
      log.warn('chdir', dir + ' is not a directory')
    } else {
      log.warn('chdir', 'error during chdir() "%s"', e.message)
    }
  }
}

async function run () {
  const command = prog.todo.shift()
  if (!command) {
    // done!
    completed = true
    log.info('ok')
    return
  }

  try {
    const args = await prog.commands[command.name](command.args) ?? []

    if (command.name === 'list') {
      if (args.length) {
        args.forEach((version) => log.stdout(version))
      } else {
        log.stdout('No node development files installed. Use `node-gyp install` to install a version.')
      }
    } else if (args.length >= 1) {
      log.stdout(...args.slice(1))
    }

    // now run the next command in the queue
    return run()
  } catch (err) {
    log.error(command.name + ' error')
    log.error('stack', err.stack)
    errorMessage()
    log.error('not ok')
    return process.exit(1)
  }
}

process.on('exit', function (code) {
  if (!completed && !code) {
    log.error('Completion callback never invoked!')
    issueMessage()
    process.exit(6)
  }
})

process.on('uncaughtException', function (err) {
  log.error('UNCAUGHT EXCEPTION')
  log.error('stack', err.stack)
  issueMessage()
  process.exit(7)
})

function errorMessage () {
  // copied from npm's lib/utils/error-handler.js
  const os = require('os')
  log.error('System', os.type() + ' ' + os.release())
  log.error('command', process.argv
    .map(JSON.stringify).join(' '))
  log.error('cwd', process.cwd())
  log.error('node -v', process.version)
  log.error('node-gyp -v', 'v' + prog.package.version)
}

function issueMessage () {
  errorMessage()
  log.error('', ['Node-gyp failed to build your package.',
    'Try to update npm and/or node-gyp and if it does not help file an issue with the package author.'
  ].join('\n'))
}

// start running the given commands!
run()
'use strict'

module.exports = require('neostandard')({})
{
    ".": "0.18.1"
}
Copyright (c) 2020 Node.js contributors. All rights reserved.
Copyright (c) 2009 Google Inc. 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.
   * Neither the name of Google Inc. nor the names of its
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 THE COPYRIGHT
OWNER 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.
rule cc
  command = cc $in $out

build my.out: cc my.in
// Copyright (c) 2013 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file is used to generate an empty .pdb -- with a 4KB pagesize -- that is
// then used during the final link for modules that have large PDBs. Otherwise,
// the linker will generate a pdb with a page size of 1KB, which imposes a limit
// of 1GB on the .pdb. By generating an initial empty .pdb with the compiler
// (rather than the linker), this limit is avoided. With this in place PDBs may
// grow to 2GB.
//
// This file is referenced by the msvs_large_pdb mechanism in MSVSUtil.py.
# vs. CMake

GYP was originally created to generate native IDE project files (Visual Studio, Xcode) for building [Chromium](http://www.chromim.org).

The functionality of GYP is very similar to the [CMake](http://www.cmake.org)
build tool.  Bradley Nelson wrote up the following description of why the team
created GYP instead of using CMake.  The text below is copied from
http://www.mail-archive.com/webkit-dev@lists.webkit.org/msg11029.html

```

Re: [webkit-dev] CMake as a build system?
Bradley Nelson
Mon, 19 Apr 2010 22:38:30 -0700

Here's the innards of an email with a laundry list of stuff I came up with a
while back on the gyp-developers list in response to Mike Craddick regarding
what motivated gyp's development, since we were aware of cmake at the time
(we'd even started a speculative port):


I did an exploratory port of portions of Chromium to cmake (I think I got as
far as net, base, sandbox, and part of webkit).
There were a number of motivations, not all of which would apply to other
projects. Also, some of the design of gyp was informed by experience at
Google with large projects built wholly from source, leading to features
absent from cmake, but not strictly required for Chromium.

1. Ability to incrementally transition on Windows. It took us about 6 months
to switch fully to gyp. Previous attempts to move to scons had taken a long
time and failed, due to the requirement to transition while in flight. For a
substantial period of time, we had a hybrid of checked in vcproj and gyp generated
vcproj. To this day we still have a good number of GUIDs pinned in the gyp files,
because different parts of our release pipeline have leftover assumptions
regarding manipulating the raw sln/vcprojs. This transition occurred from
the bottom up, largely because modules like base were easier to convert, and
had a lower churn rate. During early stages of the transition, the majority
of the team wasn't even aware they were using gyp, as it integrated into
their existing workflow, and only affected modules that had been converted.

2. Generation of a more 'normal' vcproj file. Gyp attempts, particularly on
Windows, to generate vcprojs which resemble hand generated projects. It
doesn't generate any Makefile type projects, but instead produces msvs
Custom Build Steps and Custom Build Rules. This makes the resulting projects
easier to understand from the IDE and avoids parts of the IDE that simply
don't function correctly if you use Makefile projects. Our early hope with
gyp was to support the least common denominator of features present in each
of the platform specific project file formats, rather than falling back on
generated Makefiles/shell scripts to emulate some common abstraction. CMake by
comparison makes a good faith attempt to use native project features, but
falls back on generated scripts in order to preserve the same semantics on
each platforms.

3. Abstraction on the level of project settings, rather than command line
flags. In gyp's syntax you can add nearly any option present in a hand
generated xcode/vcproj file. This allows you to use abstractions built into
the IDEs rather than reverse engineering them possibly incorrectly for
things like: manifest generation, precompiled headers, bundle generation.
When somebody wants to use a particular menu option from msvs, I'm able to
do a web search on the name of the setting from the IDE and provide them
with a gyp stanza that does the equivalent. In many cases, not all project
file constructs correspond to command line flags.

4. Strong notion of module public/private interface. Gyp allows targets to
publish a set of direct_dependent_settings, specifying things like
include_dirs, defines, platforms specific settings, etc. This means that
when module A depends on module B, it automatically acquires the right build
settings without module A being filled with assumptions/knowledge of exactly
how module B is built. Additionally, all of the transitive dependencies of
module B are pulled in. This avoids their being a single top level view of
the project, rather each gyp file expresses knowledge about its immediate
neighbors. This keep local knowledge local. CMake effectively has a large
shared global namespace.

5. Cross platform generation. CMake is not able to generate all project
files on all platforms. For example xcode projects cannot be generated from
windows (cmake uses mac specific libraries to do project generation). This
means that for instance generating a tarball containing pregenerated
projects for all platforms is hard with Cmake (requires distribution to
several machine types).

6. Gyp has rudimentary cross compile support. Currently we've added enough
functionality to gyp to support x86 -> arm cross compiles. Last I checked
this functionality wasn't present in cmake. (This occurred later).


That being said there are a number of drawbacks currently to gyp:

1. Because platform specific settings are expressed at the project file
level (rather than the command line level). Settings which might otherwise
be shared in common between platforms (flags to gcc on mac/linux), end up
being repeated twice. Though in fairness there is actually less sharing here
than you'd think. include_dirs and defines actually represent 90% of what
can be typically shared.

2. CMake may be more mature, having been applied to a broader range of
projects. There a number of 'tool modules' for cmake, which are shared in a
common community.

3. gyp currently makes some nasty assumptions about the availability of
chromium's hermetic copy of cygwin on windows. This causes you to either
have to special case a number of rules, or swallow this copy of cygwin as a
build time dependency.

4. CMake includes a fairly readable imperative language. Currently Gyp has a
somewhat poorly specified declarative language (variable expansion happens
in sometimes weird and counter-intuitive ways). In fairness though, gyp assumes
that external python scripts can be used as an escape hatch. Also gyp avoids
a lot of the things you'd need imperative code for, by having a nice target
settings publication mechanism.

5. (Feature/drawback depending on personal preference). Gyp's syntax is
DEEPLY nested. It suffers from all of Lisp's advantages and drawbacks.

-BradN
```
# Hacking

## Getting the sources

Git is required to hack on anything, you can set up a git clone of GYP
as follows:

```
mkdir foo
cd foo
git clone git@github.com:nodejs/gyp-next.git
cd gyp
```

(this will clone gyp underneath it into `foo/gyp`.
`foo` can be any directory name you want. Once you've done that,
you can use the repo like anything other Git repo.

## Testing your change

GYP has a suite of tests which you can run with the provided test driver
to make sure your changes aren't breaking anything important.

You run the test driver with e.g.

``` sh
$ python -m pip install --upgrade pip setuptools
$ pip install --editable ".[dev]"
$ python -m pytest
```

See [Testing](Testing.md) for more details on the test framework.

Note that it can be handy to look at the project files output by the tests
to diagnose problems. The easiest way to do that is by kindly asking the
test driver to leave the temporary directories it creates in-place.
This is done by setting the enviroment variable "PRESERVE", e.g.

```
set PRESERVE=all     # On Windows
export PRESERVE=all  # On saner platforms.
```

## Reviewing your change

All changes to GYP must be code reviewed before submission.
# Input Format Reference

## Primitive Types

The following primitive types are found within input files:

  * String values, which may be represented by enclosing them in
    `'single quotes'` or `"double quotes"`.  By convention, single
    quotes are used.
  * Integer values, which are represented in decimal without any special
    decoration.  Integers are fairly rare in input files, but have a few
    applications in boolean contexts, where the convention is to
    represent true values with `1` and false with `0`.
  * Lists, which are represented as a sequence of items separated by
    commas (`,`) within square brackets (`[` and `]`).  A list may
    contain any other primitive types, including other lists.
    Generally, each item of a list must be of the same type as all other
    items in the list, but in some cases (such as within `conditions`
    sections), the list structure is more tightly specified.  A trailing
    comma is permitted.

    This example list contains three string values.

      ```
      [ 'Generate', 'Your', 'Projects', ]
      ```

  * Dictionaries, which map keys to values.  All keys are strings.
    Values may be of any other primitive type, including other
    dictionaries.  A dictionary is enclosed within curly braces (`{` and
    `}`).  Keys precede values, separated by a colon (`:`).  Successive
    dictionary entries are separated by commas (`,`).  A trailing comma
    is permitted.  It is an error for keys to be duplicated within a
    single dictionary as written in an input file, although keys may
    replace other keys during [merging](#Merging).

    This example dictionary maps each of three keys to different values.

      ```
      {
        'inputs': ['version.c.in'],
        'outputs': ['version.c'],
        'process_outputs_as_sources': 1,
      }
      ```

## Overall Structure

A GYP input file is organized as structured data.  At the root scope of
each `.gyp` or `.gypi` (include) file is a dictionary.  The keys and
values of this dictionary, along with any descendants contained within
the values, provide the data contained within the file.  This data is
given meaning by interpreting specific key names and their associated
values in specific ways (see [Settings Keys](#Settings_Keys)).

### Comments (#)

Within an input file, a comment is introduced by a pound sign (`#`) not
within a string.  Any text following the pound sign, up until the end of
the line, is treated as a comment.

#### Example

```
{
  'school_supplies': [
    'Marble composition book',
    'Sharp #2 pencil',
    'Safety scissors',  # You still shouldn't run with these
  ],
}
```

In this example, the # in `'Sharp #2 pencil'` is not taken as
introducing a comment because it occurs within a string, but the text
after `'Safety scissors'` is treated as a comment having no impact on
the data within the file.

## Merging

### Merge Basics (=, ?, +)

Many operations on GYP input files occurs by merging dictionary and list
items together.  During merge operations, it is important to recognize
the distinction between source and destination values.  Items from the
source value are merged into the destination, which leaves the source
unchanged and the destination modified by the source.  A dictionary may
only be merged into another dictionary, and a list may only be merged
into another list.

  * When merging a dictionary, for each key in the source:
    * If the key does not exist in the destination dictionary, insert it
      and copy the associated value directly.
    * If the key does exist:
      * If the associated value is a dictionary, perform the dictionary
        merging procedure using the source's and destination's value
        dictionaries.
      * If the associated value is a list, perform the list merging
        procedure using the source's and destination's value lists.
      * If the associated value is a string or integer, the destination
        value is replaced by the source value.
  * When merging a list, merge according to the suffix appended to the
    key name, if the list is a value within a dictionary.
    * If the key ends with an equals sign (`=`), the policy is for the
      source list to completely replace the destination list if it
      exists.  _Mnemonic: `=` for assignment._
    * If the key ends with a question mark (`?`), the policy is for the
      source list to be set as the destination list only if the key is
      not already present in the destination.  _Mnemonic: `?` for
      conditional assignment_.
    * If the key ends with a plus sign (`+`), the policy is for the
      source list contents to be prepended to the destination list.
      _Mnemonic: `+` for addition or concatenation._
    * If the list key is undecorated, the policy is for the source list
      contents to be appended to the destination list.  This is the
      default list merge policy.

#### Example

Source dictionary:

```
{
  'include_dirs+': [
    'shared_stuff/public',
  ],
  'link_settings': {
    'libraries': [
      '-lshared_stuff',
    ],
  },
  'test': 1,
}
```

Destination dictionary:

```
{
  'target_name': 'hello',
  'sources': [
    'kitty.cc',
  ],
  'include_dirs': [
    'headers',
  ],
  'link_settings': {
    'libraries': [
      '-lm',
    ],
    'library_dirs': [
      '/usr/lib',
    ],
  },
  'test': 0,
}
```

Merged dictionary:

```
{
  'target_name': 'hello',
  'sources': [
    'kitty.cc',
  ],
  'include_dirs': [
    'shared_stuff/public',  # Merged, list item prepended due to include_dirs+
    'headers',
  ],
  'link_settings': {
    'libraries': [
      '-lm',
      '-lshared_stuff',  # Merged, list item appended
    ],
    'library_dirs': [
      '/usr/lib',
    ],
  },
  'test': 1,  # Merged, int value replaced
}
```

## Pathname Relativization

In a `.gyp` or `.gypi` file, many string values are treated as pathnames
relative to the file in which they are defined.

String values associated with the following keys, or contained within
lists associated with the following keys, are treated as pathnames:

  * destination
  * files
  * include\_dirs
  * inputs
  * libraries
  * outputs
  * sources
  * mac\_bundle\_resources
  * mac\_framework\_dirs
  * msvs\_cygwin\_dirs
  * msvs\_props

Additionally, string values associated with keys ending in the following
suffixes, or contained within lists associated with keys ending in the
following suffixes, are treated as pathnames:

  * `_dir`
  * `_dirs`
  * `_file`
  * `_files`
  * `_path`
  * `_paths`

However, any string value beginning with any of these characters is
excluded from pathname relativization:

  * `/` for identifying absolute paths.
  * `$` for introducing build system variable expansions.
  * `-` to support specifying such items as `-llib`, meaning “library
    `lib` in the library search path.â€
  * `<`, `>`, and `!` for GYP expansions.

When merging such relative pathnames, they are adjusted so that they can
remain valid relative pathnames, despite being relative to a new home.

#### Example

Source dictionary from `../build/common.gypi`:

```
{
  'include_dirs': ['include'],  # Treated as relative to ../build
  'libraries': ['-lz'],  # Not treated as a pathname, begins with a dash
  'defines': ['NDEBUG'],  # defines does not contain pathnames
}
```

Target dictionary, from `base.gyp`:

```
{
  'sources': ['string_util.cc'],
}
```

Merged dictionary:

```
{
  'sources': ['string_util.cc'],
  'include_dirs': ['../build/include'],
  'libraries': ['-lz'],
  'defines': ['NDEBUG'],
}
```

Because of pathname relativization, after the merge is complete, all of
the pathnames in the merged dictionary are valid relative to the
directory containing `base.gyp`.

## List Singletons

Some list items are treated as singletons, and the list merge process
will enforce special rules when merging them.  At present, any string
item in a list that does not begin with a dash (`-`) is treated as a
singleton, although **this is subject to change.**  When appending or
prepending a singleton to a list, if the item is already in the list,
only the earlier instance is retained in the merged list.

#### Example

Source dictionary:

```
{
  'defines': [
    'EXPERIMENT=1',
    'NDEBUG',
  ],
}
```

Destination dictionary:

```
{
  'defines': [
    'NDEBUG',
    'USE_THREADS',
  ],
}
```

Merged dictionary:

```
{
  'defines': [
    'NDEBUG',
    'USE_THREADS',
    'EXPERIMENT=1',  # Note that NDEBUG is not appended after this.
  ],
}
```

## Including Other Files

If the `-I` (`--include`) argument was used to invoke GYP, any files
specified will be implicitly merged into the root dictionary of all
`.gyp` files.

An [includes](#includes) section may be placed anywhere within a
`.gyp` or `.gypi` (include) file.  `includes` sections contain lists of
other files to include.  They are processed sequentially and merged into
the enclosing dictionary at the point that the `includes` section was
found.  `includes` sections at the root of a `.gyp` file dictionary are
merged after any `-I` includes from the command line.

[includes](#includes) sections are processed immediately after a file is
loaded, even before [variable and conditional
processing](#Variables_and_Conditionals), so it is not possible to
include a file based on a [variable reference](#Variable_Expansions).
While it would be useful to be able to include files based on variable
expansions, it is most likely more useful to allow included files access
to variables set by the files that included them.

An [includes](#includes) section may, however, be placed within a
[conditional](#Conditionals) section.  The included file itself will
be loaded unconditionally, but its dictionary will be discarded if the
associated condition is not true.

## Variables and Conditionals

### Variables

There are three main types of variables within GYP.

  * Predefined variables.  By convention, these are named with
    `CAPITAL_LETTERS`.  Predefined variables are set automatically by
    GYP.  They may be overridden, but it is not advisable to do so.  See
    [Predefined Variables](#Predefined_Variables) for a list of
    variables that GYP provides.
  * User-defined variables.  Within any dictionary, a key named
    `variables` can be provided, containing a mapping between variable
    names (keys) and their contents (values), which may be strings,
    integers, or lists of strings.  By convention, user-defined
    variables are named with `lowercase_letters`.
  * Automatic variables.  Within any dictionary, any key with a string
    value has a corresponding automatic variable whose name is the same
    as the key name with an underscore (`_`) prefixed.  For example, if
    your dictionary contains `type: 'static_library'`, an automatic
    variable named `_type` will be provided, and its value will be a
    string, `'static_library'`.

Variables are inherited from enclosing scopes.

### Providing Default Values for Variables (%)

Within a `variables` section, keys named with percent sign (`%`)
suffixes mean that the variable should be set only if it is undefined at
the time it is processed.  This can be used to provide defaults for
variables that would otherwise be undefined, so that they may reliably
be used in [variable expansion or conditional
processing](#Variables_and_Conditionals).

### Predefined Variables

Each GYP generator module provides defaults for the following variables:

  * `OS`: The name of the operating system that the generator produces
    output for.  Common values for values for `OS` are:

    * `'linux'`
    * `'mac'`
    * `'win'`

    But other values may be encountered and this list should not be
    considered exhaustive.  The `gypd` (debug) generator module does not
    provide a predefined value for `OS`.  When invoking GYP with the
    `gypd` module, if a value for `OS` is needed, it must be provided on
    the command line, such as `gyp -f gypd -DOS=mac`.

    GYP generators also provide defaults for these variables.  They may
    be expressed in terms of variables used by the build system that
    they generate for, often in `$(VARIABLE)` format.  For example, the
    GYP `PRODUCT_DIR` variable maps to the Xcode `BUILT_PRODUCTS_DIR`
    variable, so `PRODUCT_DIR` is defined by the Xcode generator as
    `$(BUILT_PRODUCTS_DIR)`.
  * `EXECUTABLE_PREFIX`: A prefix, if any, applied to executable names.
    Usually this will be an empty string.
  * `EXECUTABLE_SUFFIX`: A suffix, if any, applied to executable names.
    On Windows, this will be `.exe`, elsewhere, it will usually be an
    empty string.
  * `INTERMEDIATE_DIR`: A directory that can be used to place
    intermediate build results in.  `INTERMEDIATE_DIR` is only
    guaranteed to be accessible within a single target (See targets).
    This variable is most useful within the context of rules and actions
    (See rules, See actions).  Compare with `SHARED_INTERMEDIATE_DIR`.
  * `PRODUCT_DIR`: The directory in which the primary output of each
    target, such as executables and libraries, is placed.
  * `RULE_INPUT_ROOT`: The base name for the input file (e.g. "`foo`").
    See Rules.
  * `RULE_INPUT_EXT`: The file extension for the input file (e.g.
    "`.cc`").  See Rules.
  * `RULE_INPUT_NAME`: Full name of the input file (e.g. "`foo.cc`").
    See Rules.
  * `RULE_INPUT_PATH`: Full path to the input file (e.g.
    "`/bar/foo.cc`").  See Rules.
  * `SHARED_INTERMEDIATE_DIR`: A directory that can be used to place
    intermediate build results in, and have them be accessible to other
    targets.  Unlike `INTERMEDIATE_DIR`, each target in a project,
    possibly spanning multiple `.gyp` files, shares the same
    `SHARED_INTERMEDIATE_DIR`.

The following additional predefined variables may be available under
certain circumstances:

  * `DEPTH`.  When GYP is invoked with a `--depth` argument, when
    processing any `.gyp` file, `DEPTH` will be a relative path from the
    `.gyp` file to the directory specified by the `--depth` argument.

### User-Defined Variables

A user-defined variable may be defined in terms of other variables, but
not other variables that have definitions provided in the same scope.

### Variable Expansions (<, >, <@, >@)

GYP provides two forms of variable expansions, “early†or “preâ€
expansions, and “late,†“post,†or “target†expansions.  They have
similar syntax, differing only in the character used to introduce them.

  * Early expansions are introduced by a less-than (`<`) character.
    _Mnemonic: the arrow points to the left, earlier on a timeline._
  * Late expansions are introduced by a less-than (`>`) character.
    _Mnemonic: the arrow points to the right, later on a timeline._

The difference the two phases of expansion is described in [Early and
Late Phases](#Early_and_Late_Phases).

These characters were chosen based upon the requirement that they not
conflict with the variable format used natively by build systems.  While
the dollar sign (`$`) is the most natural fit for variable expansions,
its use was ruled out because most build systems already use that
character for their own variable expansions.  Using different characters
means that no escaping mechanism was needed to differentiate between GYP
variables and build system variables, and writing build system variables
into GYP files is not cumbersome.

Variables may contain lists or strings, and variable expansions may
occur in list or string context.  There are variant forms of variable
expansions that may be used to determine how each type of variable is to
be expanded in each context.

  * When a variable is referenced by `<(VAR)` or `>(VAR)`:
    * If `VAR` is a string, the variable reference within the string is
      replaced by variable's string value.
    * If `VAR` is a list, the variable reference within the string is
      replaced by a string containing the concatenation of all of the
      variable’s list items.  Generally, the items are joined with
      spaces between each, but the specific behavior is
      generator-specific.  The precise encoding used by any generator
      should be one that would allow each list item to be treated as a
      separate argument when used as program arguments on the system
      that the generator produces output for.
  * When a variable is referenced by `<@(VAR)` or `>@(VAR)`:
    * The expansion must occur in list context.
    * The list item must be `'<@(VAR)'` or `'>@(VAR)'` exactly.
    * If `VAR` is a list, each of its elements are inserted into the
      list in which expansion is taking place, replacing the list item
      containing the variable reference.
    * If `VAR` is a string, the string is converted to a list which is
      inserted into the list in which expansion is taking place as
      above.  The conversion into a list is generator-specific, but
      generally, spaces in the string are taken as separators between
      list items.  The specific method of converting the string to a
      list should be the inverse of the encoding method used to expand
      list variables in string context, above.

GYP treats references to undefined variables as errors.

### Command Expansions (` form
    of [variable expansions](#Variable_Expansions),
    and on the `!` form of [command
    expansions](#Command_Expansions_(!,_!@)).

These two phases are provided because there are some circumstances in
which each is desirable.

The “early†phase is appropriate for most expansions and evaluations.
“Early†expansions and evaluations may be performed anywhere within any
`.gyp` or `.gypi` file.

The “late†phase is appropriate when expansion or evaluation must be
deferred until a specific section has been merged into target context.
“Late†expansions and evaluations only occur within `targets` sections
and their descendants.  The typical use case for a late-phase expansion
is to provide, in some globally-included `.gypi` file, distinct
behaviors depending on the specifics of a target.

#### Example

Given this input:

```
{
  'target_defaults': {
    'target_conditions': [
      ['_type=="shared_library"', {'cflags': ['-fPIC']}],
    ],
  },
  'targets': [
    {
      'target_name': 'sharing_is_caring',
      'type': 'shared_library',
    },
    {
      'target_name': 'static_in_the_attic',
      'type': 'static_library',
    },
  ]
}
```

The conditional needs to be evaluated only in target context; it is
nonsense outside of target context because no `_type` variable is
defined.  [target\_conditions](#target_conditions) allows evaluation
to be deferred until after the [targets](#targets) sections are
merged into their copies of [target\_defaults](#target_defaults).
The resulting targets, after “late†phase processing:

```
{
  'targets': [
    {
      'target_name': 'sharing_is_caring',
      'type': 'shared_library',
      'cflags': ['-fPIC'],
    },
    {
      'target_name': 'static_in_the_attic',
      'type': 'static_library',
    },
  ]
}
```

### Expansion and Evaluation Performed Simultaneously

During any expansion and evaluation phase, both expansion and evaluation
are performed simultaneously.  The process for handling variable
expansions and conditional evaluation within a dictionary is:

  * Load [automatic variables](#Variables) (those with leading
    underscores).
  * If a [variables](#variables) section is present, recurse into its
    dictionary.  This allows [conditionals](#Conditionals) to be
    present within the `variables` dictionary.
  * Load [Variables user-defined variables](#User-Defined) from the
    [variables](#variables) section.
  * For each string value in the dictionary, perform [variable
    expansion](#Variable_Expansions) and, if operating
    during the “late†phase, [command
    expansions](#Command_Expansions).
  * Reload [automatic variables](#Variables) and [Variables
    user-defined variables](#User-Defined) because the variable
    expansion step may have resulted in changes to the automatic
    variables.
  * If a [conditions](#conditions) or
    [target\_conditions](#target_conditions) section (depending on
    phase) is present, recurse into its dictionary.  This is done after
    variable expansion so that conditionals may take advantage of
    expanded automatic variables.
  * Evaluate [conditionals](#Conditionals).
  * Reload [automatic variables](#Variables) and [Variables
    user-defined variables](#User-Defined) because the conditional
    evaluation step may have resulted in changes to the automatic
    variables.
  * Recurse into child dictionaries or lists that have not yet been
    processed.

One quirk of this ordering is that you cannot expect a
[variables](#variables) section within a dictionary’s
[conditional](#Conditionals) to be effective in the dictionary
itself, but the added variables will be effective in any child
dictionaries or lists.  It is thought to be far more worthwhile to
provide resolved [automatic variables](#Variables) to
[conditional](#Conditionals) sections, though.  As a workaround, to
conditionalize variable values, place a [conditions](#conditions) or
[target\_conditions](#target_conditions) section within the
[variables](#variables) section.

## Dependencies and Dependents

In GYP, “dependents†are targets that rely on other targets, called
“dependencies.† Dependents declare their reliance with a special
section within their target dictionary,
[dependencies](#dependencies).

### Dependent Settings

It is useful for targets to “advertise†settings to their dependents.
For example, a target might require that all of its dependents add
certain directories to their include paths, link against special
libraries, or define certain preprocessor macros.  GYP allows these
cases to be handled gracefully with “dependent settings†sections.
There are three types of such sections:

  * [direct\_dependent\_settings](#direct_dependent_settings), which
    advertises settings to a target's direct dependents only.
  * [all\_dependent\_settings](#all_dependnet_settings), which
    advertises settings to all of a target's dependents, both direct and
    indirect.
  * [link\_settings](#link_settings), which contains settings that
    should be applied when a target’s object files are used as linker
    input.

Furthermore, in some cases, a target needs to pass its dependencies’
settings on to its own dependents.  This might happen when a target’s
own public header files include header files provided by its dependency.
[export\_dependent\_settings](#export_dependent_settings) allows a
target to declare dependencies for which
[direct\_dependent\_settings](#direct_dependent_settings) should be
passed through to its own dependents.

Dependent settings processing merges a copy of the relevant dependent
settings dictionary from a dependency into its relevant dependent
targets.

In most instances,
[direct\_dependent\_settings](#direct_dependent_settings) will be
used.  There are very few cases where
[all\_dependent\_settings](#all_dependent_settings) is actually
correct; in most of the cases where it is tempting to use, it would be
preferable to declare
[export\_dependent\_settings](#export_dependent_settings).  Most
[libraries](#libraries) and [library\_dirs](#library_dirs)
sections should be placed within [link\_settings](#link_settings)
sections.

#### Example

Given:

```
{
  'targets': [
    {
      'target_name': 'cruncher',
      'type': 'static_library',
      'sources': ['cruncher.cc'],
      'direct_dependent_settings': {
        'include_dirs': ['.'],  # dependents need to find cruncher.h.
      },
      'link_settings': {
        'libraries': ['-lm'],  # cruncher.cc does math.
      },
    },
    {
      'target_name': 'cruncher_test',
      'type': 'executable',
      'dependencies': ['cruncher'],
      'sources': ['cruncher_test.cc'],
    },
  ],
}
```

After dependent settings processing, the dictionary for `cruncher_test`
will be:

```
{
  'target_name': 'cruncher_test',
  'type': 'executable',
  'dependencies': ['cruncher'],  # implies linking against cruncher
  'sources': ['cruncher_test.cc'],
  'include_dirs': ['.']
  'libraries': ['-lm'],
},
```

If `cruncher` was declared as a `shared_library` instead of a
`static_library`, the `cruncher_test` target would not contain `-lm`,
but instead, `cruncher` itself would link against `-lm`.

## Linking Dependencies

The precise meaning of a dependency relationship varies with the
[types](#type) of the [targets](#targets) at either end of the
relationship.  In GYP, a dependency relationship can indicate two things
about how targets relate to each other:

  * Whether the dependent target needs to link against the dependency.
  * Whether the dependency target needs to be built prior to the
    dependent.  If the former case is true, this case must be true as
    well.

The analysis of the first item is complicated by the differences between
static and shared libraries.

  * Static libraries are simply collections of object files (`.o` or
    `.obj`) that are used as inputs to a linker (`ld` or `link.exe`).
    Static libraries don't link against other libraries, they’re
    collected together and used when eventually linking a shared library
    or executable.
  * Shared libraries are linker output and must undergo symbol
    resolution.  They must link against other libraries (static or
    shared) in order to facilitate symbol resolution.  They may be used
    as libraries in subsequent link steps.
  * Executables are also linker output, and also undergo symbol
    resolution.  Like shared libraries, they must link against static
    and shared libraries to facilitate symbol resolution.  They may not
    be reused as linker inputs in subsequent link steps.

Accordingly, GYP performs an operation referred to as “static library
dependency adjustment,†in which it makes each linker output target
(shared libraries and executables) link against the static libraries it
depends on, either directly or indirectly.  Because the linkable targets
link against these static libraries, they are also made direct
dependents of the static libraries.

As part of this process, GYP is also able to remove the direct
dependency relationships between two static library targets, as a
dependent static library does not actually need to link against a
dependency static library.  This removal facilitates speedier builds
under some build systems, as they are now free to build the two targets
in parallel.  The removal of this dependency is incorrect in some cases,
such as when the dependency target contains [rules](#rules) or
[actions](#actions) that generate header files required by the
dependent target.  In such cases, the dependency target, the one
providing the side-effect files, must declare itself as a
[hard\_dependency](#hard_dependency).  This setting instructs GYP to
not remove the dependency link between two static library targets in its
generated output.

## Loading Files to Resolve Dependencies

When GYP runs, it loads all `.gyp` files needed to resolve dependencies
found in [dependencies](#dependencies) sections.  These files are not
merged into the files that reference them, but they may contain special
sections that are merged into dependent target dictionaries.

## Build Configurations

Explain this.

## List Filters

GYP allows list items to be filtered by “exclusions†and “patterns.â€
Any list containing string values in a dictionary may have this
filtering applied.  For the purposes of this section, a list modified by
exclusions or patterns is referred to as a “base listâ€, in contrast to
the “exclusion list†and “pattern list†that operates on it.

  * For a base list identified by key name `key`, the `key!` list
    provides exclusions.
  * For a base list identified by key name `key`, the `key/` list
    provides regular expression pattern-based filtering.

Both `key!` and `key/` may be present.  The `key!` exclusion list will
be processed first, followed by the `key/` pattern list.

Exclusion lists are most powerful when used in conjunction with
[conditionals](#Conditionals).

## Exclusion Lists (!)

An exclusion list provides a way to remove items from the related list
based on exact matching.  Any item found in an exclusion list will be
removed from the corresponding base list.

#### Example

This example excludes files from the `sources` based on the setting of
the `OS` variable.

```
{
  'sources:' [
    'mac_util.mm',
    'win_util.cc',
  ],
  'conditions': [
    ['OS=="mac"', {'sources!': ['win_util.cc']}],
    ['OS=="win"', {'sources!': ['mac_util.cc']}],
  ],
}
```

## Pattern Lists (/)

Pattern lists are similar to, but more powerful than, [exclusion
lists](#Exclusion_Lists_(!)).  Each item in a pattern list is itself
a two-element list.  The first item is a string, either `'include'` or
`'exclude'`, specifying the action to take.  The second item is a string
specifying a regular expression.  Any item in the base list matching the
regular expression pattern will either be included or excluded, based on
the action specified.

Items in a pattern list are processed in sequence, and an excluded item
that is later included will not be removed from the list (unless it is
subsequently excluded again.)

Pattern lists are processed after [exclusion
lists](#Exclusion_Lists_(!)), so it is possible for a pattern list to
re-include items previously excluded by an exclusion list.

Nothing is actually removed from a base list until all items in an
[exclusion list](#Exclusion_Lists_(!)) and pattern list have been
evaluated.  This allows items to retain their correct position relative
to one another even after being excluded and subsequently included.

#### Example

In this example, a uniform naming scheme is adopted for
platform-specific files.

```
{
  'sources': [
    'io_posix.cc',
    'io_win.cc',
    'launcher_mac.cc',
    'main.cc',
    'platform_util_linux.cc',
    'platform_util_mac.mm',
  ],
  'sources/': [
    ['exclude', '_win\\.cc$'],
  ],
  'conditions': [
    ['OS!="linux"', {'sources/': [['exclude', '_linux\\.cc$']]}],
    ['OS!="mac"', {'sources/': [['exclude', '_mac\\.cc|mm?$']]}],
    ['OS=="win"', {'sources/': [
      ['include', '_win\\.cc$'],
      ['exclude', '_posix\\.cc$'],
    ]}],
  ],
}
```

After the pattern list is applied, `sources` will have the following
values, depending on the setting of `OS`:

  * When `OS` is `linux`: `['io_posix.cc', 'main.cc',
    'platform_util_linux.cc']`
  * When `OS` is `mac`: `['io_posix.cc', 'launcher_mac.cc', 'main.cc',
    'platform_util_mac.mm']`
  * When `OS` is `win`: `['io_win.cc', 'main.cc',
    'platform_util_win.cc']`

Note that when `OS` is `win`, the `include` for `_win.cc` files is
processed after the `exclude` matching the same pattern, because the
`sources/` list participates in [merging](#Merging) during
[conditional evaluation](#Conditonals) just like any other list
would.  This guarantees that the `_win.cc` files, previously
unconditionally excluded, will be re-included when `OS` is `win`.

## Locating Excluded Items

In some cases, a GYP generator needs to access to items that were
excluded by an [exclusion list](#Exclusion_Lists_(!)) or [pattern
list](#Pattern_Lists_(/)).  When GYP excludes items during processing
of either of these list types, it places the results in an `_excluded`
list.  In the example above, when `OS` is `mac`, `sources_excluded`
would be set to `['io_win.cc', 'platform_util_linux.cc']`.  Some GYP
generators use this feature to display excluded files in the project
files they generate for the convenience of users, who may wish to refer
to other implementations.

## Processing Order

GYP uses a defined and predictable order to execute the various steps
performed between loading files and generating output.

  * Load files.
    * Load `.gyp` files.  Merge any [command-line
      includes](#Including_Other_Files) into each `.gyp` file’s root
      dictionary.  As [includes](#Including_Other_Files) are found,
      load them as well and [merge](#Merging) them into the scope in
      which the [includes](#includes) section was found.
    * Perform [“early†or “preâ€](#Early_and_Late_Phases) [variable
      expansion and conditional
      evaluation](#Variables_and_Conditionals).
    * [Merge](#Merging) each [target’s](#targets) dictionary into
      the `.gyp` file’s root [target\_defaults](#target_defaults)
      dictionary.
    * Scan each [target](#targets) for
      [dependencies](#dependencies), and repeat the above steps for
      any newly-referenced `.gyp` files not yet loaded.
  * Scan each [target](#targets) for wildcard
    [dependencies](#dependencies), expanding the wildcards.
  * Process [dependent settings](#Dependent_Settings).  These
    sections are processed, in order:
    * [all\_dependent\_settings](#all_dependent_settings)
    * [direct\_dependent\_settings](#direct_dependent_settings)
    * [link\_dependent\_settings](#link_dependent_settings)
  * Perform [static library dependency
    adjustment](#Linking_Dependencies).
  * Perform [“late,†“post,†or “targetâ€](#Early_and_Late_Phases)
    [variable expansion and conditional
    evaluation](#Variables_and_Conditionals) on [target](#targets)
    dictionaries.
  * Merge [target](#targets) settings into
    [configurations](#configurations) as appropriate.
  * Process [exclusion and pattern
    lists](#List_Exclusions_and_Patterns).

## Settings Keys

### Settings that may appear anywhere

#### conditions

_List of `condition` items_

A `conditions` section introduces a subdictionary that is only merged
into the enclosing scope based on the evaluation of a conditional
expression.  Each `condition` within a `conditions` list is itself a
list of at least two items:

  1. A string containing the conditional expression itself.  Conditional
  expressions may take the following forms:
    * For string values, `var=="value"` and `var!="value"` to test
      equality and inequality.  For example, `'OS=="linux"'` is true
      when the `OS` variable is set to `"linux"`.
    * For integer values, `var==value`, `var!=value`, `var=value`, and `var>value`, to test equality and
      several common forms of inequality.  For example,
      `'chromium_code==0'` is true when the `chromium_code` variable is
      set to `0`.
    * It is an error for a conditional expression to reference any
      undefined variable.
  1. A dictionary containing the subdictionary to be merged into the
  enclosing scope if the conditional expression evaluates to true.

These two items can be followed by any number of similar two items that
will be evaluated if the previous conditional expression does not
evaluate to true.

An additional optional dictionary can be appended to this sequence of
two items.  This optional dictionary will be merged into the enclosing
scope if none of the conditional expressions evaluate to true.

Within a `conditions` section, each item is processed sequentially, so
it is possible to predict the order in which operations will occur.

There is no restriction on nesting `conditions` sections.

`conditions` sections are very similar to `target_conditions` sections.
See target\_conditions.

#### Example

```
{
  'sources': [
    'common.cc',
  ],
  'conditions': [
    ['OS=="mac"', {'sources': ['mac_util.mm']}],
    ['OS=="win"', {'sources': ['win_main.cc']}, {'sources': ['posix_main.cc']}],
    ['OS=="mac"', {'sources': ['mac_impl.mm']},
     'OS=="win"', {'sources': ['win_impl.cc']},
     {'sources': ['default_impl.cc']}
    ],
  ],
}
```

Given this input, the `sources` list will take on different values based
on the `OS` variable.

  * If `OS` is `"mac"`, `sources` will contain `['common.cc',
    'mac_util.mm', 'posix_main.cc', 'mac_impl.mm']`.
  * If `OS` is `"win"`, `sources` will contain `['common.cc',
    'win_main.cc', 'win_impl.cc']`.
  * If `OS` is any other value such as `"linux"`, `sources` will contain
    `['common.cc', 'posix_main.cc', 'default_impl.cc']`.
# Language Specification

## Objective

Create a tool for the Chromium project that generates native Visual Studio,
Xcode and SCons and/or make build files from a platform-independent input
format.  Make the input format as reasonably general as possible without
spending extra time trying to "get everything right," except where not doing so
would likely lead Chromium to an eventual dead end.  When in doubt, do what
Chromium needs and don't worry about generalizing the solution.

## Background

Numerous other projects, both inside and outside Google, have tried to
create a simple, universal cross-platform build representation that
still allows sufficient per-platform flexibility to accommodate
irreconcilable differences.  The fact that no obvious working candidate
exists that meets Chromium's requirements indicates this is probably a
tougher problem than it appears at first glance.  We aim to succeed by
creating a tool that is highly specific to Chromium's specific use case,
not to the general case of design a completely platform-independent tool
for expressing any possible build.

The Mac has the most sophisticated model for application development
through an IDE.  Consequently, we will use the Xcode model as the
starting point (the input file format must handle Chromium's use of
Xcode seamlessly) and adapt the design as necessary for the other
platforms.

## Overview

The overall design has the following characteristics:

  * Input configurations are specified in files with the suffix `.gyp`.
  * Each `.gyp` file specifies how to build the targets for the
    "component" defined by that file.
  * Each `.gyp` file generates one or more output files appropriate to
    the platform:
    * On Mac, a `.gyp` file generates one Xcode .xcodeproj bundle with
      information about how its targets are built.
    * On Windows, a `.gyp` file generates one Visual Studio .sln file,
      and one Visual Studio .vcproj file per target.
    * On Linux, a `.gyp` file generates one SCons file and/or one
      Makefile per target
  * The `.gyp` file syntax is a Python data structure.
  * Use of arbitrary Python in `.gyp` files is forbidden.
    * Use of eval() with restricted globals and locals on `.gyp` file
      contents restricts the input to an evaluated expression, not
      arbitrary Python statements.
    * All input is expected to comply with JSON, with two exceptions:
      the # character (not inside strings) begins a comment that lasts
      until the end of the line, and trailing commas are permitted at
      the end of list and dict contents.
  * Input data is a dictionary of keywords and values.
  * "Invalid" keywords on any given data structure are not illegal,
    they're just ignored.
    * TODO:  providing warnings on use of illegal keywords would help
      users catch typos.  Figure out something nice to do with this.

## Detailed Design

Some up-front design principles/thoughts/TODOs:

  * Re-use keywords consistently.
  * Keywords that allow configuration of a platform-specific concept get
    prefixed appropriately:
    * Examples:  `msvs_disabled_warnings`, `xcode_framework_dirs`
  * The input syntax is declarative and data-driven.
    * This gets enforced by using Python `eval()` (which only evaluates
      an expression) instead of `exec` (which executes arbitrary python)
  * Semantic meanings of specific keyword values get deferred until all
    are read and the configuration is being evaluated to spit out the
    appropriate file(s)
  * Source file lists:
    * Are flat lists.  Any imposed ordering within the `.gyp` file (e.g.
      alphabetically) is purely by convention and for developer
      convenience.  When source files are linked or archived together,
      it is expected that this will occur in the order that files are
      listed in the `.gyp` file.
    * Source file lists contain no mechanism for by-hand folder
      configuration (`Filter` tags in Visual Studio, `Groups` in Xcode)
    * A folder hierarchy is created automatically that mirrors the file
      system

### Example

```
{
  'target_defaults': {
    'defines': [
      'U_STATIC_IMPLEMENTATION',
      ['LOGFILE', 'foo.log',],
    ],
    'include_dirs': [
      '..',
    ],
  },
  'targets': [
    {
      'target_name': 'foo',
      'type': 'static_library',
      'sources': [
        'foo/src/foo.cc',
        'foo/src/foo_main.cc',
      ],
      'include_dirs': [
         'foo',
         'foo/include',
      ],
      'conditions': [
         [ 'OS==mac', { 'sources': [ 'platform_test_mac.mm' ] } ]
      ],
      'direct_dependent_settings': {
        'defines': [
          'UNIT_TEST',
        ],
        'include_dirs': [
          'foo',
          'foo/include',
        ],
      },
    },
  ],
}
```

### Structural Elements

### Top-level Dictionary

This is the single dictionary in the `.gyp` file that defines the
targets and how they're to be built.

The following keywords are meaningful within the top-level dictionary
definition:

| *Keyword*         | *Description*     |
|:------------------|:------------------|
| `conditions`      | A conditional section that may contain other items that can be present in a top-level dictionary, on a conditional basis.  See the "Conditionals" section below. |
| `includes`        | A list of `.gypi` files to be included in the top-level dictionary. |
| `target_defaults` | A dictionary of default settings to be inherited by all targets in the top-level dictionary.  See the "Settings keywords" section below. |
| `targets`         | A list of target specifications.  See the "targets" below. |
| `variables`       | A dictionary containing variable definitions.  Each key in this dictionary is the name of a variable, and each value must be a string value that the variable is to be set to. |

### targets

A list of dictionaries defining targets to be built by the files
generated from this `.gyp` file.

Targets may contain `includes`, `conditions`, and `variables` sections
as permitted in the root dictionary. The following additional keywords
have structural meaning for target definitions:

| *Keyword*         | *Description*     |
|:---------------------------- |:------------------------------------------|
| `actions`                    | A list of special custom actions to perform on a specific input file, or files, to produce output files.  See the "Actions" section below. |
| `all_dependent_settings`     | A dictionary of settings to be applied to all dependents of the target, transitively.  This includes direct dependents and the entire set of their dependents, and so on.  This section may contain anything found within a `target` dictionary, except `configurations`, `target_name`, and `type` sections.  Compare `direct_dependent_settings` and `link_settings`. |
| `configurations`             | A list of dictionaries defining build configurations for the target.  See the "Configurations" section below.  |
| `copies`                     | A list of copy actions to perform. See the "Copies" section below. |
| `defines`                    | A list of preprocesor definitions to be passed on the command line to the C/C++ compiler (via `-D` or `/D` options). |
| `dependencies`               | A list of targets on which this target depends.  Targets in other `.gyp` files are specified as `../path/to/other.gyp:target_we_want`. |
| `direct_dependent_settings`  | A dictionary of settings to be applied to other targets that depend on this target.  These settings will only be applied to direct dependents.  This section may contain anything found within a `target` dictionary, except `configurations`, `target_name`, and `type` sections.  Compare with `all_dependent_settings` and `link_settings`. |
| `include_dirs`               | A list of include directories to be passed on the command line to the C/C++ compiler (via `-I` or `/I` options). |
| `libraries`                  | A list of list of libraries (and/or frameworks) on which this target depends. |
| `link_settings`              | A dictionary of settings to be applied to targets in which this target's contents are linked.  `executable` and `shared_library` targets are linkable, so if they depend on a non-linkable target such as a `static_library`, they will adopt its `link_settings`.  This section can contain anything found within a `target` dictionary, except `configurations`, `target_name`, and `type` sections.  Compare `all_dependent_settings` and `direct_dependent_settings`. |
| `rules`                      | A special custom action to perform on a list of input files, to produce output files.  See the "Rules" section below. |
| `sources`                    | A list of source files that are used to build this target or which should otherwise show up in the IDE for this target.  In practice, we expect this list to be a union of all files necessary to build the target on all platforms, as well as other related files that aren't actually used for building, like README files. |
| `target_conditions`          | Like `conditions`, but evaluation is delayed until the settings have been merged into an actual target.  `target_conditions` may be used to place conditionals into a `target_defaults` section but have them still depend on specific target settings. |
| `target_name`                | The name of a target being defined. |
| `type`                       | The type of target being defined. This field currently supports `executable`, `static_library`, `shared_library`, and `none`.  The `none` target type is useful when producing output which is not linked. For example, converting raw translation files into resources or documentation into platform specific help files. |
| `msvs_props`                 | A list of Visual Studio property sheets (`.vsprops` files) to be used to build the target. |
| `xcode_config_file`          | An Xcode configuration (`.xcconfig` file) to be used to build the target. |
| `xcode_framework_dirs`       | A list of framework directories be used to build the target. |

You can affect the way that lists/dictionaries are merged together (for
example the way a list in target\_defaults interacts with the same named
list in the target itself) with a couple of special characters, which
are covered in [Merge
Basics](InputFormatReference#Merge_Basics_(=,_?,_+).md) and [List
Filters](InputFormatReference#List_Filters.md) on the
InputFormatReference page.

### configurations

`configurations` sections may be found within `targets` or
`target_defaults` sections.  The `configurations` section is a list of
dictionaries specifying different build configurations.  Because
configurations are implemented as lists, it is not currently possible to
override aspects of configurations that are imported into a target from
a `target_defaults` section.

NOTE: It is extremely important that each target within a project define
the same set of configurations.  This continues to apply even when a
project spans across multiple `.gyp` files.

A configuration dictionary may contain anything that can be found within
a target dictionary, except for `actions`, `all_dependent_settings`,
`configurations`, `dependencies`, `direct_dependent_settings`,
`libraries`, `link_settings`, `sources`, `target_name`, and `type`.

Configuration dictionaries may also contain these elements:

| *Keyword*            | *Description*                                       |
|:---------------------|:----------------------------------------------------|
| `configuration_name` | Required attribute.  The name of the configuration. |

### Conditionals

Conditionals may appear within any dictionary in a `.gyp` file.  There
are two tpes of conditionals, which differ only in the timing of their
processing.  `conditons` sections are processed shortly after loading
`.gyp` files, and `target_conditons` sections are processed after all
dependencies have been computed.

A conditional section is introduced with a `conditions` or
`target_conditions` dictionary keyword, and is composed of a list.  Each
list contains two or three elements.  The first two elements, which are
always required, are the conditional expression to evaluate and a
dictionary containing settings to merge into the dictionary containing
the `conditions` or `target_conditions` section if the expression
evaluates to true.  The third, optional, list element is a dictionary to
merge if the expression evaluates to false.

The `eval()` of the expression string takes place in the context of
global and/or local dictionaries that constructed from the `.gyp` input
data, and overrides the `__builtin__` dictionary, to prevent the
execution of arbitrary Python code.

### Actions

An `actions` section provides a list of custom build actions to perform
on inputs, producing outputs.  The `actions` section is organized as a
list.  Each item in the list is a dictionary having the following form:

| *Keyword*     | *Type* | *Description*                |
|:--------------|:-------|:-----------------------------|
| `action_name` | string | The name of the action.  Depending on how actions are implemented in the various generators, some may desire or require this property to be set to a unique name; others may ignore this property entirely. |
| `inputs`      | list   | A list of pathnames treated as inputs to the custom action. |
| `outputs`     | list   | A list of pathnames that the custom action produces. |
| `action`      | list   | A command line invocation used to produce `outputs` from `inputs`.  For maximum cross-platform compatibility, invocations that require a Python interpreter should be specified with a first element `"python"`.  This will enable generators for environments with specialized Python installations to be able to perform the action in an appropriate Python environment. |
| `message`     | string | A message to be displayed to the user by the build system when the action is run. |

Build environments will compare `inputs` and `outputs`.  If any `output`
is missing or is outdated relative to any `input`, the custom action
will be invoked.  If all `outputs` are present and newer than all
`inputs`, the `outputs` are considered up-to-date and the action need
not be invoked.

Actions are implemented in Xcode as shell script build phases performed
prior to the compilation phase.  In the Visual Studio generator, actions
appear files with a `FileConfiguration` containing a custom
`VCCustomBuildTool` specifying the remainder of the inputs, the outputs,
and the action.

Combined with variable expansions, actions can be quite powerful.  Here
is an example action that leverages variable expansions to minimize
duplication of pathnames:

```
      'sources': [
        # libraries.cc is generated by the js2c action below.
        '<(INTERMEDIATE_DIR)/libraries.cc',
      ],
      'actions': [
        {
          'variables': {
            'core_library_files': [
              'src/runtime.js',
              'src/v8natives.js',
              'src/macros.py',
            ],
          },
          'action_name': 'js2c',
          'inputs': [
            'tools/js2c.py',
            '<@(core_library_files)',
          ],
          'outputs': [
            '<(INTERMEDIATE_DIR)/libraries.cc',
            '<(INTERMEDIATE_DIR)/libraries-empty.cc',
          ],
          'action': ['python', 'tools/js2c.py', '<@(_outputs)', 'CORE', '<@(core_library_files)'],
        },
      ],
```

### Rules

A `rules` section provides custom build action to perform on inputs, producing
outputs.  The `rules` section is organized as a list.  Each item in the list is
a dictionary having the following form:

| *Keyword*   | *Type* | *Description*                            |
|:------------|:-------|:-----------------------------------------|
| `rule_name` | string | The name of the rule.  Depending on how Rules are implemented in the various generators, some may desire or require this property to be set to a unique name; others may ignore this property entirely. |
| `extension` | string | All source files of the current target with the given extension will be treated successively as inputs to the rule. |
| `inputs`    | list   | Additional dependencies of the rule. |
| `outputs`   | list   | A list of pathnames that the rule produces. Has access to `RULE_INPUT_` variables (see below). |
| `action`    | list   | A command line invocation used to produce `outputs` from `inputs`.  For maximum cross-platform compatibility, invocations that require a Python interpreter should be specified with a first element `"python"`.  This will enable generators for environments with specialized Python installations to be able to perform the action in an appropriate Python environment. Has access to `RULE_INPUT_` variables (see below). |
| `message`   | string | A message to be displayed to the user by the build system when the action is run. Has access to `RULE_INPUT_` variables (see below). |

There are several variables available to `outputs`, `action`, and `message`.

|  *Variable*          | *Description*                       |
|:---------------------|:------------------------------------|
| `RULE_INPUT_PATH`    | The full path to the current input. |
| `RULE_INPUT_DIRNAME` | The directory of the current input. |
| `RULE_INPUT_NAME`    | The file name of the current input. |
| `RULE_INPUT_ROOT`    | The file name of the current input without extension. |
| `RULE_INPUT_EXT`     | The file name extension of the current input. |

Rules can be thought of as Action generators. For each source selected
by `extension` an special action is created. This action starts out with
the same `inputs`, `outputs`, `action`, and `message` as the rule. The
source is added to the action's `inputs`. The `outputs`, `action`, and
`message` are then handled the same but with the additional variables.
If the `_output` variable is used in the `action` or `message` the
`RULE_INPUT_` variables in `output` will be expanded for the current
source.

### Copies

A `copies` section provides a simple means of copying files.  The
`copies` section is organized as a list.  Each item in the list is a
dictionary having the following form:

| *Keyword*     | *Type* | *Description*                 |
|:--------------|:-------|:------------------------------|
| `destination` | string | The directory into which the `files` will be copied. |
| `files`       | list   | A list of files to be copied. |

The copies will be created in `destination` and have the same file name
as the file they are copied from. Even if the `files` are from multiple
directories they will all be copied into the `destination` directory.
Each `destination` file has an implicit build dependency on the file it
is copied from.

### Generated Xcode .pbxproj Files

We derive the following things in a `project.pbxproj` plist file within
an `.xcodeproj` bundle from the above input file formats as follows:

  * `Group hierarchy`: This is generated in a fixed format with contents
    derived from the input files. There is no provision for the user to
    specify additional groups or create a custom hierarchy.
    * `Configuration group`: This will be used with the
      `xcode_config_file` property above, if needed.
    * `Source group`: The union of the `sources` lists of all `targets`
      after applying appropriate `conditions`.  The resulting list is
      sorted and put into a group hierarchy that matches the layout of
      the directory tree on disk, with a root of // (the top of the
      hierarchy).
    * `Frameworks group`: Taken directly from `libraries` value for the
      target, after applying appropriate conditions.
    * `Projects group`: References to other `.xcodeproj` bundles that
      are needed by the `.xcodeproj` in which the group is contained.
    * `Products group`: Output from the various targets.
  * `Project References`:
  * `Project Configurations`:
    * Per-`.xcodeproj` file settings are not supported, all settings are
      applied at the target level.
  * `Targets`:
    * `Phases`: Copy sources, link with libraries/frameworks, ...
    * `Target Configurations`: Specified by input.
    * `Dependencies`: (local and remote)

### Generated Visual Studio .vcproj Files

We derive the following sections in a `.vcproj` file from the above
input file formats as follows:

  * `VisualStudioProject`:
    * `Platforms`:
    * `ToolFiles`:
    * `Configurations`:
      * `Configuration`:
    * `References`:
    * `Files`:
      * `Filter`:
      * `File`:
        * `FileConfiguration`:
          * `Tool`:
    * `Globals`:

### Generated Visual Studio .sln Files

We derive the following sections in a `.sln` file from the above input
file formats as follows:

  * `Projects`:
    * `WebsiteProperties`:
    * `ProjectDependencies`:
  * `Global`:
    * `SolutionConfigurationPlatforms`:
    * `ProjectConfigurationPlatforms`:
    * `SolutionProperties`:
    * `NestedProjects`:

## Caveats

Notes/Question from very first prototype draft of the language.
Make sure these issues are addressed somewhere before deleting.

  * Libraries are easy, application abstraction is harder
    * Applications involves resource compilation
    * Applications involve many inputs
    * Applications include transitive closure of dependencies
  * Specific use cases like cc\_library
    * Mac compiles more than just .c/.cpp files (specifically, .m and .mm
      files)
    * Compiler options vary by:
      * File type
      * Target type
      * Individual file
    * Files may have custom settings per file per platform, but we probably
      don't care or need to support this in gyp.
  * Will all linked non-Chromium projects always use the same versions of every
    subsystem?
  * Variants are difficult.  We've identified the following variants (some
    specific to Chromium, some typical of other projects in the same ballpark):
    * Target platform
    * V8 vs. JSC
    * Debug vs. Release
    * Toolchain (VS version, gcc, version)
    * Host platform
    * L10N
    * Vendor
    * Purify / Valgrind
  * Will everyone upgrade VS at once?
  * What does a dylib dependency mean?
# Generate Your Projects (gyp-next)

GYP is a Meta-Build system: a build system that generates other build systems.

* [User documentation](./UserDocumentation.md)
* [Input Format Reference](./InputFormatReference.md)
* [Language specification](./LanguageSpecification.md)
* [Hacking](./Hacking.md)
* [Testing](./Testing.md)
* [GYP vs. CMake](./GypVsCMake.md)

GYP is intended to support large projects that need to be built on multiple
platforms (e.g., Mac, Windows, Linux), and where it is important that
the project can be built using the IDEs that are popular on each platform
as if the project is a "native" one.

It can be used to generate XCode projects, Visual Studio projects, Ninja
build files, and Makefiles. In each case GYP's goal is to replicate as
closely as possible the way one would set up a native build of the project
using the IDE.

GYP can also be used to generate "hybrid" projects that provide the IDE
scaffolding for a nice user experience but call out to Ninja to do the actual
building (which is usually much faster than the native build systems of the
IDEs).

For more information on GYP, click on the links above.
# Testing

NOTE: this document is outdated and needs to be updated. Read with your own discretion.

## Introduction

This document describes the GYP testing infrastructure,
as provided by the `TestGyp.py` module.

These tests emphasize testing the _behavior_ of the
various GYP-generated build configurations:
Visual Studio, Xcode, SCons, Make, etc.
The goal is _not_ to test the output of the GYP generators by,
for example, comparing a GYP-generated Makefile
against a set of known "golden" Makefiles
(although the testing infrastructure could
be used to write those kinds of tests).
The idea is that the generated build configuration files
could be completely written to add a feature or fix a bug
so long as they continue to support the functional behaviors
defined by the tests:  building programs, shared libraries, etc.

## "Hello, world!" GYP test configuration

Here is an actual test configuration,
a simple build of a C program to print `"Hello, world!"`.

```
  $ ls -l test/hello
  total 20
  -rw-r--r-- 1 knight knight 312 Jul 30 20:22 gyptest-all.py
  -rw-r--r-- 1 knight knight 307 Jul 30 20:22 gyptest-default.py
  -rwxr-xr-x 1 knight knight 326 Jul 30 20:22 gyptest-target.py
  -rw-r--r-- 1 knight knight  98 Jul 30 20:22 hello.c
  -rw-r--r-- 1 knight knight 142 Jul 30 20:22 hello.gyp
  $
```

The `gyptest-*.py` files are three separate tests (test scripts)
that use this configuration.  The first one, `gyptest-all.py`,
looks like this:

```
  #!/usr/bin/env python

  """
  Verifies simplest-possible build of a "Hello, world!" program
  using an explicit build target of 'all'.
  """

  import TestGyp

  test = TestGyp.TestGyp()

  test.run_gyp('hello.gyp')

  test.build_all('hello.gyp')

  test.run_built_executable('hello', stdout="Hello, world!\n")

  test.pass_test()
```

The test script above runs GYP against the specified input file
(`hello.gyp`) to generate a build configuration.
It then tries to build the `'all'` target
(or its equivalent) using the generated build configuration.
Last, it verifies that the build worked as expected
by running the executable program (`hello`)
that was just presumably built by the generated configuration,
and verifies that the output from the program
matches the expected `stdout` string (`"Hello, world!\n"`).

Which configuration is generated
(i.e., which build tool to test)
is specified when the test is run;
see the next section.

Surrounding the functional parts of the test
described above are the header,
which should be basically the same for each test
(modulo a different description in the docstring):

```
  #!/usr/bin/env python

  """
  Verifies simplest-possible build of a "Hello, world!" program
  using an explicit build target of 'all'.
  """

  import TestGyp

  test = TestGyp.TestGyp()
```

Similarly, the footer should be the same in every test:

```
  test.pass_test()
```

## Running tests

Test scripts are run by the `gyptest.py` script.
You can specify (an) explicit test script(s) to run:

```
  $ python gyptest.py test/hello/gyptest-all.py
  PYTHONPATH=/home/knight/src/gyp/trunk/test/lib
  TESTGYP_FORMAT=scons
  /usr/bin/python test/hello/gyptest-all.py
  PASSED
  $
```

If you specify a directory, all test scripts
(scripts prefixed with `gyptest-`) underneath
the directory will be run:

```
  $ python gyptest.py test/hello
  PYTHONPATH=/home/knight/src/gyp/trunk/test/lib
  TESTGYP_FORMAT=scons
  /usr/bin/python test/hello/gyptest-all.py
  PASSED
  /usr/bin/python test/hello/gyptest-default.py
  PASSED
  /usr/bin/python test/hello/gyptest-target.py
  PASSED
  $
```

Or you can specify the `-a` option to run all scripts
in the tree:

```
  $ python gyptest.py -a
  PYTHONPATH=/home/knight/src/gyp/trunk/test/lib
  TESTGYP_FORMAT=scons
  /usr/bin/python test/configurations/gyptest-configurations.py
  PASSED
  /usr/bin/python test/defines/gyptest-defines.py
  PASSED
      .
      .
      .
      .
  /usr/bin/python test/variables/gyptest-commands.py
  PASSED
  $
```

If any tests fail during the run,
the `gyptest.py` script will report them in a
summary at the end.

## Debugging tests

Tests that create intermediate output do so under the gyp/out/testworkarea
directory. On test completion, intermediate output is cleaned up. To preserve
this output, set the environment variable PRESERVE=1. This can be handy to
inspect intermediate data when debugging a test.

You can also set PRESERVE\_PASS=1, PRESERVE\_FAIL=1 or PRESERVE\_NO\_RESULT=1
to preserve output for tests that fall into one of those categories.

# Specifying the format (build tool) to use

By default, the `gyptest.py` script will generate configurations for
the "primary" supported build tool for the platform you're on:
Visual Studio on Windows,
Xcode on Mac,
and (currently) SCons on Linux.
An alternate format (build tool) may be specified
using the `-f` option:

```
  $ python gyptest.py -f make test/hello/gyptest-all.py
  PYTHONPATH=/home/knight/src/gyp/trunk/test/lib
  TESTGYP_FORMAT=make
  /usr/bin/python test/hello/gyptest-all.py
  PASSED
  $
```

Multiple tools may be specified in a single pass as
a comma-separated list:

```
  $ python gyptest.py -f make,scons test/hello/gyptest-all.py
  PYTHONPATH=/home/knight/src/gyp/trunk/test/lib
  TESTGYP_FORMAT=make
  /usr/bin/python test/hello/gyptest-all.py
  PASSED
  TESTGYP_FORMAT=scons
  /usr/bin/python test/hello/gyptest-all.py
  PASSED
  $
```

## Test script functions and methods

The `TestGyp` class contains a lot of functionality
intended to make it easy to write tests.
This section describes the most useful pieces for GYP testing.

(The `TestGyp` class is actually a subclass of more generic
`TestCommon` and `TestCmd` base classes
that contain even more functionality than is
described here.)

### Initialization

The standard initialization formula is:

```
  import TestGyp
  test = TestGyp.TestGyp()
```

This copies the contents of the directory tree in which
the test script lives to a temporary directory for execution,
and arranges for the temporary directory's removal on exit.

By default, any comparisons of output or file contents
must be exact matches for the test to pass.
If you need to use regular expressions for matches,
a useful alternative initialization is:

```
  import TestGyp
  test = TestGyp.TestGyp(match = TestGyp.match_re,
                         diff = TestGyp.diff_re)`
```

### Running GYP

The canonical invocation is to simply specify the `.gyp` file to be executed:

```
  test.run_gyp('file.gyp')
```

Additional GYP arguments may be specified:

```
  test.run_gyp('file.gyp', arguments=['arg1', 'arg2', ...])
```

To execute GYP from a subdirectory (where, presumably, the specified file
lives):

```
  test.run_gyp('file.gyp', chdir='subdir')
```

### Running the build tool

Running the build tool requires passing in a `.gyp` file, which may be used to
calculate the name of a specific build configuration file (such as a MSVS
solution file corresponding to the `.gyp` file).

There are several different `.build_*()` methods for invoking different types
of builds.

To invoke a build tool with an explicit `all` target (or equivalent):

```
  test.build_all('file.gyp')
```

To invoke a build tool with its default behavior (for example, executing `make`
with no targets specified):

```
  test.build_default('file.gyp')
```

To invoke a build tool with an explicit specified target:

```
  test.build_target('file.gyp', 'target')
```

### Running executables

The most useful method executes a program built by the GYP-generated
configuration:

```
  test.run_built_executable('program')
```

The `.run_built_executable()` method will account for the actual built target
output location for the build tool being tested, as well as tack on any
necessary executable file suffix for the platform (for example `.exe` on
Windows).

`stdout=` and `stderr=` keyword arguments specify expected standard output and
error output, respectively.  Failure to match these (if specified) will cause
the test to fail.  An explicit `None` value will suppress that verification:

```
  test.run_built_executable('program',
                            stdout="expect this output\n",
							stderr=None)
```

Note that the default values are `stdout=None` and `stderr=''` (that is, no
check for standard output, and error output must be empty).

Arbitrary executables (not necessarily those built by GYP) can be executed with
the lower-level `.run()` method:

```
  test.run('program')
```

The program must be in the local directory (that is, the temporary directory
for test execution) or be an absolute path name.

### Fetching command output

```
  test.stdout()
```

Returns the standard output from the most recent executed command (including
`.run_gyp()`, `.build_*()`, or `.run*()` methods).

```
  test.stderr()
```

Returns the error output from the most recent executed command (including
`.run_gyp()`, `.build_*()`, or `.run*()` methods).

### Verifying existence or non-existence of files or directories

```
  test.must_exist('file_or_dir')
```

Verifies that the specified file or directory exists, and fails the test if it
doesn't.

```
  test.must_not_exist('file_or_dir')
```

Verifies that the specified file or directory does not exist, and fails the
test if it does.

### Verifying file contents

```
  test.must_match('file', 'expected content\n')
```

Verifies that the content of the specified file match the expected string, and
fails the test if it does not.  By default, the match must be exact, but
line-by-line regular expressions may be used if the `TestGyp` object was
initialized with `TestGyp.match_re`.

```
  test.must_not_match('file', 'expected content\n')
```

Verifies that the content of the specified file does _not_ match the expected
string, and fails the test if it does.  By default, the match must be exact,
but line-by-line regular expressions may be used if the `TestGyp` object was
initialized with `TestGyp.match_re`.

```
  test.must_contain('file', 'substring')
```

Verifies that the specified file contains the specified substring, and fails
the test if it does not.

```
  test.must_not_contain('file', 'substring')
```

Verifies that the specified file does not contain the specified substring, and
fails the test if it does.

```
  test.must_contain_all_lines(output, lines)
```

Verifies that the output string contains all of the "lines" in the specified
list of lines.  In practice, the lines can be any substring and need not be
`\n`-terminaed lines per se.  If any line is missing, the test fails.

```
  test.must_not_contain_any_lines(output, lines)
```

Verifies that the output string does _not_ contain any of the "lines" in the
specified list of lines.  In practice, the lines can be any substring and need
not be `\n`-terminaed lines per se.  If any line exists in the output string,
the test fails.

```
  test.must_contain_any_line(output, lines)
```

Verifies that the output string contains at least one of the "lines" in the
specified list of lines.  In practice, the lines can be any substring and need
not be `\n`-terminaed lines per se.  If none of the specified lines is present,
the test fails.

### Reading file contents

```
  test.read('file')
```

Returns the contents of the specified file.  Directory elements contained in a
list will be joined:

```
  test.read(['subdir', 'file'])
```

### Test success or failure

```
  test.fail_test()
```

Fails the test, reporting `FAILED` on standard output and exiting with an exit
status of `1`.

```
  test.pass_test()
```

Passes the test, reporting `PASSED` on standard output and exiting with an exit
status of `0`.

```
  test.no_result()
```

Indicates the test had no valid result (i.e., the conditions could not be
tested because of an external factor like a full file system).  Reports `NO
RESULT` on standard output and exits with a status of `2`.
# User Documentation

## Introduction

This document is intended to provide a user-level guide to GYP.  The
emphasis here is on how to use GYP to accomplish specific tasks, not on
the complete technical language specification.  (For that, see the
[LanguageSpecification](LanguageSpecification.md).)

The document below starts with some overviews to provide context: an
overview of the structure of a `.gyp` file itself, an overview of a
typical executable-program target in a `.gyp` file, an an overview of a
typical library target in a `.gyp` file.

After the overviews, there are examples of `gyp` patterns for different
common use cases.

## Skeleton of a typical Chromium .gyp file

Here is the skeleton of a typical `.gyp` file in the Chromium tree:

```
  {
    'variables': {
      .
      .
      .
    },
    'includes': [
      '../build/common.gypi',
    ],
    'target_defaults': {
      .
      .
      .
    },
    'targets': [
      {
        'target_name': 'target_1',
          .
          .
          .
      },
      {
        'target_name': 'target_2',
          .
          .
          .
      },
    ],
    'conditions': [
      ['OS=="linux"', {
        'targets': [
          {
            'target_name': 'linux_target_3',
              .
              .
              .
          },
        ],
      }],
      ['OS=="win"', {
        'targets': [
          {
            'target_name': 'windows_target_4',
              .
              .
              .
          },
        ],
      }, { # OS != "win"
        'targets': [
          {
            'target_name': 'non_windows_target_5',
              .
              .
              .
          },
      }],
    ],
  }
```

The entire file just contains a Python dictionary.  (It's actually JSON,
with two small Pythonic deviations: comments are introduced with `#`,
and a `,` (comma)) is legal after the last element in a list or
dictionary.)

The top-level pieces in the `.gyp` file are as follows:

`'variables'`:  Definitions of variables that can be interpolated and
used in various other parts of the file.

`'includes'`:  A list of of other files that will be included in this
file.  By convention, included files have the suffix `.gypi` (gyp
include).

`'target_defaults'`:  Settings that will apply to _all_ of the targets
defined in this `.gyp` file.

`'targets'`:  The list of targets for which this `.gyp` file can
generate builds.  Each target is a dictionary that contains settings
describing all the information necessary to build the target.

`'conditions'`:  A list of condition specifications that can modify the
contents of the items in the global dictionary defined by this `.gyp`
file based on the values of different variablwes.  As implied by the
above example, the most common use of a `conditions` section in the
top-level dictionary is to add platform-specific targets to the
`targets` list.

## Skeleton of a typical executable target in a .gyp file

The most straightforward target is probably a simple executable program.
Here is an example `executable` target that demonstrates the features
that should cover most simple uses of gyp:

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'type': 'executable',
        'msvs_guid': '5ECEC9E5-8F23-47B6-93E0-C3B328B3BE65',
        'dependencies': [
          'xyzzy',
          '../bar/bar.gyp:bar',
        ],
        'defines': [
          'DEFINE_FOO',
          'DEFINE_A_VALUE=value',
        ],
        'include_dirs': [
          '..',
        ],
        'sources': [
          'file1.cc',
          'file2.cc',
        ],
        'conditions': [
          ['OS=="linux"', {
            'defines': [
              'LINUX_DEFINE',
            ],
            'include_dirs': [
              'include/linux',
            ],
          }],
          ['OS=="win"', {
            'defines': [
              'WINDOWS_SPECIFIC_DEFINE',
            ],
          }, { # OS != "win",
            'defines': [
              'NON_WINDOWS_DEFINE',
            ],
          }]
        ],
      },
    ],
  }
```

The top-level settings in the target include:

`'target_name'`: The name by which the target should be known, which
should be unique across all `.gyp` files.  This name will be used as the
project name in the generated Visual Studio solution, as the target name
in the generated XCode configuration, and as the alias for building this
target from the command line of the generated SCons configuration.

`'type'`: Set to `executable`, logically enough.

`'msvs_guid'`: THIS IS ONLY TRANSITIONAL.  This is a hard-coded GUID
values that will be used in the generated Visual Studio solution
file(s).  This allows us to check in a `chrome.sln` file that
interoperates with gyp-generated project files.  Once everything in
Chromium is being generated by gyp, it will no longer be important that
the GUIDs stay constant across invocations, and we'll likely get rid of
these settings,

`'dependencies'`: This lists other targets that this target depends on.
The gyp-generated files will guarantee that the other targets are built
before this target.  Any library targets in the `dependencies` list will
be linked with this target.  The various settings (`defines`,
`include_dirs`, etc.) listed in the `direct_dependent_settings` sections
of the targets in this list will be applied to how _this_ target is
built and linked.  See the more complete discussion of
`direct_dependent_settings`, below.

`'defines'`: The C preprocessor definitions that will be passed in on
compilation command lines (using `-D` or `/D` options).

`'include_dirs'`: The directories in which included header files live.
These will be passed in on compilation command lines (using `-I` or `/I`
options).

`'sources'`: The source files for this target.

`'conditions'`: A block of conditions that will be evaluated to update
the different settings in the target dictionary.

## Skeleton of a typical library target in a .gyp file

The vast majority of targets are libraries.  Here is an example of a
library target including the additional features that should cover most
needs of libraries:

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'type': '<(library)'
        'msvs_guid': '5ECEC9E5-8F23-47B6-93E0-C3B328B3BE65',
        'dependencies': [
          'xyzzy',
          '../bar/bar.gyp:bar',
        ],
        'defines': [
          'DEFINE_FOO',
          'DEFINE_A_VALUE=value',
        ],
        'include_dirs': [
          '..',
        ],
        'direct_dependent_settings': {
          'defines': [
            'DEFINE_FOO',
            'DEFINE_ADDITIONAL',
          ],
          'linkflags': [
          ],
        },
        'export_dependent_settings': [
          '../bar/bar.gyp:bar',
        ],
        'sources': [
          'file1.cc',
          'file2.cc',
        ],
        'conditions': [
          ['OS=="linux"', {
            'defines': [
              'LINUX_DEFINE',
            ],
            'include_dirs': [
              'include/linux',
            ],
          ],
          ['OS=="win"', {
            'defines': [
              'WINDOWS_SPECIFIC_DEFINE',
            ],
          }, { # OS != "win",
            'defines': [
              'NON_WINDOWS_DEFINE',
            ],
          }]
        ],
    ],
  }
```

The possible entries in a library target are largely the same as those
that can be specified for an executable target (`defines`,
`include_dirs`, etc.).  The differences include:

`'type'`: This should almost always be set to '<(library)', which allows
the user to define at gyp time whether libraries are to be built static
or shared.  (On Linux, at least, linking with shared libraries saves
significant link time.) If it's necessary to pin down the type of
library to be built, the `type` can be set explicitly to
`static_library` or `shared_library`.

`'direct_dependent_settings'`: This defines the settings that will be
applied to other targets that _directly depend_ on this target--that is,
that list _this_ target in their `'dependencies'` setting.  This is
where you list the `defines`, `include_dirs`, `cflags` and `linkflags`
that other targets that compile or link against this target need to
build consistently.

`'export_dependent_settings'`: This lists the targets whose
`direct_dependent_settings` should be "passed on" to other targets that
use (depend on) this target.  `TODO:  expand on this description.`

## Use Cases

These use cases are intended to cover the most common actions performed
by developers using GYP.

Note that these examples are _not_ fully-functioning, self-contained
examples (or else they'd be way too long).  Each example mostly contains
just the keywords and settings relevant to the example, with perhaps a
few extra keywords for context.  The intent is to try to show the
specific pieces you need to pay attention to when doing something.
[NOTE:  if practical use shows that these examples are confusing without
additional context, please add what's necessary to clarify things.]

### Add new source files

There are similar but slightly different patterns for adding a
platform-independent source file vs. adding a source file that only
builds on some of the supported platforms.

#### Add a source file that builds on all platforms

**Simplest possible case**: You are adding a file(s) that builds on all
platforms.

Just add the file(s) to the `sources` list of the appropriate dictionary
in the `targets` list:

```
  {
    'targets': [
      {
        'target_name': 'my_target',
        'type': 'executable',
        'sources': [
          '../other/file_1.cc',
          'new_file.cc',
          'subdir/file3.cc',
        ],
      },
    ],
  },
```

File path names are relative to the directory in which the `.gyp` file lives.

Keep the list sorted alphabetically (unless there's a really, really,
_really_ good reason not to).

#### Add a platform-specific source file

##### Your platform-specific file is named `*_linux.{ext}`, `*_mac.{ext}`, `*_posix.{ext}` or `*_win.{ext}`

The simplest way to add a platform-specific source file, assuming you're
adding a completely new file and get to name it, is to use one of the
following standard suffixes:

  * `_linux`  (e.g. `foo_linux.cc`)
  * `_mac`    (e.g. `foo_mac.cc`)
  * `_posix`  (e.g. `foo_posix.cc`)
  * `_win`    (e.g. `foo_win.cc`)

Simply add the file to the `sources` list of the appropriate dict within
the `targets` list, like you would any other source file.

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'type': 'executable',
        'sources': [
          'independent.cc',
          'specific_win.cc',
        ],
      },
    ],
  },
```

The Chromium `.gyp` files all have appropriate `conditions` entries to
filter out the files that aren't appropriate for the current platform.
In the above example, the `specific_win.cc` file will be removed
automatically from the source-list on non-Windows builds.

##### Your platform-specific file does not use an already-defined pattern

If your platform-specific file does not contain a
`*_{linux,mac,posix,win}` substring (or some other pattern that's
already in the `conditions` for the target), and you can't change the
file name, there are two patterns that can be used.

**Prefererred**:  Add the file to the `sources` list of the appropriate
dictionary within the `targets` list.  Add an appropriate `conditions`
section to exclude the specific files name:

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'type': 'executable',
        'sources': [
          'linux_specific.cc',
        ],
        'conditions': [
          ['OS != "linux"', {
            'sources!': [
              # Linux-only; exclude on other platforms.
              'linux_specific.cc',
            ]
          }[,
        ],
      },
    ],
  },
```

Despite the duplicate listing, the above is generally preferred because
the `sources` list contains a useful global list of all sources on all
platforms with consistent sorting on all platforms.

**Non-preferred**: In some situations, however, it might make sense to
list a platform-specific file only in a `conditions` section that
specifically _includes_ it in the `sources` list:

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'type': 'executable',
        'sources': [],
        ['OS == "linux"', {
          'sources': [
            # Only add to sources list on Linux.
            'linux_specific.cc',
          ]
        }],
      },
    ],
  },
```

The above two examples end up generating equivalent builds, with the
small exception that the `sources` lists will list the files in
different orders.  (The first example defines explicitly where
`linux_specific.cc` appears in the list--perhaps in in the
middle--whereas the second example will always tack it on to the end of
the list.)

**Including or excluding files using patterns**: There are more
complicated ways to construct a `sources` list based on patterns.  See
`TODO` below.

### Add a new executable

An executable program is probably the most straightforward type of
target, since all it typically needs is a list of source files, some
compiler/linker settings (probably varied by platform), and some library
targets on which it depends and which must be used in the final link.

#### Add an executable that builds on all platforms

Add a dictionary defining the new executable target to the `targets`
list in the appropriate `.gyp` file.  Example:

```
  {
    'targets': [
      {
        'target_name': 'new_unit_tests',
        'type': 'executable',
        'defines': [
          'FOO',
        ],
        'include_dirs': [
          '..',
        ],
        'dependencies': [
          'other_target_in_this_file',
          'other_gyp2:target_in_other_gyp2',
        ],
        'sources': [
          'new_additional_source.cc',
          'new_unit_tests.cc',
        ],
      },
    ],
  }
```

#### Add a platform-specific executable

Add a dictionary defining the new executable target to the `targets`
list within an appropriate `conditions` block for the platform.  The
`conditions` block should be a sibling to the top-level `targets` list:

```
  {
    'targets': [
    ],
    'conditions': [
      ['OS=="win"', {
        'targets': [
          {
            'target_name': 'new_unit_tests',
            'type': 'executable',
            'defines': [
              'FOO',
            ],
            'include_dirs': [
              '..',
            ],
            'dependencies': [
              'other_target_in_this_file',
              'other_gyp2:target_in_other_gyp2',
            ],
            'sources': [
              'new_additional_source.cc',
              'new_unit_tests.cc',
            ],
          },
        ],
      }],
    ],
  }
```

### Add settings to a target

There are several different types of settings that can be defined for
any given target.

#### Add new preprocessor definitions (`-D` or `/D` flags)

New preprocessor definitions are added by the `defines` setting:

```
  {
    'targets': [
      {
        'target_name': 'existing_target',
        'defines': [
          'FOO',
          'BAR=some_value',
        ],
      },
    ],
  },
```

These may be specified directly in a target's settings, as in the above
example, or in a `conditions` section.

#### Add a new include directory (`-I` or `/I` flags)

New include directories are added by the `include_dirs` setting:

```
  {
    'targets': [
      {
        'target_name': 'existing_target',
        'include_dirs': [
          '..',
          'include',
        ],
      },
    ],
  },
```

These may be specified directly in a target's settings, as in the above
example, or in a `conditions` section.

#### Add new compiler flags

Specific compiler flags can be added with the `cflags` setting:

```
  {
    'targets': [
      {
        'target_name': 'existing_target',
        'conditions': [
          ['OS=="win"', {
            'cflags': [
              '/WX',
            ],
          }, { # OS != "win"
            'cflags': [
              '-Werror',
            ],
          }],
        ],
      },
    ],
  },
```

Because these flags will be specific to the actual compiler involved,
they will almost always be only set within a `conditions` section.

#### Add new linker flags

Setting linker flags is OS-specific. On linux and most non-mac posix
systems, they can be added with the `ldflags` setting:

```
  {
    'targets': [
      {
        'target_name': 'existing_target',
        'conditions': [
          ['OS=="linux"', {
            'ldflags': [
              '-pthread',
            ],
          }],
        ],
      },
    ],
  },
```

Because these flags will be specific to the actual linker involved,
they will almost always be only set within a `conditions` section.

On OS X, linker settings are set via `xcode_settings`, on Windows via
`msvs_settings`.

#### Exclude settings on a platform

Any given settings keyword (`defines`, `include_dirs`, etc.) has a
corresponding form with a trailing `!` (exclamation point) to remove
values from a setting.  One useful example of this is to remove the
Linux `-Werror` flag from the global settings defined in
`build/common.gypi`:

```
  {
    'targets': [
      {
        'target_name': 'third_party_target',
        'conditions': [
          ['OS=="linux"', {
            'cflags!': [
              '-Werror',
            ],
          }],
        ],
      },
    ],
  },
```

### Cross-compiling

GYP has some (relatively limited) support for cross-compiling.

If the variable `GYP_CROSSCOMPILE` or one of the toolchain-related
variables (like `CC_host` or `CC_target`) is set, GYP will think that
you wish to do a cross-compile.

When cross-compiling, each target can be part of a "host" build, a
"target" build, or both. By default, the target is assumed to be (only)
part of the "target" build. The 'toolsets' property can be set on a
target to change the default.

A target's dependencies are assumed to match the build type (so, if A
depends on B, by default that means that a target build of A depends on
a target build of B). You can explicitly depend on targets across
toolchains by specifying "#host" or "#target" in the dependencies list.
If GYP is not doing a cross-compile, the "#host" and "#target" will be
stripped as needed, so nothing breaks.

### Add a new library

TODO:  write intro

#### Add a library that builds on all platforms

Add the a dictionary defining the new library target to the `targets`
list in the appropriate `.gyp` file.  Example:

```
  {
    'targets': [
      {
        'target_name': 'new_library',
        'type': '<(library)',
        'defines': [
          'FOO',
          'BAR=some_value',
        ],
        'include_dirs': [
          '..',
        ],
        'dependencies': [
          'other_target_in_this_file',
          'other_gyp2:target_in_other_gyp2',
        ],
        'direct_dependent_settings': {
          'include_dirs': '.',
        },
        'export_dependent_settings': [
          'other_target_in_this_file',
        ],
        'sources': [
          'new_additional_source.cc',
          'new_library.cc',
        ],
      },
    ],
  }
```

The use of the `<(library)` variable above should be the default `type`
setting for most library targets, as it allows the developer to choose,
at `gyp` time, whether to build with static or shared libraries.
(Building with shared libraries saves a _lot_ of link time on Linux.)

It may be necessary to build a specific library as a fixed type.  Is so,
the `type` field can be hard-wired appropriately.  For a static library:

```
        'type': 'static_library',
```

For a shared library:

```
        'type': 'shared_library',
```

#### Add a platform-specific library

Add a dictionary defining the new library target to the `targets` list
within a `conditions` block that's a sibling to the top-level `targets`
list:

```
  {
    'targets': [
    ],
    'conditions': [
      ['OS=="win"', {
        'targets': [
          {
            'target_name': 'new_library',
            'type': '<(library)',
            'defines': [
              'FOO',
              'BAR=some_value',
            ],
            'include_dirs': [
              '..',
            ],
            'dependencies': [
              'other_target_in_this_file',
              'other_gyp2:target_in_other_gyp2',
            ],
            'direct_dependent_settings': {
              'include_dirs': '.',
            },
            'export_dependent_settings': [
              'other_target_in_this_file',
            ],
            'sources': [
              'new_additional_source.cc',
              'new_library.cc',
            ],
          },
        ],
      }],
    ],
  }
```

### Dependencies between targets

GYP provides useful primitives for establishing dependencies between
targets, which need to be configured in the following situations.

#### Linking with another library target

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'dependencies': [
          'libbar',
        ],
      },
      {
        'target_name': 'libbar',
        'type': '<(library)',
        'sources': [
        ],
      },
    ],
  }
```

Note that if the library target is in a different `.gyp` file, you have
to specify the path to other `.gyp` file, relative to this `.gyp` file's
directory:

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'dependencies': [
          '../bar/bar.gyp:libbar',
        ],
      },
    ],
  }
```

Adding a library often involves updating multiple `.gyp` files, adding
the target to the approprate `.gyp` file (possibly a newly-added `.gyp`
file), and updating targets in the other `.gyp` files that depend on
(link with) the new library.

#### Compiling with necessary flags for a library target dependency

We need to build a library (often a third-party library) with specific
preprocessor definitions or command-line flags, and need to ensure that
targets that depend on the library build with the same settings.  This
situation is handled by a `direct_dependent_settings` block:

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'type': 'executable',
        'dependencies': [
          'libbar',
        ],
      },
      {
        'target_name': 'libbar',
        'type': '<(library)',
        'defines': [
          'LOCAL_DEFINE_FOR_LIBBAR',
          'DEFINE_TO_USE_LIBBAR',
        ],
        'include_dirs': [
          '..',
          'include/libbar',
        ],
        'direct_dependent_settings': {
          'defines': [
            'DEFINE_TO_USE_LIBBAR',
          ],
          'include_dirs': [
            'include/libbar',
          ],
        },
      },
    ],
  }
```

In the above example, the sources of the `foo` executable will be
compiled with the options `-DDEFINE_TO_USE_LIBBAR -Iinclude/libbar`,
because of those settings' being listed in the
`direct_dependent_settings` block.

Note that these settings will likely need to be replicated in the
settings for the library target itsef, so that the library will build
with the same options.  This does not prevent the target from defining
additional options for its "internal" use when compiling its own source
files.  (In the above example, these are the `LOCAL_DEFINE_FOR_LIBBAR`
define, and the `..` entry in the `include_dirs` list.)

#### When a library depends on an additional library at final link time

```
  {
    'targets': [
      {
        'target_name': 'foo',
        'type': 'executable',
        'dependencies': [
          'libbar',
        ],
      },
      {
        'target_name': 'libbar',
        'type': '<(library)',
        'dependencies': [
          'libother'
        ],
        'export_dependent_settings': [
          'libother'
        ],
      },
      {
        'target_name': 'libother',
        'type': '<(library)',
        'direct_dependent_settings': {
          'defines': [
            'DEFINE_FOR_LIBOTHER',
          ],
          'include_dirs': [
            'include/libother',
          ],
        },
      },
    ],
  }
```

### Support for Mac OS X bundles

gyp supports building bundles on OS X (.app, .framework, .bundle, etc).
Here is an example of this:

```
    {
      'target_name': 'test_app',
      'product_name': 'Test App Gyp',
      'type': 'executable',
      'mac_bundle': 1,
      'sources': [
        'main.m',
        'TestAppAppDelegate.h',
        'TestAppAppDelegate.m',
      ],
      'mac_bundle_resources': [
        'TestApp/English.lproj/InfoPlist.strings',
        'TestApp/English.lproj/MainMenu.xib',
      ],
      'link_settings': {
        'libraries': [
          '$(SDKROOT)/System/Library/Frameworks/Cocoa.framework',
        ],
      },
      'xcode_settings': {
        'INFOPLIST_FILE': 'TestApp/TestApp-Info.plist',
      },
    },
```

The `mac_bundle` key tells gyp that this target should be a bundle.
`executable` targets get extension `.app` by default, `shared_library`
targets get `.framework` – but you can change the bundle extensions by
setting `product_extension` if you want. Files listed in
`mac_bundle_resources` will be copied to the bundle's `Resource` folder
of the bundle. You can also set
`process_outputs_as_mac_bundle_resources` to 1 in actions and rules to
let the output of actions and rules be added to that folder (similar to
`process_outputs_as_sources`). If `product_name` is not set, the bundle
will be named after `target_name`as usual.

### Move files (refactoring)

TODO

### Custom build steps

TODO

#### Adding an explicit build step to generate specific files

TODO

#### Adding a rule to handle files with a new suffix

TODO

### Build flavors

TODO
#!/bin/sh
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

set -e
base=$(dirname "$0")
exec python "${base}/gyp_main.py" "$@"
@rem Copyright (c) 2009 Google Inc. All rights reserved.
@rem Use of this source code is governed by a BSD-style license that can be
@rem found in the LICENSE file.

@python "%~dp0gyp_main.py" %*
#!/usr/bin/env python3

# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import sys
import subprocess


def IsCygwin():
    # Function copied from pylib/gyp/common.py
    try:
        out = subprocess.Popen(
            "uname", stdout=subprocess.PIPE, stderr=subprocess.STDOUT
        )
        stdout, _ = out.communicate()
        return "CYGWIN" in stdout.decode("utf-8")
    except Exception:
        return False


def UnixifyPath(path):
    try:
        if not IsCygwin():
            return path
        out = subprocess.Popen(
            ["cygpath", "-u", path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT
        )
        stdout, _ = out.communicate()
        return stdout.decode("utf-8")
    except Exception:
        return path


# Make sure we're using the version of pylib in this repo, not one installed
# elsewhere on the system. Also convert to Unix style path on Cygwin systems,
# else the 'gyp' library will not be found
path = UnixifyPath(sys.argv[0])
sys.path.insert(0, os.path.join(os.path.dirname(path), "pylib"))
import gyp  # noqa: E402

if __name__ == "__main__":
    sys.exit(gyp.script_main())
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""New implementation of Visual Studio project generation."""

import hashlib
import os
import random
from operator import attrgetter

import gyp.common


def cmp(x, y):
    return (x > y) - (x < y)


# Initialize random number generator
random.seed()

# GUIDs for project types
ENTRY_TYPE_GUIDS = {
    "project": "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}",
    "folder": "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
}

# ------------------------------------------------------------------------------
# Helper functions


def MakeGuid(name, seed="msvs_new"):
    """Returns a GUID for the specified target name.

  Args:
    name: Target name.
    seed: Seed for MD5 hash.
  Returns:
    A GUID-line string calculated from the name and seed.

  This generates something which looks like a GUID, but depends only on the
  name and seed.  This means the same name/seed will always generate the same
  GUID, so that projects and solutions which refer to each other can explicitly
  determine the GUID to refer to explicitly.  It also means that the GUID will
  not change when the project for a target is rebuilt.
  """
    # Calculate a MD5 signature for the seed and name.
    d = hashlib.md5((str(seed) + str(name)).encode("utf-8")).hexdigest().upper()
    # Convert most of the signature to GUID form (discard the rest)
    guid = (
        "{"
        + d[:8]
        + "-"
        + d[8:12]
        + "-"
        + d[12:16]
        + "-"
        + d[16:20]
        + "-"
        + d[20:32]
        + "}"
    )
    return guid


# ------------------------------------------------------------------------------


class MSVSSolutionEntry:
    def __cmp__(self, other):
        # Sort by name then guid (so things are in order on vs2008).
        return cmp((self.name, self.get_guid()), (other.name, other.get_guid()))


class MSVSFolder(MSVSSolutionEntry):
    """Folder in a Visual Studio project or solution."""

    def __init__(self, path, name=None, entries=None, guid=None, items=None):
        """Initializes the folder.

    Args:
      path: Full path to the folder.
      name: Name of the folder.
      entries: List of folder entries to nest inside this folder.  May contain
          Folder or Project objects.  May be None, if the folder is empty.
      guid: GUID to use for folder, if not None.
      items: List of solution items to include in the folder project.  May be
          None, if the folder does not directly contain items.
    """
        if name:
            self.name = name
        else:
            # Use last layer.
            self.name = os.path.basename(path)

        self.path = path
        self.guid = guid

        # Copy passed lists (or set to empty lists)
        self.entries = sorted(entries or [], key=attrgetter("path"))
        self.items = list(items or [])

        self.entry_type_guid = ENTRY_TYPE_GUIDS["folder"]

    def get_guid(self):
        if self.guid is None:
            # Use consistent guids for folders (so things don't regenerate).
            self.guid = MakeGuid(self.path, seed="msvs_folder")
        return self.guid


# ------------------------------------------------------------------------------


class MSVSProject(MSVSSolutionEntry):
    """Visual Studio project."""

    def __init__(
        self,
        path,
        name=None,
        dependencies=None,
        guid=None,
        spec=None,
        build_file=None,
        config_platform_overrides=None,
        fixpath_prefix=None,
    ):
        """Initializes the project.

    Args:
      path: Absolute path to the project file.
      name: Name of project.  If None, the name will be the same as the base
          name of the project file.
      dependencies: List of other Project objects this project is dependent
          upon, if not None.
      guid: GUID to use for project, if not None.
      spec: Dictionary specifying how to build this project.
      build_file: Filename of the .gyp file that the vcproj file comes from.
      config_platform_overrides: optional dict of configuration platforms to
          used in place of the default for this target.
      fixpath_prefix: the path used to adjust the behavior of _fixpath
    """
        self.path = path
        self.guid = guid
        self.spec = spec
        self.build_file = build_file
        # Use project filename if name not specified
        self.name = name or os.path.splitext(os.path.basename(path))[0]

        # Copy passed lists (or set to empty lists)
        self.dependencies = list(dependencies or [])

        self.entry_type_guid = ENTRY_TYPE_GUIDS["project"]

        if config_platform_overrides:
            self.config_platform_overrides = config_platform_overrides
        else:
            self.config_platform_overrides = {}
        self.fixpath_prefix = fixpath_prefix
        self.msbuild_toolset = None

    def set_dependencies(self, dependencies):
        self.dependencies = list(dependencies or [])

    def get_guid(self):
        if self.guid is None:
            # Set GUID from path
            # TODO(rspangler): This is fragile.
            # 1. We can't just use the project filename sans path, since there could
            #    be multiple projects with the same base name (for example,
            #    foo/unittest.vcproj and bar/unittest.vcproj).
            # 2. The path needs to be relative to $SOURCE_ROOT, so that the project
            #    GUID is the same whether it's included from base/base.sln or
            #    foo/bar/baz/baz.sln.
            # 3. The GUID needs to be the same each time this builder is invoked, so
            #    that we don't need to rebuild the solution when the project changes.
            # 4. We should be able to handle pre-built project files by reading the
            #    GUID from the files.
            self.guid = MakeGuid(self.name)
        return self.guid

    def set_msbuild_toolset(self, msbuild_toolset):
        self.msbuild_toolset = msbuild_toolset


# ------------------------------------------------------------------------------


class MSVSSolution:
    """Visual Studio solution."""

    def __init__(
        self, path, version, entries=None, variants=None, websiteProperties=True
    ):
        """Initializes the solution.

    Args:
      path: Path to solution file.
      version: Format version to emit.
      entries: List of entries in solution.  May contain Folder or Project
          objects.  May be None, if the folder is empty.
      variants: List of build variant strings.  If none, a default list will
          be used.
      websiteProperties: Flag to decide if the website properties section
          is generated.
    """
        self.path = path
        self.websiteProperties = websiteProperties
        self.version = version

        # Copy passed lists (or set to empty lists)
        self.entries = list(entries or [])

        if variants:
            # Copy passed list
            self.variants = variants[:]
        else:
            # Use default
            self.variants = ["Debug|Win32", "Release|Win32"]
        # TODO(rspangler): Need to be able to handle a mapping of solution config
        # to project config.  Should we be able to handle variants being a dict,
        # or add a separate variant_map variable?  If it's a dict, we can't
        # guarantee the order of variants since dict keys aren't ordered.

        # TODO(rspangler): Automatically write to disk for now; should delay until
        # node-evaluation time.
        self.Write()

    def Write(self, writer=gyp.common.WriteOnDiff):
        """Writes the solution file to disk.

    Raises:
      IndexError: An entry appears multiple times.
    """
        # Walk the entry tree and collect all the folders and projects.
        all_entries = set()
        entries_to_check = self.entries[:]
        while entries_to_check:
            e = entries_to_check.pop(0)

            # If this entry has been visited, nothing to do.
            if e in all_entries:
                continue

            all_entries.add(e)

            # If this is a folder, check its entries too.
            if isinstance(e, MSVSFolder):
                entries_to_check += e.entries

        all_entries = sorted(all_entries, key=attrgetter("path"))

        # Open file and print header
        f = writer(self.path)
        f.write(
            "Microsoft Visual Studio Solution File, "
            "Format Version %s\r\n" % self.version.SolutionVersion()
        )
        f.write("# %s\r\n" % self.version.Description())

        # Project entries
        sln_root = os.path.split(self.path)[0]
        for e in all_entries:
            relative_path = gyp.common.RelativePath(e.path, sln_root)
            # msbuild does not accept an empty folder_name.
            # use '.' in case relative_path is empty.
            folder_name = relative_path.replace("/", "\\") or "."
            f.write(
                'Project("%s") = "%s", "%s", "%s"\r\n'
                % (
                    e.entry_type_guid,  # Entry type GUID
                    e.name,  # Folder name
                    folder_name,  # Folder name (again)
                    e.get_guid(),  # Entry GUID
                )
            )

            # TODO(rspangler): Need a way to configure this stuff
            if self.websiteProperties:
                f.write(
                    "\tProjectSection(WebsiteProperties) = preProject\r\n"
                    '\t\tDebug.AspNetCompiler.Debug = "True"\r\n'
                    '\t\tRelease.AspNetCompiler.Debug = "False"\r\n'
                    "\tEndProjectSection\r\n"
                )

            if isinstance(e, MSVSFolder) and e.items:
                f.write("\tProjectSection(SolutionItems) = preProject\r\n")
                for i in e.items:
                    f.write(f"\t\t{i} = {i}\r\n")
                f.write("\tEndProjectSection\r\n")

            if isinstance(e, MSVSProject) and e.dependencies:
                f.write("\tProjectSection(ProjectDependencies) = postProject\r\n")
                for d in e.dependencies:
                    f.write(f"\t\t{d.get_guid()} = {d.get_guid()}\r\n")
                f.write("\tEndProjectSection\r\n")

            f.write("EndProject\r\n")

        # Global section
        f.write("Global\r\n")

        # Configurations (variants)
        f.write("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n")
        for v in self.variants:
            f.write(f"\t\t{v} = {v}\r\n")
        f.write("\tEndGlobalSection\r\n")

        # Sort config guids for easier diffing of solution changes.
        config_guids = []
        config_guids_overrides = {}
        for e in all_entries:
            if isinstance(e, MSVSProject):
                config_guids.append(e.get_guid())
                config_guids_overrides[e.get_guid()] = e.config_platform_overrides
        config_guids.sort()

        f.write("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n")
        for g in config_guids:
            for v in self.variants:
                nv = config_guids_overrides[g].get(v, v)
                # Pick which project configuration to build for this solution
                # configuration.
                f.write(
                    "\t\t%s.%s.ActiveCfg = %s\r\n"
                    % (
                        g,  # Project GUID
                        v,  # Solution build configuration
                        nv,  # Project build config for that solution config
                    )
                )

                # Enable project in this solution configuration.
                f.write(
                    "\t\t%s.%s.Build.0 = %s\r\n"
                    % (
                        g,  # Project GUID
                        v,  # Solution build configuration
                        nv,  # Project build config for that solution config
                    )
                )
        f.write("\tEndGlobalSection\r\n")

        # TODO(rspangler): Should be able to configure this stuff too (though I've
        # never seen this be any different)
        f.write("\tGlobalSection(SolutionProperties) = preSolution\r\n")
        f.write("\t\tHideSolutionNode = FALSE\r\n")
        f.write("\tEndGlobalSection\r\n")

        # Folder mappings
        # Omit this section if there are no folders
        if any(e.entries for e in all_entries if isinstance(e, MSVSFolder)):
            f.write("\tGlobalSection(NestedProjects) = preSolution\r\n")
            for e in all_entries:
                if not isinstance(e, MSVSFolder):
                    continue  # Does not apply to projects, only folders
                for subentry in e.entries:
                    f.write(f"\t\t{subentry.get_guid()} = {e.get_guid()}\r\n")
            f.write("\tEndGlobalSection\r\n")

        f.write("EndGlobal\r\n")

        f.close()
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Visual Studio project reader/writer."""

import gyp.easy_xml as easy_xml

# ------------------------------------------------------------------------------


class Tool:
    """Visual Studio tool."""

    def __init__(self, name, attrs=None):
        """Initializes the tool.

    Args:
      name: Tool name.
      attrs: Dict of tool attributes; may be None.
    """
        self._attrs = attrs or {}
        self._attrs["Name"] = name

    def _GetSpecification(self):
        """Creates an element for the tool.

    Returns:
      A new xml.dom.Element for the tool.
    """
        return ["Tool", self._attrs]


class Filter:
    """Visual Studio filter - that is, a virtual folder."""

    def __init__(self, name, contents=None):
        """Initializes the folder.

    Args:
      name: Filter (folder) name.
      contents: List of filenames and/or Filter objects contained.
    """
        self.name = name
        self.contents = list(contents or [])


# ------------------------------------------------------------------------------


class Writer:
    """Visual Studio XML project writer."""

    def __init__(self, project_path, version, name, guid=None, platforms=None):
        """Initializes the project.

    Args:
      project_path: Path to the project file.
      version: Format version to emit.
      name: Name of the project.
      guid: GUID to use for project, if not None.
      platforms: Array of string, the supported platforms.  If null, ['Win32']
    """
        self.project_path = project_path
        self.version = version
        self.name = name
        self.guid = guid

        # Default to Win32 for platforms.
        if not platforms:
            platforms = ["Win32"]

        # Initialize the specifications of the various sections.
        self.platform_section = ["Platforms"]
        for platform in platforms:
            self.platform_section.append(["Platform", {"Name": platform}])
        self.tool_files_section = ["ToolFiles"]
        self.configurations_section = ["Configurations"]
        self.files_section = ["Files"]

        # Keep a dict keyed on filename to speed up access.
        self.files_dict = {}

    def AddToolFile(self, path):
        """Adds a tool file to the project.

    Args:
      path: Relative path from project to tool file.
    """
        self.tool_files_section.append(["ToolFile", {"RelativePath": path}])

    def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools):
        """Returns the specification for a configuration.

    Args:
      config_type: Type of configuration node.
      config_name: Configuration name.
      attrs: Dict of configuration attributes; may be None.
      tools: List of tools (strings or Tool objects); may be None.
    Returns:
    """
        # Handle defaults
        if not attrs:
            attrs = {}
        if not tools:
            tools = []

        # Add configuration node and its attributes
        node_attrs = attrs.copy()
        node_attrs["Name"] = config_name
        specification = [config_type, node_attrs]

        # Add tool nodes and their attributes
        if tools:
            for t in tools:
                if isinstance(t, Tool):
                    specification.append(t._GetSpecification())
                else:
                    specification.append(Tool(t)._GetSpecification())
        return specification

    def AddConfig(self, name, attrs=None, tools=None):
        """Adds a configuration to the project.

    Args:
      name: Configuration name.
      attrs: Dict of configuration attributes; may be None.
      tools: List of tools (strings or Tool objects); may be None.
    """
        spec = self._GetSpecForConfiguration("Configuration", name, attrs, tools)
        self.configurations_section.append(spec)

    def _AddFilesToNode(self, parent, files):
        """Adds files and/or filters to the parent node.

    Args:
      parent: Destination node
      files: A list of Filter objects and/or relative paths to files.

    Will call itself recursively, if the files list contains Filter objects.
    """
        for f in files:
            if isinstance(f, Filter):
                node = ["Filter", {"Name": f.name}]
                self._AddFilesToNode(node, f.contents)
            else:
                node = ["File", {"RelativePath": f}]
                self.files_dict[f] = node
            parent.append(node)

    def AddFiles(self, files):
        """Adds files to the project.

    Args:
      files: A list of Filter objects and/or relative paths to files.

    This makes a copy of the file/filter tree at the time of this call.  If you
    later add files to a Filter object which was passed into a previous call
    to AddFiles(), it will not be reflected in this project.
    """
        self._AddFilesToNode(self.files_section, files)
        # TODO(rspangler) This also doesn't handle adding files to an existing
        # filter.  That is, it doesn't merge the trees.

    def AddFileConfig(self, path, config, attrs=None, tools=None):
        """Adds a configuration to a file.

    Args:
      path: Relative path to the file.
      config: Name of configuration to add.
      attrs: Dict of configuration attributes; may be None.
      tools: List of tools (strings or Tool objects); may be None.

    Raises:
      ValueError: Relative path does not match any file added via AddFiles().
    """
        # Find the file node with the right relative path
        parent = self.files_dict.get(path)
        if not parent:
            raise ValueError('AddFileConfig: file "%s" not in project.' % path)

        # Add the config to the file node
        spec = self._GetSpecForConfiguration("FileConfiguration", config, attrs, tools)
        parent.append(spec)

    def WriteIfChanged(self):
        """Writes the project file."""
        # First create XML content definition
        content = [
            "VisualStudioProject",
            {
                "ProjectType": "Visual C++",
                "Version": self.version.ProjectVersion(),
                "Name": self.name,
                "ProjectGUID": self.guid,
                "RootNamespace": self.name,
                "Keyword": "Win32Proj",
            },
            self.platform_section,
            self.tool_files_section,
            self.configurations_section,
            ["References"],  # empty section
            self.files_section,
            ["Globals"],  # empty section
        ]
        easy_xml.WriteXmlIfChanged(content, self.project_path, encoding="Windows-1252")
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

r"""Code to validate and convert settings of the Microsoft build tools.

This file contains code to validate and convert settings of the Microsoft
build tools.  The function ConvertToMSBuildSettings(), ValidateMSVSSettings(),
and ValidateMSBuildSettings() are the entry points.

This file was created by comparing the projects created by Visual Studio 2008
and Visual Studio 2010 for all available settings through the user interface.
The MSBuild schemas were also considered.  They are typically found in the
MSBuild install directory, e.g. c:\Program Files (x86)\MSBuild
"""

import re
import sys

# Dictionaries of settings validators. The key is the tool name, the value is
# a dictionary mapping setting names to validation functions.
_msvs_validators = {}
_msbuild_validators = {}


# A dictionary of settings converters. The key is the tool name, the value is
# a dictionary mapping setting names to conversion functions.
_msvs_to_msbuild_converters = {}


# Tool name mapping from MSVS to MSBuild.
_msbuild_name_of_tool = {}


class _Tool:
    """Represents a tool used by MSVS or MSBuild.

  Attributes:
      msvs_name: The name of the tool in MSVS.
      msbuild_name: The name of the tool in MSBuild.
  """

    def __init__(self, msvs_name, msbuild_name):
        self.msvs_name = msvs_name
        self.msbuild_name = msbuild_name


def _AddTool(tool):
    """Adds a tool to the four dictionaries used to process settings.

  This only defines the tool.  Each setting also needs to be added.

  Args:
    tool: The _Tool object to be added.
  """
    _msvs_validators[tool.msvs_name] = {}
    _msbuild_validators[tool.msbuild_name] = {}
    _msvs_to_msbuild_converters[tool.msvs_name] = {}
    _msbuild_name_of_tool[tool.msvs_name] = tool.msbuild_name


def _GetMSBuildToolSettings(msbuild_settings, tool):
    """Returns an MSBuild tool dictionary.  Creates it if needed."""
    return msbuild_settings.setdefault(tool.msbuild_name, {})


class _Type:
    """Type of settings (Base class)."""

    def ValidateMSVS(self, value):
        """Verifies that the value is legal for MSVS.

    Args:
      value: the value to check for this type.

    Raises:
      ValueError if value is not valid for MSVS.
    """

    def ValidateMSBuild(self, value):
        """Verifies that the value is legal for MSBuild.

    Args:
      value: the value to check for this type.

    Raises:
      ValueError if value is not valid for MSBuild.
    """

    def ConvertToMSBuild(self, value):
        """Returns the MSBuild equivalent of the MSVS value given.

    Args:
      value: the MSVS value to convert.

    Returns:
      the MSBuild equivalent.

    Raises:
      ValueError if value is not valid.
    """
        return value


class _String(_Type):
    """A setting that's just a string."""

    def ValidateMSVS(self, value):
        if not isinstance(value, str):
            raise ValueError("expected string; got %r" % value)

    def ValidateMSBuild(self, value):
        if not isinstance(value, str):
            raise ValueError("expected string; got %r" % value)

    def ConvertToMSBuild(self, value):
        # Convert the macros
        return ConvertVCMacrosToMSBuild(value)


class _StringList(_Type):
    """A settings that's a list of strings."""

    def ValidateMSVS(self, value):
        if not isinstance(value, (list, str)):
            raise ValueError("expected string list; got %r" % value)

    def ValidateMSBuild(self, value):
        if not isinstance(value, (list, str)):
            raise ValueError("expected string list; got %r" % value)

    def ConvertToMSBuild(self, value):
        # Convert the macros
        if isinstance(value, list):
            return [ConvertVCMacrosToMSBuild(i) for i in value]
        else:
            return ConvertVCMacrosToMSBuild(value)


class _Boolean(_Type):
    """Boolean settings, can have the values 'false' or 'true'."""

    def _Validate(self, value):
        if value not in {"true", "false"}:
            raise ValueError("expected bool; got %r" % value)

    def ValidateMSVS(self, value):
        self._Validate(value)

    def ValidateMSBuild(self, value):
        self._Validate(value)

    def ConvertToMSBuild(self, value):
        self._Validate(value)
        return value


class _Integer(_Type):
    """Integer settings."""

    def __init__(self, msbuild_base=10):
        _Type.__init__(self)
        self._msbuild_base = msbuild_base

    def ValidateMSVS(self, value):
        # Try to convert, this will raise ValueError if invalid.
        self.ConvertToMSBuild(value)

    def ValidateMSBuild(self, value):
        # Try to convert, this will raise ValueError if invalid.
        int(value, self._msbuild_base)

    def ConvertToMSBuild(self, value):
        msbuild_format = (self._msbuild_base == 10) and "%d" or "0x%04x"
        return msbuild_format % int(value)


class _Enumeration(_Type):
    """Type of settings that is an enumeration.

  In MSVS, the values are indexes like '0', '1', and '2'.
  MSBuild uses text labels that are more representative, like 'Win32'.

  Constructor args:
    label_list: an array of MSBuild labels that correspond to the MSVS index.
        In the rare cases where MSVS has skipped an index value, None is
        used in the array to indicate the unused spot.
    new: an array of labels that are new to MSBuild.
  """

    def __init__(self, label_list, new=None):
        _Type.__init__(self)
        self._label_list = label_list
        self._msbuild_values = {value for value in label_list if value is not None}
        if new is not None:
            self._msbuild_values.update(new)

    def ValidateMSVS(self, value):
        # Try to convert.  It will raise an exception if not valid.
        self.ConvertToMSBuild(value)

    def ValidateMSBuild(self, value):
        if value not in self._msbuild_values:
            raise ValueError("unrecognized enumerated value %s" % value)

    def ConvertToMSBuild(self, value):
        index = int(value)
        if index < 0 or index >= len(self._label_list):
            raise ValueError(
                "index value (%d) not in expected range [0, %d)"
                % (index, len(self._label_list))
            )
        label = self._label_list[index]
        if label is None:
            raise ValueError("converted value for %s not specified." % value)
        return label


# Instantiate the various generic types.
_boolean = _Boolean()
_integer = _Integer()
# For now, we don't do any special validation on these types:
_string = _String()
_file_name = _String()
_folder_name = _String()
_file_list = _StringList()
_folder_list = _StringList()
_string_list = _StringList()
# Some boolean settings went from numerical values to boolean.  The
# mapping is 0: default, 1: false, 2: true.
_newly_boolean = _Enumeration(["", "false", "true"])


def _Same(tool, name, setting_type):
    """Defines a setting that has the same name in MSVS and MSBuild.

  Args:
    tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
    name: the name of the setting.
    setting_type: the type of this setting.
  """
    _Renamed(tool, name, name, setting_type)


def _Renamed(tool, msvs_name, msbuild_name, setting_type):
    """Defines a setting for which the name has changed.

  Args:
    tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
    msvs_name: the name of the MSVS setting.
    msbuild_name: the name of the MSBuild setting.
    setting_type: the type of this setting.
  """

    def _Translate(value, msbuild_settings):
        msbuild_tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool)
        msbuild_tool_settings[msbuild_name] = setting_type.ConvertToMSBuild(value)

    _msvs_validators[tool.msvs_name][msvs_name] = setting_type.ValidateMSVS
    _msbuild_validators[tool.msbuild_name][msbuild_name] = setting_type.ValidateMSBuild
    _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate


def _Moved(tool, settings_name, msbuild_tool_name, setting_type):
    _MovedAndRenamed(
        tool, settings_name, msbuild_tool_name, settings_name, setting_type
    )


def _MovedAndRenamed(
    tool, msvs_settings_name, msbuild_tool_name, msbuild_settings_name, setting_type
):
    """Defines a setting that may have moved to a new section.

  Args:
    tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
    msvs_settings_name: the MSVS name of the setting.
    msbuild_tool_name: the name of the MSBuild tool to place the setting under.
    msbuild_settings_name: the MSBuild name of the setting.
    setting_type: the type of this setting.
  """

    def _Translate(value, msbuild_settings):
        tool_settings = msbuild_settings.setdefault(msbuild_tool_name, {})
        tool_settings[msbuild_settings_name] = setting_type.ConvertToMSBuild(value)

    _msvs_validators[tool.msvs_name][msvs_settings_name] = setting_type.ValidateMSVS
    validator = setting_type.ValidateMSBuild
    _msbuild_validators[msbuild_tool_name][msbuild_settings_name] = validator
    _msvs_to_msbuild_converters[tool.msvs_name][msvs_settings_name] = _Translate


def _MSVSOnly(tool, name, setting_type):
    """Defines a setting that is only found in MSVS.

  Args:
    tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
    name: the name of the setting.
    setting_type: the type of this setting.
  """

    def _Translate(unused_value, unused_msbuild_settings):
        # Since this is for MSVS only settings, no translation will happen.
        pass

    _msvs_validators[tool.msvs_name][name] = setting_type.ValidateMSVS
    _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate


def _MSBuildOnly(tool, name, setting_type):
    """Defines a setting that is only found in MSBuild.

  Args:
    tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
    name: the name of the setting.
    setting_type: the type of this setting.
  """

    def _Translate(value, msbuild_settings):
        # Let msbuild-only properties get translated as-is from msvs_settings.
        tool_settings = msbuild_settings.setdefault(tool.msbuild_name, {})
        tool_settings[name] = value

    _msbuild_validators[tool.msbuild_name][name] = setting_type.ValidateMSBuild
    _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate


def _ConvertedToAdditionalOption(tool, msvs_name, flag):
    """Defines a setting that's handled via a command line option in MSBuild.

  Args:
    tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
    msvs_name: the name of the MSVS setting that if 'true' becomes a flag
    flag: the flag to insert at the end of the AdditionalOptions
  """

    def _Translate(value, msbuild_settings):
        if value == "true":
            tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool)
            if "AdditionalOptions" in tool_settings:
                new_flags = "{} {}".format(tool_settings["AdditionalOptions"], flag)
            else:
                new_flags = flag
            tool_settings["AdditionalOptions"] = new_flags

    _msvs_validators[tool.msvs_name][msvs_name] = _boolean.ValidateMSVS
    _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate


def _CustomGeneratePreprocessedFile(tool, msvs_name):
    def _Translate(value, msbuild_settings):
        tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool)
        if value == "0":
            tool_settings["PreprocessToFile"] = "false"
            tool_settings["PreprocessSuppressLineNumbers"] = "false"
        elif value == "1":  # /P
            tool_settings["PreprocessToFile"] = "true"
            tool_settings["PreprocessSuppressLineNumbers"] = "false"
        elif value == "2":  # /EP /P
            tool_settings["PreprocessToFile"] = "true"
            tool_settings["PreprocessSuppressLineNumbers"] = "true"
        else:
            raise ValueError("value must be one of [0, 1, 2]; got %s" % value)

    # Create a bogus validator that looks for '0', '1', or '2'
    msvs_validator = _Enumeration(["a", "b", "c"]).ValidateMSVS
    _msvs_validators[tool.msvs_name][msvs_name] = msvs_validator
    msbuild_validator = _boolean.ValidateMSBuild
    msbuild_tool_validators = _msbuild_validators[tool.msbuild_name]
    msbuild_tool_validators["PreprocessToFile"] = msbuild_validator
    msbuild_tool_validators["PreprocessSuppressLineNumbers"] = msbuild_validator
    _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate


fix_vc_macro_slashes_regex_list = ("IntDir", "OutDir")
fix_vc_macro_slashes_regex = re.compile(
    r"(\$\((?:%s)\))(?:[\\/]+)" % "|".join(fix_vc_macro_slashes_regex_list)
)

# Regular expression to detect keys that were generated by exclusion lists
_EXCLUDED_SUFFIX_RE = re.compile("^(.*)_excluded$")


def _ValidateExclusionSetting(setting, settings, error_msg, stderr=sys.stderr):
    """Verify that 'setting' is valid if it is generated from an exclusion list.

  If the setting appears to be generated from an exclusion list, the root name
  is checked.

  Args:
      setting:   A string that is the setting name to validate
      settings:  A dictionary where the keys are valid settings
      error_msg: The message to emit in the event of error
      stderr:    The stream receiving the error messages.
  """
    # This may be unrecognized because it's an exclusion list. If the
    # setting name has the _excluded suffix, then check the root name.
    unrecognized = True
    m = re.match(_EXCLUDED_SUFFIX_RE, setting)
    if m:
        root_setting = m.group(1)
        unrecognized = root_setting not in settings

    if unrecognized:
        # We don't know this setting. Give a warning.
        print(error_msg, file=stderr)


def FixVCMacroSlashes(s):
    """Replace macros which have excessive following slashes.

  These macros are known to have a built-in trailing slash. Furthermore, many
  scripts hiccup on processing paths with extra slashes in the middle.

  This list is probably not exhaustive.  Add as needed.
  """
    if "$" in s:
        s = fix_vc_macro_slashes_regex.sub(r"\1", s)
    return s


def ConvertVCMacrosToMSBuild(s):
    """Convert the MSVS macros found in the string to the MSBuild equivalent.

  This list is probably not exhaustive.  Add as needed.
  """
    if "$" in s:
        replace_map = {
            "$(ConfigurationName)": "$(Configuration)",
            "$(InputDir)": "%(RelativeDir)",
            "$(InputExt)": "%(Extension)",
            "$(InputFileName)": "%(Filename)%(Extension)",
            "$(InputName)": "%(Filename)",
            "$(InputPath)": "%(Identity)",
            "$(ParentName)": "$(ProjectFileName)",
            "$(PlatformName)": "$(Platform)",
            "$(SafeInputName)": "%(Filename)",
        }
        for old, new in replace_map.items():
            s = s.replace(old, new)
        s = FixVCMacroSlashes(s)
    return s


def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr):
    """Converts MSVS settings (VS2008 and earlier) to MSBuild settings (VS2010+).

  Args:
      msvs_settings: A dictionary.  The key is the tool name.  The values are
          themselves dictionaries of settings and their values.
      stderr: The stream receiving the error messages.

  Returns:
      A dictionary of MSBuild settings.  The key is either the MSBuild tool name
      or the empty string (for the global settings).  The values are themselves
      dictionaries of settings and their values.
  """
    msbuild_settings = {}
    for msvs_tool_name, msvs_tool_settings in msvs_settings.items():
        if msvs_tool_name in _msvs_to_msbuild_converters:
            msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name]
            for msvs_setting, msvs_value in msvs_tool_settings.items():
                if msvs_setting in msvs_tool:
                    # Invoke the translation function.
                    try:
                        msvs_tool[msvs_setting](msvs_value, msbuild_settings)
                    except ValueError as e:
                        print(
                            "Warning: while converting %s/%s to MSBuild, "
                            "%s" % (msvs_tool_name, msvs_setting, e),
                            file=stderr,
                        )
                else:
                    _ValidateExclusionSetting(
                        msvs_setting,
                        msvs_tool,
                        (
                            "Warning: unrecognized setting %s/%s "
                            "while converting to MSBuild."
                            % (msvs_tool_name, msvs_setting)
                        ),
                        stderr,
                    )
        else:
            print(
                "Warning: unrecognized tool %s while converting to "
                "MSBuild." % msvs_tool_name,
                file=stderr,
            )
    return msbuild_settings


def ValidateMSVSSettings(settings, stderr=sys.stderr):
    """Validates that the names of the settings are valid for MSVS.

  Args:
      settings: A dictionary.  The key is the tool name.  The values are
          themselves dictionaries of settings and their values.
      stderr: The stream receiving the error messages.
  """
    _ValidateSettings(_msvs_validators, settings, stderr)


def ValidateMSBuildSettings(settings, stderr=sys.stderr):
    """Validates that the names of the settings are valid for MSBuild.

  Args:
      settings: A dictionary.  The key is the tool name.  The values are
          themselves dictionaries of settings and their values.
      stderr: The stream receiving the error messages.
  """
    _ValidateSettings(_msbuild_validators, settings, stderr)


def _ValidateSettings(validators, settings, stderr):
    """Validates that the settings are valid for MSBuild or MSVS.

  We currently only validate the names of the settings, not their values.

  Args:
      validators: A dictionary of tools and their validators.
      settings: A dictionary.  The key is the tool name.  The values are
          themselves dictionaries of settings and their values.
      stderr: The stream receiving the error messages.
  """
    for tool_name in settings:
        if tool_name in validators:
            tool_validators = validators[tool_name]
            for setting, value in settings[tool_name].items():
                if setting in tool_validators:
                    try:
                        tool_validators[setting](value)
                    except ValueError as e:
                        print(
                            f"Warning: for {tool_name}/{setting}, {e}",
                            file=stderr,
                        )
                else:
                    _ValidateExclusionSetting(
                        setting,
                        tool_validators,
                        (f"Warning: unrecognized setting {tool_name}/{setting}"),
                        stderr,
                    )

        else:
            print("Warning: unrecognized tool %s" % (tool_name), file=stderr)


# MSVS and MBuild names of the tools.
_compile = _Tool("VCCLCompilerTool", "ClCompile")
_link = _Tool("VCLinkerTool", "Link")
_midl = _Tool("VCMIDLTool", "Midl")
_rc = _Tool("VCResourceCompilerTool", "ResourceCompile")
_lib = _Tool("VCLibrarianTool", "Lib")
_manifest = _Tool("VCManifestTool", "Manifest")
_masm = _Tool("MASM", "MASM")
_armasm = _Tool("ARMASM", "ARMASM")


_AddTool(_compile)
_AddTool(_link)
_AddTool(_midl)
_AddTool(_rc)
_AddTool(_lib)
_AddTool(_manifest)
_AddTool(_masm)
_AddTool(_armasm)
# Add sections only found in the MSBuild settings.
_msbuild_validators[""] = {}
_msbuild_validators["ProjectReference"] = {}
_msbuild_validators["ManifestResourceCompile"] = {}

# Descriptions of the compiler options, i.e. VCCLCompilerTool in MSVS and
# ClCompile in MSBuild.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\cl.xml" for
# the schema of the MSBuild ClCompile settings.

# Options that have the same name in MSVS and MSBuild
_Same(_compile, "AdditionalIncludeDirectories", _folder_list)  # /I
_Same(_compile, "AdditionalOptions", _string_list)
_Same(_compile, "AdditionalUsingDirectories", _folder_list)  # /AI
_Same(_compile, "AssemblerListingLocation", _file_name)  # /Fa
_Same(_compile, "BrowseInformationFile", _file_name)
_Same(_compile, "BufferSecurityCheck", _boolean)  # /GS
_Same(_compile, "DisableLanguageExtensions", _boolean)  # /Za
_Same(_compile, "DisableSpecificWarnings", _string_list)  # /wd
_Same(_compile, "EnableFiberSafeOptimizations", _boolean)  # /GT
_Same(_compile, "EnablePREfast", _boolean)  # /analyze Visible='false'
_Same(_compile, "ExpandAttributedSource", _boolean)  # /Fx
_Same(_compile, "FloatingPointExceptions", _boolean)  # /fp:except
_Same(_compile, "ForceConformanceInForLoopScope", _boolean)  # /Zc:forScope
_Same(_compile, "ForcedIncludeFiles", _file_list)  # /FI
_Same(_compile, "ForcedUsingFiles", _file_list)  # /FU
_Same(_compile, "GenerateXMLDocumentationFiles", _boolean)  # /doc
_Same(_compile, "IgnoreStandardIncludePath", _boolean)  # /X
_Same(_compile, "MinimalRebuild", _boolean)  # /Gm
_Same(_compile, "OmitDefaultLibName", _boolean)  # /Zl
_Same(_compile, "OmitFramePointers", _boolean)  # /Oy
_Same(_compile, "PreprocessorDefinitions", _string_list)  # /D
_Same(_compile, "ProgramDataBaseFileName", _file_name)  # /Fd
_Same(_compile, "RuntimeTypeInfo", _boolean)  # /GR
_Same(_compile, "ShowIncludes", _boolean)  # /showIncludes
_Same(_compile, "SmallerTypeCheck", _boolean)  # /RTCc
_Same(_compile, "StringPooling", _boolean)  # /GF
_Same(_compile, "SuppressStartupBanner", _boolean)  # /nologo
_Same(_compile, "TreatWChar_tAsBuiltInType", _boolean)  # /Zc:wchar_t
_Same(_compile, "UndefineAllPreprocessorDefinitions", _boolean)  # /u
_Same(_compile, "UndefinePreprocessorDefinitions", _string_list)  # /U
_Same(_compile, "UseFullPaths", _boolean)  # /FC
_Same(_compile, "WholeProgramOptimization", _boolean)  # /GL
_Same(_compile, "XMLDocumentationFileName", _file_name)
_Same(_compile, "CompileAsWinRT", _boolean)  # /ZW

_Same(
    _compile,
    "AssemblerOutput",
    _Enumeration(
        [
            "NoListing",
            "AssemblyCode",  # /FA
            "All",  # /FAcs
            "AssemblyAndMachineCode",  # /FAc
            "AssemblyAndSourceCode",
        ]
    ),
)  # /FAs
_Same(
    _compile,
    "BasicRuntimeChecks",
    _Enumeration(
        [
            "Default",
            "StackFrameRuntimeCheck",  # /RTCs
            "UninitializedLocalUsageCheck",  # /RTCu
            "EnableFastChecks",
        ]
    ),
)  # /RTC1
_Same(
    _compile, "BrowseInformation", _Enumeration(["false", "true", "true"])  # /FR
)  # /Fr
_Same(
    _compile,
    "CallingConvention",
    _Enumeration(["Cdecl", "FastCall", "StdCall", "VectorCall"]),  # /Gd  # /Gr  # /Gz
)  # /Gv
_Same(
    _compile,
    "CompileAs",
    _Enumeration(["Default", "CompileAsC", "CompileAsCpp"]),  # /TC
)  # /TP
_Same(
    _compile,
    "DebugInformationFormat",
    _Enumeration(
        [
            "",  # Disabled
            "OldStyle",  # /Z7
            None,
            "ProgramDatabase",  # /Zi
            "EditAndContinue",
        ]
    ),
)  # /ZI
_Same(
    _compile,
    "EnableEnhancedInstructionSet",
    _Enumeration(
        [
            "NotSet",
            "StreamingSIMDExtensions",  # /arch:SSE
            "StreamingSIMDExtensions2",  # /arch:SSE2
            "AdvancedVectorExtensions",  # /arch:AVX (vs2012+)
            "NoExtensions",  # /arch:IA32 (vs2012+)
            # This one only exists in the new msbuild format.
            "AdvancedVectorExtensions2",  # /arch:AVX2 (vs2013r2+)
        ]
    ),
)
_Same(
    _compile,
    "ErrorReporting",
    _Enumeration(
        [
            "None",  # /errorReport:none
            "Prompt",  # /errorReport:prompt
            "Queue",
        ],  # /errorReport:queue
        new=["Send"],
    ),
)  # /errorReport:send"
_Same(
    _compile,
    "ExceptionHandling",
    _Enumeration(["false", "Sync", "Async"], new=["SyncCThrow"]),  # /EHsc  # /EHa
)  # /EHs
_Same(
    _compile, "FavorSizeOrSpeed", _Enumeration(["Neither", "Speed", "Size"])  # /Ot
)  # /Os
_Same(
    _compile,
    "FloatingPointModel",
    _Enumeration(["Precise", "Strict", "Fast"]),  # /fp:precise  # /fp:strict
)  # /fp:fast
_Same(
    _compile,
    "InlineFunctionExpansion",
    _Enumeration(
        ["Default", "OnlyExplicitInline", "AnySuitable"],  # /Ob1  # /Ob2
        new=["Disabled"],
    ),
)  # /Ob0
_Same(
    _compile,
    "Optimization",
    _Enumeration(["Disabled", "MinSpace", "MaxSpeed", "Full"]),  # /Od  # /O1  # /O2
)  # /Ox
_Same(
    _compile,
    "RuntimeLibrary",
    _Enumeration(
        [
            "MultiThreaded",  # /MT
            "MultiThreadedDebug",  # /MTd
            "MultiThreadedDLL",  # /MD
            "MultiThreadedDebugDLL",
        ]
    ),
)  # /MDd
_Same(
    _compile,
    "StructMemberAlignment",
    _Enumeration(
        [
            "Default",
            "1Byte",  # /Zp1
            "2Bytes",  # /Zp2
            "4Bytes",  # /Zp4
            "8Bytes",  # /Zp8
            "16Bytes",
        ]
    ),
)  # /Zp16
_Same(
    _compile,
    "WarningLevel",
    _Enumeration(
        [
            "TurnOffAllWarnings",  # /W0
            "Level1",  # /W1
            "Level2",  # /W2
            "Level3",  # /W3
            "Level4",
        ],  # /W4
        new=["EnableAllWarnings"],
    ),
)  # /Wall

# Options found in MSVS that have been renamed in MSBuild.
_Renamed(
    _compile, "EnableFunctionLevelLinking", "FunctionLevelLinking", _boolean
)  # /Gy
_Renamed(_compile, "EnableIntrinsicFunctions", "IntrinsicFunctions", _boolean)  # /Oi
_Renamed(_compile, "KeepComments", "PreprocessKeepComments", _boolean)  # /C
_Renamed(_compile, "ObjectFile", "ObjectFileName", _file_name)  # /Fo
_Renamed(_compile, "OpenMP", "OpenMPSupport", _boolean)  # /openmp
_Renamed(
    _compile, "PrecompiledHeaderThrough", "PrecompiledHeaderFile", _file_name
)  # Used with /Yc and /Yu
_Renamed(
    _compile, "PrecompiledHeaderFile", "PrecompiledHeaderOutputFile", _file_name
)  # /Fp
_Renamed(
    _compile,
    "UsePrecompiledHeader",
    "PrecompiledHeader",
    _Enumeration(
        ["NotUsing", "Create", "Use"]  # VS recognized '' for this value too.  # /Yc
    ),
)  # /Yu
_Renamed(_compile, "WarnAsError", "TreatWarningAsError", _boolean)  # /WX

_ConvertedToAdditionalOption(_compile, "DefaultCharIsUnsigned", "/J")

# MSVS options not found in MSBuild.
_MSVSOnly(_compile, "Detect64BitPortabilityProblems", _boolean)
_MSVSOnly(_compile, "UseUnicodeResponseFiles", _boolean)

# MSBuild options not found in MSVS.
_MSBuildOnly(_compile, "BuildingInIDE", _boolean)
_MSBuildOnly(
    _compile, "CompileAsManaged", _Enumeration([], new=["false", "true"])
)  # /clr
_MSBuildOnly(_compile, "CreateHotpatchableImage", _boolean)  # /hotpatch
_MSBuildOnly(_compile, "LanguageStandard", _string)
_MSBuildOnly(_compile, "LanguageStandard_C", _string)
_MSBuildOnly(_compile, "MultiProcessorCompilation", _boolean)  # /MP
_MSBuildOnly(_compile, "PreprocessOutputPath", _string)  # /Fi
_MSBuildOnly(_compile, "ProcessorNumber", _integer)  # the number of processors
_MSBuildOnly(_compile, "TrackerLogDirectory", _folder_name)
_MSBuildOnly(_compile, "TreatSpecificWarningsAsErrors", _string_list)  # /we
_MSBuildOnly(_compile, "UseUnicodeForAssemblerListing", _boolean)  # /FAu

# Defines a setting that needs very customized processing
_CustomGeneratePreprocessedFile(_compile, "GeneratePreprocessedFile")


# Directives for converting MSVS VCLinkerTool to MSBuild Link.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\link.xml" for
# the schema of the MSBuild Link settings.

# Options that have the same name in MSVS and MSBuild
_Same(_link, "AdditionalDependencies", _file_list)
_Same(_link, "AdditionalLibraryDirectories", _folder_list)  # /LIBPATH
#  /MANIFESTDEPENDENCY:
_Same(_link, "AdditionalManifestDependencies", _file_list)
_Same(_link, "AdditionalOptions", _string_list)
_Same(_link, "AddModuleNamesToAssembly", _file_list)  # /ASSEMBLYMODULE
_Same(_link, "AllowIsolation", _boolean)  # /ALLOWISOLATION
_Same(_link, "AssemblyLinkResource", _file_list)  # /ASSEMBLYLINKRESOURCE
_Same(_link, "BaseAddress", _string)  # /BASE
_Same(_link, "CLRUnmanagedCodeCheck", _boolean)  # /CLRUNMANAGEDCODECHECK
_Same(_link, "DelayLoadDLLs", _file_list)  # /DELAYLOAD
_Same(_link, "DelaySign", _boolean)  # /DELAYSIGN
_Same(_link, "EmbedManagedResourceFile", _file_list)  # /ASSEMBLYRESOURCE
_Same(_link, "EnableUAC", _boolean)  # /MANIFESTUAC
_Same(_link, "EntryPointSymbol", _string)  # /ENTRY
_Same(_link, "ForceSymbolReferences", _file_list)  # /INCLUDE
_Same(_link, "FunctionOrder", _file_name)  # /ORDER
_Same(_link, "GenerateDebugInformation", _boolean)  # /DEBUG
_Same(_link, "GenerateMapFile", _boolean)  # /MAP
_Same(_link, "HeapCommitSize", _string)
_Same(_link, "HeapReserveSize", _string)  # /HEAP
_Same(_link, "IgnoreAllDefaultLibraries", _boolean)  # /NODEFAULTLIB
_Same(_link, "IgnoreEmbeddedIDL", _boolean)  # /IGNOREIDL
_Same(_link, "ImportLibrary", _file_name)  # /IMPLIB
_Same(_link, "KeyContainer", _file_name)  # /KEYCONTAINER
_Same(_link, "KeyFile", _file_name)  # /KEYFILE
_Same(_link, "ManifestFile", _file_name)  # /ManifestFile
_Same(_link, "MapExports", _boolean)  # /MAPINFO:EXPORTS
_Same(_link, "MapFileName", _file_name)
_Same(_link, "MergedIDLBaseFileName", _file_name)  # /IDLOUT
_Same(_link, "MergeSections", _string)  # /MERGE
_Same(_link, "MidlCommandFile", _file_name)  # /MIDL
_Same(_link, "ModuleDefinitionFile", _file_name)  # /DEF
_Same(_link, "OutputFile", _file_name)  # /OUT
_Same(_link, "PerUserRedirection", _boolean)
_Same(_link, "Profile", _boolean)  # /PROFILE
_Same(_link, "ProfileGuidedDatabase", _file_name)  # /PGD
_Same(_link, "ProgramDatabaseFile", _file_name)  # /PDB
_Same(_link, "RegisterOutput", _boolean)
_Same(_link, "SetChecksum", _boolean)  # /RELEASE
_Same(_link, "StackCommitSize", _string)
_Same(_link, "StackReserveSize", _string)  # /STACK
_Same(_link, "StripPrivateSymbols", _file_name)  # /PDBSTRIPPED
_Same(_link, "SupportUnloadOfDelayLoadedDLL", _boolean)  # /DELAY:UNLOAD
_Same(_link, "SuppressStartupBanner", _boolean)  # /NOLOGO
_Same(_link, "SwapRunFromCD", _boolean)  # /SWAPRUN:CD
_Same(_link, "TurnOffAssemblyGeneration", _boolean)  # /NOASSEMBLY
_Same(_link, "TypeLibraryFile", _file_name)  # /TLBOUT
_Same(_link, "TypeLibraryResourceID", _integer)  # /TLBID
_Same(_link, "UACUIAccess", _boolean)  # /uiAccess='true'
_Same(_link, "Version", _string)  # /VERSION

_Same(_link, "EnableCOMDATFolding", _newly_boolean)  # /OPT:ICF
_Same(_link, "FixedBaseAddress", _newly_boolean)  # /FIXED
_Same(_link, "LargeAddressAware", _newly_boolean)  # /LARGEADDRESSAWARE
_Same(_link, "OptimizeReferences", _newly_boolean)  # /OPT:REF
_Same(_link, "RandomizedBaseAddress", _newly_boolean)  # /DYNAMICBASE
_Same(_link, "TerminalServerAware", _newly_boolean)  # /TSAWARE

_subsystem_enumeration = _Enumeration(
    [
        "NotSet",
        "Console",  # /SUBSYSTEM:CONSOLE
        "Windows",  # /SUBSYSTEM:WINDOWS
        "Native",  # /SUBSYSTEM:NATIVE
        "EFI Application",  # /SUBSYSTEM:EFI_APPLICATION
        "EFI Boot Service Driver",  # /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER
        "EFI ROM",  # /SUBSYSTEM:EFI_ROM
        "EFI Runtime",  # /SUBSYSTEM:EFI_RUNTIME_DRIVER
        "WindowsCE",
    ],  # /SUBSYSTEM:WINDOWSCE
    new=["POSIX"],
)  # /SUBSYSTEM:POSIX

_target_machine_enumeration = _Enumeration(
    [
        "NotSet",
        "MachineX86",  # /MACHINE:X86
        None,
        "MachineARM",  # /MACHINE:ARM
        "MachineEBC",  # /MACHINE:EBC
        "MachineIA64",  # /MACHINE:IA64
        None,
        "MachineMIPS",  # /MACHINE:MIPS
        "MachineMIPS16",  # /MACHINE:MIPS16
        "MachineMIPSFPU",  # /MACHINE:MIPSFPU
        "MachineMIPSFPU16",  # /MACHINE:MIPSFPU16
        None,
        None,
        None,
        "MachineSH4",  # /MACHINE:SH4
        None,
        "MachineTHUMB",  # /MACHINE:THUMB
        "MachineX64",
    ]
)  # /MACHINE:X64

_Same(
    _link, "AssemblyDebug", _Enumeration(["", "true", "false"])  # /ASSEMBLYDEBUG
)  # /ASSEMBLYDEBUG:DISABLE
_Same(
    _link,
    "CLRImageType",
    _Enumeration(
        [
            "Default",
            "ForceIJWImage",  # /CLRIMAGETYPE:IJW
            "ForcePureILImage",  # /Switch="CLRIMAGETYPE:PURE
            "ForceSafeILImage",
        ]
    ),
)  # /Switch="CLRIMAGETYPE:SAFE
_Same(
    _link,
    "CLRThreadAttribute",
    _Enumeration(
        [
            "DefaultThreadingAttribute",  # /CLRTHREADATTRIBUTE:NONE
            "MTAThreadingAttribute",  # /CLRTHREADATTRIBUTE:MTA
            "STAThreadingAttribute",
        ]
    ),
)  # /CLRTHREADATTRIBUTE:STA
_Same(
    _link,
    "DataExecutionPrevention",
    _Enumeration(["", "false", "true"]),  # /NXCOMPAT:NO
)  # /NXCOMPAT
_Same(
    _link,
    "Driver",
    _Enumeration(["NotSet", "Driver", "UpOnly", "WDM"]),  # /Driver  # /DRIVER:UPONLY
)  # /DRIVER:WDM
_Same(
    _link,
    "LinkTimeCodeGeneration",
    _Enumeration(
        [
            "Default",
            "UseLinkTimeCodeGeneration",  # /LTCG
            "PGInstrument",  # /LTCG:PGInstrument
            "PGOptimization",  # /LTCG:PGOptimize
            "PGUpdate",
        ]
    ),
)  # /LTCG:PGUpdate
_Same(
    _link,
    "ShowProgress",
    _Enumeration(
        ["NotSet", "LinkVerbose", "LinkVerboseLib"],  # /VERBOSE  # /VERBOSE:Lib
        new=[
            "LinkVerboseICF",  # /VERBOSE:ICF
            "LinkVerboseREF",  # /VERBOSE:REF
            "LinkVerboseSAFESEH",  # /VERBOSE:SAFESEH
            "LinkVerboseCLR",
        ],
    ),
)  # /VERBOSE:CLR
_Same(_link, "SubSystem", _subsystem_enumeration)
_Same(_link, "TargetMachine", _target_machine_enumeration)
_Same(
    _link,
    "UACExecutionLevel",
    _Enumeration(
        [
            "AsInvoker",  # /level='asInvoker'
            "HighestAvailable",  # /level='highestAvailable'
            "RequireAdministrator",
        ]
    ),
)  # /level='requireAdministrator'
_Same(_link, "MinimumRequiredVersion", _string)
_Same(_link, "TreatLinkerWarningAsErrors", _boolean)  # /WX


# Options found in MSVS that have been renamed in MSBuild.
_Renamed(
    _link,
    "ErrorReporting",
    "LinkErrorReporting",
    _Enumeration(
        [
            "NoErrorReport",  # /ERRORREPORT:NONE
            "PromptImmediately",  # /ERRORREPORT:PROMPT
            "QueueForNextLogin",
        ],  # /ERRORREPORT:QUEUE
        new=["SendErrorReport"],
    ),
)  # /ERRORREPORT:SEND
_Renamed(
    _link, "IgnoreDefaultLibraryNames", "IgnoreSpecificDefaultLibraries", _file_list
)  # /NODEFAULTLIB
_Renamed(_link, "ResourceOnlyDLL", "NoEntryPoint", _boolean)  # /NOENTRY
_Renamed(_link, "SwapRunFromNet", "SwapRunFromNET", _boolean)  # /SWAPRUN:NET

_Moved(_link, "GenerateManifest", "", _boolean)
_Moved(_link, "IgnoreImportLibrary", "", _boolean)
_Moved(_link, "LinkIncremental", "", _newly_boolean)
_Moved(_link, "LinkLibraryDependencies", "ProjectReference", _boolean)
_Moved(_link, "UseLibraryDependencyInputs", "ProjectReference", _boolean)

# MSVS options not found in MSBuild.
_MSVSOnly(_link, "OptimizeForWindows98", _newly_boolean)
_MSVSOnly(_link, "UseUnicodeResponseFiles", _boolean)

# MSBuild options not found in MSVS.
_MSBuildOnly(_link, "BuildingInIDE", _boolean)
_MSBuildOnly(_link, "ImageHasSafeExceptionHandlers", _boolean)  # /SAFESEH
_MSBuildOnly(_link, "LinkDLL", _boolean)  # /DLL Visible='false'
_MSBuildOnly(_link, "LinkStatus", _boolean)  # /LTCG:STATUS
_MSBuildOnly(_link, "PreventDllBinding", _boolean)  # /ALLOWBIND
_MSBuildOnly(_link, "SupportNobindOfDelayLoadedDLL", _boolean)  # /DELAY:NOBIND
_MSBuildOnly(_link, "TrackerLogDirectory", _folder_name)
_MSBuildOnly(_link, "MSDOSStubFileName", _file_name)  # /STUB Visible='false'
_MSBuildOnly(_link, "SectionAlignment", _integer)  # /ALIGN
_MSBuildOnly(_link, "SpecifySectionAttributes", _string)  # /SECTION
_MSBuildOnly(
    _link,
    "ForceFileOutput",
    _Enumeration(
        [],
        new=[
            "Enabled",  # /FORCE
            # /FORCE:MULTIPLE
            "MultiplyDefinedSymbolOnly",
            "UndefinedSymbolOnly",
        ],
    ),
)  # /FORCE:UNRESOLVED
_MSBuildOnly(
    _link,
    "CreateHotPatchableImage",
    _Enumeration(
        [],
        new=[
            "Enabled",  # /FUNCTIONPADMIN
            "X86Image",  # /FUNCTIONPADMIN:5
            "X64Image",  # /FUNCTIONPADMIN:6
            "ItaniumImage",
        ],
    ),
)  # /FUNCTIONPADMIN:16
_MSBuildOnly(
    _link,
    "CLRSupportLastError",
    _Enumeration(
        [],
        new=[
            "Enabled",  # /CLRSupportLastError
            "Disabled",  # /CLRSupportLastError:NO
            # /CLRSupportLastError:SYSTEMDLL
            "SystemDlls",
        ],
    ),
)


# Directives for converting VCResourceCompilerTool to ResourceCompile.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\rc.xml" for
# the schema of the MSBuild ResourceCompile settings.

_Same(_rc, "AdditionalOptions", _string_list)
_Same(_rc, "AdditionalIncludeDirectories", _folder_list)  # /I
_Same(_rc, "Culture", _Integer(msbuild_base=16))
_Same(_rc, "IgnoreStandardIncludePath", _boolean)  # /X
_Same(_rc, "PreprocessorDefinitions", _string_list)  # /D
_Same(_rc, "ResourceOutputFileName", _string)  # /fo
_Same(_rc, "ShowProgress", _boolean)  # /v
# There is no UI in VisualStudio 2008 to set the following properties.
# However they are found in CL and other tools.  Include them here for
# completeness, as they are very likely to have the same usage pattern.
_Same(_rc, "SuppressStartupBanner", _boolean)  # /nologo
_Same(_rc, "UndefinePreprocessorDefinitions", _string_list)  # /u

# MSBuild options not found in MSVS.
_MSBuildOnly(_rc, "NullTerminateStrings", _boolean)  # /n
_MSBuildOnly(_rc, "TrackerLogDirectory", _folder_name)


# Directives for converting VCMIDLTool to Midl.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\midl.xml" for
# the schema of the MSBuild Midl settings.

_Same(_midl, "AdditionalIncludeDirectories", _folder_list)  # /I
_Same(_midl, "AdditionalOptions", _string_list)
_Same(_midl, "CPreprocessOptions", _string)  # /cpp_opt
_Same(_midl, "ErrorCheckAllocations", _boolean)  # /error allocation
_Same(_midl, "ErrorCheckBounds", _boolean)  # /error bounds_check
_Same(_midl, "ErrorCheckEnumRange", _boolean)  # /error enum
_Same(_midl, "ErrorCheckRefPointers", _boolean)  # /error ref
_Same(_midl, "ErrorCheckStubData", _boolean)  # /error stub_data
_Same(_midl, "GenerateStublessProxies", _boolean)  # /Oicf
_Same(_midl, "GenerateTypeLibrary", _boolean)
_Same(_midl, "HeaderFileName", _file_name)  # /h
_Same(_midl, "IgnoreStandardIncludePath", _boolean)  # /no_def_idir
_Same(_midl, "InterfaceIdentifierFileName", _file_name)  # /iid
_Same(_midl, "MkTypLibCompatible", _boolean)  # /mktyplib203
_Same(_midl, "OutputDirectory", _string)  # /out
_Same(_midl, "PreprocessorDefinitions", _string_list)  # /D
_Same(_midl, "ProxyFileName", _file_name)  # /proxy
_Same(_midl, "RedirectOutputAndErrors", _file_name)  # /o
_Same(_midl, "SuppressStartupBanner", _boolean)  # /nologo
_Same(_midl, "TypeLibraryName", _file_name)  # /tlb
_Same(_midl, "UndefinePreprocessorDefinitions", _string_list)  # /U
_Same(_midl, "WarnAsError", _boolean)  # /WX

_Same(
    _midl,
    "DefaultCharType",
    _Enumeration(["Unsigned", "Signed", "Ascii"]),  # /char unsigned  # /char signed
)  # /char ascii7
_Same(
    _midl,
    "TargetEnvironment",
    _Enumeration(
        [
            "NotSet",
            "Win32",  # /env win32
            "Itanium",  # /env ia64
            "X64",  # /env x64
            "ARM64",  # /env arm64
        ]
    ),
)
_Same(
    _midl,
    "EnableErrorChecks",
    _Enumeration(["EnableCustom", "None", "All"]),  # /error none
)  # /error all
_Same(
    _midl,
    "StructMemberAlignment",
    _Enumeration(["NotSet", "1", "2", "4", "8"]),  # Zp1  # Zp2  # Zp4
)  # Zp8
_Same(
    _midl,
    "WarningLevel",
    _Enumeration(["0", "1", "2", "3", "4"]),  # /W0  # /W1  # /W2  # /W3
)  # /W4

_Renamed(_midl, "DLLDataFileName", "DllDataFileName", _file_name)  # /dlldata
_Renamed(_midl, "ValidateParameters", "ValidateAllParameters", _boolean)  # /robust

# MSBuild options not found in MSVS.
_MSBuildOnly(_midl, "ApplicationConfigurationMode", _boolean)  # /app_config
_MSBuildOnly(_midl, "ClientStubFile", _file_name)  # /cstub
_MSBuildOnly(
    _midl, "GenerateClientFiles", _Enumeration([], new=["Stub", "None"])  # /client stub
)  # /client none
_MSBuildOnly(
    _midl, "GenerateServerFiles", _Enumeration([], new=["Stub", "None"])  # /client stub
)  # /client none
_MSBuildOnly(_midl, "LocaleID", _integer)  # /lcid DECIMAL
_MSBuildOnly(_midl, "ServerStubFile", _file_name)  # /sstub
_MSBuildOnly(_midl, "SuppressCompilerWarnings", _boolean)  # /no_warn
_MSBuildOnly(_midl, "TrackerLogDirectory", _folder_name)
_MSBuildOnly(
    _midl, "TypeLibFormat", _Enumeration([], new=["NewFormat", "OldFormat"])  # /newtlb
)  # /oldtlb


# Directives for converting VCLibrarianTool to Lib.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\lib.xml" for
# the schema of the MSBuild Lib settings.

_Same(_lib, "AdditionalDependencies", _file_list)
_Same(_lib, "AdditionalLibraryDirectories", _folder_list)  # /LIBPATH
_Same(_lib, "AdditionalOptions", _string_list)
_Same(_lib, "ExportNamedFunctions", _string_list)  # /EXPORT
_Same(_lib, "ForceSymbolReferences", _string)  # /INCLUDE
_Same(_lib, "IgnoreAllDefaultLibraries", _boolean)  # /NODEFAULTLIB
_Same(_lib, "IgnoreSpecificDefaultLibraries", _file_list)  # /NODEFAULTLIB
_Same(_lib, "ModuleDefinitionFile", _file_name)  # /DEF
_Same(_lib, "OutputFile", _file_name)  # /OUT
_Same(_lib, "SuppressStartupBanner", _boolean)  # /NOLOGO
_Same(_lib, "UseUnicodeResponseFiles", _boolean)
_Same(_lib, "LinkTimeCodeGeneration", _boolean)  # /LTCG
_Same(_lib, "TargetMachine", _target_machine_enumeration)

# TODO(jeanluc) _link defines the same value that gets moved to
# ProjectReference.  We may want to validate that they are consistent.
_Moved(_lib, "LinkLibraryDependencies", "ProjectReference", _boolean)

_MSBuildOnly(_lib, "DisplayLibrary", _string)  # /LIST Visible='false'
_MSBuildOnly(
    _lib,
    "ErrorReporting",
    _Enumeration(
        [],
        new=[
            "PromptImmediately",  # /ERRORREPORT:PROMPT
            "QueueForNextLogin",  # /ERRORREPORT:QUEUE
            "SendErrorReport",  # /ERRORREPORT:SEND
            "NoErrorReport",
        ],
    ),
)  # /ERRORREPORT:NONE
_MSBuildOnly(_lib, "MinimumRequiredVersion", _string)
_MSBuildOnly(_lib, "Name", _file_name)  # /NAME
_MSBuildOnly(_lib, "RemoveObjects", _file_list)  # /REMOVE
_MSBuildOnly(_lib, "SubSystem", _subsystem_enumeration)
_MSBuildOnly(_lib, "TrackerLogDirectory", _folder_name)
_MSBuildOnly(_lib, "TreatLibWarningAsErrors", _boolean)  # /WX
_MSBuildOnly(_lib, "Verbose", _boolean)


# Directives for converting VCManifestTool to Mt.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\mt.xml" for
# the schema of the MSBuild Lib settings.

# Options that have the same name in MSVS and MSBuild
_Same(_manifest, "AdditionalManifestFiles", _file_list)  # /manifest
_Same(_manifest, "AdditionalOptions", _string_list)
_Same(_manifest, "AssemblyIdentity", _string)  # /identity:
_Same(_manifest, "ComponentFileName", _file_name)  # /dll
_Same(_manifest, "GenerateCatalogFiles", _boolean)  # /makecdfs
_Same(_manifest, "InputResourceManifests", _string)  # /inputresource
_Same(_manifest, "OutputManifestFile", _file_name)  # /out
_Same(_manifest, "RegistrarScriptFile", _file_name)  # /rgs
_Same(_manifest, "ReplacementsFile", _file_name)  # /replacements
_Same(_manifest, "SuppressStartupBanner", _boolean)  # /nologo
_Same(_manifest, "TypeLibraryFile", _file_name)  # /tlb:
_Same(_manifest, "UpdateFileHashes", _boolean)  # /hashupdate
_Same(_manifest, "UpdateFileHashesSearchPath", _file_name)
_Same(_manifest, "VerboseOutput", _boolean)  # /verbose

# Options that have moved location.
_MovedAndRenamed(
    _manifest,
    "ManifestResourceFile",
    "ManifestResourceCompile",
    "ResourceOutputFileName",
    _file_name,
)
_Moved(_manifest, "EmbedManifest", "", _boolean)

# MSVS options not found in MSBuild.
_MSVSOnly(_manifest, "DependencyInformationFile", _file_name)
_MSVSOnly(_manifest, "UseFAT32Workaround", _boolean)
_MSVSOnly(_manifest, "UseUnicodeResponseFiles", _boolean)

# MSBuild options not found in MSVS.
_MSBuildOnly(_manifest, "EnableDPIAwareness", _boolean)
_MSBuildOnly(_manifest, "GenerateCategoryTags", _boolean)  # /category
_MSBuildOnly(
    _manifest, "ManifestFromManagedAssembly", _file_name
)  # /managedassemblyname
_MSBuildOnly(_manifest, "OutputResourceManifests", _string)  # /outputresource
_MSBuildOnly(_manifest, "SuppressDependencyElement", _boolean)  # /nodependency
_MSBuildOnly(_manifest, "TrackerLogDirectory", _folder_name)


# Directives for MASM.
# See "$(VCTargetsPath)\BuildCustomizations\masm.xml" for the schema of the
# MSBuild MASM settings.

# Options that have the same name in MSVS and MSBuild.
_Same(_masm, "UseSafeExceptionHandlers", _boolean)  # /safeseh
#!/usr/bin/env python3

# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Unit tests for the MSVSSettings.py file."""

import unittest
import gyp.MSVSSettings as MSVSSettings

from io import StringIO


class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.stderr = StringIO()

    def _ExpectedWarnings(self, expected):
        """Compares recorded lines to expected warnings."""
        self.stderr.seek(0)
        actual = self.stderr.read().split("\n")
        actual = [line for line in actual if line]
        self.assertEqual(sorted(expected), sorted(actual))

    def testValidateMSVSSettings_tool_names(self):
        """Tests that only MSVS tool names are allowed."""
        MSVSSettings.ValidateMSVSSettings(
            {
                "VCCLCompilerTool": {},
                "VCLinkerTool": {},
                "VCMIDLTool": {},
                "foo": {},
                "VCResourceCompilerTool": {},
                "VCLibrarianTool": {},
                "VCManifestTool": {},
                "ClCompile": {},
            },
            self.stderr,
        )
        self._ExpectedWarnings(
            ["Warning: unrecognized tool foo", "Warning: unrecognized tool ClCompile"]
        )

    def testValidateMSVSSettings_settings(self):
        """Tests that for invalid MSVS settings."""
        MSVSSettings.ValidateMSVSSettings(
            {
                "VCCLCompilerTool": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": ["string1", "string2"],
                    "AdditionalUsingDirectories": "folder1;folder2",
                    "AssemblerListingLocation": "a_file_name",
                    "AssemblerOutput": "0",
                    "BasicRuntimeChecks": "5",
                    "BrowseInformation": "fdkslj",
                    "BrowseInformationFile": "a_file_name",
                    "BufferSecurityCheck": "true",
                    "CallingConvention": "-1",
                    "CompileAs": "1",
                    "DebugInformationFormat": "2",
                    "DefaultCharIsUnsigned": "true",
                    "Detect64BitPortabilityProblems": "true",
                    "DisableLanguageExtensions": "true",
                    "DisableSpecificWarnings": "string1;string2",
                    "EnableEnhancedInstructionSet": "1",
                    "EnableFiberSafeOptimizations": "true",
                    "EnableFunctionLevelLinking": "true",
                    "EnableIntrinsicFunctions": "true",
                    "EnablePREfast": "true",
                    "Enableprefast": "bogus",
                    "ErrorReporting": "1",
                    "ExceptionHandling": "1",
                    "ExpandAttributedSource": "true",
                    "FavorSizeOrSpeed": "1",
                    "FloatingPointExceptions": "true",
                    "FloatingPointModel": "1",
                    "ForceConformanceInForLoopScope": "true",
                    "ForcedIncludeFiles": "file1;file2",
                    "ForcedUsingFiles": "file1;file2",
                    "GeneratePreprocessedFile": "1",
                    "GenerateXMLDocumentationFiles": "true",
                    "IgnoreStandardIncludePath": "true",
                    "InlineFunctionExpansion": "1",
                    "KeepComments": "true",
                    "MinimalRebuild": "true",
                    "ObjectFile": "a_file_name",
                    "OmitDefaultLibName": "true",
                    "OmitFramePointers": "true",
                    "OpenMP": "true",
                    "Optimization": "1",
                    "PrecompiledHeaderFile": "a_file_name",
                    "PrecompiledHeaderThrough": "a_file_name",
                    "PreprocessorDefinitions": "string1;string2",
                    "ProgramDataBaseFileName": "a_file_name",
                    "RuntimeLibrary": "1",
                    "RuntimeTypeInfo": "true",
                    "ShowIncludes": "true",
                    "SmallerTypeCheck": "true",
                    "StringPooling": "true",
                    "StructMemberAlignment": "1",
                    "SuppressStartupBanner": "true",
                    "TreatWChar_tAsBuiltInType": "true",
                    "UndefineAllPreprocessorDefinitions": "true",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                    "UseFullPaths": "true",
                    "UsePrecompiledHeader": "1",
                    "UseUnicodeResponseFiles": "true",
                    "WarnAsError": "true",
                    "WarningLevel": "1",
                    "WholeProgramOptimization": "true",
                    "XMLDocumentationFileName": "a_file_name",
                    "ZZXYZ": "bogus",
                },
                "VCLinkerTool": {
                    "AdditionalDependencies": "file1;file2",
                    "AdditionalDependencies_excluded": "file3",
                    "AdditionalLibraryDirectories": "folder1;folder2",
                    "AdditionalManifestDependencies": "file1;file2",
                    "AdditionalOptions": "a string1",
                    "AddModuleNamesToAssembly": "file1;file2",
                    "AllowIsolation": "true",
                    "AssemblyDebug": "2",
                    "AssemblyLinkResource": "file1;file2",
                    "BaseAddress": "a string1",
                    "CLRImageType": "2",
                    "CLRThreadAttribute": "2",
                    "CLRUnmanagedCodeCheck": "true",
                    "DataExecutionPrevention": "2",
                    "DelayLoadDLLs": "file1;file2",
                    "DelaySign": "true",
                    "Driver": "2",
                    "EmbedManagedResourceFile": "file1;file2",
                    "EnableCOMDATFolding": "2",
                    "EnableUAC": "true",
                    "EntryPointSymbol": "a string1",
                    "ErrorReporting": "2",
                    "FixedBaseAddress": "2",
                    "ForceSymbolReferences": "file1;file2",
                    "FunctionOrder": "a_file_name",
                    "GenerateDebugInformation": "true",
                    "GenerateManifest": "true",
                    "GenerateMapFile": "true",
                    "HeapCommitSize": "a string1",
                    "HeapReserveSize": "a string1",
                    "IgnoreAllDefaultLibraries": "true",
                    "IgnoreDefaultLibraryNames": "file1;file2",
                    "IgnoreEmbeddedIDL": "true",
                    "IgnoreImportLibrary": "true",
                    "ImportLibrary": "a_file_name",
                    "KeyContainer": "a_file_name",
                    "KeyFile": "a_file_name",
                    "LargeAddressAware": "2",
                    "LinkIncremental": "2",
                    "LinkLibraryDependencies": "true",
                    "LinkTimeCodeGeneration": "2",
                    "ManifestFile": "a_file_name",
                    "MapExports": "true",
                    "MapFileName": "a_file_name",
                    "MergedIDLBaseFileName": "a_file_name",
                    "MergeSections": "a string1",
                    "MidlCommandFile": "a_file_name",
                    "ModuleDefinitionFile": "a_file_name",
                    "OptimizeForWindows98": "1",
                    "OptimizeReferences": "2",
                    "OutputFile": "a_file_name",
                    "PerUserRedirection": "true",
                    "Profile": "true",
                    "ProfileGuidedDatabase": "a_file_name",
                    "ProgramDatabaseFile": "a_file_name",
                    "RandomizedBaseAddress": "2",
                    "RegisterOutput": "true",
                    "ResourceOnlyDLL": "true",
                    "SetChecksum": "true",
                    "ShowProgress": "2",
                    "StackCommitSize": "a string1",
                    "StackReserveSize": "a string1",
                    "StripPrivateSymbols": "a_file_name",
                    "SubSystem": "2",
                    "SupportUnloadOfDelayLoadedDLL": "true",
                    "SuppressStartupBanner": "true",
                    "SwapRunFromCD": "true",
                    "SwapRunFromNet": "true",
                    "TargetMachine": "2",
                    "TerminalServerAware": "2",
                    "TurnOffAssemblyGeneration": "true",
                    "TypeLibraryFile": "a_file_name",
                    "TypeLibraryResourceID": "33",
                    "UACExecutionLevel": "2",
                    "UACUIAccess": "true",
                    "UseLibraryDependencyInputs": "true",
                    "UseUnicodeResponseFiles": "true",
                    "Version": "a string1",
                },
                "VCMIDLTool": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "CPreprocessOptions": "a string1",
                    "DefaultCharType": "1",
                    "DLLDataFileName": "a_file_name",
                    "EnableErrorChecks": "1",
                    "ErrorCheckAllocations": "true",
                    "ErrorCheckBounds": "true",
                    "ErrorCheckEnumRange": "true",
                    "ErrorCheckRefPointers": "true",
                    "ErrorCheckStubData": "true",
                    "GenerateStublessProxies": "true",
                    "GenerateTypeLibrary": "true",
                    "HeaderFileName": "a_file_name",
                    "IgnoreStandardIncludePath": "true",
                    "InterfaceIdentifierFileName": "a_file_name",
                    "MkTypLibCompatible": "true",
                    "notgood": "bogus",
                    "OutputDirectory": "a string1",
                    "PreprocessorDefinitions": "string1;string2",
                    "ProxyFileName": "a_file_name",
                    "RedirectOutputAndErrors": "a_file_name",
                    "StructMemberAlignment": "1",
                    "SuppressStartupBanner": "true",
                    "TargetEnvironment": "1",
                    "TypeLibraryName": "a_file_name",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                    "ValidateParameters": "true",
                    "WarnAsError": "true",
                    "WarningLevel": "1",
                },
                "VCResourceCompilerTool": {
                    "AdditionalOptions": "a string1",
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "Culture": "1003",
                    "IgnoreStandardIncludePath": "true",
                    "notgood2": "bogus",
                    "PreprocessorDefinitions": "string1;string2",
                    "ResourceOutputFileName": "a string1",
                    "ShowProgress": "true",
                    "SuppressStartupBanner": "true",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                },
                "VCLibrarianTool": {
                    "AdditionalDependencies": "file1;file2",
                    "AdditionalLibraryDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "ExportNamedFunctions": "string1;string2",
                    "ForceSymbolReferences": "a string1",
                    "IgnoreAllDefaultLibraries": "true",
                    "IgnoreSpecificDefaultLibraries": "file1;file2",
                    "LinkLibraryDependencies": "true",
                    "ModuleDefinitionFile": "a_file_name",
                    "OutputFile": "a_file_name",
                    "SuppressStartupBanner": "true",
                    "UseUnicodeResponseFiles": "true",
                },
                "VCManifestTool": {
                    "AdditionalManifestFiles": "file1;file2",
                    "AdditionalOptions": "a string1",
                    "AssemblyIdentity": "a string1",
                    "ComponentFileName": "a_file_name",
                    "DependencyInformationFile": "a_file_name",
                    "GenerateCatalogFiles": "true",
                    "InputResourceManifests": "a string1",
                    "ManifestResourceFile": "a_file_name",
                    "OutputManifestFile": "a_file_name",
                    "RegistrarScriptFile": "a_file_name",
                    "ReplacementsFile": "a_file_name",
                    "SuppressStartupBanner": "true",
                    "TypeLibraryFile": "a_file_name",
                    "UpdateFileHashes": "truel",
                    "UpdateFileHashesSearchPath": "a_file_name",
                    "UseFAT32Workaround": "true",
                    "UseUnicodeResponseFiles": "true",
                    "VerboseOutput": "true",
                },
            },
            self.stderr,
        )
        self._ExpectedWarnings(
            [
                "Warning: for VCCLCompilerTool/BasicRuntimeChecks, "
                "index value (5) not in expected range [0, 4)",
                "Warning: for VCCLCompilerTool/BrowseInformation, "
                "invalid literal for int() with base 10: 'fdkslj'",
                "Warning: for VCCLCompilerTool/CallingConvention, "
                "index value (-1) not in expected range [0, 4)",
                "Warning: for VCCLCompilerTool/DebugInformationFormat, "
                "converted value for 2 not specified.",
                "Warning: unrecognized setting VCCLCompilerTool/Enableprefast",
                "Warning: unrecognized setting VCCLCompilerTool/ZZXYZ",
                "Warning: for VCLinkerTool/TargetMachine, "
                "converted value for 2 not specified.",
                "Warning: unrecognized setting VCMIDLTool/notgood",
                "Warning: unrecognized setting VCResourceCompilerTool/notgood2",
                "Warning: for VCManifestTool/UpdateFileHashes, "
                "expected bool; got 'truel'"
                "",
            ]
        )

    def testValidateMSBuildSettings_settings(self):
        """Tests that for invalid MSBuild settings."""
        MSVSSettings.ValidateMSBuildSettings(
            {
                "ClCompile": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": ["string1", "string2"],
                    "AdditionalUsingDirectories": "folder1;folder2",
                    "AssemblerListingLocation": "a_file_name",
                    "AssemblerOutput": "NoListing",
                    "BasicRuntimeChecks": "StackFrameRuntimeCheck",
                    "BrowseInformation": "false",
                    "BrowseInformationFile": "a_file_name",
                    "BufferSecurityCheck": "true",
                    "BuildingInIDE": "true",
                    "CallingConvention": "Cdecl",
                    "CompileAs": "CompileAsC",
                    "CompileAsManaged": "true",
                    "CreateHotpatchableImage": "true",
                    "DebugInformationFormat": "ProgramDatabase",
                    "DisableLanguageExtensions": "true",
                    "DisableSpecificWarnings": "string1;string2",
                    "EnableEnhancedInstructionSet": "StreamingSIMDExtensions",
                    "EnableFiberSafeOptimizations": "true",
                    "EnablePREfast": "true",
                    "Enableprefast": "bogus",
                    "ErrorReporting": "Prompt",
                    "ExceptionHandling": "SyncCThrow",
                    "ExpandAttributedSource": "true",
                    "FavorSizeOrSpeed": "Neither",
                    "FloatingPointExceptions": "true",
                    "FloatingPointModel": "Precise",
                    "ForceConformanceInForLoopScope": "true",
                    "ForcedIncludeFiles": "file1;file2",
                    "ForcedUsingFiles": "file1;file2",
                    "FunctionLevelLinking": "false",
                    "GenerateXMLDocumentationFiles": "true",
                    "IgnoreStandardIncludePath": "true",
                    "InlineFunctionExpansion": "OnlyExplicitInline",
                    "IntrinsicFunctions": "false",
                    "MinimalRebuild": "true",
                    "MultiProcessorCompilation": "true",
                    "ObjectFileName": "a_file_name",
                    "OmitDefaultLibName": "true",
                    "OmitFramePointers": "true",
                    "OpenMPSupport": "true",
                    "Optimization": "Disabled",
                    "PrecompiledHeader": "NotUsing",
                    "PrecompiledHeaderFile": "a_file_name",
                    "PrecompiledHeaderOutputFile": "a_file_name",
                    "PreprocessKeepComments": "true",
                    "PreprocessorDefinitions": "string1;string2",
                    "PreprocessOutputPath": "a string1",
                    "PreprocessSuppressLineNumbers": "false",
                    "PreprocessToFile": "false",
                    "ProcessorNumber": "33",
                    "ProgramDataBaseFileName": "a_file_name",
                    "RuntimeLibrary": "MultiThreaded",
                    "RuntimeTypeInfo": "true",
                    "ShowIncludes": "true",
                    "SmallerTypeCheck": "true",
                    "StringPooling": "true",
                    "StructMemberAlignment": "1Byte",
                    "SuppressStartupBanner": "true",
                    "TrackerLogDirectory": "a_folder",
                    "TreatSpecificWarningsAsErrors": "string1;string2",
                    "TreatWarningAsError": "true",
                    "TreatWChar_tAsBuiltInType": "true",
                    "UndefineAllPreprocessorDefinitions": "true",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                    "UseFullPaths": "true",
                    "UseUnicodeForAssemblerListing": "true",
                    "WarningLevel": "TurnOffAllWarnings",
                    "WholeProgramOptimization": "true",
                    "XMLDocumentationFileName": "a_file_name",
                    "ZZXYZ": "bogus",
                },
                "Link": {
                    "AdditionalDependencies": "file1;file2",
                    "AdditionalLibraryDirectories": "folder1;folder2",
                    "AdditionalManifestDependencies": "file1;file2",
                    "AdditionalOptions": "a string1",
                    "AddModuleNamesToAssembly": "file1;file2",
                    "AllowIsolation": "true",
                    "AssemblyDebug": "",
                    "AssemblyLinkResource": "file1;file2",
                    "BaseAddress": "a string1",
                    "BuildingInIDE": "true",
                    "CLRImageType": "ForceIJWImage",
                    "CLRSupportLastError": "Enabled",
                    "CLRThreadAttribute": "MTAThreadingAttribute",
                    "CLRUnmanagedCodeCheck": "true",
                    "CreateHotPatchableImage": "X86Image",
                    "DataExecutionPrevention": "false",
                    "DelayLoadDLLs": "file1;file2",
                    "DelaySign": "true",
                    "Driver": "NotSet",
                    "EmbedManagedResourceFile": "file1;file2",
                    "EnableCOMDATFolding": "false",
                    "EnableUAC": "true",
                    "EntryPointSymbol": "a string1",
                    "FixedBaseAddress": "false",
                    "ForceFileOutput": "Enabled",
                    "ForceSymbolReferences": "file1;file2",
                    "FunctionOrder": "a_file_name",
                    "GenerateDebugInformation": "true",
                    "GenerateMapFile": "true",
                    "HeapCommitSize": "a string1",
                    "HeapReserveSize": "a string1",
                    "IgnoreAllDefaultLibraries": "true",
                    "IgnoreEmbeddedIDL": "true",
                    "IgnoreSpecificDefaultLibraries": "a_file_list",
                    "ImageHasSafeExceptionHandlers": "true",
                    "ImportLibrary": "a_file_name",
                    "KeyContainer": "a_file_name",
                    "KeyFile": "a_file_name",
                    "LargeAddressAware": "false",
                    "LinkDLL": "true",
                    "LinkErrorReporting": "SendErrorReport",
                    "LinkStatus": "true",
                    "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration",
                    "ManifestFile": "a_file_name",
                    "MapExports": "true",
                    "MapFileName": "a_file_name",
                    "MergedIDLBaseFileName": "a_file_name",
                    "MergeSections": "a string1",
                    "MidlCommandFile": "a_file_name",
                    "MinimumRequiredVersion": "a string1",
                    "ModuleDefinitionFile": "a_file_name",
                    "MSDOSStubFileName": "a_file_name",
                    "NoEntryPoint": "true",
                    "OptimizeReferences": "false",
                    "OutputFile": "a_file_name",
                    "PerUserRedirection": "true",
                    "PreventDllBinding": "true",
                    "Profile": "true",
                    "ProfileGuidedDatabase": "a_file_name",
                    "ProgramDatabaseFile": "a_file_name",
                    "RandomizedBaseAddress": "false",
                    "RegisterOutput": "true",
                    "SectionAlignment": "33",
                    "SetChecksum": "true",
                    "ShowProgress": "LinkVerboseREF",
                    "SpecifySectionAttributes": "a string1",
                    "StackCommitSize": "a string1",
                    "StackReserveSize": "a string1",
                    "StripPrivateSymbols": "a_file_name",
                    "SubSystem": "Console",
                    "SupportNobindOfDelayLoadedDLL": "true",
                    "SupportUnloadOfDelayLoadedDLL": "true",
                    "SuppressStartupBanner": "true",
                    "SwapRunFromCD": "true",
                    "SwapRunFromNET": "true",
                    "TargetMachine": "MachineX86",
                    "TerminalServerAware": "false",
                    "TrackerLogDirectory": "a_folder",
                    "TreatLinkerWarningAsErrors": "true",
                    "TurnOffAssemblyGeneration": "true",
                    "TypeLibraryFile": "a_file_name",
                    "TypeLibraryResourceID": "33",
                    "UACExecutionLevel": "AsInvoker",
                    "UACUIAccess": "true",
                    "Version": "a string1",
                },
                "ResourceCompile": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "Culture": "0x236",
                    "IgnoreStandardIncludePath": "true",
                    "NullTerminateStrings": "true",
                    "PreprocessorDefinitions": "string1;string2",
                    "ResourceOutputFileName": "a string1",
                    "ShowProgress": "true",
                    "SuppressStartupBanner": "true",
                    "TrackerLogDirectory": "a_folder",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                },
                "Midl": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "ApplicationConfigurationMode": "true",
                    "ClientStubFile": "a_file_name",
                    "CPreprocessOptions": "a string1",
                    "DefaultCharType": "Signed",
                    "DllDataFileName": "a_file_name",
                    "EnableErrorChecks": "EnableCustom",
                    "ErrorCheckAllocations": "true",
                    "ErrorCheckBounds": "true",
                    "ErrorCheckEnumRange": "true",
                    "ErrorCheckRefPointers": "true",
                    "ErrorCheckStubData": "true",
                    "GenerateClientFiles": "Stub",
                    "GenerateServerFiles": "None",
                    "GenerateStublessProxies": "true",
                    "GenerateTypeLibrary": "true",
                    "HeaderFileName": "a_file_name",
                    "IgnoreStandardIncludePath": "true",
                    "InterfaceIdentifierFileName": "a_file_name",
                    "LocaleID": "33",
                    "MkTypLibCompatible": "true",
                    "OutputDirectory": "a string1",
                    "PreprocessorDefinitions": "string1;string2",
                    "ProxyFileName": "a_file_name",
                    "RedirectOutputAndErrors": "a_file_name",
                    "ServerStubFile": "a_file_name",
                    "StructMemberAlignment": "NotSet",
                    "SuppressCompilerWarnings": "true",
                    "SuppressStartupBanner": "true",
                    "TargetEnvironment": "Itanium",
                    "TrackerLogDirectory": "a_folder",
                    "TypeLibFormat": "NewFormat",
                    "TypeLibraryName": "a_file_name",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                    "ValidateAllParameters": "true",
                    "WarnAsError": "true",
                    "WarningLevel": "1",
                },
                "Lib": {
                    "AdditionalDependencies": "file1;file2",
                    "AdditionalLibraryDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "DisplayLibrary": "a string1",
                    "ErrorReporting": "PromptImmediately",
                    "ExportNamedFunctions": "string1;string2",
                    "ForceSymbolReferences": "a string1",
                    "IgnoreAllDefaultLibraries": "true",
                    "IgnoreSpecificDefaultLibraries": "file1;file2",
                    "LinkTimeCodeGeneration": "true",
                    "MinimumRequiredVersion": "a string1",
                    "ModuleDefinitionFile": "a_file_name",
                    "Name": "a_file_name",
                    "OutputFile": "a_file_name",
                    "RemoveObjects": "file1;file2",
                    "SubSystem": "Console",
                    "SuppressStartupBanner": "true",
                    "TargetMachine": "MachineX86i",
                    "TrackerLogDirectory": "a_folder",
                    "TreatLibWarningAsErrors": "true",
                    "UseUnicodeResponseFiles": "true",
                    "Verbose": "true",
                },
                "Manifest": {
                    "AdditionalManifestFiles": "file1;file2",
                    "AdditionalOptions": "a string1",
                    "AssemblyIdentity": "a string1",
                    "ComponentFileName": "a_file_name",
                    "EnableDPIAwareness": "fal",
                    "GenerateCatalogFiles": "truel",
                    "GenerateCategoryTags": "true",
                    "InputResourceManifests": "a string1",
                    "ManifestFromManagedAssembly": "a_file_name",
                    "notgood3": "bogus",
                    "OutputManifestFile": "a_file_name",
                    "OutputResourceManifests": "a string1",
                    "RegistrarScriptFile": "a_file_name",
                    "ReplacementsFile": "a_file_name",
                    "SuppressDependencyElement": "true",
                    "SuppressStartupBanner": "true",
                    "TrackerLogDirectory": "a_folder",
                    "TypeLibraryFile": "a_file_name",
                    "UpdateFileHashes": "true",
                    "UpdateFileHashesSearchPath": "a_file_name",
                    "VerboseOutput": "true",
                },
                "ProjectReference": {
                    "LinkLibraryDependencies": "true",
                    "UseLibraryDependencyInputs": "true",
                },
                "ManifestResourceCompile": {"ResourceOutputFileName": "a_file_name"},
                "": {
                    "EmbedManifest": "true",
                    "GenerateManifest": "true",
                    "IgnoreImportLibrary": "true",
                    "LinkIncremental": "false",
                },
            },
            self.stderr,
        )
        self._ExpectedWarnings(
            [
                "Warning: unrecognized setting ClCompile/Enableprefast",
                "Warning: unrecognized setting ClCompile/ZZXYZ",
                "Warning: unrecognized setting Manifest/notgood3",
                "Warning: for Manifest/GenerateCatalogFiles, "
                "expected bool; got 'truel'",
                "Warning: for Lib/TargetMachine, unrecognized enumerated value "
                "MachineX86i",
                "Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'",
            ]
        )

    def testConvertToMSBuildSettings_empty(self):
        """Tests an empty conversion."""
        msvs_settings = {}
        expected_msbuild_settings = {}
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings([])

    def testConvertToMSBuildSettings_minimal(self):
        """Tests a minimal conversion."""
        msvs_settings = {
            "VCCLCompilerTool": {
                "AdditionalIncludeDirectories": "dir1",
                "AdditionalOptions": "/foo",
                "BasicRuntimeChecks": "0",
            },
            "VCLinkerTool": {
                "LinkTimeCodeGeneration": "1",
                "ErrorReporting": "1",
                "DataExecutionPrevention": "2",
            },
        }
        expected_msbuild_settings = {
            "ClCompile": {
                "AdditionalIncludeDirectories": "dir1",
                "AdditionalOptions": "/foo",
                "BasicRuntimeChecks": "Default",
            },
            "Link": {
                "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration",
                "LinkErrorReporting": "PromptImmediately",
                "DataExecutionPrevention": "true",
            },
        }
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings([])

    def testConvertToMSBuildSettings_warnings(self):
        """Tests conversion that generates warnings."""
        msvs_settings = {
            "VCCLCompilerTool": {
                "AdditionalIncludeDirectories": "1",
                "AdditionalOptions": "2",
                # These are incorrect values:
                "BasicRuntimeChecks": "12",
                "BrowseInformation": "21",
                "UsePrecompiledHeader": "13",
                "GeneratePreprocessedFile": "14",
            },
            "VCLinkerTool": {
                # These are incorrect values:
                "Driver": "10",
                "LinkTimeCodeGeneration": "31",
                "ErrorReporting": "21",
                "FixedBaseAddress": "6",
            },
            "VCResourceCompilerTool": {
                # Custom
                "Culture": "1003"
            },
        }
        expected_msbuild_settings = {
            "ClCompile": {
                "AdditionalIncludeDirectories": "1",
                "AdditionalOptions": "2",
            },
            "Link": {},
            "ResourceCompile": {
                # Custom
                "Culture": "0x03eb"
            },
        }
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings(
            [
                "Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to "
                "MSBuild, index value (12) not in expected range [0, 4)",
                "Warning: while converting VCCLCompilerTool/BrowseInformation to "
                "MSBuild, index value (21) not in expected range [0, 3)",
                "Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to "
                "MSBuild, index value (13) not in expected range [0, 3)",
                "Warning: while converting "
                "VCCLCompilerTool/GeneratePreprocessedFile to "
                "MSBuild, value must be one of [0, 1, 2]; got 14",
                "Warning: while converting VCLinkerTool/Driver to "
                "MSBuild, index value (10) not in expected range [0, 4)",
                "Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to "
                "MSBuild, index value (31) not in expected range [0, 5)",
                "Warning: while converting VCLinkerTool/ErrorReporting to "
                "MSBuild, index value (21) not in expected range [0, 3)",
                "Warning: while converting VCLinkerTool/FixedBaseAddress to "
                "MSBuild, index value (6) not in expected range [0, 3)",
            ]
        )

    def testConvertToMSBuildSettings_full_synthetic(self):
        """Tests conversion of all the MSBuild settings."""
        msvs_settings = {
            "VCCLCompilerTool": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "AdditionalUsingDirectories": "folder1;folder2;folder3",
                "AssemblerListingLocation": "a_file_name",
                "AssemblerOutput": "0",
                "BasicRuntimeChecks": "1",
                "BrowseInformation": "2",
                "BrowseInformationFile": "a_file_name",
                "BufferSecurityCheck": "true",
                "CallingConvention": "0",
                "CompileAs": "1",
                "DebugInformationFormat": "4",
                "DefaultCharIsUnsigned": "true",
                "Detect64BitPortabilityProblems": "true",
                "DisableLanguageExtensions": "true",
                "DisableSpecificWarnings": "d1;d2;d3",
                "EnableEnhancedInstructionSet": "0",
                "EnableFiberSafeOptimizations": "true",
                "EnableFunctionLevelLinking": "true",
                "EnableIntrinsicFunctions": "true",
                "EnablePREfast": "true",
                "ErrorReporting": "1",
                "ExceptionHandling": "2",
                "ExpandAttributedSource": "true",
                "FavorSizeOrSpeed": "0",
                "FloatingPointExceptions": "true",
                "FloatingPointModel": "1",
                "ForceConformanceInForLoopScope": "true",
                "ForcedIncludeFiles": "file1;file2;file3",
                "ForcedUsingFiles": "file1;file2;file3",
                "GeneratePreprocessedFile": "1",
                "GenerateXMLDocumentationFiles": "true",
                "IgnoreStandardIncludePath": "true",
                "InlineFunctionExpansion": "2",
                "KeepComments": "true",
                "MinimalRebuild": "true",
                "ObjectFile": "a_file_name",
                "OmitDefaultLibName": "true",
                "OmitFramePointers": "true",
                "OpenMP": "true",
                "Optimization": "3",
                "PrecompiledHeaderFile": "a_file_name",
                "PrecompiledHeaderThrough": "a_file_name",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ProgramDataBaseFileName": "a_file_name",
                "RuntimeLibrary": "0",
                "RuntimeTypeInfo": "true",
                "ShowIncludes": "true",
                "SmallerTypeCheck": "true",
                "StringPooling": "true",
                "StructMemberAlignment": "1",
                "SuppressStartupBanner": "true",
                "TreatWChar_tAsBuiltInType": "true",
                "UndefineAllPreprocessorDefinitions": "true",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
                "UseFullPaths": "true",
                "UsePrecompiledHeader": "1",
                "UseUnicodeResponseFiles": "true",
                "WarnAsError": "true",
                "WarningLevel": "2",
                "WholeProgramOptimization": "true",
                "XMLDocumentationFileName": "a_file_name",
            },
            "VCLinkerTool": {
                "AdditionalDependencies": "file1;file2;file3",
                "AdditionalLibraryDirectories": "folder1;folder2;folder3",
                "AdditionalLibraryDirectories_excluded": "folder1;folder2;folder3",
                "AdditionalManifestDependencies": "file1;file2;file3",
                "AdditionalOptions": "a_string",
                "AddModuleNamesToAssembly": "file1;file2;file3",
                "AllowIsolation": "true",
                "AssemblyDebug": "0",
                "AssemblyLinkResource": "file1;file2;file3",
                "BaseAddress": "a_string",
                "CLRImageType": "1",
                "CLRThreadAttribute": "2",
                "CLRUnmanagedCodeCheck": "true",
                "DataExecutionPrevention": "0",
                "DelayLoadDLLs": "file1;file2;file3",
                "DelaySign": "true",
                "Driver": "1",
                "EmbedManagedResourceFile": "file1;file2;file3",
                "EnableCOMDATFolding": "0",
                "EnableUAC": "true",
                "EntryPointSymbol": "a_string",
                "ErrorReporting": "0",
                "FixedBaseAddress": "1",
                "ForceSymbolReferences": "file1;file2;file3",
                "FunctionOrder": "a_file_name",
                "GenerateDebugInformation": "true",
                "GenerateManifest": "true",
                "GenerateMapFile": "true",
                "HeapCommitSize": "a_string",
                "HeapReserveSize": "a_string",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreDefaultLibraryNames": "file1;file2;file3",
                "IgnoreEmbeddedIDL": "true",
                "IgnoreImportLibrary": "true",
                "ImportLibrary": "a_file_name",
                "KeyContainer": "a_file_name",
                "KeyFile": "a_file_name",
                "LargeAddressAware": "2",
                "LinkIncremental": "1",
                "LinkLibraryDependencies": "true",
                "LinkTimeCodeGeneration": "2",
                "ManifestFile": "a_file_name",
                "MapExports": "true",
                "MapFileName": "a_file_name",
                "MergedIDLBaseFileName": "a_file_name",
                "MergeSections": "a_string",
                "MidlCommandFile": "a_file_name",
                "ModuleDefinitionFile": "a_file_name",
                "OptimizeForWindows98": "1",
                "OptimizeReferences": "0",
                "OutputFile": "a_file_name",
                "PerUserRedirection": "true",
                "Profile": "true",
                "ProfileGuidedDatabase": "a_file_name",
                "ProgramDatabaseFile": "a_file_name",
                "RandomizedBaseAddress": "1",
                "RegisterOutput": "true",
                "ResourceOnlyDLL": "true",
                "SetChecksum": "true",
                "ShowProgress": "0",
                "StackCommitSize": "a_string",
                "StackReserveSize": "a_string",
                "StripPrivateSymbols": "a_file_name",
                "SubSystem": "2",
                "SupportUnloadOfDelayLoadedDLL": "true",
                "SuppressStartupBanner": "true",
                "SwapRunFromCD": "true",
                "SwapRunFromNet": "true",
                "TargetMachine": "3",
                "TerminalServerAware": "2",
                "TurnOffAssemblyGeneration": "true",
                "TypeLibraryFile": "a_file_name",
                "TypeLibraryResourceID": "33",
                "UACExecutionLevel": "1",
                "UACUIAccess": "true",
                "UseLibraryDependencyInputs": "false",
                "UseUnicodeResponseFiles": "true",
                "Version": "a_string",
            },
            "VCResourceCompilerTool": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "Culture": "1003",
                "IgnoreStandardIncludePath": "true",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ResourceOutputFileName": "a_string",
                "ShowProgress": "true",
                "SuppressStartupBanner": "true",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
            },
            "VCMIDLTool": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "CPreprocessOptions": "a_string",
                "DefaultCharType": "0",
                "DLLDataFileName": "a_file_name",
                "EnableErrorChecks": "2",
                "ErrorCheckAllocations": "true",
                "ErrorCheckBounds": "true",
                "ErrorCheckEnumRange": "true",
                "ErrorCheckRefPointers": "true",
                "ErrorCheckStubData": "true",
                "GenerateStublessProxies": "true",
                "GenerateTypeLibrary": "true",
                "HeaderFileName": "a_file_name",
                "IgnoreStandardIncludePath": "true",
                "InterfaceIdentifierFileName": "a_file_name",
                "MkTypLibCompatible": "true",
                "OutputDirectory": "a_string",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ProxyFileName": "a_file_name",
                "RedirectOutputAndErrors": "a_file_name",
                "StructMemberAlignment": "3",
                "SuppressStartupBanner": "true",
                "TargetEnvironment": "1",
                "TypeLibraryName": "a_file_name",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
                "ValidateParameters": "true",
                "WarnAsError": "true",
                "WarningLevel": "4",
            },
            "VCLibrarianTool": {
                "AdditionalDependencies": "file1;file2;file3",
                "AdditionalLibraryDirectories": "folder1;folder2;folder3",
                "AdditionalLibraryDirectories_excluded": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "ExportNamedFunctions": "d1;d2;d3",
                "ForceSymbolReferences": "a_string",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreSpecificDefaultLibraries": "file1;file2;file3",
                "LinkLibraryDependencies": "true",
                "ModuleDefinitionFile": "a_file_name",
                "OutputFile": "a_file_name",
                "SuppressStartupBanner": "true",
                "UseUnicodeResponseFiles": "true",
            },
            "VCManifestTool": {
                "AdditionalManifestFiles": "file1;file2;file3",
                "AdditionalOptions": "a_string",
                "AssemblyIdentity": "a_string",
                "ComponentFileName": "a_file_name",
                "DependencyInformationFile": "a_file_name",
                "EmbedManifest": "true",
                "GenerateCatalogFiles": "true",
                "InputResourceManifests": "a_string",
                "ManifestResourceFile": "my_name",
                "OutputManifestFile": "a_file_name",
                "RegistrarScriptFile": "a_file_name",
                "ReplacementsFile": "a_file_name",
                "SuppressStartupBanner": "true",
                "TypeLibraryFile": "a_file_name",
                "UpdateFileHashes": "true",
                "UpdateFileHashesSearchPath": "a_file_name",
                "UseFAT32Workaround": "true",
                "UseUnicodeResponseFiles": "true",
                "VerboseOutput": "true",
            },
        }
        expected_msbuild_settings = {
            "ClCompile": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string /J",
                "AdditionalUsingDirectories": "folder1;folder2;folder3",
                "AssemblerListingLocation": "a_file_name",
                "AssemblerOutput": "NoListing",
                "BasicRuntimeChecks": "StackFrameRuntimeCheck",
                "BrowseInformation": "true",
                "BrowseInformationFile": "a_file_name",
                "BufferSecurityCheck": "true",
                "CallingConvention": "Cdecl",
                "CompileAs": "CompileAsC",
                "DebugInformationFormat": "EditAndContinue",
                "DisableLanguageExtensions": "true",
                "DisableSpecificWarnings": "d1;d2;d3",
                "EnableEnhancedInstructionSet": "NotSet",
                "EnableFiberSafeOptimizations": "true",
                "EnablePREfast": "true",
                "ErrorReporting": "Prompt",
                "ExceptionHandling": "Async",
                "ExpandAttributedSource": "true",
                "FavorSizeOrSpeed": "Neither",
                "FloatingPointExceptions": "true",
                "FloatingPointModel": "Strict",
                "ForceConformanceInForLoopScope": "true",
                "ForcedIncludeFiles": "file1;file2;file3",
                "ForcedUsingFiles": "file1;file2;file3",
                "FunctionLevelLinking": "true",
                "GenerateXMLDocumentationFiles": "true",
                "IgnoreStandardIncludePath": "true",
                "InlineFunctionExpansion": "AnySuitable",
                "IntrinsicFunctions": "true",
                "MinimalRebuild": "true",
                "ObjectFileName": "a_file_name",
                "OmitDefaultLibName": "true",
                "OmitFramePointers": "true",
                "OpenMPSupport": "true",
                "Optimization": "Full",
                "PrecompiledHeader": "Create",
                "PrecompiledHeaderFile": "a_file_name",
                "PrecompiledHeaderOutputFile": "a_file_name",
                "PreprocessKeepComments": "true",
                "PreprocessorDefinitions": "d1;d2;d3",
                "PreprocessSuppressLineNumbers": "false",
                "PreprocessToFile": "true",
                "ProgramDataBaseFileName": "a_file_name",
                "RuntimeLibrary": "MultiThreaded",
                "RuntimeTypeInfo": "true",
                "ShowIncludes": "true",
                "SmallerTypeCheck": "true",
                "StringPooling": "true",
                "StructMemberAlignment": "1Byte",
                "SuppressStartupBanner": "true",
                "TreatWarningAsError": "true",
                "TreatWChar_tAsBuiltInType": "true",
                "UndefineAllPreprocessorDefinitions": "true",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
                "UseFullPaths": "true",
                "WarningLevel": "Level2",
                "WholeProgramOptimization": "true",
                "XMLDocumentationFileName": "a_file_name",
            },
            "Link": {
                "AdditionalDependencies": "file1;file2;file3",
                "AdditionalLibraryDirectories": "folder1;folder2;folder3",
                "AdditionalManifestDependencies": "file1;file2;file3",
                "AdditionalOptions": "a_string",
                "AddModuleNamesToAssembly": "file1;file2;file3",
                "AllowIsolation": "true",
                "AssemblyDebug": "",
                "AssemblyLinkResource": "file1;file2;file3",
                "BaseAddress": "a_string",
                "CLRImageType": "ForceIJWImage",
                "CLRThreadAttribute": "STAThreadingAttribute",
                "CLRUnmanagedCodeCheck": "true",
                "DataExecutionPrevention": "",
                "DelayLoadDLLs": "file1;file2;file3",
                "DelaySign": "true",
                "Driver": "Driver",
                "EmbedManagedResourceFile": "file1;file2;file3",
                "EnableCOMDATFolding": "",
                "EnableUAC": "true",
                "EntryPointSymbol": "a_string",
                "FixedBaseAddress": "false",
                "ForceSymbolReferences": "file1;file2;file3",
                "FunctionOrder": "a_file_name",
                "GenerateDebugInformation": "true",
                "GenerateMapFile": "true",
                "HeapCommitSize": "a_string",
                "HeapReserveSize": "a_string",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreEmbeddedIDL": "true",
                "IgnoreSpecificDefaultLibraries": "file1;file2;file3",
                "ImportLibrary": "a_file_name",
                "KeyContainer": "a_file_name",
                "KeyFile": "a_file_name",
                "LargeAddressAware": "true",
                "LinkErrorReporting": "NoErrorReport",
                "LinkTimeCodeGeneration": "PGInstrument",
                "ManifestFile": "a_file_name",
                "MapExports": "true",
                "MapFileName": "a_file_name",
                "MergedIDLBaseFileName": "a_file_name",
                "MergeSections": "a_string",
                "MidlCommandFile": "a_file_name",
                "ModuleDefinitionFile": "a_file_name",
                "NoEntryPoint": "true",
                "OptimizeReferences": "",
                "OutputFile": "a_file_name",
                "PerUserRedirection": "true",
                "Profile": "true",
                "ProfileGuidedDatabase": "a_file_name",
                "ProgramDatabaseFile": "a_file_name",
                "RandomizedBaseAddress": "false",
                "RegisterOutput": "true",
                "SetChecksum": "true",
                "ShowProgress": "NotSet",
                "StackCommitSize": "a_string",
                "StackReserveSize": "a_string",
                "StripPrivateSymbols": "a_file_name",
                "SubSystem": "Windows",
                "SupportUnloadOfDelayLoadedDLL": "true",
                "SuppressStartupBanner": "true",
                "SwapRunFromCD": "true",
                "SwapRunFromNET": "true",
                "TargetMachine": "MachineARM",
                "TerminalServerAware": "true",
                "TurnOffAssemblyGeneration": "true",
                "TypeLibraryFile": "a_file_name",
                "TypeLibraryResourceID": "33",
                "UACExecutionLevel": "HighestAvailable",
                "UACUIAccess": "true",
                "Version": "a_string",
            },
            "ResourceCompile": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "Culture": "0x03eb",
                "IgnoreStandardIncludePath": "true",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ResourceOutputFileName": "a_string",
                "ShowProgress": "true",
                "SuppressStartupBanner": "true",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
            },
            "Midl": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "CPreprocessOptions": "a_string",
                "DefaultCharType": "Unsigned",
                "DllDataFileName": "a_file_name",
                "EnableErrorChecks": "All",
                "ErrorCheckAllocations": "true",
                "ErrorCheckBounds": "true",
                "ErrorCheckEnumRange": "true",
                "ErrorCheckRefPointers": "true",
                "ErrorCheckStubData": "true",
                "GenerateStublessProxies": "true",
                "GenerateTypeLibrary": "true",
                "HeaderFileName": "a_file_name",
                "IgnoreStandardIncludePath": "true",
                "InterfaceIdentifierFileName": "a_file_name",
                "MkTypLibCompatible": "true",
                "OutputDirectory": "a_string",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ProxyFileName": "a_file_name",
                "RedirectOutputAndErrors": "a_file_name",
                "StructMemberAlignment": "4",
                "SuppressStartupBanner": "true",
                "TargetEnvironment": "Win32",
                "TypeLibraryName": "a_file_name",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
                "ValidateAllParameters": "true",
                "WarnAsError": "true",
                "WarningLevel": "4",
            },
            "Lib": {
                "AdditionalDependencies": "file1;file2;file3",
                "AdditionalLibraryDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "ExportNamedFunctions": "d1;d2;d3",
                "ForceSymbolReferences": "a_string",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreSpecificDefaultLibraries": "file1;file2;file3",
                "ModuleDefinitionFile": "a_file_name",
                "OutputFile": "a_file_name",
                "SuppressStartupBanner": "true",
                "UseUnicodeResponseFiles": "true",
            },
            "Manifest": {
                "AdditionalManifestFiles": "file1;file2;file3",
                "AdditionalOptions": "a_string",
                "AssemblyIdentity": "a_string",
                "ComponentFileName": "a_file_name",
                "GenerateCatalogFiles": "true",
                "InputResourceManifests": "a_string",
                "OutputManifestFile": "a_file_name",
                "RegistrarScriptFile": "a_file_name",
                "ReplacementsFile": "a_file_name",
                "SuppressStartupBanner": "true",
                "TypeLibraryFile": "a_file_name",
                "UpdateFileHashes": "true",
                "UpdateFileHashesSearchPath": "a_file_name",
                "VerboseOutput": "true",
            },
            "ManifestResourceCompile": {"ResourceOutputFileName": "my_name"},
            "ProjectReference": {
                "LinkLibraryDependencies": "true",
                "UseLibraryDependencyInputs": "false",
            },
            "": {
                "EmbedManifest": "true",
                "GenerateManifest": "true",
                "IgnoreImportLibrary": "true",
                "LinkIncremental": "false",
            },
        }
        self.maxDiff = 9999  # on failure display a long diff
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings([])

    def testConvertToMSBuildSettings_actual(self):
        """Tests the conversion of an actual project.

    A VS2008 project with most of the options defined was created through the
    VS2008 IDE.  It was then converted to VS2010.  The tool settings found in
    the .vcproj and .vcxproj files were converted to the two dictionaries
    msvs_settings and expected_msbuild_settings.

    Note that for many settings, the VS2010 converter adds macros like
    %(AdditionalIncludeDirectories) to make sure than inherited values are
    included.  Since the Gyp projects we generate do not use inheritance,
    we removed these macros.  They were:
        ClCompile:
            AdditionalIncludeDirectories:  ';%(AdditionalIncludeDirectories)'
            AdditionalOptions:  ' %(AdditionalOptions)'
            AdditionalUsingDirectories:  ';%(AdditionalUsingDirectories)'
            DisableSpecificWarnings: ';%(DisableSpecificWarnings)',
            ForcedIncludeFiles:  ';%(ForcedIncludeFiles)',
            ForcedUsingFiles:  ';%(ForcedUsingFiles)',
            PreprocessorDefinitions:  ';%(PreprocessorDefinitions)',
            UndefinePreprocessorDefinitions:
                ';%(UndefinePreprocessorDefinitions)',
        Link:
            AdditionalDependencies:  ';%(AdditionalDependencies)',
            AdditionalLibraryDirectories:  ';%(AdditionalLibraryDirectories)',
            AdditionalManifestDependencies:
                ';%(AdditionalManifestDependencies)',
            AdditionalOptions:  ' %(AdditionalOptions)',
            AddModuleNamesToAssembly:  ';%(AddModuleNamesToAssembly)',
            AssemblyLinkResource:  ';%(AssemblyLinkResource)',
            DelayLoadDLLs:  ';%(DelayLoadDLLs)',
            EmbedManagedResourceFile:  ';%(EmbedManagedResourceFile)',
            ForceSymbolReferences:  ';%(ForceSymbolReferences)',
            IgnoreSpecificDefaultLibraries:
                ';%(IgnoreSpecificDefaultLibraries)',
        ResourceCompile:
            AdditionalIncludeDirectories:  ';%(AdditionalIncludeDirectories)',
            AdditionalOptions:  ' %(AdditionalOptions)',
            PreprocessorDefinitions:  ';%(PreprocessorDefinitions)',
        Manifest:
            AdditionalManifestFiles:  ';%(AdditionalManifestFiles)',
            AdditionalOptions:  ' %(AdditionalOptions)',
            InputResourceManifests:  ';%(InputResourceManifests)',
    """
        msvs_settings = {
            "VCCLCompilerTool": {
                "AdditionalIncludeDirectories": "dir1",
                "AdditionalOptions": "/more",
                "AdditionalUsingDirectories": "test",
                "AssemblerListingLocation": "$(IntDir)\\a",
                "AssemblerOutput": "1",
                "BasicRuntimeChecks": "3",
                "BrowseInformation": "1",
                "BrowseInformationFile": "$(IntDir)\\e",
                "BufferSecurityCheck": "false",
                "CallingConvention": "1",
                "CompileAs": "1",
                "DebugInformationFormat": "4",
                "DefaultCharIsUnsigned": "true",
                "Detect64BitPortabilityProblems": "true",
                "DisableLanguageExtensions": "true",
                "DisableSpecificWarnings": "abc",
                "EnableEnhancedInstructionSet": "1",
                "EnableFiberSafeOptimizations": "true",
                "EnableFunctionLevelLinking": "true",
                "EnableIntrinsicFunctions": "true",
                "EnablePREfast": "true",
                "ErrorReporting": "2",
                "ExceptionHandling": "2",
                "ExpandAttributedSource": "true",
                "FavorSizeOrSpeed": "2",
                "FloatingPointExceptions": "true",
                "FloatingPointModel": "1",
                "ForceConformanceInForLoopScope": "false",
                "ForcedIncludeFiles": "def",
                "ForcedUsingFiles": "ge",
                "GeneratePreprocessedFile": "2",
                "GenerateXMLDocumentationFiles": "true",
                "IgnoreStandardIncludePath": "true",
                "InlineFunctionExpansion": "1",
                "KeepComments": "true",
                "MinimalRebuild": "true",
                "ObjectFile": "$(IntDir)\\b",
                "OmitDefaultLibName": "true",
                "OmitFramePointers": "true",
                "OpenMP": "true",
                "Optimization": "3",
                "PrecompiledHeaderFile": "$(IntDir)\\$(TargetName).pche",
                "PrecompiledHeaderThrough": "StdAfx.hd",
                "PreprocessorDefinitions": "WIN32;_DEBUG;_CONSOLE",
                "ProgramDataBaseFileName": "$(IntDir)\\vc90b.pdb",
                "RuntimeLibrary": "3",
                "RuntimeTypeInfo": "false",
                "ShowIncludes": "true",
                "SmallerTypeCheck": "true",
                "StringPooling": "true",
                "StructMemberAlignment": "3",
                "SuppressStartupBanner": "false",
                "TreatWChar_tAsBuiltInType": "false",
                "UndefineAllPreprocessorDefinitions": "true",
                "UndefinePreprocessorDefinitions": "wer",
                "UseFullPaths": "true",
                "UsePrecompiledHeader": "0",
                "UseUnicodeResponseFiles": "false",
                "WarnAsError": "true",
                "WarningLevel": "3",
                "WholeProgramOptimization": "true",
                "XMLDocumentationFileName": "$(IntDir)\\c",
            },
            "VCLinkerTool": {
                "AdditionalDependencies": "zx",
                "AdditionalLibraryDirectories": "asd",
                "AdditionalManifestDependencies": "s2",
                "AdditionalOptions": "/mor2",
                "AddModuleNamesToAssembly": "d1",
                "AllowIsolation": "false",
                "AssemblyDebug": "1",
                "AssemblyLinkResource": "d5",
                "BaseAddress": "23423",
                "CLRImageType": "3",
                "CLRThreadAttribute": "1",
                "CLRUnmanagedCodeCheck": "true",
                "DataExecutionPrevention": "0",
                "DelayLoadDLLs": "d4",
                "DelaySign": "true",
                "Driver": "2",
                "EmbedManagedResourceFile": "d2",
                "EnableCOMDATFolding": "1",
                "EnableUAC": "false",
                "EntryPointSymbol": "f5",
                "ErrorReporting": "2",
                "FixedBaseAddress": "1",
                "ForceSymbolReferences": "d3",
                "FunctionOrder": "fssdfsd",
                "GenerateDebugInformation": "true",
                "GenerateManifest": "false",
                "GenerateMapFile": "true",
                "HeapCommitSize": "13",
                "HeapReserveSize": "12",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreDefaultLibraryNames": "flob;flok",
                "IgnoreEmbeddedIDL": "true",
                "IgnoreImportLibrary": "true",
                "ImportLibrary": "f4",
                "KeyContainer": "f7",
                "KeyFile": "f6",
                "LargeAddressAware": "2",
                "LinkIncremental": "0",
                "LinkLibraryDependencies": "false",
                "LinkTimeCodeGeneration": "1",
                "ManifestFile": "$(IntDir)\\$(TargetFileName).2intermediate.manifest",
                "MapExports": "true",
                "MapFileName": "d5",
                "MergedIDLBaseFileName": "f2",
                "MergeSections": "f5",
                "MidlCommandFile": "f1",
                "ModuleDefinitionFile": "sdsd",
                "OptimizeForWindows98": "2",
                "OptimizeReferences": "2",
                "OutputFile": "$(OutDir)\\$(ProjectName)2.exe",
                "PerUserRedirection": "true",
                "Profile": "true",
                "ProfileGuidedDatabase": "$(TargetDir)$(TargetName).pgdd",
                "ProgramDatabaseFile": "Flob.pdb",
                "RandomizedBaseAddress": "1",
                "RegisterOutput": "true",
                "ResourceOnlyDLL": "true",
                "SetChecksum": "false",
                "ShowProgress": "1",
                "StackCommitSize": "15",
                "StackReserveSize": "14",
                "StripPrivateSymbols": "d3",
                "SubSystem": "1",
                "SupportUnloadOfDelayLoadedDLL": "true",
                "SuppressStartupBanner": "false",
                "SwapRunFromCD": "true",
                "SwapRunFromNet": "true",
                "TargetMachine": "1",
                "TerminalServerAware": "1",
                "TurnOffAssemblyGeneration": "true",
                "TypeLibraryFile": "f3",
                "TypeLibraryResourceID": "12",
                "UACExecutionLevel": "2",
                "UACUIAccess": "true",
                "UseLibraryDependencyInputs": "true",
                "UseUnicodeResponseFiles": "false",
                "Version": "333",
            },
            "VCResourceCompilerTool": {
                "AdditionalIncludeDirectories": "f3",
                "AdditionalOptions": "/more3",
                "Culture": "3084",
                "IgnoreStandardIncludePath": "true",
                "PreprocessorDefinitions": "_UNICODE;UNICODE2",
                "ResourceOutputFileName": "$(IntDir)/$(InputName)3.res",
                "ShowProgress": "true",
            },
            "VCManifestTool": {
                "AdditionalManifestFiles": "sfsdfsd",
                "AdditionalOptions": "afdsdafsd",
                "AssemblyIdentity": "sddfdsadfsa",
                "ComponentFileName": "fsdfds",
                "DependencyInformationFile": "$(IntDir)\\mt.depdfd",
                "EmbedManifest": "false",
                "GenerateCatalogFiles": "true",
                "InputResourceManifests": "asfsfdafs",
                "ManifestResourceFile":
                    "$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf",
                "OutputManifestFile": "$(TargetPath).manifestdfs",
                "RegistrarScriptFile": "sdfsfd",
                "ReplacementsFile": "sdffsd",
                "SuppressStartupBanner": "false",
                "TypeLibraryFile": "sfsd",
                "UpdateFileHashes": "true",
                "UpdateFileHashesSearchPath": "sfsd",
                "UseFAT32Workaround": "true",
                "UseUnicodeResponseFiles": "false",
                "VerboseOutput": "true",
            },
        }
        expected_msbuild_settings = {
            "ClCompile": {
                "AdditionalIncludeDirectories": "dir1",
                "AdditionalOptions": "/more /J",
                "AdditionalUsingDirectories": "test",
                "AssemblerListingLocation": "$(IntDir)a",
                "AssemblerOutput": "AssemblyCode",
                "BasicRuntimeChecks": "EnableFastChecks",
                "BrowseInformation": "true",
                "BrowseInformationFile": "$(IntDir)e",
                "BufferSecurityCheck": "false",
                "CallingConvention": "FastCall",
                "CompileAs": "CompileAsC",
                "DebugInformationFormat": "EditAndContinue",
                "DisableLanguageExtensions": "true",
                "DisableSpecificWarnings": "abc",
                "EnableEnhancedInstructionSet": "StreamingSIMDExtensions",
                "EnableFiberSafeOptimizations": "true",
                "EnablePREfast": "true",
                "ErrorReporting": "Queue",
                "ExceptionHandling": "Async",
                "ExpandAttributedSource": "true",
                "FavorSizeOrSpeed": "Size",
                "FloatingPointExceptions": "true",
                "FloatingPointModel": "Strict",
                "ForceConformanceInForLoopScope": "false",
                "ForcedIncludeFiles": "def",
                "ForcedUsingFiles": "ge",
                "FunctionLevelLinking": "true",
                "GenerateXMLDocumentationFiles": "true",
                "IgnoreStandardIncludePath": "true",
                "InlineFunctionExpansion": "OnlyExplicitInline",
                "IntrinsicFunctions": "true",
                "MinimalRebuild": "true",
                "ObjectFileName": "$(IntDir)b",
                "OmitDefaultLibName": "true",
                "OmitFramePointers": "true",
                "OpenMPSupport": "true",
                "Optimization": "Full",
                "PrecompiledHeader": "NotUsing",  # Actual conversion gives ''
                "PrecompiledHeaderFile": "StdAfx.hd",
                "PrecompiledHeaderOutputFile": "$(IntDir)$(TargetName).pche",
                "PreprocessKeepComments": "true",
                "PreprocessorDefinitions": "WIN32;_DEBUG;_CONSOLE",
                "PreprocessSuppressLineNumbers": "true",
                "PreprocessToFile": "true",
                "ProgramDataBaseFileName": "$(IntDir)vc90b.pdb",
                "RuntimeLibrary": "MultiThreadedDebugDLL",
                "RuntimeTypeInfo": "false",
                "ShowIncludes": "true",
                "SmallerTypeCheck": "true",
                "StringPooling": "true",
                "StructMemberAlignment": "4Bytes",
                "SuppressStartupBanner": "false",
                "TreatWarningAsError": "true",
                "TreatWChar_tAsBuiltInType": "false",
                "UndefineAllPreprocessorDefinitions": "true",
                "UndefinePreprocessorDefinitions": "wer",
                "UseFullPaths": "true",
                "WarningLevel": "Level3",
                "WholeProgramOptimization": "true",
                "XMLDocumentationFileName": "$(IntDir)c",
            },
            "Link": {
                "AdditionalDependencies": "zx",
                "AdditionalLibraryDirectories": "asd",
                "AdditionalManifestDependencies": "s2",
                "AdditionalOptions": "/mor2",
                "AddModuleNamesToAssembly": "d1",
                "AllowIsolation": "false",
                "AssemblyDebug": "true",
                "AssemblyLinkResource": "d5",
                "BaseAddress": "23423",
                "CLRImageType": "ForceSafeILImage",
                "CLRThreadAttribute": "MTAThreadingAttribute",
                "CLRUnmanagedCodeCheck": "true",
                "DataExecutionPrevention": "",
                "DelayLoadDLLs": "d4",
                "DelaySign": "true",
                "Driver": "UpOnly",
                "EmbedManagedResourceFile": "d2",
                "EnableCOMDATFolding": "false",
                "EnableUAC": "false",
                "EntryPointSymbol": "f5",
                "FixedBaseAddress": "false",
                "ForceSymbolReferences": "d3",
                "FunctionOrder": "fssdfsd",
                "GenerateDebugInformation": "true",
                "GenerateMapFile": "true",
                "HeapCommitSize": "13",
                "HeapReserveSize": "12",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreEmbeddedIDL": "true",
                "IgnoreSpecificDefaultLibraries": "flob;flok",
                "ImportLibrary": "f4",
                "KeyContainer": "f7",
                "KeyFile": "f6",
                "LargeAddressAware": "true",
                "LinkErrorReporting": "QueueForNextLogin",
                "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration",
                "ManifestFile": "$(IntDir)$(TargetFileName).2intermediate.manifest",
                "MapExports": "true",
                "MapFileName": "d5",
                "MergedIDLBaseFileName": "f2",
                "MergeSections": "f5",
                "MidlCommandFile": "f1",
                "ModuleDefinitionFile": "sdsd",
                "NoEntryPoint": "true",
                "OptimizeReferences": "true",
                "OutputFile": "$(OutDir)$(ProjectName)2.exe",
                "PerUserRedirection": "true",
                "Profile": "true",
                "ProfileGuidedDatabase": "$(TargetDir)$(TargetName).pgdd",
                "ProgramDatabaseFile": "Flob.pdb",
                "RandomizedBaseAddress": "false",
                "RegisterOutput": "true",
                "SetChecksum": "false",
                "ShowProgress": "LinkVerbose",
                "StackCommitSize": "15",
                "StackReserveSize": "14",
                "StripPrivateSymbols": "d3",
                "SubSystem": "Console",
                "SupportUnloadOfDelayLoadedDLL": "true",
                "SuppressStartupBanner": "false",
                "SwapRunFromCD": "true",
                "SwapRunFromNET": "true",
                "TargetMachine": "MachineX86",
                "TerminalServerAware": "false",
                "TurnOffAssemblyGeneration": "true",
                "TypeLibraryFile": "f3",
                "TypeLibraryResourceID": "12",
                "UACExecutionLevel": "RequireAdministrator",
                "UACUIAccess": "true",
                "Version": "333",
            },
            "ResourceCompile": {
                "AdditionalIncludeDirectories": "f3",
                "AdditionalOptions": "/more3",
                "Culture": "0x0c0c",
                "IgnoreStandardIncludePath": "true",
                "PreprocessorDefinitions": "_UNICODE;UNICODE2",
                "ResourceOutputFileName": "$(IntDir)%(Filename)3.res",
                "ShowProgress": "true",
            },
            "Manifest": {
                "AdditionalManifestFiles": "sfsdfsd",
                "AdditionalOptions": "afdsdafsd",
                "AssemblyIdentity": "sddfdsadfsa",
                "ComponentFileName": "fsdfds",
                "GenerateCatalogFiles": "true",
                "InputResourceManifests": "asfsfdafs",
                "OutputManifestFile": "$(TargetPath).manifestdfs",
                "RegistrarScriptFile": "sdfsfd",
                "ReplacementsFile": "sdffsd",
                "SuppressStartupBanner": "false",
                "TypeLibraryFile": "sfsd",
                "UpdateFileHashes": "true",
                "UpdateFileHashesSearchPath": "sfsd",
                "VerboseOutput": "true",
            },
            "ProjectReference": {
                "LinkLibraryDependencies": "false",
                "UseLibraryDependencyInputs": "true",
            },
            "": {
                "EmbedManifest": "false",
                "GenerateManifest": "false",
                "IgnoreImportLibrary": "true",
                "LinkIncremental": "",
            },
            "ManifestResourceCompile": {
                "ResourceOutputFileName":
                    "$(IntDir)$(TargetFileName).embed.manifest.resfdsf"
            },
        }
        self.maxDiff = 9999  # on failure display a long diff
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings([])


if __name__ == "__main__":
    unittest.main()
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Visual Studio project reader/writer."""

import gyp.easy_xml as easy_xml


class Writer:
    """Visual Studio XML tool file writer."""

    def __init__(self, tool_file_path, name):
        """Initializes the tool file.

    Args:
      tool_file_path: Path to the tool file.
      name: Name of the tool file.
    """
        self.tool_file_path = tool_file_path
        self.name = name
        self.rules_section = ["Rules"]

    def AddCustomBuildRule(
        self, name, cmd, description, additional_dependencies, outputs, extensions
    ):
        """Adds a rule to the tool file.

    Args:
      name: Name of the rule.
      description: Description of the rule.
      cmd: Command line of the rule.
      additional_dependencies: other files which may trigger the rule.
      outputs: outputs of the rule.
      extensions: extensions handled by the rule.
    """
        rule = [
            "CustomBuildRule",
            {
                "Name": name,
                "ExecutionDescription": description,
                "CommandLine": cmd,
                "Outputs": ";".join(outputs),
                "FileExtensions": ";".join(extensions),
                "AdditionalDependencies": ";".join(additional_dependencies),
            },
        ]
        self.rules_section.append(rule)

    def WriteIfChanged(self):
        """Writes the tool file."""
        content = [
            "VisualStudioToolFile",
            {"Version": "8.00", "Name": self.name},
            self.rules_section,
        ]
        easy_xml.WriteXmlIfChanged(
            content, self.tool_file_path, encoding="Windows-1252"
        )
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Visual Studio user preferences file writer."""

import os
import re
import socket  # for gethostname

import gyp.easy_xml as easy_xml


# ------------------------------------------------------------------------------


def _FindCommandInPath(command):
    """If there are no slashes in the command given, this function
     searches the PATH env to find the given command, and converts it
     to an absolute path.  We have to do this because MSVS is looking
     for an actual file to launch a debugger on, not just a command
     line.  Note that this happens at GYP time, so anything needing to
     be built needs to have a full path."""
    if "/" in command or "\\" in command:
        # If the command already has path elements (either relative or
        # absolute), then assume it is constructed properly.
        return command
    else:
        # Search through the path list and find an existing file that
        # we can access.
        paths = os.environ.get("PATH", "").split(os.pathsep)
        for path in paths:
            item = os.path.join(path, command)
            if os.path.isfile(item) and os.access(item, os.X_OK):
                return item
    return command


def _QuoteWin32CommandLineArgs(args):
    new_args = []
    for arg in args:
        # Replace all double-quotes with double-double-quotes to escape
        # them for cmd shell, and then quote the whole thing if there
        # are any.
        if arg.find('"') != -1:
            arg = '""'.join(arg.split('"'))
            arg = '"%s"' % arg

        # Otherwise, if there are any spaces, quote the whole arg.
        elif re.search(r"[ \t\n]", arg):
            arg = '"%s"' % arg
        new_args.append(arg)
    return new_args


class Writer:
    """Visual Studio XML user user file writer."""

    def __init__(self, user_file_path, version, name):
        """Initializes the user file.

    Args:
      user_file_path: Path to the user file.
      version: Version info.
      name: Name of the user file.
    """
        self.user_file_path = user_file_path
        self.version = version
        self.name = name
        self.configurations = {}

    def AddConfig(self, name):
        """Adds a configuration to the project.

    Args:
      name: Configuration name.
    """
        self.configurations[name] = ["Configuration", {"Name": name}]

    def AddDebugSettings(
        self, config_name, command, environment={}, working_directory=""
    ):
        """Adds a DebugSettings node to the user file for a particular config.

    Args:
      command: command line to run.  First element in the list is the
        executable.  All elements of the command will be quoted if
        necessary.
      working_directory: other files which may trigger the rule. (optional)
    """
        command = _QuoteWin32CommandLineArgs(command)

        abs_command = _FindCommandInPath(command[0])

        if environment and isinstance(environment, dict):
            env_list = [f'{key}="{val}"' for (key, val) in environment.items()]
            environment = " ".join(env_list)
        else:
            environment = ""

        n_cmd = [
            "DebugSettings",
            {
                "Command": abs_command,
                "WorkingDirectory": working_directory,
                "CommandArguments": " ".join(command[1:]),
                "RemoteMachine": socket.gethostname(),
                "Environment": environment,
                "EnvironmentMerge": "true",
                # Currently these are all "dummy" values that we're just setting
                # in the default manner that MSVS does it.  We could use some of
                # these to add additional capabilities, I suppose, but they might
                # not have parity with other platforms then.
                "Attach": "false",
                "DebuggerType": "3",  # 'auto' debugger
                "Remote": "1",
                "RemoteCommand": "",
                "HttpUrl": "",
                "PDBPath": "",
                "SQLDebugging": "",
                "DebuggerFlavor": "0",
                "MPIRunCommand": "",
                "MPIRunArguments": "",
                "MPIRunWorkingDirectory": "",
                "ApplicationCommand": "",
                "ApplicationArguments": "",
                "ShimCommand": "",
                "MPIAcceptMode": "",
                "MPIAcceptFilter": "",
            },
        ]

        # Find the config, and add it if it doesn't exist.
        if config_name not in self.configurations:
            self.AddConfig(config_name)

        # Add the DebugSettings onto the appropriate config.
        self.configurations[config_name].append(n_cmd)

    def WriteIfChanged(self):
        """Writes the user file."""
        configs = ["Configurations"]
        for config, spec in sorted(self.configurations.items()):
            configs.append(spec)

        content = [
            "VisualStudioUserFile",
            {"Version": self.version.ProjectVersion(), "Name": self.name},
            configs,
        ]
        easy_xml.WriteXmlIfChanged(
            content, self.user_file_path, encoding="Windows-1252"
        )
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Utility functions shared amongst the Windows generators."""

import copy
import os


# A dictionary mapping supported target types to extensions.
TARGET_TYPE_EXT = {
    "executable": "exe",
    "loadable_module": "dll",
    "shared_library": "dll",
    "static_library": "lib",
    "windows_driver": "sys",
}


def _GetLargePdbShimCcPath():
    """Returns the path of the large_pdb_shim.cc file."""
    this_dir = os.path.abspath(os.path.dirname(__file__))
    src_dir = os.path.abspath(os.path.join(this_dir, "..", ".."))
    win_data_dir = os.path.join(src_dir, "data", "win")
    large_pdb_shim_cc = os.path.join(win_data_dir, "large-pdb-shim.cc")
    return large_pdb_shim_cc


def _DeepCopySomeKeys(in_dict, keys):
    """Performs a partial deep-copy on |in_dict|, only copying the keys in |keys|.

  Arguments:
    in_dict: The dictionary to copy.
    keys: The keys to be copied. If a key is in this list and doesn't exist in
        |in_dict| this is not an error.
  Returns:
    The partially deep-copied dictionary.
  """
    d = {}
    for key in keys:
        if key not in in_dict:
            continue
        d[key] = copy.deepcopy(in_dict[key])
    return d


def _SuffixName(name, suffix):
    """Add a suffix to the end of a target.

  Arguments:
    name: name of the target (foo#target)
    suffix: the suffix to be added
  Returns:
    Target name with suffix added (foo_suffix#target)
  """
    parts = name.rsplit("#", 1)
    parts[0] = f"{parts[0]}_{suffix}"
    return "#".join(parts)


def _ShardName(name, number):
    """Add a shard number to the end of a target.

  Arguments:
    name: name of the target (foo#target)
    number: shard number
  Returns:
    Target name with shard added (foo_1#target)
  """
    return _SuffixName(name, str(number))


def ShardTargets(target_list, target_dicts):
    """Shard some targets apart to work around the linkers limits.

  Arguments:
    target_list: List of target pairs: 'base/base.gyp:base'.
    target_dicts: Dict of target properties keyed on target pair.
  Returns:
    Tuple of the new sharded versions of the inputs.
  """
    # Gather the targets to shard, and how many pieces.
    targets_to_shard = {}
    for t in target_dicts:
        shards = int(target_dicts[t].get("msvs_shard", 0))
        if shards:
            targets_to_shard[t] = shards
    # Shard target_list.
    new_target_list = []
    for t in target_list:
        if t in targets_to_shard:
            for i in range(targets_to_shard[t]):
                new_target_list.append(_ShardName(t, i))
        else:
            new_target_list.append(t)
    # Shard target_dict.
    new_target_dicts = {}
    for t in target_dicts:
        if t in targets_to_shard:
            for i in range(targets_to_shard[t]):
                name = _ShardName(t, i)
                new_target_dicts[name] = copy.copy(target_dicts[t])
                new_target_dicts[name]["target_name"] = _ShardName(
                    new_target_dicts[name]["target_name"], i
                )
                sources = new_target_dicts[name].get("sources", [])
                new_sources = []
                for pos in range(i, len(sources), targets_to_shard[t]):
                    new_sources.append(sources[pos])
                new_target_dicts[name]["sources"] = new_sources
        else:
            new_target_dicts[t] = target_dicts[t]
    # Shard dependencies.
    for t in sorted(new_target_dicts):
        for deptype in ("dependencies", "dependencies_original"):
            dependencies = copy.copy(new_target_dicts[t].get(deptype, []))
            new_dependencies = []
            for d in dependencies:
                if d in targets_to_shard:
                    for i in range(targets_to_shard[d]):
                        new_dependencies.append(_ShardName(d, i))
                else:
                    new_dependencies.append(d)
            new_target_dicts[t][deptype] = new_dependencies

    return (new_target_list, new_target_dicts)


def _GetPdbPath(target_dict, config_name, vars):
    """Returns the path to the PDB file that will be generated by a given
  configuration.

  The lookup proceeds as follows:
    - Look for an explicit path in the VCLinkerTool configuration block.
    - Look for an 'msvs_large_pdb_path' variable.
    - Use '<(PRODUCT_DIR)/<(product_name).(exe|dll).pdb' if 'product_name' is
      specified.
    - Use '<(PRODUCT_DIR)/<(target_name).(exe|dll).pdb'.

  Arguments:
    target_dict: The target dictionary to be searched.
    config_name: The name of the configuration of interest.
    vars: A dictionary of common GYP variables with generator-specific values.
  Returns:
    The path of the corresponding PDB file.
  """
    config = target_dict["configurations"][config_name]
    msvs = config.setdefault("msvs_settings", {})

    linker = msvs.get("VCLinkerTool", {})

    pdb_path = linker.get("ProgramDatabaseFile")
    if pdb_path:
        return pdb_path

    variables = target_dict.get("variables", {})
    pdb_path = variables.get("msvs_large_pdb_path", None)
    if pdb_path:
        return pdb_path

    pdb_base = target_dict.get("product_name", target_dict["target_name"])
    pdb_base = "{}.{}.pdb".format(pdb_base, TARGET_TYPE_EXT[target_dict["type"]])
    pdb_path = vars["PRODUCT_DIR"] + "/" + pdb_base

    return pdb_path


def InsertLargePdbShims(target_list, target_dicts, vars):
    """Insert a shim target that forces the linker to use 4KB pagesize PDBs.

  This is a workaround for targets with PDBs greater than 1GB in size, the
  limit for the 1KB pagesize PDBs created by the linker by default.

  Arguments:
    target_list: List of target pairs: 'base/base.gyp:base'.
    target_dicts: Dict of target properties keyed on target pair.
    vars: A dictionary of common GYP variables with generator-specific values.
  Returns:
    Tuple of the shimmed version of the inputs.
  """
    # Determine which targets need shimming.
    targets_to_shim = []
    for t in target_dicts:
        target_dict = target_dicts[t]

        # We only want to shim targets that have msvs_large_pdb enabled.
        if not int(target_dict.get("msvs_large_pdb", 0)):
            continue
        # This is intended for executable, shared_library and loadable_module
        # targets where every configuration is set up to produce a PDB output.
        # If any of these conditions is not true then the shim logic will fail
        # below.
        targets_to_shim.append(t)

    large_pdb_shim_cc = _GetLargePdbShimCcPath()

    for t in targets_to_shim:
        target_dict = target_dicts[t]
        target_name = target_dict.get("target_name")

        base_dict = _DeepCopySomeKeys(
            target_dict, ["configurations", "default_configuration", "toolset"]
        )

        # This is the dict for copying the source file (part of the GYP tree)
        # to the intermediate directory of the project. This is necessary because
        # we can't always build a relative path to the shim source file (on Windows
        # GYP and the project may be on different drives), and Ninja hates absolute
        # paths (it ends up generating the .obj and .obj.d alongside the source
        # file, polluting GYPs tree).
        copy_suffix = "large_pdb_copy"
        copy_target_name = target_name + "_" + copy_suffix
        full_copy_target_name = _SuffixName(t, copy_suffix)
        shim_cc_basename = os.path.basename(large_pdb_shim_cc)
        shim_cc_dir = vars["SHARED_INTERMEDIATE_DIR"] + "/" + copy_target_name
        shim_cc_path = shim_cc_dir + "/" + shim_cc_basename
        copy_dict = copy.deepcopy(base_dict)
        copy_dict["target_name"] = copy_target_name
        copy_dict["type"] = "none"
        copy_dict["sources"] = [large_pdb_shim_cc]
        copy_dict["copies"] = [
            {"destination": shim_cc_dir, "files": [large_pdb_shim_cc]}
        ]

        # This is the dict for the PDB generating shim target. It depends on the
        # copy target.
        shim_suffix = "large_pdb_shim"
        shim_target_name = target_name + "_" + shim_suffix
        full_shim_target_name = _SuffixName(t, shim_suffix)
        shim_dict = copy.deepcopy(base_dict)
        shim_dict["target_name"] = shim_target_name
        shim_dict["type"] = "static_library"
        shim_dict["sources"] = [shim_cc_path]
        shim_dict["dependencies"] = [full_copy_target_name]

        # Set up the shim to output its PDB to the same location as the final linker
        # target.
        for config_name, config in shim_dict.get("configurations").items():
            pdb_path = _GetPdbPath(target_dict, config_name, vars)

            # A few keys that we don't want to propagate.
            for key in ["msvs_precompiled_header", "msvs_precompiled_source", "test"]:
                config.pop(key, None)

            msvs = config.setdefault("msvs_settings", {})

            # Update the compiler directives in the shim target.
            compiler = msvs.setdefault("VCCLCompilerTool", {})
            compiler["DebugInformationFormat"] = "3"
            compiler["ProgramDataBaseFileName"] = pdb_path

            # Set the explicit PDB path in the appropriate configuration of the
            # original target.
            config = target_dict["configurations"][config_name]
            msvs = config.setdefault("msvs_settings", {})
            linker = msvs.setdefault("VCLinkerTool", {})
            linker["GenerateDebugInformation"] = "true"
            linker["ProgramDatabaseFile"] = pdb_path

        # Add the new targets. They must go to the beginning of the list so that
        # the dependency generation works as expected in ninja.
        target_list.insert(0, full_copy_target_name)
        target_list.insert(0, full_shim_target_name)
        target_dicts[full_copy_target_name] = copy_dict
        target_dicts[full_shim_target_name] = shim_dict

        # Update the original target to depend on the shim target.
        target_dict.setdefault("dependencies", []).append(full_shim_target_name)

    return (target_list, target_dicts)
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Handle version information related to Visual Stuio."""

import errno
import os
import re
import subprocess
import sys
import glob


def JoinPath(*args):
    return os.path.normpath(os.path.join(*args))


class VisualStudioVersion:
    """Information regarding a version of Visual Studio."""

    def __init__(
        self,
        short_name,
        description,
        solution_version,
        project_version,
        flat_sln,
        uses_vcxproj,
        path,
        sdk_based,
        default_toolset=None,
        compatible_sdks=None,
    ):
        self.short_name = short_name
        self.description = description
        self.solution_version = solution_version
        self.project_version = project_version
        self.flat_sln = flat_sln
        self.uses_vcxproj = uses_vcxproj
        self.path = path
        self.sdk_based = sdk_based
        self.default_toolset = default_toolset
        compatible_sdks = compatible_sdks or []
        compatible_sdks.sort(key=lambda v: float(v.replace("v", "")), reverse=True)
        self.compatible_sdks = compatible_sdks

    def ShortName(self):
        return self.short_name

    def Description(self):
        """Get the full description of the version."""
        return self.description

    def SolutionVersion(self):
        """Get the version number of the sln files."""
        return self.solution_version

    def ProjectVersion(self):
        """Get the version number of the vcproj or vcxproj files."""
        return self.project_version

    def FlatSolution(self):
        return self.flat_sln

    def UsesVcxproj(self):
        """Returns true if this version uses a vcxproj file."""
        return self.uses_vcxproj

    def ProjectExtension(self):
        """Returns the file extension for the project."""
        return self.uses_vcxproj and ".vcxproj" or ".vcproj"

    def Path(self):
        """Returns the path to Visual Studio installation."""
        return self.path

    def ToolPath(self, tool):
        """Returns the path to a given compiler tool. """
        return os.path.normpath(os.path.join(self.path, "VC/bin", tool))

    def DefaultToolset(self):
        """Returns the msbuild toolset version that will be used in the absence
    of a user override."""
        return self.default_toolset

    def _SetupScriptInternal(self, target_arch):
        """Returns a command (with arguments) to be used to set up the
    environment."""
        assert target_arch in ("x86", "x64"), "target_arch not supported"
        # If WindowsSDKDir is set and SetEnv.Cmd exists then we are using the
        # depot_tools build tools and should run SetEnv.Cmd to set up the
        # environment. The check for WindowsSDKDir alone is not sufficient because
        # this is set by running vcvarsall.bat.
        sdk_dir = os.environ.get("WindowsSDKDir", "")
        setup_path = JoinPath(sdk_dir, "Bin", "SetEnv.Cmd")
        if self.sdk_based and sdk_dir and os.path.exists(setup_path):
            return [setup_path, "/" + target_arch]

        is_host_arch_x64 = (
            os.environ.get("PROCESSOR_ARCHITECTURE") == "AMD64"
            or os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64"
        )

        # For VS2017 (and newer) it's fairly easy
        if self.short_name >= "2017":
            script_path = JoinPath(
                self.path, "VC", "Auxiliary", "Build", "vcvarsall.bat"
            )

            # Always use a native executable, cross-compiling if necessary.
            host_arch = "amd64" if is_host_arch_x64 else "x86"
            msvc_target_arch = "amd64" if target_arch == "x64" else "x86"
            arg = host_arch
            if host_arch != msvc_target_arch:
                arg += "_" + msvc_target_arch

            return [script_path, arg]

        # We try to find the best version of the env setup batch.
        vcvarsall = JoinPath(self.path, "VC", "vcvarsall.bat")
        if target_arch == "x86":
            if (
                self.short_name >= "2013"
                and self.short_name[-1] != "e"
                and is_host_arch_x64
            ):
                # VS2013 and later, non-Express have a x64-x86 cross that we want
                # to prefer.
                return [vcvarsall, "amd64_x86"]
            else:
                # Otherwise, the standard x86 compiler. We don't use VC/vcvarsall.bat
                # for x86 because vcvarsall calls vcvars32, which it can only find if
                # VS??COMNTOOLS is set, which isn't guaranteed.
                return [JoinPath(self.path, "Common7", "Tools", "vsvars32.bat")]
        elif target_arch == "x64":
            arg = "x86_amd64"
            # Use the 64-on-64 compiler if we're not using an express edition and
            # we're running on a 64bit OS.
            if self.short_name[-1] != "e" and is_host_arch_x64:
                arg = "amd64"
            return [vcvarsall, arg]

    def SetupScript(self, target_arch):
        script_data = self._SetupScriptInternal(target_arch)
        script_path = script_data[0]
        if not os.path.exists(script_path):
            raise Exception(
                "%s is missing - make sure VC++ tools are installed." % script_path
            )
        return script_data


def _RegistryQueryBase(sysdir, key, value):
    """Use reg.exe to read a particular key.

  While ideally we might use the win32 module, we would like gyp to be
  python neutral, so for instance cygwin python lacks this module.

  Arguments:
    sysdir: The system subdirectory to attempt to launch reg.exe from.
    key: The registry key to read from.
    value: The particular value to read.
  Return:
    stdout from reg.exe, or None for failure.
  """
    # Skip if not on Windows or Python Win32 setup issue
    if sys.platform not in ("win32", "cygwin"):
        return None
    # Setup params to pass to and attempt to launch reg.exe
    cmd = [os.path.join(os.environ.get("WINDIR", ""), sysdir, "reg.exe"), "query", key]
    if value:
        cmd.extend(["/v", value])
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # Obtain the stdout from reg.exe, reading to the end so p.returncode is valid
    # Note that the error text may be in [1] in some cases
    text = p.communicate()[0].decode("utf-8")
    # Check return code from reg.exe; officially 0==success and 1==error
    if p.returncode:
        return None
    return text


def _RegistryQuery(key, value=None):
    r"""Use reg.exe to read a particular key through _RegistryQueryBase.

  First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If
  that fails, it falls back to System32.  Sysnative is available on Vista and
  up and available on Windows Server 2003 and XP through KB patch 942589. Note
  that Sysnative will always fail if using 64-bit python due to it being a
  virtual directory and System32 will work correctly in the first place.

  KB 942589 - http://support.microsoft.com/kb/942589/en-us.

  Arguments:
    key: The registry key.
    value: The particular registry value to read (optional).
  Return:
    stdout from reg.exe, or None for failure.
  """
    text = None
    try:
        text = _RegistryQueryBase("Sysnative", key, value)
    except OSError as e:
        if e.errno == errno.ENOENT:
            text = _RegistryQueryBase("System32", key, value)
        else:
            raise
    return text


def _RegistryGetValueUsingWinReg(key, value):
    """Use the _winreg module to obtain the value of a registry key.

  Args:
    key: The registry key.
    value: The particular registry value to read.
  Return:
    contents of the registry key's value, or None on failure.  Throws
    ImportError if winreg is unavailable.
  """
    from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
    try:
        root, subkey = key.split("\\", 1)
        assert root == "HKLM"  # Only need HKLM for now.
        with OpenKey(HKEY_LOCAL_MACHINE, subkey) as hkey:
            return QueryValueEx(hkey, value)[0]
    except OSError:
        return None


def _RegistryGetValue(key, value):
    """Use _winreg or reg.exe to obtain the value of a registry key.

  Using _winreg is preferable because it solves an issue on some corporate
  environments where access to reg.exe is locked down. However, we still need
  to fallback to reg.exe for the case where the _winreg module is not available
  (for example in cygwin python).

  Args:
    key: The registry key.
    value: The particular registry value to read.
  Return:
    contents of the registry key's value, or None on failure.
  """
    try:
        return _RegistryGetValueUsingWinReg(key, value)
    except ImportError:
        pass

    # Fallback to reg.exe if we fail to import _winreg.
    text = _RegistryQuery(key, value)
    if not text:
        return None
    # Extract value.
    match = re.search(r"REG_\w+\s+([^\r]+)\r\n", text)
    if not match:
        return None
    return match.group(1)


def _CreateVersion(name, path, sdk_based=False):
    """Sets up MSVS project generation.

  Setup is based off the GYP_MSVS_VERSION environment variable or whatever is
  autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is
  passed in that doesn't match a value in versions python will throw a error.
  """
    if path:
        path = os.path.normpath(path)
    versions = {
        "2022": VisualStudioVersion(
            "2022",
            "Visual Studio 2022",
            solution_version="12.00",
            project_version="17.0",
            flat_sln=False,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
            default_toolset="v143",
            compatible_sdks=["v8.1", "v10.0"],
        ),
        "2019": VisualStudioVersion(
            "2019",
            "Visual Studio 2019",
            solution_version="12.00",
            project_version="16.0",
            flat_sln=False,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
            default_toolset="v142",
            compatible_sdks=["v8.1", "v10.0"],
        ),
        "2017": VisualStudioVersion(
            "2017",
            "Visual Studio 2017",
            solution_version="12.00",
            project_version="15.0",
            flat_sln=False,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
            default_toolset="v141",
            compatible_sdks=["v8.1", "v10.0"],
        ),
        "2015": VisualStudioVersion(
            "2015",
            "Visual Studio 2015",
            solution_version="12.00",
            project_version="14.0",
            flat_sln=False,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
            default_toolset="v140",
        ),
        "2013": VisualStudioVersion(
            "2013",
            "Visual Studio 2013",
            solution_version="13.00",
            project_version="12.0",
            flat_sln=False,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
            default_toolset="v120",
        ),
        "2013e": VisualStudioVersion(
            "2013e",
            "Visual Studio 2013",
            solution_version="13.00",
            project_version="12.0",
            flat_sln=True,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
            default_toolset="v120",
        ),
        "2012": VisualStudioVersion(
            "2012",
            "Visual Studio 2012",
            solution_version="12.00",
            project_version="4.0",
            flat_sln=False,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
            default_toolset="v110",
        ),
        "2012e": VisualStudioVersion(
            "2012e",
            "Visual Studio 2012",
            solution_version="12.00",
            project_version="4.0",
            flat_sln=True,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
            default_toolset="v110",
        ),
        "2010": VisualStudioVersion(
            "2010",
            "Visual Studio 2010",
            solution_version="11.00",
            project_version="4.0",
            flat_sln=False,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
        ),
        "2010e": VisualStudioVersion(
            "2010e",
            "Visual C++ Express 2010",
            solution_version="11.00",
            project_version="4.0",
            flat_sln=True,
            uses_vcxproj=True,
            path=path,
            sdk_based=sdk_based,
        ),
        "2008": VisualStudioVersion(
            "2008",
            "Visual Studio 2008",
            solution_version="10.00",
            project_version="9.00",
            flat_sln=False,
            uses_vcxproj=False,
            path=path,
            sdk_based=sdk_based,
        ),
        "2008e": VisualStudioVersion(
            "2008e",
            "Visual Studio 2008",
            solution_version="10.00",
            project_version="9.00",
            flat_sln=True,
            uses_vcxproj=False,
            path=path,
            sdk_based=sdk_based,
        ),
        "2005": VisualStudioVersion(
            "2005",
            "Visual Studio 2005",
            solution_version="9.00",
            project_version="8.00",
            flat_sln=False,
            uses_vcxproj=False,
            path=path,
            sdk_based=sdk_based,
        ),
        "2005e": VisualStudioVersion(
            "2005e",
            "Visual Studio 2005",
            solution_version="9.00",
            project_version="8.00",
            flat_sln=True,
            uses_vcxproj=False,
            path=path,
            sdk_based=sdk_based,
        ),
    }
    return versions[str(name)]


def _ConvertToCygpath(path):
    """Convert to cygwin path if we are using cygwin."""
    if sys.platform == "cygwin":
        p = subprocess.Popen(["cygpath", path], stdout=subprocess.PIPE)
        path = p.communicate()[0].decode("utf-8").strip()
    return path


def _DetectVisualStudioVersions(versions_to_check, force_express):
    """Collect the list of installed visual studio versions.

  Returns:
    A list of visual studio versions installed in descending order of
    usage preference.
    Base this on the registry and a quick check if devenv.exe exists.
    Possibilities are:
      2005(e) - Visual Studio 2005 (8)
      2008(e) - Visual Studio 2008 (9)
      2010(e) - Visual Studio 2010 (10)
      2012(e) - Visual Studio 2012 (11)
      2013(e) - Visual Studio 2013 (12)
      2015    - Visual Studio 2015 (14)
      2017    - Visual Studio 2017 (15)
      2019    - Visual Studio 2019 (16)
      2022    - Visual Studio 2022 (17)
    Where (e) is e for express editions of MSVS and blank otherwise.
  """
    version_to_year = {
        "8.0": "2005",
        "9.0": "2008",
        "10.0": "2010",
        "11.0": "2012",
        "12.0": "2013",
        "14.0": "2015",
        "15.0": "2017",
        "16.0": "2019",
        "17.0": "2022",
    }
    versions = []
    for version in versions_to_check:
        # Old method of searching for which VS version is installed
        # We don't use the 2010-encouraged-way because we also want to get the
        # path to the binaries, which it doesn't offer.
        keys = [
            r"HKLM\Software\Microsoft\VisualStudio\%s" % version,
            r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s" % version,
            r"HKLM\Software\Microsoft\VCExpress\%s" % version,
            r"HKLM\Software\Wow6432Node\Microsoft\VCExpress\%s" % version,
        ]
        for index in range(len(keys)):
            path = _RegistryGetValue(keys[index], "InstallDir")
            if not path:
                continue
            path = _ConvertToCygpath(path)
            # Check for full.
            full_path = os.path.join(path, "devenv.exe")
            express_path = os.path.join(path, "*express.exe")
            if not force_express and os.path.exists(full_path):
                # Add this one.
                versions.append(
                    _CreateVersion(
                        version_to_year[version], os.path.join(path, "..", "..")
                    )
                )
            # Check for express.
            elif glob.glob(express_path):
                # Add this one.
                versions.append(
                    _CreateVersion(
                        version_to_year[version] + "e", os.path.join(path, "..", "..")
                    )
                )

        # The old method above does not work when only SDK is installed.
        keys = [
            r"HKLM\Software\Microsoft\VisualStudio\SxS\VC7",
            r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VC7",
            r"HKLM\Software\Microsoft\VisualStudio\SxS\VS7",
            r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VS7",
        ]
        for index in range(len(keys)):
            path = _RegistryGetValue(keys[index], version)
            if not path:
                continue
            path = _ConvertToCygpath(path)
            if version == "15.0":
                if os.path.exists(path):
                    versions.append(_CreateVersion("2017", path))
            elif version != "14.0":  # There is no Express edition for 2015.
                versions.append(
                    _CreateVersion(
                        version_to_year[version] + "e",
                        os.path.join(path, ".."),
                        sdk_based=True,
                    )
                )

    return versions


def SelectVisualStudioVersion(version="auto", allow_fallback=True):
    """Select which version of Visual Studio projects to generate.

  Arguments:
    version: Hook to allow caller to force a particular version (vs auto).
  Returns:
    An object representing a visual studio project format version.
  """
    # In auto mode, check environment variable for override.
    if version == "auto":
        version = os.environ.get("GYP_MSVS_VERSION", "auto")
    version_map = {
        "auto": ("17.0", "16.0", "15.0", "14.0", "12.0", "10.0", "9.0", "8.0", "11.0"),
        "2005": ("8.0",),
        "2005e": ("8.0",),
        "2008": ("9.0",),
        "2008e": ("9.0",),
        "2010": ("10.0",),
        "2010e": ("10.0",),
        "2012": ("11.0",),
        "2012e": ("11.0",),
        "2013": ("12.0",),
        "2013e": ("12.0",),
        "2015": ("14.0",),
        "2017": ("15.0",),
        "2019": ("16.0",),
        "2022": ("17.0",),
    }
    override_path = os.environ.get("GYP_MSVS_OVERRIDE_PATH")
    if override_path:
        msvs_version = os.environ.get("GYP_MSVS_VERSION")
        if not msvs_version:
            raise ValueError(
                "GYP_MSVS_OVERRIDE_PATH requires GYP_MSVS_VERSION to be "
                "set to a particular version (e.g. 2010e)."
            )
        return _CreateVersion(msvs_version, override_path, sdk_based=True)
    version = str(version)
    versions = _DetectVisualStudioVersions(version_map[version], "e" in version)
    if not versions:
        if not allow_fallback:
            raise ValueError("Could not locate Visual Studio installation.")
        if version == "auto":
            # Default to 2005 if we couldn't find anything
            return _CreateVersion("2005", None)
        else:
            return _CreateVersion(version, None)
    return versions[0]
#!/usr/bin/env python3

# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.


import copy
import gyp.input
import argparse
import os.path
import re
import shlex
import sys
import traceback
from gyp.common import GypError


# Default debug modes for GYP
debug = {}

# List of "official" debug modes, but you can use anything you like.
DEBUG_GENERAL = "general"
DEBUG_VARIABLES = "variables"
DEBUG_INCLUDES = "includes"


def DebugOutput(mode, message, *args):
    if "all" in gyp.debug or mode in gyp.debug:
        ctx = ("unknown", 0, "unknown")
        try:
            f = traceback.extract_stack(limit=2)
            if f:
                ctx = f[0][:3]
        except Exception:
            pass
        if args:
            message %= args
        print(
            "%s:%s:%d:%s %s"
            % (mode.upper(), os.path.basename(ctx[0]), ctx[1], ctx[2], message)
        )


def FindBuildFiles():
    extension = ".gyp"
    files = os.listdir(os.getcwd())
    build_files = []
    for file in files:
        if file.endswith(extension):
            build_files.append(file)
    return build_files


def Load(
    build_files,
    format,
    default_variables={},
    includes=[],
    depth=".",
    params=None,
    check=False,
    circular_check=True,
):
    """
  Loads one or more specified build files.
  default_variables and includes will be copied before use.
  Returns the generator for the specified format and the
  data returned by loading the specified build files.
  """
    if params is None:
        params = {}

    if "-" in format:
        format, params["flavor"] = format.split("-", 1)

    default_variables = copy.copy(default_variables)

    # Default variables provided by this program and its modules should be
    # named WITH_CAPITAL_LETTERS to provide a distinct "best practice" namespace,
    # avoiding collisions with user and automatic variables.
    default_variables["GENERATOR"] = format
    default_variables["GENERATOR_FLAVOR"] = params.get("flavor", "")

    # Format can be a custom python file, or by default the name of a module
    # within gyp.generator.
    if format.endswith(".py"):
        generator_name = os.path.splitext(format)[0]
        path, generator_name = os.path.split(generator_name)

        # Make sure the path to the custom generator is in sys.path
        # Don't worry about removing it once we are done.  Keeping the path
        # to each generator that is used in sys.path is likely harmless and
        # arguably a good idea.
        path = os.path.abspath(path)
        if path not in sys.path:
            sys.path.insert(0, path)
    else:
        generator_name = "gyp.generator." + format

    # These parameters are passed in order (as opposed to by key)
    # because ActivePython cannot handle key parameters to __import__.
    generator = __import__(generator_name, globals(), locals(), generator_name)
    for (key, val) in generator.generator_default_variables.items():
        default_variables.setdefault(key, val)

    output_dir = params["options"].generator_output or params["options"].toplevel_dir
    if default_variables["GENERATOR"] == "ninja":
        default_variables.setdefault(
            "PRODUCT_DIR_ABS",
            os.path.join(
                output_dir, "out", default_variables.get("build_type", "default")
            ),
        )
    else:
        default_variables.setdefault(
            "PRODUCT_DIR_ABS",
            os.path.join(output_dir, default_variables["CONFIGURATION_NAME"]),
        )

    # Give the generator the opportunity to set additional variables based on
    # the params it will receive in the output phase.
    if getattr(generator, "CalculateVariables", None):
        generator.CalculateVariables(default_variables, params)

    # Give the generator the opportunity to set generator_input_info based on
    # the params it will receive in the output phase.
    if getattr(generator, "CalculateGeneratorInputInfo", None):
        generator.CalculateGeneratorInputInfo(params)

    # Fetch the generator specific info that gets fed to input, we use getattr
    # so we can default things and the generators only have to provide what
    # they need.
    generator_input_info = {
        "non_configuration_keys": getattr(
            generator, "generator_additional_non_configuration_keys", []
        ),
        "path_sections": getattr(generator, "generator_additional_path_sections", []),
        "extra_sources_for_rules": getattr(
            generator, "generator_extra_sources_for_rules", []
        ),
        "generator_supports_multiple_toolsets": getattr(
            generator, "generator_supports_multiple_toolsets", False
        ),
        "generator_wants_static_library_dependencies_adjusted": getattr(
            generator, "generator_wants_static_library_dependencies_adjusted", True
        ),
        "generator_wants_sorted_dependencies": getattr(
            generator, "generator_wants_sorted_dependencies", False
        ),
        "generator_filelist_paths": getattr(
            generator, "generator_filelist_paths", None
        ),
    }

    # Process the input specific to this generator.
    result = gyp.input.Load(
        build_files,
        default_variables,
        includes[:],
        depth,
        generator_input_info,
        check,
        circular_check,
        params["parallel"],
        params["root_targets"],
    )
    return [generator] + result


def NameValueListToDict(name_value_list):
    """
  Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary
  of the pairs.  If a string is simply NAME, then the value in the dictionary
  is set to True.  If VALUE can be converted to an integer, it is.
  """
    result = {}
    for item in name_value_list:
        tokens = item.split("=", 1)
        if len(tokens) == 2:
            # If we can make it an int, use that, otherwise, use the string.
            try:
                token_value = int(tokens[1])
            except ValueError:
                token_value = tokens[1]
            # Set the variable to the supplied value.
            result[tokens[0]] = token_value
        else:
            # No value supplied, treat it as a boolean and set it.
            result[tokens[0]] = True
    return result


def ShlexEnv(env_name):
    flags = os.environ.get(env_name, [])
    if flags:
        flags = shlex.split(flags)
    return flags


def FormatOpt(opt, value):
    if opt.startswith("--"):
        return f"{opt}={value}"
    return opt + value


def RegenerateAppendFlag(flag, values, predicate, env_name, options):
    """Regenerate a list of command line flags, for an option of action='append'.

  The |env_name|, if given, is checked in the environment and used to generate
  an initial list of options, then the options that were specified on the
  command line (given in |values|) are appended.  This matches the handling of
  environment variables and command line flags where command line flags override
  the environment, while not requiring the environment to be set when the flags
  are used again.
  """
    flags = []
    if options.use_environment and env_name:
        for flag_value in ShlexEnv(env_name):
            value = FormatOpt(flag, predicate(flag_value))
            if value in flags:
                flags.remove(value)
            flags.append(value)
    if values:
        for flag_value in values:
            flags.append(FormatOpt(flag, predicate(flag_value)))
    return flags


def RegenerateFlags(options):
    """Given a parsed options object, and taking the environment variables into
  account, returns a list of flags that should regenerate an equivalent options
  object (even in the absence of the environment variables.)

  Any path options will be normalized relative to depth.

  The format flag is not included, as it is assumed the calling generator will
  set that as appropriate.
  """

    def FixPath(path):
        path = gyp.common.FixIfRelativePath(path, options.depth)
        if not path:
            return os.path.curdir
        return path

    def Noop(value):
        return value

    # We always want to ignore the environment when regenerating, to avoid
    # duplicate or changed flags in the environment at the time of regeneration.
    flags = ["--ignore-environment"]
    for name, metadata in options._regeneration_metadata.items():
        opt = metadata["opt"]
        value = getattr(options, name)
        value_predicate = metadata["type"] == "path" and FixPath or Noop
        action = metadata["action"]
        env_name = metadata["env_name"]
        if action == "append":
            flags.extend(
                RegenerateAppendFlag(opt, value, value_predicate, env_name, options)
            )
        elif action in ("store", None):  # None is a synonym for 'store'.
            if value:
                flags.append(FormatOpt(opt, value_predicate(value)))
            elif options.use_environment and env_name and os.environ.get(env_name):
                flags.append(FormatOpt(opt, value_predicate(os.environ.get(env_name))))
        elif action in ("store_true", "store_false"):
            if (action == "store_true" and value) or (
                action == "store_false" and not value
            ):
                flags.append(opt)
            elif options.use_environment and env_name:
                print(
                    "Warning: environment regeneration unimplemented "
                    "for %s flag %r env_name %r" % (action, opt, env_name),
                    file=sys.stderr,
                )
        else:
            print(
                "Warning: regeneration unimplemented for action %r "
                "flag %r" % (action, opt),
                file=sys.stderr,
            )

    return flags


class RegeneratableOptionParser(argparse.ArgumentParser):
    def __init__(self, usage):
        self.__regeneratable_options = {}
        argparse.ArgumentParser.__init__(self, usage=usage)

    def add_argument(self, *args, **kw):
        """Add an option to the parser.

    This accepts the same arguments as ArgumentParser.add_argument, plus the
    following:
      regenerate: can be set to False to prevent this option from being included
                  in regeneration.
      env_name: name of environment variable that additional values for this
                option come from.
      type: adds type='path', to tell the regenerator that the values of
            this option need to be made relative to options.depth
    """
        env_name = kw.pop("env_name", None)
        if "dest" in kw and kw.pop("regenerate", True):
            dest = kw["dest"]

            # The path type is needed for regenerating, for optparse we can just treat
            # it as a string.
            type = kw.get("type")
            if type == "path":
                kw["type"] = str

            self.__regeneratable_options[dest] = {
                "action": kw.get("action"),
                "type": type,
                "env_name": env_name,
                "opt": args[0],
            }

        argparse.ArgumentParser.add_argument(self, *args, **kw)

    def parse_args(self, *args):
        values, args = argparse.ArgumentParser.parse_known_args(self, *args)
        values._regeneration_metadata = self.__regeneratable_options
        return values, args


def gyp_main(args):
    my_name = os.path.basename(sys.argv[0])
    usage = "usage: %(prog)s [options ...] [build_file ...]"

    parser = RegeneratableOptionParser(usage=usage.replace("%s", "%(prog)s"))
    parser.add_argument(
        "--build",
        dest="configs",
        action="append",
        help="configuration for build after project generation",
    )
    parser.add_argument(
        "--check", dest="check", action="store_true", help="check format of gyp files"
    )
    parser.add_argument(
        "--config-dir",
        dest="config_dir",
        action="store",
        env_name="GYP_CONFIG_DIR",
        default=None,
        help="The location for configuration files like " "include.gypi.",
    )
    parser.add_argument(
        "-d",
        "--debug",
        dest="debug",
        metavar="DEBUGMODE",
        action="append",
        default=[],
        help="turn on a debugging "
        'mode for debugging GYP.  Supported modes are "variables", '
        '"includes" and "general" or "all" for all of them.',
    )
    parser.add_argument(
        "-D",
        dest="defines",
        action="append",
        metavar="VAR=VAL",
        env_name="GYP_DEFINES",
        help="sets variable VAR to value VAL",
    )
    parser.add_argument(
        "--depth",
        dest="depth",
        metavar="PATH",
        type="path",
        help="set DEPTH gyp variable to a relative path to PATH",
    )
    parser.add_argument(
        "-f",
        "--format",
        dest="formats",
        action="append",
        env_name="GYP_GENERATORS",
        regenerate=False,
        help="output formats to generate",
    )
    parser.add_argument(
        "-G",
        dest="generator_flags",
        action="append",
        default=[],
        metavar="FLAG=VAL",
        env_name="GYP_GENERATOR_FLAGS",
        help="sets generator flag FLAG to VAL",
    )
    parser.add_argument(
        "--generator-output",
        dest="generator_output",
        action="store",
        default=None,
        metavar="DIR",
        type="path",
        env_name="GYP_GENERATOR_OUTPUT",
        help="puts generated build files under DIR",
    )
    parser.add_argument(
        "--ignore-environment",
        dest="use_environment",
        action="store_false",
        default=True,
        regenerate=False,
        help="do not read options from environment variables",
    )
    parser.add_argument(
        "-I",
        "--include",
        dest="includes",
        action="append",
        metavar="INCLUDE",
        type="path",
        help="files to include in all loaded .gyp files",
    )
    # --no-circular-check disables the check for circular relationships between
    # .gyp files.  These relationships should not exist, but they've only been
    # observed to be harmful with the Xcode generator.  Chromium's .gyp files
    # currently have some circular relationships on non-Mac platforms, so this
    # option allows the strict behavior to be used on Macs and the lenient
    # behavior to be used elsewhere.
    # TODO(mark): Remove this option when http://crbug.com/35878 is fixed.
    parser.add_argument(
        "--no-circular-check",
        dest="circular_check",
        action="store_false",
        default=True,
        regenerate=False,
        help="don't check for circular relationships between files",
    )
    parser.add_argument(
        "--no-parallel",
        action="store_true",
        default=False,
        help="Disable multiprocessing",
    )
    parser.add_argument(
        "-S",
        "--suffix",
        dest="suffix",
        default="",
        help="suffix to add to generated files",
    )
    parser.add_argument(
        "--toplevel-dir",
        dest="toplevel_dir",
        action="store",
        default=None,
        metavar="DIR",
        type="path",
        help="directory to use as the root of the source tree",
    )
    parser.add_argument(
        "-R",
        "--root-target",
        dest="root_targets",
        action="append",
        metavar="TARGET",
        help="include only TARGET and its deep dependencies",
    )
    parser.add_argument(
        "-V",
        "--version",
        dest="version",
        action="store_true",
        help="Show the version and exit.",
    )

    options, build_files_arg = parser.parse_args(args)
    if options.version:
        import pkg_resources
        print(f"v{pkg_resources.get_distribution('gyp-next').version}")
        return 0
    build_files = build_files_arg

    # Set up the configuration directory (defaults to ~/.gyp)
    if not options.config_dir:
        home = None
        home_dot_gyp = None
        if options.use_environment:
            home_dot_gyp = os.environ.get("GYP_CONFIG_DIR", None)
            if home_dot_gyp:
                home_dot_gyp = os.path.expanduser(home_dot_gyp)

        if not home_dot_gyp:
            home_vars = ["HOME"]
            if sys.platform in ("cygwin", "win32"):
                home_vars.append("USERPROFILE")
            for home_var in home_vars:
                home = os.getenv(home_var)
                if home:
                    home_dot_gyp = os.path.join(home, ".gyp")
                    if not os.path.exists(home_dot_gyp):
                        home_dot_gyp = None
                    else:
                        break
    else:
        home_dot_gyp = os.path.expanduser(options.config_dir)

    if home_dot_gyp and not os.path.exists(home_dot_gyp):
        home_dot_gyp = None

    if not options.formats:
        # If no format was given on the command line, then check the env variable.
        generate_formats = []
        if options.use_environment:
            generate_formats = os.environ.get("GYP_GENERATORS", [])
        if generate_formats:
            generate_formats = re.split(r"[\s,]", generate_formats)
        if generate_formats:
            options.formats = generate_formats
        else:
            # Nothing in the variable, default based on platform.
            if sys.platform == "darwin":
                options.formats = ["xcode"]
            elif sys.platform in ("win32", "cygwin"):
                options.formats = ["msvs"]
            else:
                options.formats = ["make"]

    if not options.generator_output and options.use_environment:
        g_o = os.environ.get("GYP_GENERATOR_OUTPUT")
        if g_o:
            options.generator_output = g_o

    options.parallel = not options.no_parallel

    for mode in options.debug:
        gyp.debug[mode] = 1

    # Do an extra check to avoid work when we're not debugging.
    if DEBUG_GENERAL in gyp.debug:
        DebugOutput(DEBUG_GENERAL, "running with these options:")
        for option, value in sorted(options.__dict__.items()):
            if option[0] == "_":
                continue
            if isinstance(value, str):
                DebugOutput(DEBUG_GENERAL, "  %s: '%s'", option, value)
            else:
                DebugOutput(DEBUG_GENERAL, "  %s: %s", option, value)

    if not build_files:
        build_files = FindBuildFiles()
    if not build_files:
        raise GypError((usage + "\n\n%s: error: no build_file") % (my_name, my_name))

    # TODO(mark): Chromium-specific hack!
    # For Chromium, the gyp "depth" variable should always be a relative path
    # to Chromium's top-level "src" directory.  If no depth variable was set
    # on the command line, try to find a "src" directory by looking at the
    # absolute path to each build file's directory.  The first "src" component
    # found will be treated as though it were the path used for --depth.
    if not options.depth:
        for build_file in build_files:
            build_file_dir = os.path.abspath(os.path.dirname(build_file))
            build_file_dir_components = build_file_dir.split(os.path.sep)
            components_len = len(build_file_dir_components)
            for index in range(components_len - 1, -1, -1):
                if build_file_dir_components[index] == "src":
                    options.depth = os.path.sep.join(build_file_dir_components)
                    break
                del build_file_dir_components[index]

            # If the inner loop found something, break without advancing to another
            # build file.
            if options.depth:
                break

        if not options.depth:
            raise GypError(
                "Could not automatically locate src directory.  This is"
                "a temporary Chromium feature that will be removed.  Use"
                "--depth as a workaround."
            )

    # If toplevel-dir is not set, we assume that depth is the root of our source
    # tree.
    if not options.toplevel_dir:
        options.toplevel_dir = options.depth

    # -D on the command line sets variable defaults - D isn't just for define,
    # it's for default.  Perhaps there should be a way to force (-F?) a
    # variable's value so that it can't be overridden by anything else.
    cmdline_default_variables = {}
    defines = []
    if options.use_environment:
        defines += ShlexEnv("GYP_DEFINES")
    if options.defines:
        defines += options.defines
    cmdline_default_variables = NameValueListToDict(defines)
    if DEBUG_GENERAL in gyp.debug:
        DebugOutput(
            DEBUG_GENERAL, "cmdline_default_variables: %s", cmdline_default_variables
        )

    # Set up includes.
    includes = []

    # If ~/.gyp/include.gypi exists, it'll be forcibly included into every
    # .gyp file that's loaded, before anything else is included.
    if home_dot_gyp:
        default_include = os.path.join(home_dot_gyp, "include.gypi")
        if os.path.exists(default_include):
            print("Using overrides found in " + default_include)
            includes.append(default_include)

    # Command-line --include files come after the default include.
    if options.includes:
        includes.extend(options.includes)

    # Generator flags should be prefixed with the target generator since they
    # are global across all generator runs.
    gen_flags = []
    if options.use_environment:
        gen_flags += ShlexEnv("GYP_GENERATOR_FLAGS")
    if options.generator_flags:
        gen_flags += options.generator_flags
    generator_flags = NameValueListToDict(gen_flags)
    if DEBUG_GENERAL in gyp.debug:
        DebugOutput(DEBUG_GENERAL, "generator_flags: %s", generator_flags)

    # Generate all requested formats (use a set in case we got one format request
    # twice)
    for format in set(options.formats):
        params = {
            "options": options,
            "build_files": build_files,
            "generator_flags": generator_flags,
            "cwd": os.getcwd(),
            "build_files_arg": build_files_arg,
            "gyp_binary": sys.argv[0],
            "home_dot_gyp": home_dot_gyp,
            "parallel": options.parallel,
            "root_targets": options.root_targets,
            "target_arch": cmdline_default_variables.get("target_arch", ""),
        }

        # Start with the default variables from the command line.
        [generator, flat_list, targets, data] = Load(
            build_files,
            format,
            cmdline_default_variables,
            includes,
            options.depth,
            params,
            options.check,
            options.circular_check,
        )

        # TODO(mark): Pass |data| for now because the generator needs a list of
        # build files that came in.  In the future, maybe it should just accept
        # a list, and not the whole data dict.
        # NOTE: flat_list is the flattened dependency graph specifying the order
        # that targets may be built.  Build systems that operate serially or that
        # need to have dependencies defined before dependents reference them should
        # generate targets in the order specified in flat_list.
        generator.GenerateOutput(flat_list, targets, data, params)

        if options.configs:
            valid_configs = targets[flat_list[0]]["configurations"]
            for conf in options.configs:
                if conf not in valid_configs:
                    raise GypError("Invalid config specified via --build: %s" % conf)
            generator.PerformBuild(data, options.configs, params)

    # Done
    return 0


def main(args):
    try:
        return gyp_main(args)
    except GypError as e:
        sys.stderr.write("gyp: %s\n" % e)
        return 1


# NOTE: setuptools generated console_scripts calls function with no arguments
def script_main():
    return main(sys.argv[1:])


if __name__ == "__main__":
    sys.exit(script_main())
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import errno
import filecmp
import os.path
import re
import tempfile
import sys
import subprocess
import shlex

from collections.abc import MutableSet


# A minimal memoizing decorator. It'll blow up if the args aren't immutable,
# among other "problems".
class memoize:
    def __init__(self, func):
        self.func = func
        self.cache = {}

    def __call__(self, *args):
        try:
            return self.cache[args]
        except KeyError:
            result = self.func(*args)
            self.cache[args] = result
            return result


class GypError(Exception):
    """Error class representing an error, which is to be presented
  to the user.  The main entry point will catch and display this.
  """

    pass


def ExceptionAppend(e, msg):
    """Append a message to the given exception's message."""
    if not e.args:
        e.args = (msg,)
    elif len(e.args) == 1:
        e.args = (str(e.args[0]) + " " + msg,)
    else:
        e.args = (str(e.args[0]) + " " + msg,) + e.args[1:]


def FindQualifiedTargets(target, qualified_list):
    """
  Given a list of qualified targets, return the qualified targets for the
  specified |target|.
  """
    return [t for t in qualified_list if ParseQualifiedTarget(t)[1] == target]


def ParseQualifiedTarget(target):
    # Splits a qualified target into a build file, target name and toolset.

    # NOTE: rsplit is used to disambiguate the Windows drive letter separator.
    target_split = target.rsplit(":", 1)
    if len(target_split) == 2:
        [build_file, target] = target_split
    else:
        build_file = None

    target_split = target.rsplit("#", 1)
    if len(target_split) == 2:
        [target, toolset] = target_split
    else:
        toolset = None

    return [build_file, target, toolset]


def ResolveTarget(build_file, target, toolset):
    # This function resolves a target into a canonical form:
    # - a fully defined build file, either absolute or relative to the current
    # directory
    # - a target name
    # - a toolset
    #
    # build_file is the file relative to which 'target' is defined.
    # target is the qualified target.
    # toolset is the default toolset for that target.
    [parsed_build_file, target, parsed_toolset] = ParseQualifiedTarget(target)

    if parsed_build_file:
        if build_file:
            # If a relative path, parsed_build_file is relative to the directory
            # containing build_file.  If build_file is not in the current directory,
            # parsed_build_file is not a usable path as-is.  Resolve it by
            # interpreting it as relative to build_file.  If parsed_build_file is
            # absolute, it is usable as a path regardless of the current directory,
            # and os.path.join will return it as-is.
            build_file = os.path.normpath(
                os.path.join(os.path.dirname(build_file), parsed_build_file)
            )
            # Further (to handle cases like ../cwd), make it relative to cwd)
            if not os.path.isabs(build_file):
                build_file = RelativePath(build_file, ".")
        else:
            build_file = parsed_build_file

    if parsed_toolset:
        toolset = parsed_toolset

    return [build_file, target, toolset]


def BuildFile(fully_qualified_target):
    # Extracts the build file from the fully qualified target.
    return ParseQualifiedTarget(fully_qualified_target)[0]


def GetEnvironFallback(var_list, default):
    """Look up a key in the environment, with fallback to secondary keys
  and finally falling back to a default value."""
    for var in var_list:
        if var in os.environ:
            return os.environ[var]
    return default


def QualifiedTarget(build_file, target, toolset):
    # "Qualified" means the file that a target was defined in and the target
    # name, separated by a colon, suffixed by a # and the toolset name:
    # /path/to/file.gyp:target_name#toolset
    fully_qualified = build_file + ":" + target
    if toolset:
        fully_qualified = fully_qualified + "#" + toolset
    return fully_qualified


@memoize
def RelativePath(path, relative_to, follow_path_symlink=True):
    # Assuming both |path| and |relative_to| are relative to the current
    # directory, returns a relative path that identifies path relative to
    # relative_to.
    # If |follow_symlink_path| is true (default) and |path| is a symlink, then
    # this method returns a path to the real file represented by |path|. If it is
    # false, this method returns a path to the symlink. If |path| is not a
    # symlink, this option has no effect.

    # Convert to normalized (and therefore absolute paths).
    path = os.path.realpath(path) if follow_path_symlink else os.path.abspath(path)
    relative_to = os.path.realpath(relative_to)

    # On Windows, we can't create a relative path to a different drive, so just
    # use the absolute path.
    if sys.platform == "win32" and (
        os.path.splitdrive(path)[0].lower()
        != os.path.splitdrive(relative_to)[0].lower()
    ):
        return path

    # Split the paths into components.
    path_split = path.split(os.path.sep)
    relative_to_split = relative_to.split(os.path.sep)

    # Determine how much of the prefix the two paths share.
    prefix_len = len(os.path.commonprefix([path_split, relative_to_split]))

    # Put enough ".." components to back up out of relative_to to the common
    # prefix, and then append the part of path_split after the common prefix.
    relative_split = [os.path.pardir] * (
        len(relative_to_split) - prefix_len
    ) + path_split[prefix_len:]

    if len(relative_split) == 0:
        # The paths were the same.
        return ""

    # Turn it back into a string and we're done.
    return os.path.join(*relative_split)


@memoize
def InvertRelativePath(path, toplevel_dir=None):
    """Given a path like foo/bar that is relative to toplevel_dir, return
  the inverse relative path back to the toplevel_dir.

  E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path)))
  should always produce the empty string, unless the path contains symlinks.
  """
    if not path:
        return path
    toplevel_dir = "." if toplevel_dir is None else toplevel_dir
    return RelativePath(toplevel_dir, os.path.join(toplevel_dir, path))


def FixIfRelativePath(path, relative_to):
    # Like RelativePath but returns |path| unchanged if it is absolute.
    if os.path.isabs(path):
        return path
    return RelativePath(path, relative_to)


def UnrelativePath(path, relative_to):
    # Assuming that |relative_to| is relative to the current directory, and |path|
    # is a path relative to the dirname of |relative_to|, returns a path that
    # identifies |path| relative to the current directory.
    rel_dir = os.path.dirname(relative_to)
    return os.path.normpath(os.path.join(rel_dir, path))


# re objects used by EncodePOSIXShellArgument.  See IEEE 1003.1 XCU.2.2 at
# http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_02
# and the documentation for various shells.

# _quote is a pattern that should match any argument that needs to be quoted
# with double-quotes by EncodePOSIXShellArgument.  It matches the following
# characters appearing anywhere in an argument:
#   \t, \n, space  parameter separators
#   #              comments
#   $              expansions (quoted to always expand within one argument)
#   %              called out by IEEE 1003.1 XCU.2.2
#   &              job control
#   '              quoting
#   (, )           subshell execution
#   *, ?, [        pathname expansion
#   ;              command delimiter
#   <, >, |        redirection
#   =              assignment
#   {, }           brace expansion (bash)
#   ~              tilde expansion
# It also matches the empty string, because "" (or '') is the only way to
# represent an empty string literal argument to a POSIX shell.
#
# This does not match the characters in _escape, because those need to be
# backslash-escaped regardless of whether they appear in a double-quoted
# string.
_quote = re.compile("[\t\n #$%&'()*;<=>?[{|}~]|^$")

# _escape is a pattern that should match any character that needs to be
# escaped with a backslash, whether or not the argument matched the _quote
# pattern.  _escape is used with re.sub to backslash anything in _escape's
# first match group, hence the (parentheses) in the regular expression.
#
# _escape matches the following characters appearing anywhere in an argument:
#   "  to prevent POSIX shells from interpreting this character for quoting
#   \  to prevent POSIX shells from interpreting this character for escaping
#   `  to prevent POSIX shells from interpreting this character for command
#      substitution
# Missing from this list is $, because the desired behavior of
# EncodePOSIXShellArgument is to permit parameter (variable) expansion.
#
# Also missing from this list is !, which bash will interpret as the history
# expansion character when history is enabled.  bash does not enable history
# by default in non-interactive shells, so this is not thought to be a problem.
# ! was omitted from this list because bash interprets "\!" as a literal string
# including the backslash character (avoiding history expansion but retaining
# the backslash), which would not be correct for argument encoding.  Handling
# this case properly would also be problematic because bash allows the history
# character to be changed with the histchars shell variable.  Fortunately,
# as history is not enabled in non-interactive shells and
# EncodePOSIXShellArgument is only expected to encode for non-interactive
# shells, there is no room for error here by ignoring !.
_escape = re.compile(r'(["\\`])')


def EncodePOSIXShellArgument(argument):
    """Encodes |argument| suitably for consumption by POSIX shells.

  argument may be quoted and escaped as necessary to ensure that POSIX shells
  treat the returned value as a literal representing the argument passed to
  this function.  Parameter (variable) expansions beginning with $ are allowed
  to remain intact without escaping the $, to allow the argument to contain
  references to variables to be expanded by the shell.
  """

    if not isinstance(argument, str):
        argument = str(argument)

    quote = '"' if _quote.search(argument) else ""

    encoded = quote + re.sub(_escape, r"\\\1", argument) + quote

    return encoded


def EncodePOSIXShellList(list):
    """Encodes |list| suitably for consumption by POSIX shells.

  Returns EncodePOSIXShellArgument for each item in list, and joins them
  together using the space character as an argument separator.
  """

    encoded_arguments = []
    for argument in list:
        encoded_arguments.append(EncodePOSIXShellArgument(argument))
    return " ".join(encoded_arguments)


def DeepDependencyTargets(target_dicts, roots):
    """Returns the recursive list of target dependencies."""
    dependencies = set()
    pending = set(roots)
    while pending:
        # Pluck out one.
        r = pending.pop()
        # Skip if visited already.
        if r in dependencies:
            continue
        # Add it.
        dependencies.add(r)
        # Add its children.
        spec = target_dicts[r]
        pending.update(set(spec.get("dependencies", [])))
        pending.update(set(spec.get("dependencies_original", [])))
    return list(dependencies - set(roots))


def BuildFileTargets(target_list, build_file):
    """From a target_list, returns the subset from the specified build_file.
  """
    return [p for p in target_list if BuildFile(p) == build_file]


def AllTargets(target_list, target_dicts, build_file):
    """Returns all targets (direct and dependencies) for the specified build_file.
  """
    bftargets = BuildFileTargets(target_list, build_file)
    deptargets = DeepDependencyTargets(target_dicts, bftargets)
    return bftargets + deptargets


def WriteOnDiff(filename):
    """Write to a file only if the new contents differ.

  Arguments:
    filename: name of the file to potentially write to.
  Returns:
    A file like object which will write to temporary file and only overwrite
    the target if it differs (on close).
  """

    class Writer:
        """Wrapper around file which only covers the target if it differs."""

        def __init__(self):
            # On Cygwin remove the "dir" argument
            # `C:` prefixed paths are treated as relative,
            # consequently ending up with current dir "/cygdrive/c/..."
            # being prefixed to those, which was
            # obviously a non-existent path,
            # for example: "/cygdrive/c//C:\".
            # For more details see:
            # https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp
            base_temp_dir = "" if IsCygwin() else os.path.dirname(filename)
            # Pick temporary file.
            tmp_fd, self.tmp_path = tempfile.mkstemp(
                suffix=".tmp",
                prefix=os.path.split(filename)[1] + ".gyp.",
                dir=base_temp_dir,
            )
            try:
                self.tmp_file = os.fdopen(tmp_fd, "wb")
            except Exception:
                # Don't leave turds behind.
                os.unlink(self.tmp_path)
                raise

        def __getattr__(self, attrname):
            # Delegate everything else to self.tmp_file
            return getattr(self.tmp_file, attrname)

        def close(self):
            try:
                # Close tmp file.
                self.tmp_file.close()
                # Determine if different.
                same = False
                try:
                    same = filecmp.cmp(self.tmp_path, filename, False)
                except OSError as e:
                    if e.errno != errno.ENOENT:
                        raise

                if same:
                    # The new file is identical to the old one, just get rid of the new
                    # one.
                    os.unlink(self.tmp_path)
                else:
                    # The new file is different from the old one,
                    # or there is no old one.
                    # Rename the new file to the permanent name.
                    #
                    # tempfile.mkstemp uses an overly restrictive mode, resulting in a
                    # file that can only be read by the owner, regardless of the umask.
                    # There's no reason to not respect the umask here,
                    # which means that an extra hoop is required
                    # to fetch it and reset the new file's mode.
                    #
                    # No way to get the umask without setting a new one?  Set a safe one
                    # and then set it back to the old value.
                    umask = os.umask(0o77)
                    os.umask(umask)
                    os.chmod(self.tmp_path, 0o666 & ~umask)
                    if sys.platform == "win32" and os.path.exists(filename):
                        # NOTE: on windows (but not cygwin) rename will not replace an
                        # existing file, so it must be preceded with a remove.
                        # Sadly there is no way to make the switch atomic.
                        os.remove(filename)
                    os.rename(self.tmp_path, filename)
            except Exception:
                # Don't leave turds behind.
                os.unlink(self.tmp_path)
                raise

        def write(self, s):
            self.tmp_file.write(s.encode("utf-8"))

    return Writer()


def EnsureDirExists(path):
    """Make sure the directory for |path| exists."""
    try:
        os.makedirs(os.path.dirname(path))
    except OSError:
        pass

def GetCrossCompilerPredefines():  # -> dict
    cmd = []

    # shlex.split() will eat '\' in posix mode, but
    # setting posix=False will preserve extra '"' cause CreateProcess fail on Windows
    # this makes '\' in %CC_target% and %CFLAGS% work
    def replace_sep(s):
        return s.replace(os.sep, "/") if os.sep != "/" else s

    if CC := os.environ.get("CC_target") or os.environ.get("CC"):
        cmd += shlex.split(replace_sep(CC))
        if CFLAGS := os.environ.get("CFLAGS"):
            cmd += shlex.split(replace_sep(CFLAGS))
    elif CXX := os.environ.get("CXX_target") or os.environ.get("CXX"):
        cmd += shlex.split(replace_sep(CXX))
        if CXXFLAGS := os.environ.get("CXXFLAGS"):
            cmd += shlex.split(replace_sep(CXXFLAGS))
    else:
        return {}

    if sys.platform == "win32":
        fd, input = tempfile.mkstemp(suffix=".c")
        real_cmd = [*cmd, "-dM", "-E", "-x", "c", input]
        try:
            os.close(fd)
            stdout = subprocess.run(
                real_cmd, shell=True,
                capture_output=True, check=True
            ).stdout
        finally:
            os.unlink(input)
    else:
        input = "/dev/null"
        real_cmd = [*cmd, "-dM", "-E", "-x", "c", input]
        stdout = subprocess.run(
            real_cmd, shell=False,
            capture_output=True, check=True
        ).stdout

    defines = {}
    lines = stdout.decode("utf-8").replace("\r\n", "\n").split("\n")
    for line in lines:
        if (line or "").startswith("#define "):
            _, key, *value = line.split(" ")
            defines[key] = " ".join(value)
    return defines

def GetFlavorByPlatform():
    """Returns |params.flavor| if it's set, the system's default flavor else."""
    flavors = {
        "cygwin": "win",
        "win32": "win",
        "darwin": "mac",
    }

    if sys.platform in flavors:
        return flavors[sys.platform]
    if sys.platform.startswith("sunos"):
        return "solaris"
    if sys.platform.startswith(("dragonfly", "freebsd")):
        return "freebsd"
    if sys.platform.startswith("openbsd"):
        return "openbsd"
    if sys.platform.startswith("netbsd"):
        return "netbsd"
    if sys.platform.startswith("aix"):
        return "aix"
    if sys.platform.startswith(("os390", "zos")):
        return "zos"
    if sys.platform == "os400":
        return "os400"

    return "linux"

def GetFlavor(params):
    if "flavor" in params:
        return params["flavor"]

    defines = GetCrossCompilerPredefines()
    if "__EMSCRIPTEN__" in defines:
        return "emscripten"
    if "__wasm__" in defines:
        return "wasi" if "__wasi__" in defines else "wasm"

    return GetFlavorByPlatform()


def CopyTool(flavor, out_path, generator_flags={}):
    """Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
  to |out_path|."""
    # aix and solaris just need flock emulation. mac and win use more complicated
    # support scripts.
    prefix = {
        "aix": "flock",
        "os400": "flock",
        "solaris": "flock",
        "mac": "mac",
        "ios": "mac",
        "win": "win",
    }.get(flavor, None)
    if not prefix:
        return

    # Slurp input file.
    source_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "%s_tool.py" % prefix
    )
    with open(source_path) as source_file:
        source = source_file.readlines()

    # Set custom header flags.
    header = "# Generated by gyp. Do not edit.\n"
    mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None)
    if flavor == "mac" and mac_toolchain_dir:
        header += "import os;\nos.environ['DEVELOPER_DIR']='%s'\n" % mac_toolchain_dir

    # Add header and write it out.
    tool_path = os.path.join(out_path, "gyp-%s-tool" % prefix)
    with open(tool_path, "w") as tool_file:
        tool_file.write("".join([source[0], header] + source[1:]))

    # Make file executable.
    os.chmod(tool_path, 0o755)


# From Alex Martelli,
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
# ASPN: Python Cookbook: Remove duplicates from a sequence
# First comment, dated 2001/10/13.
# (Also in the printed Python Cookbook.)


def uniquer(seq, idfun=lambda x: x):
    seen = {}
    result = []
    for item in seq:
        marker = idfun(item)
        if marker in seen:
            continue
        seen[marker] = 1
        result.append(item)
    return result


# Based on http://code.activestate.com/recipes/576694/.
class OrderedSet(MutableSet):
    def __init__(self, iterable=None):
        self.end = end = []
        end += [None, end, end]  # sentinel node for doubly linked list
        self.map = {}  # key --> [key, prev, next]
        if iterable is not None:
            self |= iterable

    def __len__(self):
        return len(self.map)

    def __contains__(self, key):
        return key in self.map

    def add(self, key):
        if key not in self.map:
            end = self.end
            curr = end[1]
            curr[2] = end[1] = self.map[key] = [key, curr, end]

    def discard(self, key):
        if key in self.map:
            key, prev_item, next_item = self.map.pop(key)
            prev_item[2] = next_item
            next_item[1] = prev_item

    def __iter__(self):
        end = self.end
        curr = end[2]
        while curr is not end:
            yield curr[0]
            curr = curr[2]

    def __reversed__(self):
        end = self.end
        curr = end[1]
        while curr is not end:
            yield curr[0]
            curr = curr[1]

    # The second argument is an addition that causes a pylint warning.
    def pop(self, last=True):  # pylint: disable=W0221
        if not self:
            raise KeyError("set is empty")
        key = self.end[1][0] if last else self.end[2][0]
        self.discard(key)
        return key

    def __repr__(self):
        if not self:
            return f"{self.__class__.__name__}()"
        return f"{self.__class__.__name__}({list(self)!r})"

    def __eq__(self, other):
        if isinstance(other, OrderedSet):
            return len(self) == len(other) and list(self) == list(other)
        return set(self) == set(other)

    # Extensions to the recipe.
    def update(self, iterable):
        for i in iterable:
            if i not in self:
                self.add(i)


class CycleError(Exception):
    """An exception raised when an unexpected cycle is detected."""

    def __init__(self, nodes):
        self.nodes = nodes

    def __str__(self):
        return "CycleError: cycle involving: " + str(self.nodes)


def TopologicallySorted(graph, get_edges):
    r"""Topologically sort based on a user provided edge definition.

  Args:
    graph: A list of node names.
    get_edges: A function mapping from node name to a hashable collection
               of node names which this node has outgoing edges to.
  Returns:
    A list containing all of the node in graph in topological order.
    It is assumed that calling get_edges once for each node and caching is
    cheaper than repeatedly calling get_edges.
  Raises:
    CycleError in the event of a cycle.
  Example:
    graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'}
    def GetEdges(node):
      return re.findall(r'\$\(([^))]\)', graph[node])
    print TopologicallySorted(graph.keys(), GetEdges)
    ==>
    ['a', 'c', b']
  """
    get_edges = memoize(get_edges)
    visited = set()
    visiting = set()
    ordered_nodes = []

    def Visit(node):
        if node in visiting:
            raise CycleError(visiting)
        if node in visited:
            return
        visited.add(node)
        visiting.add(node)
        for neighbor in get_edges(node):
            Visit(neighbor)
        visiting.remove(node)
        ordered_nodes.insert(0, node)

    for node in sorted(graph):
        Visit(node)
    return ordered_nodes


def CrossCompileRequested():
    # TODO: figure out how to not build extra host objects in the
    # non-cross-compile case when this is enabled, and enable unconditionally.
    return (
        os.environ.get("GYP_CROSSCOMPILE")
        or os.environ.get("AR_host")
        or os.environ.get("CC_host")
        or os.environ.get("CXX_host")
        or os.environ.get("AR_target")
        or os.environ.get("CC_target")
        or os.environ.get("CXX_target")
    )


def IsCygwin():
    try:
        out = subprocess.Popen(
            "uname", stdout=subprocess.PIPE, stderr=subprocess.STDOUT
        )
        stdout = out.communicate()[0].decode("utf-8")
        return "CYGWIN" in str(stdout)
    except Exception:
        return False
#!/usr/bin/env python3

# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Unit tests for the common.py file."""

import gyp.common
import unittest
import sys
import os
from unittest.mock import patch, MagicMock

class TestTopologicallySorted(unittest.TestCase):
    def test_Valid(self):
        """Test that sorting works on a valid graph with one possible order."""
        graph = {
            "a": ["b", "c"],
            "b": [],
            "c": ["d"],
            "d": ["b"],
        }

        def GetEdge(node):
            return tuple(graph[node])

        assert gyp.common.TopologicallySorted(
            graph.keys(), GetEdge) == ["a", "c", "d", "b"]

    def test_Cycle(self):
        """Test that an exception is thrown on a cyclic graph."""
        graph = {
            "a": ["b"],
            "b": ["c"],
            "c": ["d"],
            "d": ["a"],
        }

        def GetEdge(node):
            return tuple(graph[node])

        self.assertRaises(
            gyp.common.CycleError, gyp.common.TopologicallySorted, graph.keys(), GetEdge
        )


class TestGetFlavor(unittest.TestCase):
    """Test that gyp.common.GetFlavor works as intended"""

    original_platform = ""

    def setUp(self):
        self.original_platform = sys.platform

    def tearDown(self):
        sys.platform = self.original_platform

    def assertFlavor(self, expected, argument, param):
        sys.platform = argument
        assert expected == gyp.common.GetFlavor(param)

    def test_platform_default(self):
        self.assertFlavor("freebsd", "freebsd9", {})
        self.assertFlavor("freebsd", "freebsd10", {})
        self.assertFlavor("openbsd", "openbsd5", {})
        self.assertFlavor("solaris", "sunos5", {})
        self.assertFlavor("solaris", "sunos", {})
        self.assertFlavor("linux", "linux2", {})
        self.assertFlavor("linux", "linux3", {})
        self.assertFlavor("linux", "linux", {})

    def test_param(self):
        self.assertFlavor("foobar", "linux2", {"flavor": "foobar"})

    class MockCommunicate:
        def __init__(self, stdout):
            self.stdout = stdout

        def decode(self, encoding):
            return self.stdout

    @patch("os.close")
    @patch("os.unlink")
    @patch("tempfile.mkstemp")
    def test_GetCrossCompilerPredefines(self, mock_mkstemp, mock_unlink, mock_close):
        mock_close.return_value = None
        mock_unlink.return_value = None
        mock_mkstemp.return_value = (0, "temp.c")

        def mock_run(env, defines_stdout, expected_cmd):
            with patch("subprocess.run") as mock_run:
                mock_process = MagicMock()
                mock_process.returncode = 0
                mock_process.stdout = TestGetFlavor.MockCommunicate(defines_stdout)
                mock_run.return_value = mock_process
                expected_input = "temp.c" if sys.platform == "win32" else "/dev/null"
                with patch.dict(os.environ, env):
                    defines = gyp.common.GetCrossCompilerPredefines()
                    flavor = gyp.common.GetFlavor({})
                if env.get("CC_target"):
                    mock_run.assert_called_with(
                        [
                            *expected_cmd,
                            "-dM", "-E", "-x", "c", expected_input
                        ],
                        shell=sys.platform == "win32",
                        capture_output=True, check=True)
                return [defines, flavor]

        [defines1, _] = mock_run({}, "", [])
        assert {} == defines1

        [defines2, flavor2] = mock_run(
            { "CC_target": "/opt/wasi-sdk/bin/clang" },
            "#define __wasm__ 1\n#define __wasi__ 1\n",
            ["/opt/wasi-sdk/bin/clang"]
        )
        assert { "__wasm__": "1", "__wasi__": "1" } == defines2
        assert flavor2 == "wasi"

        [defines3, flavor3] = mock_run(
            { "CC_target": "/opt/wasi-sdk/bin/clang --target=wasm32" },
            "#define __wasm__ 1\n",
            ["/opt/wasi-sdk/bin/clang", "--target=wasm32"]
        )
        assert { "__wasm__": "1" } == defines3
        assert flavor3 == "wasm"

        [defines4, flavor4] = mock_run(
            { "CC_target": "/emsdk/upstream/emscripten/emcc" },
            "#define __EMSCRIPTEN__ 1\n",
            ["/emsdk/upstream/emscripten/emcc"]
        )
        assert { "__EMSCRIPTEN__": "1" } == defines4
        assert flavor4 == "emscripten"

        # Test path which include white space
        [defines5, flavor5] = mock_run(
            {
                "CC_target": "\"/Users/Toyo Li/wasi-sdk/bin/clang\" -O3",
                "CFLAGS": "--target=wasm32-wasi-threads -pthread"
            },
            "#define __wasm__ 1\n#define __wasi__ 1\n#define _REENTRANT 1\n",
            [
                "/Users/Toyo Li/wasi-sdk/bin/clang",
                "-O3",
                "--target=wasm32-wasi-threads",
                "-pthread"
            ]
        )
        assert {
            "__wasm__": "1",
            "__wasi__": "1",
            "_REENTRANT": "1"
        } == defines5
        assert flavor5 == "wasi"

        original_sep = os.sep
        os.sep = "\\"
        [defines6, flavor6] = mock_run(
            { "CC_target": "\"C:\\Program Files\\wasi-sdk\\clang.exe\"" },
            "#define __wasm__ 1\n#define __wasi__ 1\n",
            ["C:/Program Files/wasi-sdk/clang.exe"]
        )
        os.sep = original_sep
        assert { "__wasm__": "1", "__wasi__": "1" } == defines6
        assert flavor6 == "wasi"

if __name__ == "__main__":
    unittest.main()
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import sys
import re
import os
import locale
from functools import reduce


def XmlToString(content, encoding="utf-8", pretty=False):
    """ Writes the XML content to disk, touching the file only if it has changed.

  Visual Studio files have a lot of pre-defined structures.  This function makes
  it easy to represent these structures as Python data structures, instead of
  having to create a lot of function calls.

  Each XML element of the content is represented as a list composed of:
  1. The name of the element, a string,
  2. The attributes of the element, a dictionary (optional), and
  3+. The content of the element, if any.  Strings are simple text nodes and
      lists are child elements.

  Example 1:
      
  becomes
      ['test']

  Example 2:
      
         This is
         it!
      

  becomes
      ['myelement', {'a':'value1', 'b':'value2'},
         ['childtype', 'This is'],
         ['childtype', 'it!'],
      ]

  Args:
    content:  The structured content to be converted.
    encoding: The encoding to report on the first XML line.
    pretty: True if we want pretty printing with indents and new lines.

  Returns:
    The XML content as a string.
  """
    # We create a huge list of all the elements of the file.
    xml_parts = ['' % encoding]
    if pretty:
        xml_parts.append("\n")
    _ConstructContentList(xml_parts, content, pretty)

    # Convert it to a string
    return "".join(xml_parts)


def _ConstructContentList(xml_parts, specification, pretty, level=0):
    """ Appends the XML parts corresponding to the specification.

  Args:
    xml_parts: A list of XML parts to be appended to.
    specification:  The specification of the element.  See EasyXml docs.
    pretty: True if we want pretty printing with indents and new lines.
    level: Indentation level.
  """
    # The first item in a specification is the name of the element.
    if pretty:
        indentation = "  " * level
        new_line = "\n"
    else:
        indentation = ""
        new_line = ""
    name = specification[0]
    if not isinstance(name, str):
        raise Exception(
            "The first item of an EasyXml specification should be "
            "a string.  Specification was " + str(specification)
        )
    xml_parts.append(indentation + "<" + name)

    # Optionally in second position is a dictionary of the attributes.
    rest = specification[1:]
    if rest and isinstance(rest[0], dict):
        for at, val in sorted(rest[0].items()):
            xml_parts.append(f' {at}="{_XmlEscape(val, attr=True)}"')
        rest = rest[1:]
    if rest:
        xml_parts.append(">")
        all_strings = reduce(lambda x, y: x and isinstance(y, str), rest, True)
        multi_line = not all_strings
        if multi_line and new_line:
            xml_parts.append(new_line)
        for child_spec in rest:
            # If it's a string, append a text node.
            # Otherwise recurse over that child definition
            if isinstance(child_spec, str):
                xml_parts.append(_XmlEscape(child_spec))
            else:
                _ConstructContentList(xml_parts, child_spec, pretty, level + 1)
        if multi_line and indentation:
            xml_parts.append(indentation)
        xml_parts.append(f"{new_line}")
    else:
        xml_parts.append("/>%s" % new_line)


def WriteXmlIfChanged(content, path, encoding="utf-8", pretty=False,
                      win32=(sys.platform == "win32")):
    """ Writes the XML content to disk, touching the file only if it has changed.

  Args:
    content:  The structured content to be written.
    path: Location of the file.
    encoding: The encoding to report on the first line of the XML file.
    pretty: True if we want pretty printing with indents and new lines.
  """
    xml_string = XmlToString(content, encoding, pretty)
    if win32 and os.linesep != "\r\n":
        xml_string = xml_string.replace("\n", "\r\n")

    try:  # getdefaultlocale() was removed in Python 3.11
        default_encoding = locale.getdefaultlocale()[1]
    except AttributeError:
        default_encoding = locale.getencoding()

    if default_encoding and default_encoding.upper() != encoding.upper():
        xml_string = xml_string.encode(encoding)

    # Get the old content
    try:
        with open(path) as file:
            existing = file.read()
    except OSError:
        existing = None

    # It has changed, write it
    if existing != xml_string:
        with open(path, "wb") as file:
            file.write(xml_string)


_xml_escape_map = {
    '"': """,
    "'": "'",
    "<": "<",
    ">": ">",
    "&": "&",
    "\n": "
",
    "\r": "
",
}


_xml_escape_re = re.compile("(%s)" % "|".join(map(re.escape, _xml_escape_map.keys())))


def _XmlEscape(value, attr=False):
    """ Escape a string for inclusion in XML."""

    def replace(match):
        m = match.string[match.start() : match.end()]
        # don't replace single quotes in attrs
        if attr and m == "'":
            return m
        return _xml_escape_map[m]

    return _xml_escape_re.sub(replace, value)
#!/usr/bin/env python3

# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

""" Unit tests for the easy_xml.py file. """

import gyp.easy_xml as easy_xml
import unittest

from io import StringIO


class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.stderr = StringIO()

    def test_EasyXml_simple(self):
        self.assertEqual(
            easy_xml.XmlToString(["test"]),
            '',
        )

        self.assertEqual(
            easy_xml.XmlToString(["test"], encoding="Windows-1252"),
            '',
        )

    def test_EasyXml_simple_with_attributes(self):
        self.assertEqual(
            easy_xml.XmlToString(["test2", {"a": "value1", "b": "value2"}]),
            '',
        )

    def test_EasyXml_escaping(self):
        original = "'\"\r&\nfoo"
        converted = "<test>'"
&
foo"
        converted_apos = converted.replace("'", "'")
        self.assertEqual(
            easy_xml.XmlToString(["test3", {"a": original}, original]),
            '%s'
            % (converted, converted_apos),
        )

    def test_EasyXml_pretty(self):
        self.assertEqual(
            easy_xml.XmlToString(
                ["test3", ["GrandParent", ["Parent1", ["Child"]], ["Parent2"]]],
                pretty=True,
            ),
            '\n'
            "\n"
            "  \n"
            "    \n"
            "      \n"
            "    \n"
            "    \n"
            "  \n"
            "\n",
        )

    def test_EasyXml_complex(self):
        # We want to create:
        target = (
            ''
            ""
            ''
            "{D2250C20-3A94-4FB9-AF73-11BC5B73884B}"
            "Win32Proj"
            "automated_ui_tests"
            ""
            ''
            "'
            "Application"
            "Unicode"
            "SpectreLoadCF"
            "14.36.32532"
            ""
            ""
        )

        xml = easy_xml.XmlToString(
            [
                "Project",
                [
                    "PropertyGroup",
                    {"Label": "Globals"},
                    ["ProjectGuid", "{D2250C20-3A94-4FB9-AF73-11BC5B73884B}"],
                    ["Keyword", "Win32Proj"],
                    ["RootNamespace", "automated_ui_tests"],
                ],
                ["Import", {"Project": "$(VCTargetsPath)\\Microsoft.Cpp.props"}],
                [
                    "PropertyGroup",
                    {
                        "Condition": "'$(Configuration)|$(Platform)'=='Debug|Win32'",
                        "Label": "Configuration",
                    },
                    ["ConfigurationType", "Application"],
                    ["CharacterSet", "Unicode"],
                    ["SpectreMitigation", "SpectreLoadCF"],
                    ["VCToolsVersion", "14.36.32532"],
                ],
            ]
        )
        self.assertEqual(xml, target)


if __name__ == "__main__":
    unittest.main()
#!/usr/bin/env python3
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""These functions are executed via gyp-flock-tool when using the Makefile
generator.  Used on systems that don't have a built-in flock."""

import fcntl
import os
import struct
import subprocess
import sys


def main(args):
    executor = FlockTool()
    executor.Dispatch(args)


class FlockTool:
    """This class emulates the 'flock' command."""

    def Dispatch(self, args):
        """Dispatches a string command to a method."""
        if len(args) < 1:
            raise Exception("Not enough arguments")

        method = "Exec%s" % self._CommandifyName(args[0])
        getattr(self, method)(*args[1:])

    def _CommandifyName(self, name_string):
        """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
        return name_string.title().replace("-", "")

    def ExecFlock(self, lockfile, *cmd_list):
        """Emulates the most basic behavior of Linux's flock(1)."""
        # Rely on exception handling to report errors.
        # Note that the stock python on SunOS has a bug
        # where fcntl.flock(fd, LOCK_EX) always fails
        # with EBADF, that's why we use this F_SETLK
        # hack instead.
        fd = os.open(lockfile, os.O_WRONLY | os.O_NOCTTY | os.O_CREAT, 0o666)
        if sys.platform.startswith("aix") or sys.platform == "os400":
            # Python on AIX is compiled with LARGEFILE support, which changes the
            # struct size.
            op = struct.pack("hhIllqq", fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
        else:
            op = struct.pack("hhllhhl", fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
        fcntl.fcntl(fd, fcntl.F_SETLK, op)
        return subprocess.call(cmd_list)


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
This script is intended for use as a GYP_GENERATOR. It takes as input (by way of
the generator flag config_path) the path of a json file that dictates the files
and targets to search for. The following keys are supported:
files: list of paths (relative) of the files to search for.
test_targets: unqualified target names to search for. Any target in this list
that depends upon a file in |files| is output regardless of the type of target
or chain of dependencies.
additional_compile_targets: Unqualified targets to search for in addition to
test_targets. Targets in the combined list that depend upon a file in |files|
are not necessarily output. For example, if the target is of type none then the
target is not output (but one of the descendants of the target will be).

The following is output:
error: only supplied if there is an error.
compile_targets: minimal set of targets that directly or indirectly (for
  targets of type none) depend on the files in |files| and is one of the
  supplied targets or a target that one of the supplied targets depends on.
  The expectation is this set of targets is passed into a build step. This list
  always contains the output of test_targets as well.
test_targets: set of targets from the supplied |test_targets| that either
  directly or indirectly depend upon a file in |files|. This list if useful
  if additional processing needs to be done for certain targets after the
  build, such as running tests.
status: outputs one of three values: none of the supplied files were found,
  one of the include files changed so that it should be assumed everything
  changed (in this case test_targets and compile_targets are not output) or at
  least one file was found.
invalid_targets: list of supplied targets that were not found.

Example:
Consider a graph like the following:
  A     D
 / \
B   C
A depends upon both B and C, A is of type none and B and C are executables.
D is an executable, has no dependencies and nothing depends on it.
If |additional_compile_targets| = ["A"], |test_targets| = ["B", "C"] and
files = ["b.cc", "d.cc"] (B depends upon b.cc and D depends upon d.cc), then
the following is output:
|compile_targets| = ["B"] B must built as it depends upon the changed file b.cc
and the supplied target A depends upon it. A is not output as a build_target
as it is of type none with no rules and actions.
|test_targets| = ["B"] B directly depends upon the change file b.cc.

Even though the file d.cc, which D depends upon, has changed D is not output
as it was not supplied by way of |additional_compile_targets| or |test_targets|.

If the generator flag analyzer_output_path is specified, output is written
there. Otherwise output is written to stdout.

In Gyp the "all" target is shorthand for the root targets in the files passed
to gyp. For example, if file "a.gyp" contains targets "a1" and
"a2", and file "b.gyp" contains targets "b1" and "b2" and "a2" has a dependency
on "b2" and gyp is supplied "a.gyp" then "all" consists of "a1" and "a2".
Notice that "b1" and "b2" are not in the "all" target as "b.gyp" was not
directly supplied to gyp. OTOH if both "a.gyp" and "b.gyp" are supplied to gyp
then the "all" target includes "b1" and "b2".
"""


import gyp.common
import json
import os
import posixpath

debug = False

found_dependency_string = "Found dependency"
no_dependency_string = "No dependencies"
# Status when it should be assumed that everything has changed.
all_changed_string = "Found dependency (all)"

# MatchStatus is used indicate if and how a target depends upon the supplied
# sources.
# The target's sources contain one of the supplied paths.
MATCH_STATUS_MATCHES = 1
# The target has a dependency on another target that contains one of the
# supplied paths.
MATCH_STATUS_MATCHES_BY_DEPENDENCY = 2
# The target's sources weren't in the supplied paths and none of the target's
# dependencies depend upon a target that matched.
MATCH_STATUS_DOESNT_MATCH = 3
# The target doesn't contain the source, but the dependent targets have not yet
# been visited to determine a more specific status yet.
MATCH_STATUS_TBD = 4

generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested()

generator_wants_static_library_dependencies_adjusted = False

generator_default_variables = {}
for dirname in [
    "INTERMEDIATE_DIR",
    "SHARED_INTERMEDIATE_DIR",
    "PRODUCT_DIR",
    "LIB_DIR",
    "SHARED_LIB_DIR",
]:
    generator_default_variables[dirname] = "!!!"

for unused in [
    "RULE_INPUT_PATH",
    "RULE_INPUT_ROOT",
    "RULE_INPUT_NAME",
    "RULE_INPUT_DIRNAME",
    "RULE_INPUT_EXT",
    "EXECUTABLE_PREFIX",
    "EXECUTABLE_SUFFIX",
    "STATIC_LIB_PREFIX",
    "STATIC_LIB_SUFFIX",
    "SHARED_LIB_PREFIX",
    "SHARED_LIB_SUFFIX",
    "CONFIGURATION_NAME",
]:
    generator_default_variables[unused] = ""


def _ToGypPath(path):
    """Converts a path to the format used by gyp."""
    if os.sep == "\\" and os.altsep == "/":
        return path.replace("\\", "/")
    return path


def _ResolveParent(path, base_path_components):
    """Resolves |path|, which starts with at least one '../'. Returns an empty
  string if the path shouldn't be considered. See _AddSources() for a
  description of |base_path_components|."""
    depth = 0
    while path.startswith("../"):
        depth += 1
        path = path[3:]
    # Relative includes may go outside the source tree. For example, an action may
    # have inputs in /usr/include, which are not in the source tree.
    if depth > len(base_path_components):
        return ""
    if depth == len(base_path_components):
        return path
    return (
        "/".join(base_path_components[0 : len(base_path_components) - depth])
        + "/"
        + path
    )


def _AddSources(sources, base_path, base_path_components, result):
    """Extracts valid sources from |sources| and adds them to |result|. Each
  source file is relative to |base_path|, but may contain '..'. To make
  resolving '..' easier |base_path_components| contains each of the
  directories in |base_path|. Additionally each source may contain variables.
  Such sources are ignored as it is assumed dependencies on them are expressed
  and tracked in some other means."""
    # NOTE: gyp paths are always posix style.
    for source in sources:
        if not len(source) or source.startswith("!!!") or source.startswith("$"):
            continue
        # variable expansion may lead to //.
        org_source = source
        source = source[0] + source[1:].replace("//", "/")
        if source.startswith("../"):
            source = _ResolveParent(source, base_path_components)
            if len(source):
                result.append(source)
            continue
        result.append(base_path + source)
        if debug:
            print("AddSource", org_source, result[len(result) - 1])


def _ExtractSourcesFromAction(action, base_path, base_path_components, results):
    if "inputs" in action:
        _AddSources(action["inputs"], base_path, base_path_components, results)


def _ToLocalPath(toplevel_dir, path):
    """Converts |path| to a path relative to |toplevel_dir|."""
    if path == toplevel_dir:
        return ""
    if path.startswith(toplevel_dir + "/"):
        return path[len(toplevel_dir) + len("/") :]
    return path


def _ExtractSources(target, target_dict, toplevel_dir):
    # |target| is either absolute or relative and in the format of the OS. Gyp
    # source paths are always posix. Convert |target| to a posix path relative to
    # |toplevel_dir_|. This is done to make it easy to build source paths.
    base_path = posixpath.dirname(_ToLocalPath(toplevel_dir, _ToGypPath(target)))
    base_path_components = base_path.split("/")

    # Add a trailing '/' so that _AddSources() can easily build paths.
    if len(base_path):
        base_path += "/"

    if debug:
        print("ExtractSources", target, base_path)

    results = []
    if "sources" in target_dict:
        _AddSources(target_dict["sources"], base_path, base_path_components, results)
    # Include the inputs from any actions. Any changes to these affect the
    # resulting output.
    if "actions" in target_dict:
        for action in target_dict["actions"]:
            _ExtractSourcesFromAction(action, base_path, base_path_components, results)
    if "rules" in target_dict:
        for rule in target_dict["rules"]:
            _ExtractSourcesFromAction(rule, base_path, base_path_components, results)

    return results


class Target:
    """Holds information about a particular target:
  deps: set of Targets this Target depends upon. This is not recursive, only the
    direct dependent Targets.
  match_status: one of the MatchStatus values.
  back_deps: set of Targets that have a dependency on this Target.
  visited: used during iteration to indicate whether we've visited this target.
    This is used for two iterations, once in building the set of Targets and
    again in _GetBuildTargets().
  name: fully qualified name of the target.
  requires_build: True if the target type is such that it needs to be built.
    See _DoesTargetTypeRequireBuild for details.
  added_to_compile_targets: used when determining if the target was added to the
    set of targets that needs to be built.
  in_roots: true if this target is a descendant of one of the root nodes.
  is_executable: true if the type of target is executable.
  is_static_library: true if the type of target is static_library.
  is_or_has_linked_ancestor: true if the target does a link (eg executable), or
    if there is a target in back_deps that does a link."""

    def __init__(self, name):
        self.deps = set()
        self.match_status = MATCH_STATUS_TBD
        self.back_deps = set()
        self.name = name
        # TODO(sky): I don't like hanging this off Target. This state is specific
        # to certain functions and should be isolated there.
        self.visited = False
        self.requires_build = False
        self.added_to_compile_targets = False
        self.in_roots = False
        self.is_executable = False
        self.is_static_library = False
        self.is_or_has_linked_ancestor = False


class Config:
    """Details what we're looking for
  files: set of files to search for
  targets: see file description for details."""

    def __init__(self):
        self.files = []
        self.targets = set()
        self.additional_compile_target_names = set()
        self.test_target_names = set()

    def Init(self, params):
        """Initializes Config. This is a separate method as it raises an exception
    if there is a parse error."""
        generator_flags = params.get("generator_flags", {})
        config_path = generator_flags.get("config_path", None)
        if not config_path:
            return
        try:
            f = open(config_path)
            config = json.load(f)
            f.close()
        except OSError:
            raise Exception("Unable to open file " + config_path)
        except ValueError as e:
            raise Exception("Unable to parse config file " + config_path + str(e))
        if not isinstance(config, dict):
            raise Exception("config_path must be a JSON file containing a dictionary")
        self.files = config.get("files", [])
        self.additional_compile_target_names = set(
            config.get("additional_compile_targets", [])
        )
        self.test_target_names = set(config.get("test_targets", []))


def _WasBuildFileModified(build_file, data, files, toplevel_dir):
    """Returns true if the build file |build_file| is either in |files| or
  one of the files included by |build_file| is in |files|. |toplevel_dir| is
  the root of the source tree."""
    if _ToLocalPath(toplevel_dir, _ToGypPath(build_file)) in files:
        if debug:
            print("gyp file modified", build_file)
        return True

    # First element of included_files is the file itself.
    if len(data[build_file]["included_files"]) <= 1:
        return False

    for include_file in data[build_file]["included_files"][1:]:
        # |included_files| are relative to the directory of the |build_file|.
        rel_include_file = _ToGypPath(
            gyp.common.UnrelativePath(include_file, build_file)
        )
        if _ToLocalPath(toplevel_dir, rel_include_file) in files:
            if debug:
                print(
                    "included gyp file modified, gyp_file=",
                    build_file,
                    "included file=",
                    rel_include_file,
                )
            return True
    return False


def _GetOrCreateTargetByName(targets, target_name):
    """Creates or returns the Target at targets[target_name]. If there is no
  Target for |target_name| one is created. Returns a tuple of whether a new
  Target was created and the Target."""
    if target_name in targets:
        return False, targets[target_name]
    target = Target(target_name)
    targets[target_name] = target
    return True, target


def _DoesTargetTypeRequireBuild(target_dict):
    """Returns true if the target type is such that it needs to be built."""
    # If a 'none' target has rules or actions we assume it requires a build.
    return bool(
        target_dict["type"] != "none"
        or target_dict.get("actions")
        or target_dict.get("rules")
    )


def _GenerateTargets(data, target_list, target_dicts, toplevel_dir, files, build_files):
    """Returns a tuple of the following:
  . A dictionary mapping from fully qualified name to Target.
  . A list of the targets that have a source file in |files|.
  . Targets that constitute the 'all' target. See description at top of file
    for details on the 'all' target.
  This sets the |match_status| of the targets that contain any of the source
  files in |files| to MATCH_STATUS_MATCHES.
  |toplevel_dir| is the root of the source tree."""
    # Maps from target name to Target.
    name_to_target = {}

    # Targets that matched.
    matching_targets = []

    # Queue of targets to visit.
    targets_to_visit = target_list[:]

    # Maps from build file to a boolean indicating whether the build file is in
    # |files|.
    build_file_in_files = {}

    # Root targets across all files.
    roots = set()

    # Set of Targets in |build_files|.
    build_file_targets = set()

    while len(targets_to_visit) > 0:
        target_name = targets_to_visit.pop()
        created_target, target = _GetOrCreateTargetByName(name_to_target, target_name)
        if created_target:
            roots.add(target)
        elif target.visited:
            continue

        target.visited = True
        target.requires_build = _DoesTargetTypeRequireBuild(target_dicts[target_name])
        target_type = target_dicts[target_name]["type"]
        target.is_executable = target_type == "executable"
        target.is_static_library = target_type == "static_library"
        target.is_or_has_linked_ancestor = (
            target_type in {"executable", "shared_library"}
        )

        build_file = gyp.common.ParseQualifiedTarget(target_name)[0]
        if build_file not in build_file_in_files:
            build_file_in_files[build_file] = _WasBuildFileModified(
                build_file, data, files, toplevel_dir
            )

        if build_file in build_files:
            build_file_targets.add(target)

        # If a build file (or any of its included files) is modified we assume all
        # targets in the file are modified.
        if build_file_in_files[build_file]:
            print("matching target from modified build file", target_name)
            target.match_status = MATCH_STATUS_MATCHES
            matching_targets.append(target)
        else:
            sources = _ExtractSources(
                target_name, target_dicts[target_name], toplevel_dir
            )
            for source in sources:
                if _ToGypPath(os.path.normpath(source)) in files:
                    print("target", target_name, "matches", source)
                    target.match_status = MATCH_STATUS_MATCHES
                    matching_targets.append(target)
                    break

        # Add dependencies to visit as well as updating back pointers for deps.
        for dep in target_dicts[target_name].get("dependencies", []):
            targets_to_visit.append(dep)

            created_dep_target, dep_target = _GetOrCreateTargetByName(
                name_to_target, dep
            )
            if not created_dep_target:
                roots.discard(dep_target)

            target.deps.add(dep_target)
            dep_target.back_deps.add(target)

    return name_to_target, matching_targets, roots & build_file_targets


def _GetUnqualifiedToTargetMapping(all_targets, to_find):
    """Returns a tuple of the following:
  . mapping (dictionary) from unqualified name to Target for all the
    Targets in |to_find|.
  . any target names not found. If this is empty all targets were found."""
    result = {}
    if not to_find:
        return {}, []
    to_find = set(to_find)
    for target_name in all_targets:
        extracted = gyp.common.ParseQualifiedTarget(target_name)
        if len(extracted) > 1 and extracted[1] in to_find:
            to_find.remove(extracted[1])
            result[extracted[1]] = all_targets[target_name]
            if not to_find:
                return result, []
    return result, list(to_find)


def _DoesTargetDependOnMatchingTargets(target):
    """Returns true if |target| or any of its dependencies is one of the
  targets containing the files supplied as input to analyzer. This updates
  |matches| of the Targets as it recurses.
  target: the Target to look for."""
    if target.match_status == MATCH_STATUS_DOESNT_MATCH:
        return False
    if (
        target.match_status in {MATCH_STATUS_MATCHES,
                                MATCH_STATUS_MATCHES_BY_DEPENDENCY}
    ):
        return True
    for dep in target.deps:
        if _DoesTargetDependOnMatchingTargets(dep):
            target.match_status = MATCH_STATUS_MATCHES_BY_DEPENDENCY
            print("\t", target.name, "matches by dep", dep.name)
            return True
    target.match_status = MATCH_STATUS_DOESNT_MATCH
    return False


def _GetTargetsDependingOnMatchingTargets(possible_targets):
    """Returns the list of Targets in |possible_targets| that depend (either
  directly on indirectly) on at least one of the targets containing the files
  supplied as input to analyzer.
  possible_targets: targets to search from."""
    found = []
    print("Targets that matched by dependency:")
    for target in possible_targets:
        if _DoesTargetDependOnMatchingTargets(target):
            found.append(target)
    return found


def _AddCompileTargets(target, roots, add_if_no_ancestor, result):
    """Recurses through all targets that depend on |target|, adding all targets
  that need to be built (and are in |roots|) to |result|.
  roots: set of root targets.
  add_if_no_ancestor: If true and there are no ancestors of |target| then add
  |target| to |result|. |target| must still be in |roots|.
  result: targets that need to be built are added here."""
    if target.visited:
        return

    target.visited = True
    target.in_roots = target in roots

    for back_dep_target in target.back_deps:
        _AddCompileTargets(back_dep_target, roots, False, result)
        target.added_to_compile_targets |= back_dep_target.added_to_compile_targets
        target.in_roots |= back_dep_target.in_roots
        target.is_or_has_linked_ancestor |= back_dep_target.is_or_has_linked_ancestor

    # Always add 'executable' targets. Even though they may be built by other
    # targets that depend upon them it makes detection of what is going to be
    # built easier.
    # And always add static_libraries that have no dependencies on them from
    # linkables. This is necessary as the other dependencies on them may be
    # static libraries themselves, which are not compile time dependencies.
    if target.in_roots and (
        target.is_executable
        or (
            not target.added_to_compile_targets
            and (add_if_no_ancestor or target.requires_build)
        )
        or (
            target.is_static_library
            and add_if_no_ancestor
            and not target.is_or_has_linked_ancestor
        )
    ):
        print(
            "\t\tadding to compile targets",
            target.name,
            "executable",
            target.is_executable,
            "added_to_compile_targets",
            target.added_to_compile_targets,
            "add_if_no_ancestor",
            add_if_no_ancestor,
            "requires_build",
            target.requires_build,
            "is_static_library",
            target.is_static_library,
            "is_or_has_linked_ancestor",
            target.is_or_has_linked_ancestor,
        )
        result.add(target)
        target.added_to_compile_targets = True


def _GetCompileTargets(matching_targets, supplied_targets):
    """Returns the set of Targets that require a build.
  matching_targets: targets that changed and need to be built.
  supplied_targets: set of targets supplied to analyzer to search from."""
    result = set()
    for target in matching_targets:
        print("finding compile targets for match", target.name)
        _AddCompileTargets(target, supplied_targets, True, result)
    return result


def _WriteOutput(params, **values):
    """Writes the output, either to stdout or a file is specified."""
    if "error" in values:
        print("Error:", values["error"])
    if "status" in values:
        print(values["status"])
    if "targets" in values:
        values["targets"].sort()
        print("Supplied targets that depend on changed files:")
        for target in values["targets"]:
            print("\t", target)
    if "invalid_targets" in values:
        values["invalid_targets"].sort()
        print("The following targets were not found:")
        for target in values["invalid_targets"]:
            print("\t", target)
    if "build_targets" in values:
        values["build_targets"].sort()
        print("Targets that require a build:")
        for target in values["build_targets"]:
            print("\t", target)
    if "compile_targets" in values:
        values["compile_targets"].sort()
        print("Targets that need to be built:")
        for target in values["compile_targets"]:
            print("\t", target)
    if "test_targets" in values:
        values["test_targets"].sort()
        print("Test targets:")
        for target in values["test_targets"]:
            print("\t", target)

    output_path = params.get("generator_flags", {}).get("analyzer_output_path", None)
    if not output_path:
        print(json.dumps(values))
        return
    try:
        f = open(output_path, "w")
        f.write(json.dumps(values) + "\n")
        f.close()
    except OSError as e:
        print("Error writing to output file", output_path, str(e))


def _WasGypIncludeFileModified(params, files):
    """Returns true if one of the files in |files| is in the set of included
  files."""
    if params["options"].includes:
        for include in params["options"].includes:
            if _ToGypPath(os.path.normpath(include)) in files:
                print("Include file modified, assuming all changed", include)
                return True
    return False


def _NamesNotIn(names, mapping):
    """Returns a list of the values in |names| that are not in |mapping|."""
    return [name for name in names if name not in mapping]


def _LookupTargets(names, mapping):
    """Returns a list of the mapping[name] for each value in |names| that is in
  |mapping|."""
    return [mapping[name] for name in names if name in mapping]


def CalculateVariables(default_variables, params):
    """Calculate additional variables for use in the build (called by gyp)."""
    flavor = gyp.common.GetFlavor(params)
    if flavor == "mac":
        default_variables.setdefault("OS", "mac")
    elif flavor == "win":
        default_variables.setdefault("OS", "win")
        gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
    else:
        operating_system = flavor
        if flavor == "android":
            operating_system = "linux"  # Keep this legacy behavior for now.
        default_variables.setdefault("OS", operating_system)


class TargetCalculator:
    """Calculates the matching test_targets and matching compile_targets."""

    def __init__(
        self,
        files,
        additional_compile_target_names,
        test_target_names,
        data,
        target_list,
        target_dicts,
        toplevel_dir,
        build_files,
    ):
        self._additional_compile_target_names = set(additional_compile_target_names)
        self._test_target_names = set(test_target_names)
        (
            self._name_to_target,
            self._changed_targets,
            self._root_targets,
        ) = _GenerateTargets(
            data, target_list, target_dicts, toplevel_dir, frozenset(files), build_files
        )
        (
            self._unqualified_mapping,
            self.invalid_targets,
        ) = _GetUnqualifiedToTargetMapping(
            self._name_to_target, self._supplied_target_names_no_all()
        )

    def _supplied_target_names(self):
        return self._additional_compile_target_names | self._test_target_names

    def _supplied_target_names_no_all(self):
        """Returns the supplied test targets without 'all'."""
        result = self._supplied_target_names()
        result.discard("all")
        return result

    def is_build_impacted(self):
        """Returns true if the supplied files impact the build at all."""
        return self._changed_targets

    def find_matching_test_target_names(self):
        """Returns the set of output test targets."""
        assert self.is_build_impacted()
        # Find the test targets first. 'all' is special cased to mean all the
        # root targets. To deal with all the supplied |test_targets| are expanded
        # to include the root targets during lookup. If any of the root targets
        # match, we remove it and replace it with 'all'.
        test_target_names_no_all = set(self._test_target_names)
        test_target_names_no_all.discard("all")
        test_targets_no_all = _LookupTargets(
            test_target_names_no_all, self._unqualified_mapping
        )
        test_target_names_contains_all = "all" in self._test_target_names
        if test_target_names_contains_all:
            test_targets = list(set(test_targets_no_all) | set(self._root_targets))
        else:
            test_targets = list(test_targets_no_all)
        print("supplied test_targets")
        for target_name in self._test_target_names:
            print("\t", target_name)
        print("found test_targets")
        for target in test_targets:
            print("\t", target.name)
        print("searching for matching test targets")
        matching_test_targets = _GetTargetsDependingOnMatchingTargets(test_targets)
        matching_test_targets_contains_all = test_target_names_contains_all and set(
            matching_test_targets
        ) & set(self._root_targets)
        if matching_test_targets_contains_all:
            # Remove any of the targets for all that were not explicitly supplied,
            # 'all' is subsequentely added to the matching names below.
            matching_test_targets = list(
                set(matching_test_targets) & set(test_targets_no_all)
            )
        print("matched test_targets")
        for target in matching_test_targets:
            print("\t", target.name)
        matching_target_names = [
            gyp.common.ParseQualifiedTarget(target.name)[1]
            for target in matching_test_targets
        ]
        if matching_test_targets_contains_all:
            matching_target_names.append("all")
            print("\tall")
        return matching_target_names

    def find_matching_compile_target_names(self):
        """Returns the set of output compile targets."""
        assert self.is_build_impacted()
        # Compile targets are found by searching up from changed targets.
        # Reset the visited status for _GetBuildTargets.
        for target in self._name_to_target.values():
            target.visited = False

        supplied_targets = _LookupTargets(
            self._supplied_target_names_no_all(), self._unqualified_mapping
        )
        if "all" in self._supplied_target_names():
            supplied_targets = list(set(supplied_targets) | set(self._root_targets))
        print("Supplied test_targets & compile_targets")
        for target in supplied_targets:
            print("\t", target.name)
        print("Finding compile targets")
        compile_targets = _GetCompileTargets(self._changed_targets, supplied_targets)
        return [
            gyp.common.ParseQualifiedTarget(target.name)[1]
            for target in compile_targets
        ]


def GenerateOutput(target_list, target_dicts, data, params):
    """Called by gyp as the final stage. Outputs results."""
    config = Config()
    try:
        config.Init(params)

        if not config.files:
            raise Exception(
                "Must specify files to analyze via config_path generator " "flag"
            )

        toplevel_dir = _ToGypPath(os.path.abspath(params["options"].toplevel_dir))
        if debug:
            print("toplevel_dir", toplevel_dir)

        if _WasGypIncludeFileModified(params, config.files):
            result_dict = {
                "status": all_changed_string,
                "test_targets": list(config.test_target_names),
                "compile_targets": list(
                    config.additional_compile_target_names | config.test_target_names
                ),
            }
            _WriteOutput(params, **result_dict)
            return

        calculator = TargetCalculator(
            config.files,
            config.additional_compile_target_names,
            config.test_target_names,
            data,
            target_list,
            target_dicts,
            toplevel_dir,
            params["build_files"],
        )
        if not calculator.is_build_impacted():
            result_dict = {
                "status": no_dependency_string,
                "test_targets": [],
                "compile_targets": [],
            }
            if calculator.invalid_targets:
                result_dict["invalid_targets"] = calculator.invalid_targets
            _WriteOutput(params, **result_dict)
            return

        test_target_names = calculator.find_matching_test_target_names()
        compile_target_names = calculator.find_matching_compile_target_names()
        found_at_least_one_target = compile_target_names or test_target_names
        result_dict = {
            "test_targets": test_target_names,
            "status": found_dependency_string
            if found_at_least_one_target
            else no_dependency_string,
            "compile_targets": list(set(compile_target_names) | set(test_target_names)),
        }
        if calculator.invalid_targets:
            result_dict["invalid_targets"] = calculator.invalid_targets
        _WriteOutput(params, **result_dict)

    except Exception as e:
        _WriteOutput(params, error=str(e))
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Notes:
#
# This generates makefiles suitable for inclusion into the Android build system
# via an Android.mk file. It is based on make.py, the standard makefile
# generator.
#
# The code below generates a separate .mk file for each target, but
# all are sourced by the top-level GypAndroid.mk.  This means that all
# variables in .mk-files clobber one another, and furthermore that any
# variables set potentially clash with other Android build system variables.
# Try to avoid setting global variables where possible.


import gyp
import gyp.common
import gyp.generator.make as make  # Reuse global functions from make backend.
import os
import re
import subprocess

generator_default_variables = {
    "OS": "android",
    "EXECUTABLE_PREFIX": "",
    "EXECUTABLE_SUFFIX": "",
    "STATIC_LIB_PREFIX": "lib",
    "SHARED_LIB_PREFIX": "lib",
    "STATIC_LIB_SUFFIX": ".a",
    "SHARED_LIB_SUFFIX": ".so",
    "INTERMEDIATE_DIR": "$(gyp_intermediate_dir)",
    "SHARED_INTERMEDIATE_DIR": "$(gyp_shared_intermediate_dir)",
    "PRODUCT_DIR": "$(gyp_shared_intermediate_dir)",
    "SHARED_LIB_DIR": "$(builddir)/lib.$(TOOLSET)",
    "LIB_DIR": "$(obj).$(TOOLSET)",
    "RULE_INPUT_ROOT": "%(INPUT_ROOT)s",  # This gets expanded by Python.
    "RULE_INPUT_DIRNAME": "%(INPUT_DIRNAME)s",  # This gets expanded by Python.
    "RULE_INPUT_PATH": "$(RULE_SOURCES)",
    "RULE_INPUT_EXT": "$(suffix $<)",
    "RULE_INPUT_NAME": "$(notdir $<)",
    "CONFIGURATION_NAME": "$(GYP_CONFIGURATION)",
}

# Make supports multiple toolsets
generator_supports_multiple_toolsets = True


# Generator-specific gyp specs.
generator_additional_non_configuration_keys = [
    # Boolean to declare that this target does not want its name mangled.
    "android_unmangled_name",
    # Map of android build system variables to set.
    "aosp_build_settings",
]
generator_additional_path_sections = []
generator_extra_sources_for_rules = []


ALL_MODULES_FOOTER = """\
# "gyp_all_modules" is a concatenation of the "gyp_all_modules" targets from
# all the included sub-makefiles. This is just here to clarify.
gyp_all_modules:
"""

header = """\
# This file is generated by gyp; do not edit.

"""

# Map gyp target types to Android module classes.
MODULE_CLASSES = {
    "static_library": "STATIC_LIBRARIES",
    "shared_library": "SHARED_LIBRARIES",
    "executable": "EXECUTABLES",
}


def IsCPPExtension(ext):
    return make.COMPILABLE_EXTENSIONS.get(ext) == "cxx"


def Sourceify(path):
    """Convert a path to its source directory form. The Android backend does not
    support options.generator_output, so this function is a noop."""
    return path


# Map from qualified target to path to output.
# For Android, the target of these maps is a tuple ('static', 'modulename'),
# ('dynamic', 'modulename'), or ('path', 'some/path') instead of a string,
# since we link by module.
target_outputs = {}
# Map from qualified target to any linkable output.  A subset
# of target_outputs.  E.g. when mybinary depends on liba, we want to
# include liba in the linker line; when otherbinary depends on
# mybinary, we just want to build mybinary first.
target_link_deps = {}


class AndroidMkWriter:
    """AndroidMkWriter packages up the writing of one target-specific Android.mk.

    Its only real entry point is Write(), and is mostly used for namespacing.
    """

    def __init__(self, android_top_dir):
        self.android_top_dir = android_top_dir

    def Write(
        self,
        qualified_target,
        relative_target,
        base_path,
        output_filename,
        spec,
        configs,
        part_of_all,
        write_alias_target,
        sdk_version,
    ):
        """The main entry point: writes a .mk file for a single target.

        Arguments:
          qualified_target: target we're generating
          relative_target: qualified target name relative to the root
          base_path: path relative to source root we're building in, used to resolve
                     target-relative paths
          output_filename: output .mk file name to write
          spec, configs: gyp info
          part_of_all: flag indicating this target is part of 'all'
          write_alias_target: flag indicating whether to create short aliases for
                              this target
          sdk_version: what to emit for LOCAL_SDK_VERSION in output
        """
        gyp.common.EnsureDirExists(output_filename)

        self.fp = open(output_filename, "w")

        self.fp.write(header)

        self.qualified_target = qualified_target
        self.relative_target = relative_target
        self.path = base_path
        self.target = spec["target_name"]
        self.type = spec["type"]
        self.toolset = spec["toolset"]

        deps, link_deps = self.ComputeDeps(spec)

        # Some of the generation below can add extra output, sources, or
        # link dependencies.  All of the out params of the functions that
        # follow use names like extra_foo.
        extra_outputs = []
        extra_sources = []

        self.android_class = MODULE_CLASSES.get(self.type, "GYP")
        self.android_module = self.ComputeAndroidModule(spec)
        (self.android_stem, self.android_suffix) = self.ComputeOutputParts(spec)
        self.output = self.output_binary = self.ComputeOutput(spec)

        # Standard header.
        self.WriteLn("include $(CLEAR_VARS)\n")

        # Module class and name.
        self.WriteLn("LOCAL_MODULE_CLASS := " + self.android_class)
        self.WriteLn("LOCAL_MODULE := " + self.android_module)
        # Only emit LOCAL_MODULE_STEM if it's different to LOCAL_MODULE.
        # The library module classes fail if the stem is set. ComputeOutputParts
        # makes sure that stem == modulename in these cases.
        if self.android_stem != self.android_module:
            self.WriteLn("LOCAL_MODULE_STEM := " + self.android_stem)
        self.WriteLn("LOCAL_MODULE_SUFFIX := " + self.android_suffix)
        if self.toolset == "host":
            self.WriteLn("LOCAL_IS_HOST_MODULE := true")
            self.WriteLn("LOCAL_MULTILIB := $(GYP_HOST_MULTILIB)")
        elif sdk_version > 0:
            self.WriteLn(
                "LOCAL_MODULE_TARGET_ARCH := " "$(TARGET_$(GYP_VAR_PREFIX)ARCH)"
            )
            self.WriteLn("LOCAL_SDK_VERSION := %s" % sdk_version)

        # Grab output directories; needed for Actions and Rules.
        if self.toolset == "host":
            self.WriteLn(
                "gyp_intermediate_dir := "
                "$(call local-intermediates-dir,,$(GYP_HOST_VAR_PREFIX))"
            )
        else:
            self.WriteLn(
                "gyp_intermediate_dir := "
                "$(call local-intermediates-dir,,$(GYP_VAR_PREFIX))"
            )
        self.WriteLn(
            "gyp_shared_intermediate_dir := "
            "$(call intermediates-dir-for,GYP,shared,,,$(GYP_VAR_PREFIX))"
        )
        self.WriteLn()

        # List files this target depends on so that actions/rules/copies/sources
        # can depend on the list.
        # TODO: doesn't pull in things through transitive link deps; needed?
        target_dependencies = [x[1] for x in deps if x[0] == "path"]
        self.WriteLn("# Make sure our deps are built first.")
        self.WriteList(
            target_dependencies, "GYP_TARGET_DEPENDENCIES", local_pathify=True
        )

        # Actions must come first, since they can generate more OBJs for use below.
        if "actions" in spec:
            self.WriteActions(spec["actions"], extra_sources, extra_outputs)

        # Rules must be early like actions.
        if "rules" in spec:
            self.WriteRules(spec["rules"], extra_sources, extra_outputs)

        if "copies" in spec:
            self.WriteCopies(spec["copies"], extra_outputs)

        # GYP generated outputs.
        self.WriteList(extra_outputs, "GYP_GENERATED_OUTPUTS", local_pathify=True)

        # Set LOCAL_ADDITIONAL_DEPENDENCIES so that Android's build rules depend
        # on both our dependency targets and our generated files.
        self.WriteLn("# Make sure our deps and generated files are built first.")
        self.WriteLn(
            "LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) "
            "$(GYP_GENERATED_OUTPUTS)"
        )
        self.WriteLn()

        # Sources.
        if spec.get("sources", []) or extra_sources:
            self.WriteSources(spec, configs, extra_sources)

        self.WriteTarget(
            spec, configs, deps, link_deps, part_of_all, write_alias_target
        )

        # Update global list of target outputs, used in dependency tracking.
        target_outputs[qualified_target] = ("path", self.output_binary)

        # Update global list of link dependencies.
        if self.type == "static_library":
            target_link_deps[qualified_target] = ("static", self.android_module)
        elif self.type == "shared_library":
            target_link_deps[qualified_target] = ("shared", self.android_module)

        self.fp.close()
        return self.android_module

    def WriteActions(self, actions, extra_sources, extra_outputs):
        """Write Makefile code for any 'actions' from the gyp input.

        extra_sources: a list that will be filled in with newly generated source
                       files, if any
        extra_outputs: a list that will be filled in with any outputs of these
                       actions (used to make other pieces dependent on these
                       actions)
        """
        for action in actions:
            name = make.StringToMakefileVariable(
                "{}_{}".format(self.relative_target, action["action_name"])
            )
            self.WriteLn('### Rules for action "%s":' % action["action_name"])
            inputs = action["inputs"]
            outputs = action["outputs"]

            # Build up a list of outputs.
            # Collect the output dirs we'll need.
            dirs = set()
            for out in outputs:
                if not out.startswith("$"):
                    print(
                        'WARNING: Action for target "%s" writes output to local path '
                        '"%s".' % (self.target, out)
                    )
                dir = os.path.split(out)[0]
                if dir:
                    dirs.add(dir)
            if int(action.get("process_outputs_as_sources", False)):
                extra_sources += outputs

            # Prepare the actual command.
            command = gyp.common.EncodePOSIXShellList(action["action"])
            if "message" in action:
                quiet_cmd = "Gyp action: %s ($@)" % action["message"]
            else:
                quiet_cmd = "Gyp action: %s ($@)" % name
            if len(dirs) > 0:
                command = "mkdir -p %s" % " ".join(dirs) + "; " + command

            cd_action = "cd $(gyp_local_path)/%s; " % self.path
            command = cd_action + command

            # The makefile rules are all relative to the top dir, but the gyp actions
            # are defined relative to their containing dir.  This replaces the gyp_*
            # variables for the action rule with an absolute version so that the
            # output goes in the right place.
            # Only write the gyp_* rules for the "primary" output (:1);
            # it's superfluous for the "extra outputs", and this avoids accidentally
            # writing duplicate dummy rules for those outputs.
            main_output = make.QuoteSpaces(self.LocalPathify(outputs[0]))
            self.WriteLn("%s: gyp_local_path := $(LOCAL_PATH)" % main_output)
            self.WriteLn("%s: gyp_var_prefix := $(GYP_VAR_PREFIX)" % main_output)
            self.WriteLn(
                "%s: gyp_intermediate_dir := "
                "$(abspath $(gyp_intermediate_dir))" % main_output
            )
            self.WriteLn(
                "%s: gyp_shared_intermediate_dir := "
                "$(abspath $(gyp_shared_intermediate_dir))" % main_output
            )

            # Android's envsetup.sh adds a number of directories to the path including
            # the built host binary directory. This causes actions/rules invoked by
            # gyp to sometimes use these instead of system versions, e.g. bison.
            # The built host binaries may not be suitable, and can cause errors.
            # So, we remove them from the PATH using the ANDROID_BUILD_PATHS variable
            # set by envsetup.
            self.WriteLn(
                "%s: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))"
                % main_output
            )

            # Don't allow spaces in input/output filenames, but make an exception for
            # filenames which start with '$(' since it's okay for there to be spaces
            # inside of make function/macro invocations.
            for input in inputs:
                if not input.startswith("$(") and " " in input:
                    raise gyp.common.GypError(
                        'Action input filename "%s" in target %s contains a space'
                        % (input, self.target)
                    )
            for output in outputs:
                if not output.startswith("$(") and " " in output:
                    raise gyp.common.GypError(
                        'Action output filename "%s" in target %s contains a space'
                        % (output, self.target)
                    )

            self.WriteLn(
                "%s: %s $(GYP_TARGET_DEPENDENCIES)"
                % (main_output, " ".join(map(self.LocalPathify, inputs)))
            )
            self.WriteLn('\t@echo "%s"' % quiet_cmd)
            self.WriteLn("\t$(hide)%s\n" % command)
            for output in outputs[1:]:
                # Make each output depend on the main output, with an empty command
                # to force make to notice that the mtime has changed.
                self.WriteLn(f"{self.LocalPathify(output)}: {main_output} ;")

            extra_outputs += outputs
            self.WriteLn()

        self.WriteLn()

    def WriteRules(self, rules, extra_sources, extra_outputs):
        """Write Makefile code for any 'rules' from the gyp input.

        extra_sources: a list that will be filled in with newly generated source
                       files, if any
        extra_outputs: a list that will be filled in with any outputs of these
                       rules (used to make other pieces dependent on these rules)
        """
        if len(rules) == 0:
            return

        for rule in rules:
            if len(rule.get("rule_sources", [])) == 0:
                continue
            name = make.StringToMakefileVariable(
                "{}_{}".format(self.relative_target, rule["rule_name"])
            )
            self.WriteLn('\n### Generated for rule "%s":' % name)
            self.WriteLn('# "%s":' % rule)

            inputs = rule.get("inputs")
            for rule_source in rule.get("rule_sources", []):
                (rule_source_dirname, rule_source_basename) = os.path.split(rule_source)
                (rule_source_root, rule_source_ext) = os.path.splitext(
                    rule_source_basename
                )

                outputs = [
                    self.ExpandInputRoot(out, rule_source_root, rule_source_dirname)
                    for out in rule["outputs"]
                ]

                dirs = set()
                for out in outputs:
                    if not out.startswith("$"):
                        print(
                            "WARNING: Rule for target %s writes output to local path %s"
                            % (self.target, out)
                        )
                    dir = os.path.dirname(out)
                    if dir:
                        dirs.add(dir)
                extra_outputs += outputs
                if int(rule.get("process_outputs_as_sources", False)):
                    extra_sources.extend(outputs)

                components = []
                for component in rule["action"]:
                    component = self.ExpandInputRoot(
                        component, rule_source_root, rule_source_dirname
                    )
                    if "$(RULE_SOURCES)" in component:
                        component = component.replace("$(RULE_SOURCES)", rule_source)
                    components.append(component)

                command = gyp.common.EncodePOSIXShellList(components)
                cd_action = "cd $(gyp_local_path)/%s; " % self.path
                command = cd_action + command
                if dirs:
                    command = "mkdir -p %s" % " ".join(dirs) + "; " + command

                # We set up a rule to build the first output, and then set up
                # a rule for each additional output to depend on the first.
                outputs = map(self.LocalPathify, outputs)
                main_output = outputs[0]
                self.WriteLn("%s: gyp_local_path := $(LOCAL_PATH)" % main_output)
                self.WriteLn("%s: gyp_var_prefix := $(GYP_VAR_PREFIX)" % main_output)
                self.WriteLn(
                    "%s: gyp_intermediate_dir := "
                    "$(abspath $(gyp_intermediate_dir))" % main_output
                )
                self.WriteLn(
                    "%s: gyp_shared_intermediate_dir := "
                    "$(abspath $(gyp_shared_intermediate_dir))" % main_output
                )

                # See explanation in WriteActions.
                self.WriteLn(
                    "%s: export PATH := "
                    "$(subst $(ANDROID_BUILD_PATHS),,$(PATH))" % main_output
                )

                main_output_deps = self.LocalPathify(rule_source)
                if inputs:
                    main_output_deps += " "
                    main_output_deps += " ".join([self.LocalPathify(f) for f in inputs])

                self.WriteLn(
                    "%s: %s $(GYP_TARGET_DEPENDENCIES)"
                    % (main_output, main_output_deps)
                )
                self.WriteLn("\t%s\n" % command)
                for output in outputs[1:]:
                    # Make each output depend on the main output, with an empty command
                    # to force make to notice that the mtime has changed.
                    self.WriteLn(f"{output}: {main_output} ;")
                self.WriteLn()

        self.WriteLn()

    def WriteCopies(self, copies, extra_outputs):
        """Write Makefile code for any 'copies' from the gyp input.

        extra_outputs: a list that will be filled in with any outputs of this action
                       (used to make other pieces dependent on this action)
        """
        self.WriteLn("### Generated for copy rule.")

        variable = make.StringToMakefileVariable(self.relative_target + "_copies")
        outputs = []
        for copy in copies:
            for path in copy["files"]:
                # The Android build system does not allow generation of files into the
                # source tree. The destination should start with a variable, which will
                # typically be $(gyp_intermediate_dir) or
                # $(gyp_shared_intermediate_dir). Note that we can't use an assertion
                # because some of the gyp tests depend on this.
                if not copy["destination"].startswith("$"):
                    print(
                        "WARNING: Copy rule for target %s writes output to "
                        "local path %s" % (self.target, copy["destination"])
                    )

                # LocalPathify() calls normpath, stripping trailing slashes.
                path = Sourceify(self.LocalPathify(path))
                filename = os.path.split(path)[1]
                output = Sourceify(
                    self.LocalPathify(os.path.join(copy["destination"], filename))
                )

                self.WriteLn(f"{output}: {path} $(GYP_TARGET_DEPENDENCIES) | $(ACP)")
                self.WriteLn("\t@echo Copying: $@")
                self.WriteLn("\t$(hide) mkdir -p $(dir $@)")
                self.WriteLn("\t$(hide) $(ACP) -rpf $< $@")
                self.WriteLn()
                outputs.append(output)
        self.WriteLn(
            "{} = {}".format(variable, " ".join(map(make.QuoteSpaces, outputs)))
        )
        extra_outputs.append("$(%s)" % variable)
        self.WriteLn()

    def WriteSourceFlags(self, spec, configs):
        """Write out the flags and include paths used to compile source files for
        the current target.

        Args:
          spec, configs: input from gyp.
        """
        for configname, config in sorted(configs.items()):
            extracted_includes = []

            self.WriteLn("\n# Flags passed to both C and C++ files.")
            cflags, includes_from_cflags = self.ExtractIncludesFromCFlags(
                config.get("cflags", []) + config.get("cflags_c", [])
            )
            extracted_includes.extend(includes_from_cflags)
            self.WriteList(cflags, "MY_CFLAGS_%s" % configname)

            self.WriteList(
                config.get("defines"),
                "MY_DEFS_%s" % configname,
                prefix="-D",
                quoter=make.EscapeCppDefine,
            )

            self.WriteLn("\n# Include paths placed before CFLAGS/CPPFLAGS")
            includes = list(config.get("include_dirs", []))
            includes.extend(extracted_includes)
            includes = map(Sourceify, map(self.LocalPathify, includes))
            includes = self.NormalizeIncludePaths(includes)
            self.WriteList(includes, "LOCAL_C_INCLUDES_%s" % configname)

            self.WriteLn("\n# Flags passed to only C++ (and not C) files.")
            self.WriteList(config.get("cflags_cc"), "LOCAL_CPPFLAGS_%s" % configname)

        self.WriteLn(
            "\nLOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) "
            "$(MY_DEFS_$(GYP_CONFIGURATION))"
        )
        # Undefine ANDROID for host modules
        # TODO: the source code should not use macro ANDROID to tell if it's host
        # or target module.
        if self.toolset == "host":
            self.WriteLn("# Undefine ANDROID for host modules")
            self.WriteLn("LOCAL_CFLAGS += -UANDROID")
        self.WriteLn(
            "LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) "
            "$(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))"
        )
        self.WriteLn("LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))")
        # Android uses separate flags for assembly file invocations, but gyp expects
        # the same CFLAGS to be applied:
        self.WriteLn("LOCAL_ASFLAGS := $(LOCAL_CFLAGS)")

    def WriteSources(self, spec, configs, extra_sources):
        """Write Makefile code for any 'sources' from the gyp input.
        These are source files necessary to build the current target.
        We need to handle shared_intermediate directory source files as
        a special case by copying them to the intermediate directory and
        treating them as a generated sources. Otherwise the Android build
        rules won't pick them up.

        Args:
          spec, configs: input from gyp.
          extra_sources: Sources generated from Actions or Rules.
        """
        sources = filter(make.Compilable, spec.get("sources", []))
        generated_not_sources = [x for x in extra_sources if not make.Compilable(x)]
        extra_sources = filter(make.Compilable, extra_sources)

        # Determine and output the C++ extension used by these sources.
        # We simply find the first C++ file and use that extension.
        all_sources = sources + extra_sources
        local_cpp_extension = ".cpp"
        for source in all_sources:
            (root, ext) = os.path.splitext(source)
            if IsCPPExtension(ext):
                local_cpp_extension = ext
                break
        if local_cpp_extension != ".cpp":
            self.WriteLn("LOCAL_CPP_EXTENSION := %s" % local_cpp_extension)

        # We need to move any non-generated sources that are coming from the
        # shared intermediate directory out of LOCAL_SRC_FILES and put them
        # into LOCAL_GENERATED_SOURCES. We also need to move over any C++ files
        # that don't match our local_cpp_extension, since Android will only
        # generate Makefile rules for a single LOCAL_CPP_EXTENSION.
        local_files = []
        for source in sources:
            (root, ext) = os.path.splitext(source)
            if "$(gyp_shared_intermediate_dir)" in source:
                extra_sources.append(source)
            elif "$(gyp_intermediate_dir)" in source:
                extra_sources.append(source)
            elif IsCPPExtension(ext) and ext != local_cpp_extension:
                extra_sources.append(source)
            else:
                local_files.append(os.path.normpath(os.path.join(self.path, source)))

        # For any generated source, if it is coming from the shared intermediate
        # directory then we add a Make rule to copy them to the local intermediate
        # directory first. This is because the Android LOCAL_GENERATED_SOURCES
        # must be in the local module intermediate directory for the compile rules
        # to work properly. If the file has the wrong C++ extension, then we add
        # a rule to copy that to intermediates and use the new version.
        final_generated_sources = []
        # If a source file gets copied, we still need to add the original source
        # directory as header search path, for GCC searches headers in the
        # directory that contains the source file by default.
        origin_src_dirs = []
        for source in extra_sources:
            local_file = source
            if "$(gyp_intermediate_dir)/" not in local_file:
                basename = os.path.basename(local_file)
                local_file = "$(gyp_intermediate_dir)/" + basename
            (root, ext) = os.path.splitext(local_file)
            if IsCPPExtension(ext) and ext != local_cpp_extension:
                local_file = root + local_cpp_extension
            if local_file != source:
                self.WriteLn(f"{local_file}: {self.LocalPathify(source)}")
                self.WriteLn("\tmkdir -p $(@D); cp $< $@")
                origin_src_dirs.append(os.path.dirname(source))
            final_generated_sources.append(local_file)

        # We add back in all of the non-compilable stuff to make sure that the
        # make rules have dependencies on them.
        final_generated_sources.extend(generated_not_sources)
        self.WriteList(final_generated_sources, "LOCAL_GENERATED_SOURCES")

        origin_src_dirs = gyp.common.uniquer(origin_src_dirs)
        origin_src_dirs = map(Sourceify, map(self.LocalPathify, origin_src_dirs))
        self.WriteList(origin_src_dirs, "GYP_COPIED_SOURCE_ORIGIN_DIRS")

        self.WriteList(local_files, "LOCAL_SRC_FILES")

        # Write out the flags used to compile the source; this must be done last
        # so that GYP_COPIED_SOURCE_ORIGIN_DIRS can be used as an include path.
        self.WriteSourceFlags(spec, configs)

    def ComputeAndroidModule(self, spec):
        """Return the Android module name used for a gyp spec.

        We use the complete qualified target name to avoid collisions between
        duplicate targets in different directories. We also add a suffix to
        distinguish gyp-generated module names.
        """

        if int(spec.get("android_unmangled_name", 0)):
            assert self.type != "shared_library" or self.target.startswith("lib")
            return self.target

        if self.type == "shared_library":
            # For reasons of convention, the Android build system requires that all
            # shared library modules are named 'libfoo' when generating -l flags.
            prefix = "lib_"
        else:
            prefix = ""

        if spec["toolset"] == "host":
            suffix = "_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp"
        else:
            suffix = "_gyp"

        if self.path:
            middle = make.StringToMakefileVariable(f"{self.path}_{self.target}")
        else:
            middle = make.StringToMakefileVariable(self.target)

        return "".join([prefix, middle, suffix])

    def ComputeOutputParts(self, spec):
        """Return the 'output basename' of a gyp spec, split into filename + ext.

        Android libraries must be named the same thing as their module name,
        otherwise the linker can't find them, so product_name and so on must be
        ignored if we are building a library, and the "lib" prepending is
        not done for Android.
        """
        assert self.type != "loadable_module"  # TODO: not supported?

        target = spec["target_name"]
        target_prefix = ""
        target_ext = ""
        if self.type == "static_library":
            target = self.ComputeAndroidModule(spec)
            target_ext = ".a"
        elif self.type == "shared_library":
            target = self.ComputeAndroidModule(spec)
            target_ext = ".so"
        elif self.type == "none":
            target_ext = ".stamp"
        elif self.type != "executable":
            print(
                "ERROR: What output file should be generated?",
                "type",
                self.type,
                "target",
                target,
            )

        if self.type not in {"static_library", "shared_library"}:
            target_prefix = spec.get("product_prefix", target_prefix)
            target = spec.get("product_name", target)
            product_ext = spec.get("product_extension")
            if product_ext:
                target_ext = "." + product_ext

        target_stem = target_prefix + target
        return (target_stem, target_ext)

    def ComputeOutputBasename(self, spec):
        """Return the 'output basename' of a gyp spec.

        E.g., the loadable module 'foobar' in directory 'baz' will produce
          'libfoobar.so'
        """
        return "".join(self.ComputeOutputParts(spec))

    def ComputeOutput(self, spec):
        """Return the 'output' (full output path) of a gyp spec.

        E.g., the loadable module 'foobar' in directory 'baz' will produce
          '$(obj)/baz/libfoobar.so'
        """
        if self.type == "executable":
            # We install host executables into shared_intermediate_dir so they can be
            # run by gyp rules that refer to PRODUCT_DIR.
            path = "$(gyp_shared_intermediate_dir)"
        elif self.type == "shared_library":
            if self.toolset == "host":
                path = "$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)"
            else:
                path = "$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)"
        else:
            # Other targets just get built into their intermediate dir.
            if self.toolset == "host":
                path = (
                    "$(call intermediates-dir-for,%s,%s,true,,"
                    "$(GYP_HOST_VAR_PREFIX))"
                    % (self.android_class, self.android_module)
                )
            else:
                path = (
                    f"$(call intermediates-dir-for,{self.android_class},"
                    f"{self.android_module},,,$(GYP_VAR_PREFIX))"
                )

        assert spec.get("product_dir") is None  # TODO: not supported?
        return os.path.join(path, self.ComputeOutputBasename(spec))

    def NormalizeIncludePaths(self, include_paths):
        """Normalize include_paths.
        Convert absolute paths to relative to the Android top directory.

        Args:
          include_paths: A list of unprocessed include paths.
        Returns:
          A list of normalized include paths.
        """
        normalized = []
        for path in include_paths:
            if path[0] == "/":
                path = gyp.common.RelativePath(path, self.android_top_dir)
            normalized.append(path)
        return normalized

    def ExtractIncludesFromCFlags(self, cflags):
        """Extract includes "-I..." out from cflags

        Args:
          cflags: A list of compiler flags, which may be mixed with "-I.."
        Returns:
          A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed.
        """
        clean_cflags = []
        include_paths = []
        for flag in cflags:
            if flag.startswith("-I"):
                include_paths.append(flag[2:])
            else:
                clean_cflags.append(flag)

        return (clean_cflags, include_paths)

    def FilterLibraries(self, libraries):
        """Filter the 'libraries' key to separate things that shouldn't be ldflags.

        Library entries that look like filenames should be converted to android
        module names instead of being passed to the linker as flags.

        Args:
          libraries: the value of spec.get('libraries')
        Returns:
          A tuple (static_lib_modules, dynamic_lib_modules, ldflags)
        """
        static_lib_modules = []
        dynamic_lib_modules = []
        ldflags = []
        for libs in libraries:
            # Libs can have multiple words.
            for lib in libs.split():
                # Filter the system libraries, which are added by default by the Android
                # build system.
                if (
                    lib == "-lc"
                    or lib == "-lstdc++"
                    or lib == "-lm"
                    or lib.endswith("libgcc.a")
                ):
                    continue
                match = re.search(r"([^/]+)\.a$", lib)
                if match:
                    static_lib_modules.append(match.group(1))
                    continue
                match = re.search(r"([^/]+)\.so$", lib)
                if match:
                    dynamic_lib_modules.append(match.group(1))
                    continue
                if lib.startswith("-l"):
                    ldflags.append(lib)
        return (static_lib_modules, dynamic_lib_modules, ldflags)

    def ComputeDeps(self, spec):
        """Compute the dependencies of a gyp spec.

        Returns a tuple (deps, link_deps), where each is a list of
        filenames that will need to be put in front of make for either
        building (deps) or linking (link_deps).
        """
        deps = []
        link_deps = []
        if "dependencies" in spec:
            deps.extend(
                [
                    target_outputs[dep]
                    for dep in spec["dependencies"]
                    if target_outputs[dep]
                ]
            )
            for dep in spec["dependencies"]:
                if dep in target_link_deps:
                    link_deps.append(target_link_deps[dep])
            deps.extend(link_deps)
        return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps))

    def WriteTargetFlags(self, spec, configs, link_deps):
        """Write Makefile code to specify the link flags and library dependencies.

        spec, configs: input from gyp.
        link_deps: link dependency list; see ComputeDeps()
        """
        # Libraries (i.e. -lfoo)
        # These must be included even for static libraries as some of them provide
        # implicit include paths through the build system.
        libraries = gyp.common.uniquer(spec.get("libraries", []))
        static_libs, dynamic_libs, ldflags_libs = self.FilterLibraries(libraries)

        if self.type != "static_library":
            for configname, config in sorted(configs.items()):
                ldflags = list(config.get("ldflags", []))
                self.WriteLn("")
                self.WriteList(ldflags, "LOCAL_LDFLAGS_%s" % configname)
            self.WriteList(ldflags_libs, "LOCAL_GYP_LIBS")
            self.WriteLn(
                "LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION)) "
                "$(LOCAL_GYP_LIBS)"
            )

        # Link dependencies (i.e. other gyp targets this target depends on)
        # These need not be included for static libraries as within the gyp build
        # we do not use the implicit include path mechanism.
        if self.type != "static_library":
            static_link_deps = [x[1] for x in link_deps if x[0] == "static"]
            shared_link_deps = [x[1] for x in link_deps if x[0] == "shared"]
        else:
            static_link_deps = []
            shared_link_deps = []

        # Only write the lists if they are non-empty.
        if static_libs or static_link_deps:
            self.WriteLn("")
            self.WriteList(static_libs + static_link_deps, "LOCAL_STATIC_LIBRARIES")
            self.WriteLn("# Enable grouping to fix circular references")
            self.WriteLn("LOCAL_GROUP_STATIC_LIBRARIES := true")
        if dynamic_libs or shared_link_deps:
            self.WriteLn("")
            self.WriteList(dynamic_libs + shared_link_deps, "LOCAL_SHARED_LIBRARIES")

    def WriteTarget(
        self, spec, configs, deps, link_deps, part_of_all, write_alias_target
    ):
        """Write Makefile code to produce the final target of the gyp spec.

        spec, configs: input from gyp.
        deps, link_deps: dependency lists; see ComputeDeps()
        part_of_all: flag indicating this target is part of 'all'
        write_alias_target: flag indicating whether to create short aliases for this
                            target
        """
        self.WriteLn("### Rules for final target.")

        if self.type != "none":
            self.WriteTargetFlags(spec, configs, link_deps)

        settings = spec.get("aosp_build_settings", {})
        if settings:
            self.WriteLn("### Set directly by aosp_build_settings.")
            for k, v in settings.items():
                if isinstance(v, list):
                    self.WriteList(v, k)
                else:
                    self.WriteLn(f"{k} := {make.QuoteIfNecessary(v)}")
            self.WriteLn("")

        # Add to the set of targets which represent the gyp 'all' target. We use the
        # name 'gyp_all_modules' as the Android build system doesn't allow the use
        # of the Make target 'all' and because 'all_modules' is the equivalent of
        # the Make target 'all' on Android.
        if part_of_all and write_alias_target:
            self.WriteLn('# Add target alias to "gyp_all_modules" target.')
            self.WriteLn(".PHONY: gyp_all_modules")
            self.WriteLn("gyp_all_modules: %s" % self.android_module)
            self.WriteLn("")

        # Add an alias from the gyp target name to the Android module name. This
        # simplifies manual builds of the target, and is required by the test
        # framework.
        if self.target != self.android_module and write_alias_target:
            self.WriteLn("# Alias gyp target name.")
            self.WriteLn(".PHONY: %s" % self.target)
            self.WriteLn(f"{self.target}: {self.android_module}")
            self.WriteLn("")

        # Add the command to trigger build of the target type depending
        # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY
        # NOTE: This has to come last!
        modifier = ""
        if self.toolset == "host":
            modifier = "HOST_"
        if self.type == "static_library":
            self.WriteLn("include $(BUILD_%sSTATIC_LIBRARY)" % modifier)
        elif self.type == "shared_library":
            self.WriteLn("LOCAL_PRELINK_MODULE := false")
            self.WriteLn("include $(BUILD_%sSHARED_LIBRARY)" % modifier)
        elif self.type == "executable":
            self.WriteLn("LOCAL_CXX_STL := libc++_static")
            # Executables are for build and test purposes only, so they're installed
            # to a directory that doesn't get included in the system image.
            self.WriteLn("LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)")
            self.WriteLn("include $(BUILD_%sEXECUTABLE)" % modifier)
        else:
            self.WriteLn("LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp")
            self.WriteLn("LOCAL_UNINSTALLABLE_MODULE := true")
            if self.toolset == "target":
                self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_VAR_PREFIX)")
            else:
                self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_HOST_VAR_PREFIX)")
            self.WriteLn()
            self.WriteLn("include $(BUILD_SYSTEM)/base_rules.mk")
            self.WriteLn()
            self.WriteLn("$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)")
            self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"')
            self.WriteLn("\t$(hide) mkdir -p $(dir $@)")
            self.WriteLn("\t$(hide) touch $@")
            self.WriteLn()
            self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX :=")

    def WriteList(
        self,
        value_list,
        variable=None,
        prefix="",
        quoter=make.QuoteIfNecessary,
        local_pathify=False,
    ):
        """Write a variable definition that is a list of values.

        E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
             foo = blaha blahb
        but in a pretty-printed style.
        """
        values = ""
        if value_list:
            value_list = [quoter(prefix + value) for value in value_list]
            if local_pathify:
                value_list = [self.LocalPathify(value) for value in value_list]
            values = " \\\n\t" + " \\\n\t".join(value_list)
        self.fp.write(f"{variable} :={values}\n\n")

    def WriteLn(self, text=""):
        self.fp.write(text + "\n")

    def LocalPathify(self, path):
        """Convert a subdirectory-relative path into a normalized path which starts
        with the make variable $(LOCAL_PATH) (i.e. the top of the project tree).
        Absolute paths, or paths that contain variables, are just normalized."""
        if "$(" in path or os.path.isabs(path):
            # path is not a file in the project tree in this case, but calling
            # normpath is still important for trimming trailing slashes.
            return os.path.normpath(path)
        local_path = os.path.join("$(LOCAL_PATH)", self.path, path)
        local_path = os.path.normpath(local_path)
        # Check that normalizing the path didn't ../ itself out of $(LOCAL_PATH)
        # - i.e. that the resulting path is still inside the project tree. The
        # path may legitimately have ended up containing just $(LOCAL_PATH), though,
        # so we don't look for a slash.
        assert local_path.startswith(
            "$(LOCAL_PATH)"
        ), f"Path {path} attempts to escape from gyp path {self.path} !)"
        return local_path

    def ExpandInputRoot(self, template, expansion, dirname):
        if "%(INPUT_ROOT)s" not in template and "%(INPUT_DIRNAME)s" not in template:
            return template
        path = template % {
            "INPUT_ROOT": expansion,
            "INPUT_DIRNAME": dirname,
        }
        return os.path.normpath(path)


def PerformBuild(data, configurations, params):
    # The android backend only supports the default configuration.
    options = params["options"]
    makefile = os.path.abspath(os.path.join(options.toplevel_dir, "GypAndroid.mk"))
    env = dict(os.environ)
    env["ONE_SHOT_MAKEFILE"] = makefile
    arguments = ["make", "-C", os.environ["ANDROID_BUILD_TOP"], "gyp_all_modules"]
    print("Building: %s" % arguments)
    subprocess.check_call(arguments, env=env)


def GenerateOutput(target_list, target_dicts, data, params):
    options = params["options"]
    generator_flags = params.get("generator_flags", {})
    limit_to_target_all = generator_flags.get("limit_to_target_all", False)
    write_alias_targets = generator_flags.get("write_alias_targets", True)
    sdk_version = generator_flags.get("aosp_sdk_version", 0)
    android_top_dir = os.environ.get("ANDROID_BUILD_TOP")
    assert android_top_dir, "$ANDROID_BUILD_TOP not set; you need to run lunch."

    def CalculateMakefilePath(build_file, base_name):
        """Determine where to write a Makefile for a given gyp file."""
        # Paths in gyp files are relative to the .gyp file, but we want
        # paths relative to the source root for the master makefile.  Grab
        # the path of the .gyp file as the base to relativize against.
        # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp".
        base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth)
        # We write the file in the base_path directory.
        output_file = os.path.join(options.depth, base_path, base_name)
        assert (
            not options.generator_output
        ), "The Android backend does not support options.generator_output."
        base_path = gyp.common.RelativePath(
            os.path.dirname(build_file), options.toplevel_dir
        )
        return base_path, output_file

    # TODO:  search for the first non-'Default' target.  This can go
    # away when we add verification that all targets have the
    # necessary configurations.
    default_configuration = None
    for target in target_list:
        spec = target_dicts[target]
        if spec["default_configuration"] != "Default":
            default_configuration = spec["default_configuration"]
            break
    if not default_configuration:
        default_configuration = "Default"

    makefile_name = "GypAndroid" + options.suffix + ".mk"
    makefile_path = os.path.join(options.toplevel_dir, makefile_name)
    assert (
        not options.generator_output
    ), "The Android backend does not support options.generator_output."
    gyp.common.EnsureDirExists(makefile_path)
    root_makefile = open(makefile_path, "w")

    root_makefile.write(header)

    # We set LOCAL_PATH just once, here, to the top of the project tree. This
    # allows all the other paths we use to be relative to the Android.mk file,
    # as the Android build system expects.
    root_makefile.write("\nLOCAL_PATH := $(call my-dir)\n")

    # Find the list of targets that derive from the gyp file(s) being built.
    needed_targets = set()
    for build_file in params["build_files"]:
        for target in gyp.common.AllTargets(target_list, target_dicts, build_file):
            needed_targets.add(target)

    build_files = set()
    include_list = set()
    android_modules = {}
    for qualified_target in target_list:
        build_file, target, toolset = gyp.common.ParseQualifiedTarget(qualified_target)
        relative_build_file = gyp.common.RelativePath(build_file, options.toplevel_dir)
        build_files.add(relative_build_file)
        included_files = data[build_file]["included_files"]
        for included_file in included_files:
            # The included_files entries are relative to the dir of the build file
            # that included them, so we have to undo that and then make them relative
            # to the root dir.
            relative_include_file = gyp.common.RelativePath(
                gyp.common.UnrelativePath(included_file, build_file),
                options.toplevel_dir,
            )
            abs_include_file = os.path.abspath(relative_include_file)
            # If the include file is from the ~/.gyp dir, we should use absolute path
            # so that relocating the src dir doesn't break the path.
            if params["home_dot_gyp"] and abs_include_file.startswith(
                params["home_dot_gyp"]
            ):
                build_files.add(abs_include_file)
            else:
                build_files.add(relative_include_file)

        base_path, output_file = CalculateMakefilePath(
            build_file, target + "." + toolset + options.suffix + ".mk"
        )

        spec = target_dicts[qualified_target]
        configs = spec["configurations"]

        part_of_all = qualified_target in needed_targets
        if limit_to_target_all and not part_of_all:
            continue

        relative_target = gyp.common.QualifiedTarget(
            relative_build_file, target, toolset
        )
        writer = AndroidMkWriter(android_top_dir)
        android_module = writer.Write(
            qualified_target,
            relative_target,
            base_path,
            output_file,
            spec,
            configs,
            part_of_all=part_of_all,
            write_alias_target=write_alias_targets,
            sdk_version=sdk_version,
        )
        if android_module in android_modules:
            print(
                "ERROR: Android module names must be unique. The following "
                "targets both generate Android module name %s.\n  %s\n  %s"
                % (android_module, android_modules[android_module], qualified_target)
            )
            return
        android_modules[android_module] = qualified_target

        # Our root_makefile lives at the source root.  Compute the relative path
        # from there to the output_file for including.
        mkfile_rel_path = gyp.common.RelativePath(
            output_file, os.path.dirname(makefile_path)
        )
        include_list.add(mkfile_rel_path)

    root_makefile.write("GYP_CONFIGURATION ?= %s\n" % default_configuration)
    root_makefile.write("GYP_VAR_PREFIX ?=\n")
    root_makefile.write("GYP_HOST_VAR_PREFIX ?=\n")
    root_makefile.write("GYP_HOST_MULTILIB ?= first\n")

    # Write out the sorted list of includes.
    root_makefile.write("\n")
    for include_file in sorted(include_list):
        root_makefile.write("include $(LOCAL_PATH)/" + include_file + "\n")
    root_makefile.write("\n")

    if write_alias_targets:
        root_makefile.write(ALL_MODULES_FOOTER)

    root_makefile.close()
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""cmake output module

This module is under development and should be considered experimental.

This module produces cmake (2.8.8+) input as its output. One CMakeLists.txt is
created for each configuration.

This module's original purpose was to support editing in IDEs like KDevelop
which use CMake for project management. It is also possible to use CMake to
generate projects for other IDEs such as eclipse cdt and code::blocks. QtCreator
will convert the CMakeLists.txt to a code::blocks cbp for the editor to read,
but build using CMake. As a result QtCreator editor is unaware of compiler
defines. The generated CMakeLists.txt can also be used to build on Linux. There
is currently no support for building on platforms other than Linux.

The generated CMakeLists.txt should properly compile all projects. However,
there is a mismatch between gyp and cmake with regard to linking. All attempts
are made to work around this, but CMake sometimes sees -Wl,--start-group as a
library and incorrectly repeats it. As a result the output of this generator
should not be relied on for building.

When using with kdevelop, use version 4.4+. Previous versions of kdevelop will
not be able to find the header file directories described in the generated
CMakeLists.txt file.
"""


import multiprocessing
import os
import signal
import subprocess
import gyp.common
import gyp.xcode_emulation

_maketrans = str.maketrans

generator_default_variables = {
    "EXECUTABLE_PREFIX": "",
    "EXECUTABLE_SUFFIX": "",
    "STATIC_LIB_PREFIX": "lib",
    "STATIC_LIB_SUFFIX": ".a",
    "SHARED_LIB_PREFIX": "lib",
    "SHARED_LIB_SUFFIX": ".so",
    "SHARED_LIB_DIR": "${builddir}/lib.${TOOLSET}",
    "LIB_DIR": "${obj}.${TOOLSET}",
    "INTERMEDIATE_DIR": "${obj}.${TOOLSET}/${TARGET}/geni",
    "SHARED_INTERMEDIATE_DIR": "${obj}/gen",
    "PRODUCT_DIR": "${builddir}",
    "RULE_INPUT_PATH": "${RULE_INPUT_PATH}",
    "RULE_INPUT_DIRNAME": "${RULE_INPUT_DIRNAME}",
    "RULE_INPUT_NAME": "${RULE_INPUT_NAME}",
    "RULE_INPUT_ROOT": "${RULE_INPUT_ROOT}",
    "RULE_INPUT_EXT": "${RULE_INPUT_EXT}",
    "CONFIGURATION_NAME": "${configuration}",
}

FULL_PATH_VARS = ("${CMAKE_CURRENT_LIST_DIR}", "${builddir}", "${obj}")

generator_supports_multiple_toolsets = True
generator_wants_static_library_dependencies_adjusted = True

COMPILABLE_EXTENSIONS = {
    ".c": "cc",
    ".cc": "cxx",
    ".cpp": "cxx",
    ".cxx": "cxx",
    ".s": "s",  # cc
    ".S": "s",  # cc
}


def RemovePrefix(a, prefix):
    """Returns 'a' without 'prefix' if it starts with 'prefix'."""
    return a[len(prefix) :] if a.startswith(prefix) else a


def CalculateVariables(default_variables, params):
    """Calculate additional variables for use in the build (called by gyp)."""
    default_variables.setdefault("OS", gyp.common.GetFlavor(params))


def Compilable(filename):
    """Return true if the file is compilable (should be in OBJS)."""
    return any(filename.endswith(e) for e in COMPILABLE_EXTENSIONS)


def Linkable(filename):
    """Return true if the file is linkable (should be on the link line)."""
    return filename.endswith(".o")


def NormjoinPathForceCMakeSource(base_path, rel_path):
    """Resolves rel_path against base_path and returns the result.

  If rel_path is an absolute path it is returned unchanged.
  Otherwise it is resolved against base_path and normalized.
  If the result is a relative path, it is forced to be relative to the
  CMakeLists.txt.
  """
    if os.path.isabs(rel_path):
        return rel_path
    if any(rel_path.startswith(var) for var in FULL_PATH_VARS):
        return rel_path
    # TODO: do we need to check base_path for absolute variables as well?
    return os.path.join(
        "${CMAKE_CURRENT_LIST_DIR}", os.path.normpath(os.path.join(base_path, rel_path))
    )


def NormjoinPath(base_path, rel_path):
    """Resolves rel_path against base_path and returns the result.
  TODO: what is this really used for?
  If rel_path begins with '$' it is returned unchanged.
  Otherwise it is resolved against base_path if relative, then normalized.
  """
    if rel_path.startswith("$") and not rel_path.startswith("${configuration}"):
        return rel_path
    return os.path.normpath(os.path.join(base_path, rel_path))


def CMakeStringEscape(a):
    """Escapes the string 'a' for use inside a CMake string.

  This means escaping
  '\' otherwise it may be seen as modifying the next character
  '"' otherwise it will end the string
  ';' otherwise the string becomes a list

  The following do not need to be escaped
  '#' when the lexer is in string state, this does not start a comment

  The following are yet unknown
  '$' generator variables (like ${obj}) must not be escaped,
      but text $ should be escaped
      what is wanted is to know which $ come from generator variables
  """
    return a.replace("\\", "\\\\").replace(";", "\\;").replace('"', '\\"')


def SetFileProperty(output, source_name, property_name, values, sep):
    """Given a set of source file, sets the given property on them."""
    output.write("set_source_files_properties(")
    output.write(source_name)
    output.write(" PROPERTIES ")
    output.write(property_name)
    output.write(' "')
    for value in values:
        output.write(CMakeStringEscape(value))
        output.write(sep)
    output.write('")\n')


def SetFilesProperty(output, variable, property_name, values, sep):
    """Given a set of source files, sets the given property on them."""
    output.write("set_source_files_properties(")
    WriteVariable(output, variable)
    output.write(" PROPERTIES ")
    output.write(property_name)
    output.write(' "')
    for value in values:
        output.write(CMakeStringEscape(value))
        output.write(sep)
    output.write('")\n')


def SetTargetProperty(output, target_name, property_name, values, sep=""):
    """Given a target, sets the given property."""
    output.write("set_target_properties(")
    output.write(target_name)
    output.write(" PROPERTIES ")
    output.write(property_name)
    output.write(' "')
    for value in values:
        output.write(CMakeStringEscape(value))
        output.write(sep)
    output.write('")\n')


def SetVariable(output, variable_name, value):
    """Sets a CMake variable."""
    output.write("set(")
    output.write(variable_name)
    output.write(' "')
    output.write(CMakeStringEscape(value))
    output.write('")\n')


def SetVariableList(output, variable_name, values):
    """Sets a CMake variable to a list."""
    if not values:
        return SetVariable(output, variable_name, "")
    if len(values) == 1:
        return SetVariable(output, variable_name, values[0])
    output.write("list(APPEND ")
    output.write(variable_name)
    output.write('\n  "')
    output.write('"\n  "'.join([CMakeStringEscape(value) for value in values]))
    output.write('")\n')


def UnsetVariable(output, variable_name):
    """Unsets a CMake variable."""
    output.write("unset(")
    output.write(variable_name)
    output.write(")\n")


def WriteVariable(output, variable_name, prepend=None):
    if prepend:
        output.write(prepend)
    output.write("${")
    output.write(variable_name)
    output.write("}")


class CMakeTargetType:
    def __init__(self, command, modifier, property_modifier):
        self.command = command
        self.modifier = modifier
        self.property_modifier = property_modifier


cmake_target_type_from_gyp_target_type = {
    "executable": CMakeTargetType("add_executable", None, "RUNTIME"),
    "static_library": CMakeTargetType("add_library", "STATIC", "ARCHIVE"),
    "shared_library": CMakeTargetType("add_library", "SHARED", "LIBRARY"),
    "loadable_module": CMakeTargetType("add_library", "MODULE", "LIBRARY"),
    "none": CMakeTargetType("add_custom_target", "SOURCES", None),
}


def StringToCMakeTargetName(a):
    """Converts the given string 'a' to a valid CMake target name.

  All invalid characters are replaced by '_'.
  Invalid for cmake: ' ', '/', '(', ')', '"'
  Invalid for make: ':'
  Invalid for unknown reasons but cause failures: '.'
  """
    return a.translate(_maketrans(' /():."', "_______"))


def WriteActions(target_name, actions, extra_sources, extra_deps, path_to_gyp, output):
    """Write CMake for the 'actions' in the target.

  Args:
    target_name: the name of the CMake target being generated.
    actions: the Gyp 'actions' dict for this target.
    extra_sources: [(, )] to append with generated source files.
    extra_deps: [] to append with generated targets.
    path_to_gyp: relative path from CMakeLists.txt being generated to
        the Gyp file in which the target being generated is defined.
  """
    for action in actions:
        action_name = StringToCMakeTargetName(action["action_name"])
        action_target_name = f"{target_name}__{action_name}"

        inputs = action["inputs"]
        inputs_name = action_target_name + "__input"
        SetVariableList(
            output,
            inputs_name,
            [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs],
        )

        outputs = action["outputs"]
        cmake_outputs = [
            NormjoinPathForceCMakeSource(path_to_gyp, out) for out in outputs
        ]
        outputs_name = action_target_name + "__output"
        SetVariableList(output, outputs_name, cmake_outputs)

        # Build up a list of outputs.
        # Collect the output dirs we'll need.
        dirs = {dir for dir in (os.path.dirname(o) for o in outputs) if dir}

        if int(action.get("process_outputs_as_sources", False)):
            extra_sources.extend(zip(cmake_outputs, outputs))

        # add_custom_command
        output.write("add_custom_command(OUTPUT ")
        WriteVariable(output, outputs_name)
        output.write("\n")

        if len(dirs) > 0:
            for directory in dirs:
                output.write("  COMMAND ${CMAKE_COMMAND} -E make_directory ")
                output.write(directory)
                output.write("\n")

        output.write("  COMMAND ")
        output.write(gyp.common.EncodePOSIXShellList(action["action"]))
        output.write("\n")

        output.write("  DEPENDS ")
        WriteVariable(output, inputs_name)
        output.write("\n")

        output.write("  WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/")
        output.write(path_to_gyp)
        output.write("\n")

        output.write("  COMMENT ")
        if "message" in action:
            output.write(action["message"])
        else:
            output.write(action_target_name)
        output.write("\n")

        output.write("  VERBATIM\n")
        output.write(")\n")

        # add_custom_target
        output.write("add_custom_target(")
        output.write(action_target_name)
        output.write("\n  DEPENDS ")
        WriteVariable(output, outputs_name)
        output.write("\n  SOURCES ")
        WriteVariable(output, inputs_name)
        output.write("\n)\n")

        extra_deps.append(action_target_name)


def NormjoinRulePathForceCMakeSource(base_path, rel_path, rule_source):
    if rel_path.startswith(("${RULE_INPUT_PATH}", "${RULE_INPUT_DIRNAME}")):
        if any(rule_source.startswith(var) for var in FULL_PATH_VARS):
            return rel_path
    return NormjoinPathForceCMakeSource(base_path, rel_path)


def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, output):
    """Write CMake for the 'rules' in the target.

  Args:
    target_name: the name of the CMake target being generated.
    actions: the Gyp 'actions' dict for this target.
    extra_sources: [(, )] to append with generated source files.
    extra_deps: [] to append with generated targets.
    path_to_gyp: relative path from CMakeLists.txt being generated to
        the Gyp file in which the target being generated is defined.
  """
    for rule in rules:
        rule_name = StringToCMakeTargetName(target_name + "__" + rule["rule_name"])

        inputs = rule.get("inputs", [])
        inputs_name = rule_name + "__input"
        SetVariableList(
            output,
            inputs_name,
            [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs],
        )
        outputs = rule["outputs"]
        var_outputs = []

        for count, rule_source in enumerate(rule.get("rule_sources", [])):
            action_name = rule_name + "_" + str(count)

            rule_source_dirname, rule_source_basename = os.path.split(rule_source)
            rule_source_root, rule_source_ext = os.path.splitext(rule_source_basename)

            SetVariable(output, "RULE_INPUT_PATH", rule_source)
            SetVariable(output, "RULE_INPUT_DIRNAME", rule_source_dirname)
            SetVariable(output, "RULE_INPUT_NAME", rule_source_basename)
            SetVariable(output, "RULE_INPUT_ROOT", rule_source_root)
            SetVariable(output, "RULE_INPUT_EXT", rule_source_ext)

            # Build up a list of outputs.
            # Collect the output dirs we'll need.
            dirs = {dir for dir in (os.path.dirname(o) for o in outputs) if dir}

            # Create variables for the output, as 'local' variable will be unset.
            these_outputs = []
            for output_index, out in enumerate(outputs):
                output_name = action_name + "_" + str(output_index)
                SetVariable(
                    output,
                    output_name,
                    NormjoinRulePathForceCMakeSource(path_to_gyp, out, rule_source),
                )
                if int(rule.get("process_outputs_as_sources", False)):
                    extra_sources.append(("${" + output_name + "}", out))
                these_outputs.append("${" + output_name + "}")
                var_outputs.append("${" + output_name + "}")

            # add_custom_command
            output.write("add_custom_command(OUTPUT\n")
            for out in these_outputs:
                output.write("  ")
                output.write(out)
                output.write("\n")

            for directory in dirs:
                output.write("  COMMAND ${CMAKE_COMMAND} -E make_directory ")
                output.write(directory)
                output.write("\n")

            output.write("  COMMAND ")
            output.write(gyp.common.EncodePOSIXShellList(rule["action"]))
            output.write("\n")

            output.write("  DEPENDS ")
            WriteVariable(output, inputs_name)
            output.write(" ")
            output.write(NormjoinPath(path_to_gyp, rule_source))
            output.write("\n")

            # CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives.
            # The cwd is the current build directory.
            output.write("  WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/")
            output.write(path_to_gyp)
            output.write("\n")

            output.write("  COMMENT ")
            if "message" in rule:
                output.write(rule["message"])
            else:
                output.write(action_name)
            output.write("\n")

            output.write("  VERBATIM\n")
            output.write(")\n")

            UnsetVariable(output, "RULE_INPUT_PATH")
            UnsetVariable(output, "RULE_INPUT_DIRNAME")
            UnsetVariable(output, "RULE_INPUT_NAME")
            UnsetVariable(output, "RULE_INPUT_ROOT")
            UnsetVariable(output, "RULE_INPUT_EXT")

        # add_custom_target
        output.write("add_custom_target(")
        output.write(rule_name)
        output.write(" DEPENDS\n")
        for out in var_outputs:
            output.write("  ")
            output.write(out)
            output.write("\n")
        output.write("SOURCES ")
        WriteVariable(output, inputs_name)
        output.write("\n")
        for rule_source in rule.get("rule_sources", []):
            output.write("  ")
            output.write(NormjoinPath(path_to_gyp, rule_source))
            output.write("\n")
        output.write(")\n")

        extra_deps.append(rule_name)


def WriteCopies(target_name, copies, extra_deps, path_to_gyp, output):
    """Write CMake for the 'copies' in the target.

  Args:
    target_name: the name of the CMake target being generated.
    actions: the Gyp 'actions' dict for this target.
    extra_deps: [] to append with generated targets.
    path_to_gyp: relative path from CMakeLists.txt being generated to
        the Gyp file in which the target being generated is defined.
  """
    copy_name = target_name + "__copies"

    # CMake gets upset with custom targets with OUTPUT which specify no output.
    have_copies = any(copy["files"] for copy in copies)
    if not have_copies:
        output.write("add_custom_target(")
        output.write(copy_name)
        output.write(")\n")
        extra_deps.append(copy_name)
        return

    class Copy:
        def __init__(self, ext, command):
            self.cmake_inputs = []
            self.cmake_outputs = []
            self.gyp_inputs = []
            self.gyp_outputs = []
            self.ext = ext
            self.inputs_name = None
            self.outputs_name = None
            self.command = command

    file_copy = Copy("", "copy")
    dir_copy = Copy("_dirs", "copy_directory")

    for copy in copies:
        files = copy["files"]
        destination = copy["destination"]
        for src in files:
            path = os.path.normpath(src)
            basename = os.path.split(path)[1]
            dst = os.path.join(destination, basename)

            copy = file_copy if os.path.basename(src) else dir_copy

            copy.cmake_inputs.append(NormjoinPathForceCMakeSource(path_to_gyp, src))
            copy.cmake_outputs.append(NormjoinPathForceCMakeSource(path_to_gyp, dst))
            copy.gyp_inputs.append(src)
            copy.gyp_outputs.append(dst)

    for copy in (file_copy, dir_copy):
        if copy.cmake_inputs:
            copy.inputs_name = copy_name + "__input" + copy.ext
            SetVariableList(output, copy.inputs_name, copy.cmake_inputs)

            copy.outputs_name = copy_name + "__output" + copy.ext
            SetVariableList(output, copy.outputs_name, copy.cmake_outputs)

    # add_custom_command
    output.write("add_custom_command(\n")

    output.write("OUTPUT")
    for copy in (file_copy, dir_copy):
        if copy.outputs_name:
            WriteVariable(output, copy.outputs_name, " ")
    output.write("\n")

    for copy in (file_copy, dir_copy):
        for src, dst in zip(copy.gyp_inputs, copy.gyp_outputs):
            # 'cmake -E copy src dst' will create the 'dst' directory if needed.
            output.write("COMMAND ${CMAKE_COMMAND} -E %s " % copy.command)
            output.write(src)
            output.write(" ")
            output.write(dst)
            output.write("\n")

    output.write("DEPENDS")
    for copy in (file_copy, dir_copy):
        if copy.inputs_name:
            WriteVariable(output, copy.inputs_name, " ")
    output.write("\n")

    output.write("WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/")
    output.write(path_to_gyp)
    output.write("\n")

    output.write("COMMENT Copying for ")
    output.write(target_name)
    output.write("\n")

    output.write("VERBATIM\n")
    output.write(")\n")

    # add_custom_target
    output.write("add_custom_target(")
    output.write(copy_name)
    output.write("\n  DEPENDS")
    for copy in (file_copy, dir_copy):
        if copy.outputs_name:
            WriteVariable(output, copy.outputs_name, " ")
    output.write("\n  SOURCES")
    if file_copy.inputs_name:
        WriteVariable(output, file_copy.inputs_name, " ")
    output.write("\n)\n")

    extra_deps.append(copy_name)


def CreateCMakeTargetBaseName(qualified_target):
    """This is the name we would like the target to have."""
    _, gyp_target_name, gyp_target_toolset = gyp.common.ParseQualifiedTarget(
        qualified_target
    )
    cmake_target_base_name = gyp_target_name
    if gyp_target_toolset and gyp_target_toolset != "target":
        cmake_target_base_name += "_" + gyp_target_toolset
    return StringToCMakeTargetName(cmake_target_base_name)


def CreateCMakeTargetFullName(qualified_target):
    """An unambiguous name for the target."""
    gyp_file, gyp_target_name, gyp_target_toolset = gyp.common.ParseQualifiedTarget(
        qualified_target
    )
    cmake_target_full_name = gyp_file + ":" + gyp_target_name
    if gyp_target_toolset and gyp_target_toolset != "target":
        cmake_target_full_name += "_" + gyp_target_toolset
    return StringToCMakeTargetName(cmake_target_full_name)


class CMakeNamer:
    """Converts Gyp target names into CMake target names.

  CMake requires that target names be globally unique. One way to ensure
  this is to fully qualify the names of the targets. Unfortunately, this
  ends up with all targets looking like "chrome_chrome_gyp_chrome" instead
  of just "chrome". If this generator were only interested in building, it
  would be possible to fully qualify all target names, then create
  unqualified target names which depend on all qualified targets which
  should have had that name. This is more or less what the 'make' generator
  does with aliases. However, one goal of this generator is to create CMake
  files for use with IDEs, and fully qualified names are not as user
  friendly.

  Since target name collision is rare, we do the above only when required.

  Toolset variants are always qualified from the base, as this is required for
  building. However, it also makes sense for an IDE, as it is possible for
  defines to be different.
  """

    def __init__(self, target_list):
        self.cmake_target_base_names_conficting = set()

        cmake_target_base_names_seen = set()
        for qualified_target in target_list:
            cmake_target_base_name = CreateCMakeTargetBaseName(qualified_target)

            if cmake_target_base_name not in cmake_target_base_names_seen:
                cmake_target_base_names_seen.add(cmake_target_base_name)
            else:
                self.cmake_target_base_names_conficting.add(cmake_target_base_name)

    def CreateCMakeTargetName(self, qualified_target):
        base_name = CreateCMakeTargetBaseName(qualified_target)
        if base_name in self.cmake_target_base_names_conficting:
            return CreateCMakeTargetFullName(qualified_target)
        return base_name


def WriteTarget(
    namer,
    qualified_target,
    target_dicts,
    build_dir,
    config_to_use,
    options,
    generator_flags,
    all_qualified_targets,
    flavor,
    output,
):
    # The make generator does this always.
    # TODO: It would be nice to be able to tell CMake all dependencies.
    circular_libs = generator_flags.get("circular", True)

    if not generator_flags.get("standalone", False):
        output.write("\n#")
        output.write(qualified_target)
        output.write("\n")

    gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target)
    rel_gyp_file = gyp.common.RelativePath(gyp_file, options.toplevel_dir)
    rel_gyp_dir = os.path.dirname(rel_gyp_file)

    # Relative path from build dir to top dir.
    build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir)
    # Relative path from build dir to gyp dir.
    build_to_gyp = os.path.join(build_to_top, rel_gyp_dir)

    path_from_cmakelists_to_gyp = build_to_gyp

    spec = target_dicts.get(qualified_target, {})
    config = spec.get("configurations", {}).get(config_to_use, {})

    xcode_settings = None
    if flavor == "mac":
        xcode_settings = gyp.xcode_emulation.XcodeSettings(spec)

    target_name = spec.get("target_name", "")
    target_type = spec.get("type", "")
    target_toolset = spec.get("toolset")

    cmake_target_type = cmake_target_type_from_gyp_target_type.get(target_type)
    if cmake_target_type is None:
        print(
            "Target %s has unknown target type %s, skipping."
            % (target_name, target_type)
        )
        return

    SetVariable(output, "TARGET", target_name)
    SetVariable(output, "TOOLSET", target_toolset)

    cmake_target_name = namer.CreateCMakeTargetName(qualified_target)

    extra_sources = []
    extra_deps = []

    # Actions must come first, since they can generate more OBJs for use below.
    if "actions" in spec:
        WriteActions(
            cmake_target_name,
            spec["actions"],
            extra_sources,
            extra_deps,
            path_from_cmakelists_to_gyp,
            output,
        )

    # Rules must be early like actions.
    if "rules" in spec:
        WriteRules(
            cmake_target_name,
            spec["rules"],
            extra_sources,
            extra_deps,
            path_from_cmakelists_to_gyp,
            output,
        )

    # Copies
    if "copies" in spec:
        WriteCopies(
            cmake_target_name,
            spec["copies"],
            extra_deps,
            path_from_cmakelists_to_gyp,
            output,
        )

    # Target and sources
    srcs = spec.get("sources", [])

    # Gyp separates the sheep from the goats based on file extensions.
    # A full separation is done here because of flag handing (see below).
    s_sources = []
    c_sources = []
    cxx_sources = []
    linkable_sources = []
    other_sources = []
    for src in srcs:
        _, ext = os.path.splitext(src)
        src_type = COMPILABLE_EXTENSIONS.get(ext, None)
        src_norm_path = NormjoinPath(path_from_cmakelists_to_gyp, src)

        if src_type == "s":
            s_sources.append(src_norm_path)
        elif src_type == "cc":
            c_sources.append(src_norm_path)
        elif src_type == "cxx":
            cxx_sources.append(src_norm_path)
        elif Linkable(ext):
            linkable_sources.append(src_norm_path)
        else:
            other_sources.append(src_norm_path)

    for extra_source in extra_sources:
        src, real_source = extra_source
        _, ext = os.path.splitext(real_source)
        src_type = COMPILABLE_EXTENSIONS.get(ext, None)

        if src_type == "s":
            s_sources.append(src)
        elif src_type == "cc":
            c_sources.append(src)
        elif src_type == "cxx":
            cxx_sources.append(src)
        elif Linkable(ext):
            linkable_sources.append(src)
        else:
            other_sources.append(src)

    s_sources_name = None
    if s_sources:
        s_sources_name = cmake_target_name + "__asm_srcs"
        SetVariableList(output, s_sources_name, s_sources)

    c_sources_name = None
    if c_sources:
        c_sources_name = cmake_target_name + "__c_srcs"
        SetVariableList(output, c_sources_name, c_sources)

    cxx_sources_name = None
    if cxx_sources:
        cxx_sources_name = cmake_target_name + "__cxx_srcs"
        SetVariableList(output, cxx_sources_name, cxx_sources)

    linkable_sources_name = None
    if linkable_sources:
        linkable_sources_name = cmake_target_name + "__linkable_srcs"
        SetVariableList(output, linkable_sources_name, linkable_sources)

    other_sources_name = None
    if other_sources:
        other_sources_name = cmake_target_name + "__other_srcs"
        SetVariableList(output, other_sources_name, other_sources)

    # CMake gets upset when executable targets provide no sources.
    # http://www.cmake.org/pipermail/cmake/2010-July/038461.html
    dummy_sources_name = None
    has_sources = (
        s_sources_name
        or c_sources_name
        or cxx_sources_name
        or linkable_sources_name
        or other_sources_name
    )
    if target_type == "executable" and not has_sources:
        dummy_sources_name = cmake_target_name + "__dummy_srcs"
        SetVariable(
            output, dummy_sources_name, "${obj}.${TOOLSET}/${TARGET}/genc/dummy.c"
        )
        output.write('if(NOT EXISTS "')
        WriteVariable(output, dummy_sources_name)
        output.write('")\n')
        output.write('  file(WRITE "')
        WriteVariable(output, dummy_sources_name)
        output.write('" "")\n')
        output.write("endif()\n")

    # CMake is opposed to setting linker directories and considers the practice
    # of setting linker directories dangerous. Instead, it favors the use of
    # find_library and passing absolute paths to target_link_libraries.
    # However, CMake does provide the command link_directories, which adds
    # link directories to targets defined after it is called.
    # As a result, link_directories must come before the target definition.
    # CMake unfortunately has no means of removing entries from LINK_DIRECTORIES.
    library_dirs = config.get("library_dirs")
    if library_dirs is not None:
        output.write("link_directories(")
        for library_dir in library_dirs:
            output.write(" ")
            output.write(NormjoinPath(path_from_cmakelists_to_gyp, library_dir))
            output.write("\n")
        output.write(")\n")

    output.write(cmake_target_type.command)
    output.write("(")
    output.write(cmake_target_name)

    if cmake_target_type.modifier is not None:
        output.write(" ")
        output.write(cmake_target_type.modifier)

    if s_sources_name:
        WriteVariable(output, s_sources_name, " ")
    if c_sources_name:
        WriteVariable(output, c_sources_name, " ")
    if cxx_sources_name:
        WriteVariable(output, cxx_sources_name, " ")
    if linkable_sources_name:
        WriteVariable(output, linkable_sources_name, " ")
    if other_sources_name:
        WriteVariable(output, other_sources_name, " ")
    if dummy_sources_name:
        WriteVariable(output, dummy_sources_name, " ")

    output.write(")\n")

    # Let CMake know if the 'all' target should depend on this target.
    exclude_from_all = (
        "TRUE" if qualified_target not in all_qualified_targets else "FALSE"
    )
    SetTargetProperty(output, cmake_target_name, "EXCLUDE_FROM_ALL", exclude_from_all)
    for extra_target_name in extra_deps:
        SetTargetProperty(
            output, extra_target_name, "EXCLUDE_FROM_ALL", exclude_from_all
        )

    # Output name and location.
    if target_type != "none":
        # Link as 'C' if there are no other files
        if not c_sources and not cxx_sources:
            SetTargetProperty(output, cmake_target_name, "LINKER_LANGUAGE", ["C"])

        # Mark uncompiled sources as uncompiled.
        if other_sources_name:
            output.write("set_source_files_properties(")
            WriteVariable(output, other_sources_name, "")
            output.write(' PROPERTIES HEADER_FILE_ONLY "TRUE")\n')

        # Mark object sources as linkable.
        if linkable_sources_name:
            output.write("set_source_files_properties(")
            WriteVariable(output, other_sources_name, "")
            output.write(' PROPERTIES EXTERNAL_OBJECT "TRUE")\n')

        # Output directory
        target_output_directory = spec.get("product_dir")
        if target_output_directory is None:
            if target_type in ("executable", "loadable_module"):
                target_output_directory = generator_default_variables["PRODUCT_DIR"]
            elif target_type == "shared_library":
                target_output_directory = "${builddir}/lib.${TOOLSET}"
            elif spec.get("standalone_static_library", False):
                target_output_directory = generator_default_variables["PRODUCT_DIR"]
            else:
                base_path = gyp.common.RelativePath(
                    os.path.dirname(gyp_file), options.toplevel_dir
                )
                target_output_directory = "${obj}.${TOOLSET}"
                target_output_directory = os.path.join(
                    target_output_directory, base_path
                )

        cmake_target_output_directory = NormjoinPathForceCMakeSource(
            path_from_cmakelists_to_gyp, target_output_directory
        )
        SetTargetProperty(
            output,
            cmake_target_name,
            cmake_target_type.property_modifier + "_OUTPUT_DIRECTORY",
            cmake_target_output_directory,
        )

        # Output name
        default_product_prefix = ""
        default_product_name = target_name
        default_product_ext = ""
        if target_type == "static_library":
            static_library_prefix = generator_default_variables["STATIC_LIB_PREFIX"]
            default_product_name = RemovePrefix(
                default_product_name, static_library_prefix
            )
            default_product_prefix = static_library_prefix
            default_product_ext = generator_default_variables["STATIC_LIB_SUFFIX"]

        elif target_type in ("loadable_module", "shared_library"):
            shared_library_prefix = generator_default_variables["SHARED_LIB_PREFIX"]
            default_product_name = RemovePrefix(
                default_product_name, shared_library_prefix
            )
            default_product_prefix = shared_library_prefix
            default_product_ext = generator_default_variables["SHARED_LIB_SUFFIX"]

        elif target_type != "executable":
            print(
                "ERROR: What output file should be generated?",
                "type",
                target_type,
                "target",
                target_name,
            )

        product_prefix = spec.get("product_prefix", default_product_prefix)
        product_name = spec.get("product_name", default_product_name)
        product_ext = spec.get("product_extension")
        product_ext = "." + product_ext if product_ext else default_product_ext

        SetTargetProperty(output, cmake_target_name, "PREFIX", product_prefix)
        SetTargetProperty(
            output,
            cmake_target_name,
            cmake_target_type.property_modifier + "_OUTPUT_NAME",
            product_name,
        )
        SetTargetProperty(output, cmake_target_name, "SUFFIX", product_ext)

        # Make the output of this target referenceable as a source.
        cmake_target_output_basename = product_prefix + product_name + product_ext
        cmake_target_output = os.path.join(
            cmake_target_output_directory, cmake_target_output_basename
        )
        SetFileProperty(output, cmake_target_output, "GENERATED", ["TRUE"], "")

        # Includes
        includes = config.get("include_dirs")
        if includes:
            # This (target include directories) is what requires CMake 2.8.8
            includes_name = cmake_target_name + "__include_dirs"
            SetVariableList(
                output,
                includes_name,
                [
                    NormjoinPathForceCMakeSource(path_from_cmakelists_to_gyp, include)
                    for include in includes
                ],
            )
            output.write("set_property(TARGET ")
            output.write(cmake_target_name)
            output.write(" APPEND PROPERTY INCLUDE_DIRECTORIES ")
            WriteVariable(output, includes_name, "")
            output.write(")\n")

        # Defines
        defines = config.get("defines")
        if defines is not None:
            SetTargetProperty(
                output, cmake_target_name, "COMPILE_DEFINITIONS", defines, ";"
            )

        # Compile Flags - http://www.cmake.org/Bug/view.php?id=6493
        # CMake currently does not have target C and CXX flags.
        # So, instead of doing...

        # cflags_c = config.get('cflags_c')
        # if cflags_c is not None:
        #   SetTargetProperty(output, cmake_target_name,
        #                       'C_COMPILE_FLAGS', cflags_c, ' ')

        # cflags_cc = config.get('cflags_cc')
        # if cflags_cc is not None:
        #   SetTargetProperty(output, cmake_target_name,
        #                       'CXX_COMPILE_FLAGS', cflags_cc, ' ')

        # Instead we must...
        cflags = config.get("cflags", [])
        cflags_c = config.get("cflags_c", [])
        cflags_cxx = config.get("cflags_cc", [])
        if xcode_settings:
            cflags = xcode_settings.GetCflags(config_to_use)
            cflags_c = xcode_settings.GetCflagsC(config_to_use)
            cflags_cxx = xcode_settings.GetCflagsCC(config_to_use)
            # cflags_objc = xcode_settings.GetCflagsObjC(config_to_use)
            # cflags_objcc = xcode_settings.GetCflagsObjCC(config_to_use)

        if (not cflags_c or not c_sources) and (not cflags_cxx or not cxx_sources):
            SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", cflags, " ")

        elif c_sources and not (s_sources or cxx_sources):
            flags = []
            flags.extend(cflags)
            flags.extend(cflags_c)
            SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", flags, " ")

        elif cxx_sources and not (s_sources or c_sources):
            flags = []
            flags.extend(cflags)
            flags.extend(cflags_cxx)
            SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", flags, " ")

        else:
            # TODO: This is broken, one cannot generally set properties on files,
            # as other targets may require different properties on the same files.
            if s_sources and cflags:
                SetFilesProperty(output, s_sources_name, "COMPILE_FLAGS", cflags, " ")

            if c_sources and (cflags or cflags_c):
                flags = []
                flags.extend(cflags)
                flags.extend(cflags_c)
                SetFilesProperty(output, c_sources_name, "COMPILE_FLAGS", flags, " ")

            if cxx_sources and (cflags or cflags_cxx):
                flags = []
                flags.extend(cflags)
                flags.extend(cflags_cxx)
                SetFilesProperty(output, cxx_sources_name, "COMPILE_FLAGS", flags, " ")

        # Linker flags
        ldflags = config.get("ldflags")
        if ldflags is not None:
            SetTargetProperty(output, cmake_target_name, "LINK_FLAGS", ldflags, " ")

        # XCode settings
        xcode_settings = config.get("xcode_settings", {})
        for xcode_setting, xcode_value in xcode_settings.items():
            SetTargetProperty(
                output,
                cmake_target_name,
                "XCODE_ATTRIBUTE_%s" % xcode_setting,
                xcode_value,
                "" if isinstance(xcode_value, str) else " ",
            )

    # Note on Dependencies and Libraries:
    # CMake wants to handle link order, resolving the link line up front.
    # Gyp does not retain or enforce specifying enough information to do so.
    # So do as other gyp generators and use --start-group and --end-group.
    # Give CMake as little information as possible so that it doesn't mess it up.

    # Dependencies
    rawDeps = spec.get("dependencies", [])

    static_deps = []
    shared_deps = []
    other_deps = []
    for rawDep in rawDeps:
        dep_cmake_name = namer.CreateCMakeTargetName(rawDep)
        dep_spec = target_dicts.get(rawDep, {})
        dep_target_type = dep_spec.get("type", None)

        if dep_target_type == "static_library":
            static_deps.append(dep_cmake_name)
        elif dep_target_type == "shared_library":
            shared_deps.append(dep_cmake_name)
        else:
            other_deps.append(dep_cmake_name)

    # ensure all external dependencies are complete before internal dependencies
    # extra_deps currently only depend on their own deps, so otherwise run early
    if static_deps or shared_deps or other_deps:
        for extra_dep in extra_deps:
            output.write("add_dependencies(")
            output.write(extra_dep)
            output.write("\n")
            for deps in (static_deps, shared_deps, other_deps):
                for dep in gyp.common.uniquer(deps):
                    output.write("  ")
                    output.write(dep)
                    output.write("\n")
            output.write(")\n")

    linkable = target_type in ("executable", "loadable_module", "shared_library")
    other_deps.extend(extra_deps)
    if other_deps or (not linkable and (static_deps or shared_deps)):
        output.write("add_dependencies(")
        output.write(cmake_target_name)
        output.write("\n")
        for dep in gyp.common.uniquer(other_deps):
            output.write("  ")
            output.write(dep)
            output.write("\n")
        if not linkable:
            for deps in (static_deps, shared_deps):
                for lib_dep in gyp.common.uniquer(deps):
                    output.write("  ")
                    output.write(lib_dep)
                    output.write("\n")
        output.write(")\n")

    # Libraries
    if linkable:
        external_libs = [lib for lib in spec.get("libraries", []) if len(lib) > 0]
        if external_libs or static_deps or shared_deps:
            output.write("target_link_libraries(")
            output.write(cmake_target_name)
            output.write("\n")
            if static_deps:
                write_group = circular_libs and len(static_deps) > 1 and flavor != "mac"
                if write_group:
                    output.write("-Wl,--start-group\n")
                for dep in gyp.common.uniquer(static_deps):
                    output.write("  ")
                    output.write(dep)
                    output.write("\n")
                if write_group:
                    output.write("-Wl,--end-group\n")
            if shared_deps:
                for dep in gyp.common.uniquer(shared_deps):
                    output.write("  ")
                    output.write(dep)
                    output.write("\n")
            if external_libs:
                for lib in gyp.common.uniquer(external_libs):
                    output.write('  "')
                    output.write(RemovePrefix(lib, "$(SDKROOT)"))
                    output.write('"\n')

            output.write(")\n")

    UnsetVariable(output, "TOOLSET")
    UnsetVariable(output, "TARGET")


def GenerateOutputForConfig(target_list, target_dicts, data, params, config_to_use):
    options = params["options"]
    generator_flags = params["generator_flags"]
    flavor = gyp.common.GetFlavor(params)

    # generator_dir: relative path from pwd to where make puts build files.
    # Makes migrating from make to cmake easier, cmake doesn't put anything here.
    # Each Gyp configuration creates a different CMakeLists.txt file
    # to avoid incompatibilities between Gyp and CMake configurations.
    generator_dir = os.path.relpath(options.generator_output or ".")

    # output_dir: relative path from generator_dir to the build directory.
    output_dir = generator_flags.get("output_dir", "out")

    # build_dir: relative path from source root to our output files.
    # e.g. "out/Debug"
    build_dir = os.path.normpath(os.path.join(generator_dir, output_dir, config_to_use))

    toplevel_build = os.path.join(options.toplevel_dir, build_dir)

    output_file = os.path.join(toplevel_build, "CMakeLists.txt")
    gyp.common.EnsureDirExists(output_file)

    output = open(output_file, "w")
    output.write("cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n")
    output.write("cmake_policy(VERSION 2.8.8)\n")

    gyp_file, project_target, _ = gyp.common.ParseQualifiedTarget(target_list[-1])
    output.write("project(")
    output.write(project_target)
    output.write(")\n")

    SetVariable(output, "configuration", config_to_use)

    ar = None
    cc = None
    cxx = None

    make_global_settings = data[gyp_file].get("make_global_settings", [])
    build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir)
    for key, value in make_global_settings:
        if key == "AR":
            ar = os.path.join(build_to_top, value)
        if key == "CC":
            cc = os.path.join(build_to_top, value)
        if key == "CXX":
            cxx = os.path.join(build_to_top, value)

    ar = gyp.common.GetEnvironFallback(["AR_target", "AR"], ar)
    cc = gyp.common.GetEnvironFallback(["CC_target", "CC"], cc)
    cxx = gyp.common.GetEnvironFallback(["CXX_target", "CXX"], cxx)

    if ar:
        SetVariable(output, "CMAKE_AR", ar)
    if cc:
        SetVariable(output, "CMAKE_C_COMPILER", cc)
    if cxx:
        SetVariable(output, "CMAKE_CXX_COMPILER", cxx)

    # The following appears to be as-yet undocumented.
    # http://public.kitware.com/Bug/view.php?id=8392
    output.write("enable_language(ASM)\n")
    # ASM-ATT does not support .S files.
    # output.write('enable_language(ASM-ATT)\n')

    if cc:
        SetVariable(output, "CMAKE_ASM_COMPILER", cc)

    SetVariable(output, "builddir", "${CMAKE_CURRENT_BINARY_DIR}")
    SetVariable(output, "obj", "${builddir}/obj")
    output.write("\n")

    # TODO: Undocumented/unsupported (the CMake Java generator depends on it).
    # CMake by default names the object resulting from foo.c to be foo.c.o.
    # Gyp traditionally names the object resulting from foo.c foo.o.
    # This should be irrelevant, but some targets extract .o files from .a
    # and depend on the name of the extracted .o files.
    output.write("set(CMAKE_C_OUTPUT_EXTENSION_REPLACE 1)\n")
    output.write("set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1)\n")
    output.write("\n")

    # Force ninja to use rsp files. Otherwise link and ar lines can get too long,
    # resulting in 'Argument list too long' errors.
    # However, rsp files don't work correctly on Mac.
    if flavor != "mac":
        output.write("set(CMAKE_NINJA_FORCE_RESPONSE_FILE 1)\n")
    output.write("\n")

    namer = CMakeNamer(target_list)

    # The list of targets upon which the 'all' target should depend.
    # CMake has it's own implicit 'all' target, one is not created explicitly.
    all_qualified_targets = set()
    for build_file in params["build_files"]:
        for qualified_target in gyp.common.AllTargets(
            target_list, target_dicts, os.path.normpath(build_file)
        ):
            all_qualified_targets.add(qualified_target)

    for qualified_target in target_list:
        if flavor == "mac":
            gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target)
            spec = target_dicts[qualified_target]
            gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[gyp_file], spec)

        WriteTarget(
            namer,
            qualified_target,
            target_dicts,
            build_dir,
            config_to_use,
            options,
            generator_flags,
            all_qualified_targets,
            flavor,
            output,
        )

    output.close()


def PerformBuild(data, configurations, params):
    options = params["options"]
    generator_flags = params["generator_flags"]

    # generator_dir: relative path from pwd to where make puts build files.
    # Makes migrating from make to cmake easier, cmake doesn't put anything here.
    generator_dir = os.path.relpath(options.generator_output or ".")

    # output_dir: relative path from generator_dir to the build directory.
    output_dir = generator_flags.get("output_dir", "out")

    for config_name in configurations:
        # build_dir: relative path from source root to our output files.
        # e.g. "out/Debug"
        build_dir = os.path.normpath(
            os.path.join(generator_dir, output_dir, config_name)
        )
        arguments = ["cmake", "-G", "Ninja"]
        print(f"Generating [{config_name}]: {arguments}")
        subprocess.check_call(arguments, cwd=build_dir)

        arguments = ["ninja", "-C", build_dir]
        print(f"Building [{config_name}]: {arguments}")
        subprocess.check_call(arguments)


def CallGenerateOutputForConfig(arglist):
    # Ignore the interrupt signal so that the parent process catches it and
    # kills all multiprocessing children.
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    target_list, target_dicts, data, params, config_name = arglist
    GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)


def GenerateOutput(target_list, target_dicts, data, params):
    user_config = params.get("generator_flags", {}).get("config", None)
    if user_config:
        GenerateOutputForConfig(target_list, target_dicts, data, params, user_config)
    else:
        config_names = target_dicts[target_list[0]]["configurations"]
        if params["parallel"]:
            try:
                pool = multiprocessing.Pool(len(config_names))
                arglists = []
                for config_name in config_names:
                    arglists.append(
                        (target_list, target_dicts, data, params, config_name)
                    )
                    pool.map(CallGenerateOutputForConfig, arglists)
            except KeyboardInterrupt as e:
                pool.terminate()
                raise e
        else:
            for config_name in config_names:
                GenerateOutputForConfig(
                    target_list, target_dicts, data, params, config_name
                )
# Copyright (c) 2016 Ben Noordhuis . All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import gyp.common
import gyp.xcode_emulation
import json
import os

generator_additional_non_configuration_keys = []
generator_additional_path_sections = []
generator_extra_sources_for_rules = []
generator_filelist_paths = None
generator_supports_multiple_toolsets = True
generator_wants_sorted_dependencies = False

# Lifted from make.py.  The actual values don't matter much.
generator_default_variables = {
    "CONFIGURATION_NAME": "$(BUILDTYPE)",
    "EXECUTABLE_PREFIX": "",
    "EXECUTABLE_SUFFIX": "",
    "INTERMEDIATE_DIR": "$(obj).$(TOOLSET)/$(TARGET)/geni",
    "PRODUCT_DIR": "$(builddir)",
    "RULE_INPUT_DIRNAME": "%(INPUT_DIRNAME)s",
    "RULE_INPUT_EXT": "$(suffix $<)",
    "RULE_INPUT_NAME": "$(notdir $<)",
    "RULE_INPUT_PATH": "$(abspath $<)",
    "RULE_INPUT_ROOT": "%(INPUT_ROOT)s",
    "SHARED_INTERMEDIATE_DIR": "$(obj)/gen",
    "SHARED_LIB_PREFIX": "lib",
    "STATIC_LIB_PREFIX": "lib",
    "STATIC_LIB_SUFFIX": ".a",
}


def IsMac(params):
    return gyp.common.GetFlavor(params) == "mac"


def CalculateVariables(default_variables, params):
    default_variables.setdefault("OS", gyp.common.GetFlavor(params))


def AddCommandsForTarget(cwd, target, params, per_config_commands):
    output_dir = params["generator_flags"].get("output_dir", "out")
    for configuration_name, configuration in target["configurations"].items():
        if IsMac(params):
            xcode_settings = gyp.xcode_emulation.XcodeSettings(target)
            cflags = xcode_settings.GetCflags(configuration_name)
            cflags_c = xcode_settings.GetCflagsC(configuration_name)
            cflags_cc = xcode_settings.GetCflagsCC(configuration_name)
        else:
            cflags = configuration.get("cflags", [])
            cflags_c = configuration.get("cflags_c", [])
            cflags_cc = configuration.get("cflags_cc", [])

        cflags_c = cflags + cflags_c
        cflags_cc = cflags + cflags_cc

        defines = configuration.get("defines", [])
        defines = ["-D" + s for s in defines]

        # TODO(bnoordhuis) Handle generated source files.
        extensions = (".c", ".cc", ".cpp", ".cxx")
        sources = [s for s in target.get("sources", []) if s.endswith(extensions)]

        def resolve(filename):
            return os.path.abspath(os.path.join(cwd, filename))

        # TODO(bnoordhuis) Handle generated header files.
        include_dirs = configuration.get("include_dirs", [])
        include_dirs = [s for s in include_dirs if not s.startswith("$(obj)")]
        includes = ["-I" + resolve(s) for s in include_dirs]

        defines = gyp.common.EncodePOSIXShellList(defines)
        includes = gyp.common.EncodePOSIXShellList(includes)
        cflags_c = gyp.common.EncodePOSIXShellList(cflags_c)
        cflags_cc = gyp.common.EncodePOSIXShellList(cflags_cc)

        commands = per_config_commands.setdefault(configuration_name, [])
        for source in sources:
            file = resolve(source)
            isc = source.endswith(".c")
            cc = "cc" if isc else "c++"
            cflags = cflags_c if isc else cflags_cc
            command = " ".join(
                (
                    cc,
                    defines,
                    includes,
                    cflags,
                    "-c",
                    gyp.common.EncodePOSIXShellArgument(file),
                )
            )
            commands.append({"command": command, "directory": output_dir, "file": file})


def GenerateOutput(target_list, target_dicts, data, params):
    per_config_commands = {}
    for qualified_target, target in target_dicts.items():
        build_file, target_name, toolset = gyp.common.ParseQualifiedTarget(
            qualified_target
        )
        if IsMac(params):
            settings = data[build_file]
            gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(settings, target)
        cwd = os.path.dirname(build_file)
        AddCommandsForTarget(cwd, target, params, per_config_commands)

    output_dir = None
    try:
        # generator_output can be `None` on Windows machines, or even not
        # defined in other cases
        output_dir = params.get("options").generator_output
    except AttributeError:
        pass
    output_dir = output_dir or params["generator_flags"].get("output_dir", "out")
    for configuration_name, commands in per_config_commands.items():
        filename = os.path.join(output_dir, configuration_name, "compile_commands.json")
        gyp.common.EnsureDirExists(filename)
        fp = open(filename, "w")
        json.dump(commands, fp=fp, indent=0, check_circular=False)


def PerformBuild(data, configurations, params):
    pass
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.


import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json

generator_supports_multiple_toolsets = True

generator_wants_static_library_dependencies_adjusted = False

generator_filelist_paths = {}

generator_default_variables = {}
for dirname in [
    "INTERMEDIATE_DIR",
    "SHARED_INTERMEDIATE_DIR",
    "PRODUCT_DIR",
    "LIB_DIR",
    "SHARED_LIB_DIR",
]:
    # Some gyp steps fail if these are empty(!).
    generator_default_variables[dirname] = "dir"
for unused in [
    "RULE_INPUT_PATH",
    "RULE_INPUT_ROOT",
    "RULE_INPUT_NAME",
    "RULE_INPUT_DIRNAME",
    "RULE_INPUT_EXT",
    "EXECUTABLE_PREFIX",
    "EXECUTABLE_SUFFIX",
    "STATIC_LIB_PREFIX",
    "STATIC_LIB_SUFFIX",
    "SHARED_LIB_PREFIX",
    "SHARED_LIB_SUFFIX",
    "CONFIGURATION_NAME",
]:
    generator_default_variables[unused] = ""


def CalculateVariables(default_variables, params):
    generator_flags = params.get("generator_flags", {})
    for key, val in generator_flags.items():
        default_variables.setdefault(key, val)
    default_variables.setdefault("OS", gyp.common.GetFlavor(params))

    flavor = gyp.common.GetFlavor(params)
    if flavor == "win":
        gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)


def CalculateGeneratorInputInfo(params):
    """Calculate the generator specific info that gets fed to input (called by
  gyp)."""
    generator_flags = params.get("generator_flags", {})
    if generator_flags.get("adjust_static_libraries", False):
        global generator_wants_static_library_dependencies_adjusted
        generator_wants_static_library_dependencies_adjusted = True

    toplevel = params["options"].toplevel_dir
    generator_dir = os.path.relpath(params["options"].generator_output or ".")
    # output_dir: relative path from generator_dir to the build directory.
    output_dir = generator_flags.get("output_dir", "out")
    qualified_out_dir = os.path.normpath(
        os.path.join(toplevel, generator_dir, output_dir, "gypfiles")
    )
    global generator_filelist_paths
    generator_filelist_paths = {
        "toplevel": toplevel,
        "qualified_out_dir": qualified_out_dir,
    }


def GenerateOutput(target_list, target_dicts, data, params):
    # Map of target -> list of targets it depends on.
    edges = {}

    # Queue of targets to visit.
    targets_to_visit = target_list[:]

    while len(targets_to_visit) > 0:
        target = targets_to_visit.pop()
        if target in edges:
            continue
        edges[target] = []

        for dep in target_dicts[target].get("dependencies", []):
            edges[target].append(dep)
            targets_to_visit.append(dep)

    try:
        filepath = params["generator_flags"]["output_dir"]
    except KeyError:
        filepath = "."
    filename = os.path.join(filepath, "dump.json")
    f = open(filename, "w")
    json.dump(edges, f)
    f.close()
    print("Wrote json to %s." % filename)
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""GYP backend that generates Eclipse CDT settings files.

This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML
files that can be imported into an Eclipse CDT project. The XML file contains a
list of include paths and symbols (i.e. defines).

Because a full .cproject definition is not created by this generator, it's not
possible to properly define the include dirs and symbols for each file
individually.  Instead, one set of includes/symbols is generated for the entire
project.  This works fairly well (and is a vast improvement in general), but may
still result in a few indexer issues here and there.

This generator has no automated tests, so expect it to be broken.
"""

from xml.sax.saxutils import escape
import os.path
import subprocess
import gyp
import gyp.common
import gyp.msvs_emulation
import shlex
import xml.etree.ElementTree as ET

generator_wants_static_library_dependencies_adjusted = False

generator_default_variables = {}

for dirname in ["INTERMEDIATE_DIR", "PRODUCT_DIR", "LIB_DIR", "SHARED_LIB_DIR"]:
    # Some gyp steps fail if these are empty(!), so we convert them to variables
    generator_default_variables[dirname] = "$" + dirname

for unused in [
    "RULE_INPUT_PATH",
    "RULE_INPUT_ROOT",
    "RULE_INPUT_NAME",
    "RULE_INPUT_DIRNAME",
    "RULE_INPUT_EXT",
    "EXECUTABLE_PREFIX",
    "EXECUTABLE_SUFFIX",
    "STATIC_LIB_PREFIX",
    "STATIC_LIB_SUFFIX",
    "SHARED_LIB_PREFIX",
    "SHARED_LIB_SUFFIX",
    "CONFIGURATION_NAME",
]:
    generator_default_variables[unused] = ""

# Include dirs will occasionally use the SHARED_INTERMEDIATE_DIR variable as
# part of the path when dealing with generated headers.  This value will be
# replaced dynamically for each configuration.
generator_default_variables["SHARED_INTERMEDIATE_DIR"] = "$SHARED_INTERMEDIATE_DIR"


def CalculateVariables(default_variables, params):
    generator_flags = params.get("generator_flags", {})
    for key, val in generator_flags.items():
        default_variables.setdefault(key, val)
    flavor = gyp.common.GetFlavor(params)
    default_variables.setdefault("OS", flavor)
    if flavor == "win":
        gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)


def CalculateGeneratorInputInfo(params):
    """Calculate the generator specific info that gets fed to input (called by
  gyp)."""
    generator_flags = params.get("generator_flags", {})
    if generator_flags.get("adjust_static_libraries", False):
        global generator_wants_static_library_dependencies_adjusted
        generator_wants_static_library_dependencies_adjusted = True


def GetAllIncludeDirectories(
    target_list,
    target_dicts,
    shared_intermediate_dirs,
    config_name,
    params,
    compiler_path,
):
    """Calculate the set of include directories to be used.

  Returns:
    A list including all the include_dir's specified for every target followed
    by any include directories that were added as cflag compiler options.
  """

    gyp_includes_set = set()
    compiler_includes_list = []

    # Find compiler's default include dirs.
    if compiler_path:
        command = shlex.split(compiler_path)
        command.extend(["-E", "-xc++", "-v", "-"])
        proc = subprocess.Popen(
            args=command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        output = proc.communicate()[1].decode("utf-8")
        # Extract the list of include dirs from the output, which has this format:
        #   ...
        #   #include "..." search starts here:
        #   #include <...> search starts here:
        #    /usr/include/c++/4.6
        #    /usr/local/include
        #   End of search list.
        #   ...
        in_include_list = False
        for line in output.splitlines():
            if line.startswith("#include"):
                in_include_list = True
                continue
            if line.startswith("End of search list."):
                break
            if in_include_list:
                include_dir = line.strip()
                if include_dir not in compiler_includes_list:
                    compiler_includes_list.append(include_dir)

    flavor = gyp.common.GetFlavor(params)
    if flavor == "win":
        generator_flags = params.get("generator_flags", {})
    for target_name in target_list:
        target = target_dicts[target_name]
        if config_name in target["configurations"]:
            config = target["configurations"][config_name]

            # Look for any include dirs that were explicitly added via cflags. This
            # may be done in gyp files to force certain includes to come at the end.
            # TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and
            # remove this.
            if flavor == "win":
                msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags)
                cflags = msvs_settings.GetCflags(config_name)
            else:
                cflags = config["cflags"]
            for cflag in cflags:
                if cflag.startswith("-I"):
                    include_dir = cflag[2:]
                    if include_dir not in compiler_includes_list:
                        compiler_includes_list.append(include_dir)

            # Find standard gyp include dirs.
            if "include_dirs" in config:
                include_dirs = config["include_dirs"]
                for shared_intermediate_dir in shared_intermediate_dirs:
                    for include_dir in include_dirs:
                        include_dir = include_dir.replace(
                            "$SHARED_INTERMEDIATE_DIR", shared_intermediate_dir
                        )
                        if not os.path.isabs(include_dir):
                            base_dir = os.path.dirname(target_name)

                            include_dir = base_dir + "/" + include_dir
                            include_dir = os.path.abspath(include_dir)

                        gyp_includes_set.add(include_dir)

    # Generate a list that has all the include dirs.
    all_includes_list = list(gyp_includes_set)
    all_includes_list.sort()
    for compiler_include in compiler_includes_list:
        if compiler_include not in gyp_includes_set:
            all_includes_list.append(compiler_include)

    # All done.
    return all_includes_list


def GetCompilerPath(target_list, data, options):
    """Determine a command that can be used to invoke the compiler.

  Returns:
    If this is a gyp project that has explicit make settings, try to determine
    the compiler from that.  Otherwise, see if a compiler was specified via the
    CC_target environment variable.
  """
    # First, see if the compiler is configured in make's settings.
    build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0])
    make_global_settings_dict = data[build_file].get("make_global_settings", {})
    for key, value in make_global_settings_dict:
        if key in ["CC", "CXX"]:
            return os.path.join(options.toplevel_dir, value)

    # Check to see if the compiler was specified as an environment variable.
    for key in ["CC_target", "CC", "CXX"]:
        compiler = os.environ.get(key)
        if compiler:
            return compiler

    return "gcc"


def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path):
    """Calculate the defines for a project.

  Returns:
    A dict that includes explicit defines declared in gyp files along with all
    of the default defines that the compiler uses.
  """

    # Get defines declared in the gyp files.
    all_defines = {}
    flavor = gyp.common.GetFlavor(params)
    if flavor == "win":
        generator_flags = params.get("generator_flags", {})
    for target_name in target_list:
        target = target_dicts[target_name]

        if flavor == "win":
            msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags)
            extra_defines = msvs_settings.GetComputedDefines(config_name)
        else:
            extra_defines = []
        if config_name in target["configurations"]:
            config = target["configurations"][config_name]
            target_defines = config["defines"]
        else:
            target_defines = []
        for define in target_defines + extra_defines:
            split_define = define.split("=", 1)
            if len(split_define) == 1:
                split_define.append("1")
            if split_define[0].strip() in all_defines:
                # Already defined
                continue
            all_defines[split_define[0].strip()] = split_define[1].strip()
    # Get default compiler defines (if possible).
    if flavor == "win":
        return all_defines  # Default defines already processed in the loop above.
    if compiler_path:
        command = shlex.split(compiler_path)
        command.extend(["-E", "-dM", "-"])
        cpp_proc = subprocess.Popen(
            args=command, cwd=".", stdin=subprocess.PIPE, stdout=subprocess.PIPE
        )
        cpp_output = cpp_proc.communicate()[0].decode("utf-8")
        cpp_lines = cpp_output.split("\n")
        for cpp_line in cpp_lines:
            if not cpp_line.strip():
                continue
            cpp_line_parts = cpp_line.split(" ", 2)
            key = cpp_line_parts[1]
            val = cpp_line_parts[2] if len(cpp_line_parts) >= 3 else "1"
            all_defines[key] = val

    return all_defines


def WriteIncludePaths(out, eclipse_langs, include_dirs):
    """Write the includes section of a CDT settings export file."""

    out.write(
        '  
\n' ) out.write(' \n') for lang in eclipse_langs: out.write(' \n' % lang) for include_dir in include_dirs: out.write( ' %s\n' % include_dir ) out.write(" \n") out.write("
\n") def WriteMacros(out, eclipse_langs, defines): """Write the macros section of a CDT settings export file.""" out.write( '
\n' ) out.write(' \n') for lang in eclipse_langs: out.write(' \n' % lang) for key in sorted(defines): out.write( " %s%s\n" % (escape(key), escape(defines[key])) ) out.write(" \n") out.write("
\n") def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params["options"] generator_flags = params.get("generator_flags", {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.join(generator_flags.get("output_dir", "out"), config_name) toplevel_build = os.path.join(options.toplevel_dir, build_dir) # Ninja uses out/Debug/gen while make uses out/Debug/obj/gen as the # SHARED_INTERMEDIATE_DIR. Include both possible locations. shared_intermediate_dirs = [ os.path.join(toplevel_build, "obj", "gen"), os.path.join(toplevel_build, "gen"), ] GenerateCdtSettingsFile( target_list, target_dicts, data, params, config_name, os.path.join(toplevel_build, "eclipse-cdt-settings.xml"), options, shared_intermediate_dirs, ) GenerateClasspathFile( target_list, target_dicts, options.toplevel_dir, toplevel_build, os.path.join(toplevel_build, "eclipse-classpath.xml"), ) def GenerateCdtSettingsFile( target_list, target_dicts, data, params, config_name, out_name, options, shared_intermediate_dirs, ): gyp.common.EnsureDirExists(out_name) with open(out_name, "w") as out: out.write('\n') out.write("\n") eclipse_langs = [ "C++ Source File", "C Source File", "Assembly Source File", "GNU C++", "GNU C", "Assembly", ] compiler_path = GetCompilerPath(target_list, data, options) include_dirs = GetAllIncludeDirectories( target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path, ) WriteIncludePaths(out, eclipse_langs, include_dirs) defines = GetAllDefines( target_list, target_dicts, data, config_name, params, compiler_path ) WriteMacros(out, eclipse_langs, defines) out.write("\n") def GenerateClasspathFile( target_list, target_dicts, toplevel_dir, toplevel_build, out_name ): """Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.""" gyp.common.EnsureDirExists(out_name) result = ET.Element("classpath") def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, "classpathentry") entry_element.set("kind", kind) entry_element.set("path", path) AddElements("lib", GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements("src", GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements("con", ["org.eclipse.jdt.launching.JRE_CONTAINER"]) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements("output", [os.path.join(toplevel_build, ".eclipse-java-build")]) ET.ElementTree(result).write(out_name) def GetJavaJars(target_list, target_dicts, toplevel_dir): """Generates a sequence of all .jars used as inputs.""" for target_name in target_list: target = target_dicts[target_name] for action in target.get("actions", []): for input_ in action["inputs"]: if os.path.splitext(input_)[1] == ".jar" and not input_.startswith("$"): if os.path.isabs(input_): yield input_ else: yield os.path.join(os.path.dirname(target_name), input_) def GetJavaSourceDirs(target_list, target_dicts, toplevel_dir): """Generates a sequence of all likely java package root directories.""" for target_name in target_list: target = target_dicts[target_name] for action in target.get("actions", []): for input_ in action["inputs"]: if os.path.splitext(input_)[1] == ".java" and not input_.startswith( "$" ): dir_ = os.path.dirname( os.path.join(os.path.dirname(target_name), input_) ) # If there is a parent 'src' or 'java' folder, navigate up to it - # these are canonical package root names in Chromium. This will # break if 'src' or 'java' exists in the package structure. This # could be further improved by inspecting the java file for the # package name if this proves to be too fragile in practice. parent_search = dir_ while os.path.basename(parent_search) not in ["src", "java"]: parent_search, _ = os.path.split(parent_search) if not parent_search or parent_search == toplevel_dir: # Didn't find a known root, just return the original path yield dir_ break else: yield parent_search def GenerateOutput(target_list, target_dicts, data, params): """Generate an XML settings file that can be imported into a CDT project.""" if params["options"].generator_output: raise NotImplementedError("--generator_output not implemented for eclipse") user_config = params.get("generator_flags", {}).get("config", None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]["configurations"] for config_name in config_names: GenerateOutputForConfig( target_list, target_dicts, data, params, config_name ) # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """gypd output module This module produces gyp input as its output. Output files are given the .gypd extension to avoid overwriting the .gyp files that they are generated from. Internal references to .gyp files (such as those found in "dependencies" sections) are not adjusted to point to .gypd files instead; unlike other paths, which are relative to the .gyp or .gypd file, such paths are relative to the directory from which gyp was run to create the .gypd file. This generator module is intended to be a sample and a debugging aid, hence the "d" for "debug" in .gypd. It is useful to inspect the results of the various merges, expansions, and conditional evaluations performed by gyp and to see a representation of what would be fed to a generator module. It's not advisable to rename .gypd files produced by this module to .gyp, because they will have all merges, expansions, and evaluations already performed and the relevant constructs not present in the output; paths to dependencies may be wrong; and various sections that do not belong in .gyp files such as such as "included_files" and "*_excluded" will be present. Output will also be stripped of comments. This is not intended to be a general-purpose gyp pretty-printer; for that, you probably just want to run "pprint.pprint(eval(open('source.gyp').read()))", which will still strip comments but won't do all of the other things done to this module's output. The specific formatting of the output generated by this module is subject to change. """ import gyp.common import pprint # These variables should just be spit back out as variable references. _generator_identity_variables = [ "CONFIGURATION_NAME", "EXECUTABLE_PREFIX", "EXECUTABLE_SUFFIX", "INTERMEDIATE_DIR", "LIB_DIR", "PRODUCT_DIR", "RULE_INPUT_ROOT", "RULE_INPUT_DIRNAME", "RULE_INPUT_EXT", "RULE_INPUT_NAME", "RULE_INPUT_PATH", "SHARED_INTERMEDIATE_DIR", "SHARED_LIB_DIR", "SHARED_LIB_PREFIX", "SHARED_LIB_SUFFIX", "STATIC_LIB_PREFIX", "STATIC_LIB_SUFFIX", ] # gypd doesn't define a default value for OS like many other generator # modules. Specify "-D OS=whatever" on the command line to provide a value. generator_default_variables = {} # gypd supports multiple toolsets generator_supports_multiple_toolsets = True # TODO(mark): This always uses <, which isn't right. The input module should # notify the generator to tell it which phase it is operating in, and this # module should use < for the early phase and then switch to > for the late # phase. Bonus points for carrying @ back into the output too. for v in _generator_identity_variables: generator_default_variables[v] = "<(%s)" % v def GenerateOutput(target_list, target_dicts, data, params): output_files = {} for qualified_target in target_list: [input_file, target] = gyp.common.ParseQualifiedTarget(qualified_target)[0:2] if input_file[-4:] != ".gyp": continue input_file_stem = input_file[:-4] output_file = input_file_stem + params["options"].suffix + ".gypd" output_files[output_file] = output_files.get(output_file, input_file) for output_file, input_file in output_files.items(): output = open(output_file, "w") pprint.pprint(data[input_file], output) output.close() # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """gypsh output module gypsh is a GYP shell. It's not really a generator per se. All it does is fire up an interactive Python session with a few local variables set to the variables passed to the generator. Like gypd, it's intended as a debugging aid, to facilitate the exploration of .gyp structures after being processed by the input module. The expected usage is "gyp -f gypsh -D OS=desired_os". """ import code import sys # All of this stuff about generator variables was lovingly ripped from gypd.py. # That module has a much better description of what's going on and why. _generator_identity_variables = [ "EXECUTABLE_PREFIX", "EXECUTABLE_SUFFIX", "INTERMEDIATE_DIR", "PRODUCT_DIR", "RULE_INPUT_ROOT", "RULE_INPUT_DIRNAME", "RULE_INPUT_EXT", "RULE_INPUT_NAME", "RULE_INPUT_PATH", "SHARED_INTERMEDIATE_DIR", ] generator_default_variables = {} for v in _generator_identity_variables: generator_default_variables[v] = "<(%s)" % v def GenerateOutput(target_list, target_dicts, data, params): locals = { "target_list": target_list, "target_dicts": target_dicts, "data": data, } # Use a banner that looks like the stock Python one and like what # code.interact uses by default, but tack on something to indicate what # locals are available, and identify gypsh. banner = ( f"Python {sys.version} on {sys.platform}\nlocals.keys() = " f"{sorted(locals.keys())!r}\ngypsh" ) code.interact(banner, local=locals) # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Notes: # # This is all roughly based on the Makefile system used by the Linux # kernel, but is a non-recursive make -- we put the entire dependency # graph in front of make and let it figure it out. # # The code below generates a separate .mk file for each target, but # all are sourced by the top-level Makefile. This means that all # variables in .mk-files clobber one another. Be careful to use := # where appropriate for immediate evaluation, and similarly to watch # that you're not relying on a variable value to last between different # .mk files. # # TODOs: # # Global settings and utility functions are currently stuffed in the # toplevel Makefile. It may make sense to generate some .mk files on # the side to keep the files readable. import os import re import subprocess import sys import gyp import gyp.common import gyp.xcode_emulation from gyp.common import GetEnvironFallback import hashlib generator_default_variables = { "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "STATIC_LIB_PREFIX": "lib", "SHARED_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", "INTERMEDIATE_DIR": "$(obj).$(TOOLSET)/$(TARGET)/geni", "SHARED_INTERMEDIATE_DIR": "$(obj)/gen", "PRODUCT_DIR": "$(builddir)", "RULE_INPUT_ROOT": "%(INPUT_ROOT)s", # This gets expanded by Python. "RULE_INPUT_DIRNAME": "%(INPUT_DIRNAME)s", # This gets expanded by Python. "RULE_INPUT_PATH": "$(abspath $<)", "RULE_INPUT_EXT": "$(suffix $<)", "RULE_INPUT_NAME": "$(notdir $<)", "CONFIGURATION_NAME": "$(BUILDTYPE)", } # Make supports multiple toolsets generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() # Request sorted dependencies in the order from dependents to dependencies. generator_wants_sorted_dependencies = False # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" flavor = gyp.common.GetFlavor(params) if flavor == "mac": default_variables.setdefault("OS", "mac") default_variables.setdefault("SHARED_LIB_SUFFIX", ".dylib") default_variables.setdefault( "SHARED_LIB_DIR", generator_default_variables["PRODUCT_DIR"] ) default_variables.setdefault( "LIB_DIR", generator_default_variables["PRODUCT_DIR"] ) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Make generator. import gyp.generator.xcode as xcode_generator global generator_additional_non_configuration_keys generator_additional_non_configuration_keys = getattr( xcode_generator, "generator_additional_non_configuration_keys", [] ) global generator_additional_path_sections generator_additional_path_sections = getattr( xcode_generator, "generator_additional_path_sections", [] ) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr( xcode_generator, "generator_extra_sources_for_rules", [] ) COMPILABLE_EXTENSIONS.update({".m": "objc", ".mm": "objcxx"}) else: operating_system = flavor if flavor == "android": operating_system = "linux" # Keep this legacy behavior for now. default_variables.setdefault("OS", operating_system) if flavor == "aix": default_variables.setdefault("SHARED_LIB_SUFFIX", ".a") elif flavor == "zos": default_variables.setdefault("SHARED_LIB_SUFFIX", ".x") COMPILABLE_EXTENSIONS.update({".pli": "pli"}) else: default_variables.setdefault("SHARED_LIB_SUFFIX", ".so") default_variables.setdefault("SHARED_LIB_DIR", "$(builddir)/lib.$(TOOLSET)") default_variables.setdefault("LIB_DIR", "$(obj).$(TOOLSET)") def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get("generator_flags", {}) android_ndk_version = generator_flags.get("android_ndk_version", None) # Android NDK requires a strict link order. if android_ndk_version: global generator_wants_sorted_dependencies generator_wants_sorted_dependencies = True output_dir = params["options"].generator_output or params["options"].toplevel_dir builddir_name = generator_flags.get("output_dir", "out") qualified_out_dir = os.path.normpath( os.path.join(output_dir, builddir_name, "gypfiles") ) global generator_filelist_paths generator_filelist_paths = { "toplevel": params["options"].toplevel_dir, "qualified_out_dir": qualified_out_dir, } # The .d checking code below uses these functions: # wildcard, sort, foreach, shell, wordlist # wildcard can handle spaces, the rest can't. # Since I could find no way to make foreach work with spaces in filenames # correctly, the .d files have spaces replaced with another character. The .d # file for # Chromium\ Framework.framework/foo # is for example # out/Release/.deps/out/Release/Chromium?Framework.framework/foo # This is the replacement character. SPACE_REPLACEMENT = "?" LINK_COMMANDS_LINUX = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) -o $@ $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,--start-group $(LD_INPUTS) $(LIBS) -Wl,--end-group # Note: this does not handle spaces in paths define xargs $(1) $(word 1,$(2)) $(if $(word 2,$(2)),$(call xargs,$(1),$(wordlist 2,$(words $(2)),$(2)))) endef define write-to-file @: >$(1) $(call xargs,@printf "%s\\n" >>$(1),$(2)) endef OBJ_FILE_LIST := ar-file-list define create_archive rm -f $(1) $(1).$(OBJ_FILE_LIST); mkdir -p `dirname $(1)` $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2))) $(AR.$(TOOLSET)) crs $(1) @$(1).$(OBJ_FILE_LIST) endef define create_thin_archive rm -f $(1) $(OBJ_FILE_LIST); mkdir -p `dirname $(1)` $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2))) $(AR.$(TOOLSET)) crsT $(1) @$(1).$(OBJ_FILE_LIST) endef # We support two kinds of shared objects (.so): # 1) shared_library, which is just bundling together many dependent libraries # into a link line. # 2) loadable_module, which is generating a module intended for dlopen(). # # They differ only slightly: # In the former case, we want to package all dependent code into the .so. # In the latter case, we want to package just the API exposed by the # outermost module. # This means shared_library uses --whole-archive, while loadable_module doesn't. # (Note that --whole-archive is incompatible with the --start-group used in # normal linking.) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) """ # noqa: E501 LINK_COMMANDS_MAC = """\ quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 LINK_COMMANDS_ANDROID = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Note: this does not handle spaces in paths define xargs $(1) $(word 1,$(2)) $(if $(word 2,$(2)),$(call xargs,$(1),$(wordlist 2,$(words $(2)),$(2)))) endef define write-to-file @: >$(1) $(call xargs,@printf "%s\\n" >>$(1),$(2)) endef OBJ_FILE_LIST := ar-file-list define create_archive rm -f $(1) $(1).$(OBJ_FILE_LIST); mkdir -p `dirname $(1)` $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2))) $(AR.$(TOOLSET)) crs $(1) @$(1).$(OBJ_FILE_LIST) endef define create_thin_archive rm -f $(1) $(OBJ_FILE_LIST); mkdir -p `dirname $(1)` $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2))) $(AR.$(TOOLSET)) crsT $(1) @$(1).$(OBJ_FILE_LIST) endef # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ quiet_cmd_link_host = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) cmd_link_host = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) quiet_cmd_solink_module_host = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module_host = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 LINK_COMMANDS_AIX = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 LINK_COMMANDS_OS400 = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X64 crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X64 crs $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 LINK_COMMANDS_OS390 = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 # Header of toplevel Makefile. # This should go into the build tree, but it's easier to keep it here for now. SHARED_HEADER = ( """\ # We borrow heavily from the kernel build setup, though we are simpler since # we don't have Kconfig tweaking settings on us. # The implicit make rules have it looking for RCS files, among other things. # We instead explicitly write all the rules we care about. # It's even quicker (saves ~200ms) to pass -r on the command line. MAKEFLAGS=-r # The source directory tree. srcdir := %(srcdir)s abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= %(builddir)s # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= %(default_configuration)s # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := %(make_global_settings)s CC.target ?= %(CC.target)s CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS) CXX.target ?= %(CXX.target)s CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS) LINK.target ?= %(LINK.target)s LDFLAGS.target ?= $(LDFLAGS) AR.target ?= %(AR.target)s PLI.target ?= %(PLI.target)s # C++ apps need to be linked with g++. LINK ?= $(CXX.target) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= %(CC.host)s CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host) CXX.host ?= %(CXX.host)s CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host) LINK.host ?= %(LINK.host)s LDFLAGS.host ?= $(LDFLAGS_host) AR.host ?= %(AR.host)s PLI.host ?= %(PLI.host)s # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),""" + SPACE_REPLACEMENT + """,$1) unreplace_spaces = $(subst """ + SPACE_REPLACEMENT + """,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = %(makedep_args)s -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \\ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters.""" r""" define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1).""" + (r""" sed -e "s|^$(notdir $@)|$@|" -re 's/\\\\([^$$])/\/\1/g' $(depfile).raw >> $(depfile)""" if sys.platform == 'win32' else r""" sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)""") + r""" # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines.""" + (""" sed -e 's/\\\\\\\\$$//' -e 's/\\\\\\\\/\\//g' -e 'y| |\\n|' $(depfile).raw |\\""" if sys.platform == 'win32' else """ sed -e 's|\\\\||' -e 'y| |\\n|' $(depfile).raw |\\""") + r""" grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef """ """ # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) -o $@ $< $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) -o $@ $< $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c %(extra_commands)s quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp %(copy_archive_args)s "$<" "$@") quiet_cmd_symlink = SYMLINK $@ cmd_symlink = ln -sf "$<" "$@" %(link_commands)s """ # noqa: E501 r""" # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%%s\n' '$(call escape_quotes,$(1))' """ """ # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \\ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain """ + SPACE_REPLACEMENT + """ instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\\ for p in $(POSTBUILDS); do\\ eval $$p;\\ E=$$?;\\ if [ $$E -ne 0 ]; then\\ break;\\ fi;\\ done;\\ if [ $$E -ne 0 ]; then\\ rm -rf "$@";\\ exit $$E;\\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains """ + SPACE_REPLACEMENT + """ for # spaces already and dirx strips the """ + SPACE_REPLACEMENT + """ characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word %(flock_index)d,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "%(default_target)s" target first so it is the default, # even though we don't have the deps yet. .PHONY: %(default_target)s %(default_target)s: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %%.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: """ # noqa: E501 ) SHARED_HEADER_MAC_COMMANDS = """ quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" """ # noqa: E501 def WriteRootHeaderSuffixRules(writer): extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower) writer.write("# Suffix rules, putting all outputs into $(obj).\n") for ext in extensions: writer.write("$(obj).$(TOOLSET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD\n" % ext) writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext]) writer.write("\n# Try building from generated source, too.\n") for ext in extensions: writer.write( "$(obj).$(TOOLSET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD\n" % ext ) writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext]) writer.write("\n") for ext in extensions: writer.write("$(obj).$(TOOLSET)/%%.o: $(obj)/%%%s FORCE_DO_CMD\n" % ext) writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext]) writer.write("\n") SHARED_HEADER_OS390_COMMANDS = """ PLIFLAGS.target ?= -qlp=64 -qlimits=extname=31 $(PLIFLAGS) PLIFLAGS.host ?= -qlp=64 -qlimits=extname=31 $(PLIFLAGS) quiet_cmd_pli = PLI($(TOOLSET)) $@ cmd_pli = $(PLI.$(TOOLSET)) $(GYP_PLIFLAGS) $(PLIFLAGS.$(TOOLSET)) -c $< && \ if [ -f $(notdir $@) ]; then /bin/cp $(notdir $@) $@; else true; fi """ SHARED_HEADER_SUFFIX_RULES_COMMENT1 = """\ # Suffix rules, putting all outputs into $(obj). """ SHARED_HEADER_SUFFIX_RULES_COMMENT2 = """\ # Try building from generated source, too. """ SHARED_FOOTER = """\ # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif """ header = """\ # This file is generated by gyp; do not edit. """ # Maps every compilable file extension to the do_cmd that compiles it. COMPILABLE_EXTENSIONS = { ".c": "cc", ".cc": "cxx", ".cpp": "cxx", ".cxx": "cxx", ".s": "cc", ".S": "cc", } def Compilable(filename): """Return true if the file is compilable (should be in OBJS).""" return any(res for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS)) def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith(".o") def Target(filename): """Translate a compilable filename to its .o target.""" return os.path.splitext(filename)[0] + ".o" def EscapeShellArgument(s): """Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python """ return "'" + s.replace("'", "'\\''") + "'" def EscapeMakeVariableExpansion(s): """Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.""" return s.replace("$", "$$") def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = EscapeMakeVariableExpansion(s) # '#' characters must be escaped even embedded in a string, else Make will # treat it as the start of a comment. return s.replace("#", r"\#") def QuoteIfNecessary(string): """TODO: Should this ideally be replaced with one or more of the above functions?""" if '"' in string: string = '"' + string.replace('"', '\\"') + '"' return string def replace_sep(string): if sys.platform == 'win32': string = string.replace('\\\\', '/').replace('\\', '/') return string def StringToMakefileVariable(string): """Convert a string to a value that is acceptable as a make variable name.""" return re.sub("[^a-zA-Z0-9_]", "_", string) srcdir_prefix = "" def Sourceify(path): """Convert a path to its source directory form.""" if "$(" in path: return path if os.path.isabs(path): return path return srcdir_prefix + path def QuoteSpaces(s, quote=r"\ "): return s.replace(" ", quote) def SourceifyAndQuoteSpaces(path): """Convert a path to its source directory form and quote spaces.""" return QuoteSpaces(Sourceify(path)) # Map from qualified target to path to output. target_outputs = {} # Map from qualified target to any linkable output. A subset # of target_outputs. E.g. when mybinary depends on liba, we want to # include liba in the linker line; when otherbinary depends on # mybinary, we just want to build mybinary first. target_link_deps = {} class MakefileWriter: """MakefileWriter packages up the writing of one target-specific foobar.mk. Its only real entry point is Write(), and is mostly used for namespacing. """ def __init__(self, generator_flags, flavor): self.generator_flags = generator_flags self.flavor = flavor self.suffix_rules_srcdir = {} self.suffix_rules_objdir1 = {} self.suffix_rules_objdir2 = {} # Generate suffix rules for all compilable extensions. for ext in COMPILABLE_EXTENSIONS: # Suffix rules for source folder. self.suffix_rules_srcdir.update( { ext: ( """\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]) ) } ) # Suffix rules for generated source files. self.suffix_rules_objdir1.update( { ext: ( """\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]) ) } ) self.suffix_rules_objdir2.update( { ext: ( """\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]) ) } ) def Write( self, qualified_target, base_path, output_filename, spec, configs, part_of_all ): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, "w") self.fp.write(header) self.qualified_target = qualified_target self.path = base_path self.target = spec["target_name"] self.type = spec["type"] self.toolset = spec["toolset"] self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) if self.flavor == "mac": self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) else: self.xcode_settings = None deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] extra_link_deps = [] extra_mac_bundle_resources = [] mac_bundle_deps = [] if self.is_mac_bundle: self.output = self.ComputeMacBundleOutput(spec) self.output_binary = self.ComputeMacBundleBinaryOutput(spec) else: self.output = self.output_binary = replace_sep(self.ComputeOutput(spec)) self.is_standalone_static_library = bool( spec.get("standalone_static_library", 0) ) self._INSTALLABLE_TARGETS = ("executable", "loadable_module", "shared_library") if self.is_standalone_static_library or self.type in self._INSTALLABLE_TARGETS: self.alias = os.path.basename(self.output) install_path = self._InstallableTargetInstallPath() else: self.alias = self.output install_path = self.output self.WriteLn("TOOLSET := " + self.toolset) self.WriteLn("TARGET := " + self.target) # Actions must come first, since they can generate more OBJs for use below. if "actions" in spec: self.WriteActions( spec["actions"], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all, ) # Rules must be early like actions. if "rules" in spec: self.WriteRules( spec["rules"], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all, ) if "copies" in spec: self.WriteCopies(spec["copies"], extra_outputs, part_of_all) # Bundle resources. if self.is_mac_bundle: all_mac_bundle_resources = ( spec.get("mac_bundle_resources", []) + extra_mac_bundle_resources ) self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps) self.WriteMacInfoPlist(mac_bundle_deps) # Sources. all_sources = spec.get("sources", []) + extra_sources if all_sources: self.WriteSources( configs, deps, all_sources, extra_outputs, extra_link_deps, part_of_all, gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), self.Pchify, ), ) sources = [x for x in all_sources if Compilable(x)] if sources: self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1) extensions = {os.path.splitext(s)[1] for s in sources} for ext in extensions: if ext in self.suffix_rules_srcdir: self.WriteLn(self.suffix_rules_srcdir[ext]) self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2) for ext in extensions: if ext in self.suffix_rules_objdir1: self.WriteLn(self.suffix_rules_objdir1[ext]) for ext in extensions: if ext in self.suffix_rules_objdir2: self.WriteLn(self.suffix_rules_objdir2[ext]) self.WriteLn("# End of this set of suffix rules") # Add dependency from bundle to bundle binary. if self.is_mac_bundle: mac_bundle_deps.append(self.output_binary) self.WriteTarget( spec, configs, deps, extra_link_deps + link_deps, mac_bundle_deps, extra_outputs, part_of_all, ) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = install_path # Update global list of link dependencies. if self.type in ("static_library", "shared_library"): target_link_deps[qualified_target] = self.output_binary # Currently any versions have the same effect, but in future the behavior # could be different. if self.generator_flags.get("android_ndk_version", None): self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps) self.fp.close() def WriteSubMake(self, output_filename, makefile_path, targets, build_dir): """Write a "sub-project" Makefile. This is a small, wrapper Makefile that calls the top-level Makefile to build the targets from a single gyp file (i.e. a sub-project). Arguments: output_filename: sub-project Makefile name to write makefile_path: path to the top-level Makefile targets: list of "all" targets for this sub-project build_dir: build output directory, relative to the sub-project """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, "w") self.fp.write(header) # For consistency with other builders, put sub-project build output in the # sub-project dir (see test/subdirectory/gyptest-subdir-all.py). self.WriteLn( "export builddir_name ?= %s" % replace_sep(os.path.join(os.path.dirname(output_filename), build_dir)) ) self.WriteLn(".PHONY: all") self.WriteLn("all:") if makefile_path: makefile_path = " -C " + makefile_path self.WriteLn("\t$(MAKE){} {}".format(makefile_path, " ".join(targets))) self.fp.close() def WriteActions( self, actions, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all, ): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for action in actions: name = StringToMakefileVariable( "{}_{}".format(self.qualified_target, action["action_name"]) ) self.WriteLn('### Rules for action "%s":' % action["action_name"]) inputs = action["inputs"] outputs = action["outputs"] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get("process_outputs_as_sources", False)): extra_sources += outputs if int(action.get("process_outputs_as_mac_bundle_resources", False)): extra_mac_bundle_resources += outputs # Write the actual command. action_commands = action["action"] if self.flavor == "mac": action_commands = [ gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action_commands ] command = gyp.common.EncodePOSIXShellList(action_commands) if "message" in action: self.WriteLn( "quiet_cmd_{} = ACTION {} $@".format(name, action["message"]) ) else: self.WriteLn(f"quiet_cmd_{name} = ACTION {name} $@") if len(dirs) > 0: command = "mkdir -p %s" % " ".join(dirs) + "; " + command cd_action = "cd %s; " % Sourceify(self.path or ".") # command and cd_action get written to a toplevel variable called # cmd_foo. Toplevel variables can't handle things that change per # makefile like $(TARGET), so hardcode the target. command = command.replace("$(TARGET)", self.target) cd_action = cd_action.replace("$(TARGET)", self.target) # Set LD_LIBRARY_PATH in case the action runs an executable from this # build which links to shared libs from this build. # actions run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target if self.flavor in {"zos", "aix"}: self.WriteLn( "cmd_%s = LIBPATH=$(builddir)/lib.host:" "$(builddir)/lib.target:$$LIBPATH; " "export LIBPATH; " "%s%s" % (name, cd_action, command) ) else: self.WriteLn( "cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:" "$(builddir)/lib.target:$$LD_LIBRARY_PATH; " "export LD_LIBRARY_PATH; " "%s%s" % (name, cd_action, command) ) self.WriteLn() outputs = [self.Absolutify(o) for o in outputs] # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the obj # variable for the action rule with an absolute version so that the output # goes in the right place. # Only write the 'obj' and 'builddir' rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. # Same for environment. self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0])) self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0])) self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv()) for input in inputs: assert " " not in input, ( "Spaces in action input filenames not supported (%s)" % input ) for output in outputs: assert " " not in output, ( "Spaces in action output filenames not supported (%s)" % output ) # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] self.WriteDoCmd( outputs, [Sourceify(self.Absolutify(i)) for i in inputs], part_of_all=part_of_all, command=name, ) # Stuff the outputs in a variable so we can refer to them later. outputs_variable = "action_%s_outputs" % name self.WriteLn("{} := {}".format(outputs_variable, " ".join(outputs))) extra_outputs.append("$(%s)" % outputs_variable) self.WriteLn() self.WriteLn() def WriteRules( self, rules, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all, ): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for rule in rules: name = StringToMakefileVariable( "{}_{}".format(self.qualified_target, rule["rule_name"]) ) count = 0 self.WriteLn("### Generated for rule %s:" % name) all_outputs = [] for rule_source in rule.get("rule_sources", []): dirs = set() (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = os.path.splitext( rule_source_basename ) outputs = [ self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule["outputs"] ] for out in outputs: dir = os.path.dirname(out) if dir: dirs.add(dir) if int(rule.get("process_outputs_as_sources", False)): extra_sources += outputs if int(rule.get("process_outputs_as_mac_bundle_resources", False)): extra_mac_bundle_resources += outputs inputs = [ Sourceify(self.Absolutify(i)) for i in [rule_source] + rule.get("inputs", []) ] actions = ["$(call do_cmd,%s_%d)" % (name, count)] if name == "resources_grit": # HACK: This is ugly. Grit intentionally doesn't touch the # timestamp of its output file when the file doesn't change, # which is fine in hash-based dependency systems like scons # and forge, but not kosher in the make world. After some # discussion, hacking around it here seems like the least # amount of pain. actions += ["@touch --no-create $@"] # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] outputs = [self.Absolutify(o) for o in outputs] all_outputs += outputs # Only write the 'obj' and 'builddir' rules for the "primary" output # (:1); it's superfluous for the "extra outputs", and this avoids # accidentally writing duplicate dummy rules for those outputs. self.WriteLn("%s: obj := $(abs_obj)" % outputs[0]) self.WriteLn("%s: builddir := $(abs_builddir)" % outputs[0]) self.WriteMakeRule( outputs, inputs, actions, command="%s_%d" % (name, count) ) # Spaces in rule filenames are not supported, but rule variables have # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)'). # The spaces within the variables are valid, so remove the variables # before checking. variables_with_spaces = re.compile(r"\$\([^ ]* \$<\)") for output in outputs: output = re.sub(variables_with_spaces, "", output) assert " " not in output, ( "Spaces in rule filenames not yet supported (%s)" % output ) self.WriteLn("all_deps += %s" % " ".join(outputs)) action = [ self.ExpandInputRoot(ac, rule_source_root, rule_source_dirname) for ac in rule["action"] ] mkdirs = "" if len(dirs) > 0: mkdirs = "mkdir -p %s; " % " ".join(dirs) cd_action = "cd %s; " % Sourceify(self.path or ".") # action, cd_action, and mkdirs get written to a toplevel variable # called cmd_foo. Toplevel variables can't handle things that change # per makefile like $(TARGET), so hardcode the target. if self.flavor == "mac": action = [ gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action ] action = gyp.common.EncodePOSIXShellList(action) action = action.replace("$(TARGET)", self.target) cd_action = cd_action.replace("$(TARGET)", self.target) mkdirs = mkdirs.replace("$(TARGET)", self.target) # Set LD_LIBRARY_PATH in case the rule runs an executable from this # build which links to shared libs from this build. # rules run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn( "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=" "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; " "export LD_LIBRARY_PATH; " "%(cd_action)s%(mkdirs)s%(action)s" % { "action": action, "cd_action": cd_action, "count": count, "mkdirs": mkdirs, "name": name, } ) self.WriteLn( "quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@" % {"count": count, "name": name} ) self.WriteLn() count += 1 outputs_variable = "rule_%s_outputs" % name self.WriteList(all_outputs, outputs_variable) extra_outputs.append("$(%s)" % outputs_variable) self.WriteLn("### Finished generating for rule: %s" % name) self.WriteLn() self.WriteLn("### Finished generating for all rules") self.WriteLn("") def WriteCopies(self, copies, extra_outputs, part_of_all): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) part_of_all: flag indicating this target is part of 'all' """ self.WriteLn("### Generated for copy rule.") variable = StringToMakefileVariable(self.qualified_target + "_copies") outputs = [] for copy in copies: for path in copy["files"]: # Absolutify() may call normpath, and will strip trailing slashes. path = Sourceify(self.Absolutify(path)) filename = os.path.split(path)[1] output = Sourceify( self.Absolutify(os.path.join(copy["destination"], filename)) ) # If the output path has variables in it, which happens in practice for # 'copies', writing the environment as target-local doesn't work, # because the variables are already needed for the target name. # Copying the environment variables into global make variables doesn't # work either, because then the .d files will potentially contain spaces # after variable expansion, and .d file handling cannot handle spaces. # As a workaround, manually expand variables at gyp time. Since 'copies' # can't run scripts, there's no need to write the env then. # WriteDoCmd() will escape spaces for .d files. env = self.GetSortedXcodeEnv() output = gyp.xcode_emulation.ExpandEnvVars(output, env) path = gyp.xcode_emulation.ExpandEnvVars(path, env) self.WriteDoCmd([output], [path], "copy", part_of_all) outputs.append(output) self.WriteLn( "{} = {}".format(variable, " ".join(QuoteSpaces(o) for o in outputs)) ) extra_outputs.append("$(%s)" % variable) self.WriteLn() def WriteMacBundleResources(self, resources, bundle_deps): """Writes Makefile code for 'mac_bundle_resources'.""" self.WriteLn("### Generated for mac_bundle_resources") for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables["PRODUCT_DIR"], self.xcode_settings, [Sourceify(self.Absolutify(r)) for r in resources], ): _, ext = os.path.splitext(output) if ext != ".xcassets": # Make does not supports '.xcassets' emulation. self.WriteDoCmd( [output], [res], "mac_tool,,,copy-bundle-resource", part_of_all=True ) bundle_deps.append(output) def WriteMacInfoPlist(self, bundle_deps): """Write Makefile code for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables["PRODUCT_DIR"], self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), ) if not info_plist: return if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = "$(obj).$(TOOLSET)/$(TARGET)/" + os.path.basename( info_plist ) self.WriteList( defines, intermediate_plist + ": INFOPLIST_DEFINES", "-D", quoter=EscapeCppDefine, ) self.WriteMakeRule( [intermediate_plist], [info_plist], [ "$(call do_cmd,infoplist)", # "Convert" the plist so that any weird whitespace changes from the # preprocessor do not affect the XML parser in mac_tool. "@plutil -convert xml1 $@ $@", ], ) info_plist = intermediate_plist # plists can contain envvars and substitute them into the file. self.WriteSortedXcodeEnv( out, self.GetSortedXcodeEnv(additional_settings=extra_env) ) self.WriteDoCmd( [out], [info_plist], "mac_tool,,,copy-info-plist", part_of_all=True ) bundle_deps.append(out) def WriteSources( self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header, ): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all' """ # Write configuration-specific variables for CFLAGS, etc. for configname in sorted(configs.keys()): config = configs[configname] self.WriteList( config.get("defines"), "DEFS_%s" % configname, prefix="-D", quoter=EscapeCppDefine, ) if self.flavor == "mac": cflags = self.xcode_settings.GetCflags( configname, arch=config.get("xcode_configuration_platform") ) cflags_c = self.xcode_settings.GetCflagsC(configname) cflags_cc = self.xcode_settings.GetCflagsCC(configname) cflags_objc = self.xcode_settings.GetCflagsObjC(configname) cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname) else: cflags = config.get("cflags") cflags_c = config.get("cflags_c") cflags_cc = config.get("cflags_cc") self.WriteLn("# Flags passed to all source files.") self.WriteList(cflags, "CFLAGS_%s" % configname) self.WriteLn("# Flags passed to only C files.") self.WriteList(cflags_c, "CFLAGS_C_%s" % configname) self.WriteLn("# Flags passed to only C++ files.") self.WriteList(cflags_cc, "CFLAGS_CC_%s" % configname) if self.flavor == "mac": self.WriteLn("# Flags passed to only ObjC files.") self.WriteList(cflags_objc, "CFLAGS_OBJC_%s" % configname) self.WriteLn("# Flags passed to only ObjC++ files.") self.WriteList(cflags_objcc, "CFLAGS_OBJCC_%s" % configname) includes = config.get("include_dirs") if includes: includes = [Sourceify(self.Absolutify(i)) for i in includes] self.WriteList(includes, "INCS_%s" % configname, prefix="-I") compilable = list(filter(Compilable, sources)) objs = [self.Objectify(self.Absolutify(Target(c))) for c in compilable] self.WriteList(objs, "OBJS") for obj in objs: assert " " not in obj, "Spaces in object filenames not supported (%s)" % obj self.WriteLn( "# Add to the list of files we specially track " "dependencies for." ) self.WriteLn("all_deps += $(OBJS)") self.WriteLn() # Make sure our dependencies are built first. if deps: self.WriteMakeRule( ["$(OBJS)"], deps, comment="Make sure our dependencies are built " "before any of us.", order_only=True, ) # Make sure the actions and rules run first. # If they generate any extra headers etc., the per-.o file dep tracking # will catch the proper rebuilds, so order only is still ok here. if extra_outputs: self.WriteMakeRule( ["$(OBJS)"], extra_outputs, comment="Make sure our actions/rules run " "before any of us.", order_only=True, ) pchdeps = precompiled_header.GetObjDependencies(compilable, objs) if pchdeps: self.WriteLn("# Dependencies from obj files to their precompiled headers") for source, obj, gch in pchdeps: self.WriteLn(f"{obj}: {gch}") self.WriteLn("# End precompiled header dependencies") if objs: extra_link_deps.append("$(OBJS)") self.WriteLn( """\ # CFLAGS et al overrides must be target-local. # See "Target-specific Variable Values" in the GNU Make manual.""" ) self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)") self.WriteLn( "$(OBJS): GYP_CFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude("c") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE))" ) self.WriteLn( "$(OBJS): GYP_CXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude("cc") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE))" ) if self.flavor == "mac": self.WriteLn( "$(OBJS): GYP_OBJCFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude("m") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE)) " "$(CFLAGS_OBJC_$(BUILDTYPE))" ) self.WriteLn( "$(OBJS): GYP_OBJCXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude("mm") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE)) " "$(CFLAGS_OBJCC_$(BUILDTYPE))" ) self.WritePchTargets(precompiled_header.GetPchBuildCommands()) # If there are any object files in our input file list, link them into our # output. extra_link_deps += [source for source in sources if Linkable(source)] self.WriteLn() def WritePchTargets(self, pch_commands): """Writes make rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: extra_flags = { "c": "$(CFLAGS_C_$(BUILDTYPE))", "cc": "$(CFLAGS_CC_$(BUILDTYPE))", "m": "$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))", "mm": "$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))", }[lang] var_name = { "c": "GYP_PCH_CFLAGS", "cc": "GYP_PCH_CXXFLAGS", "m": "GYP_PCH_OBJCFLAGS", "mm": "GYP_PCH_OBJCXXFLAGS", }[lang] self.WriteLn( f"{gch}: {var_name} := {lang_flag} " + "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "$(CFLAGS_$(BUILDTYPE)) " + extra_flags ) self.WriteLn(f"{gch}: {input} FORCE_DO_CMD") self.WriteLn("\t@$(call do_cmd,pch_%s,1)" % lang) self.WriteLn("") assert " " not in gch, "Spaces in gch filenames not supported (%s)" % gch self.WriteLn("all_deps += %s" % gch) self.WriteLn("") def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ assert not self.is_mac_bundle if self.flavor == "mac" and self.type in ( "static_library", "executable", "shared_library", "loadable_module", ): return self.xcode_settings.GetExecutablePath() target = spec["target_name"] target_prefix = "" target_ext = "" if self.type == "static_library": if target[:3] == "lib": target = target[3:] target_prefix = "lib" target_ext = ".a" elif self.type in ("loadable_module", "shared_library"): if target[:3] == "lib": target = target[3:] target_prefix = "lib" if self.flavor == "aix": target_ext = ".a" elif self.flavor == "zos": target_ext = ".x" else: target_ext = ".so" elif self.type == "none": target = "%s.stamp" % target elif self.type != "executable": print( "ERROR: What output file should be generated?", "type", self.type, "target", target, ) target_prefix = spec.get("product_prefix", target_prefix) target = spec.get("product_name", target) product_ext = spec.get("product_extension") if product_ext: target_ext = "." + product_ext return target_prefix + target + target_ext def _InstallImmediately(self): return ( self.toolset == "target" and self.flavor == "mac" and self.type in ("static_library", "executable", "shared_library", "loadable_module") ) def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ assert not self.is_mac_bundle path = os.path.join("$(obj)." + self.toolset, self.path) if self.type == "executable" or self._InstallImmediately(): path = "$(builddir)" path = spec.get("product_dir", path) return os.path.join(path, self.ComputeOutputBasename(spec)) def ComputeMacBundleOutput(self, spec): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables["PRODUCT_DIR"] return os.path.join(path, self.xcode_settings.GetWrapperName()) def ComputeMacBundleBinaryOutput(self, spec): """Return the 'output' (full output path) to the binary in a bundle.""" path = generator_default_variables["PRODUCT_DIR"] return os.path.join(path, self.xcode_settings.GetExecutablePath()) def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if "dependencies" in spec: deps.extend( [ target_outputs[dep] for dep in spec["dependencies"] if target_outputs[dep] ] ) for dep in spec["dependencies"]: if dep in target_link_deps: link_deps.append(target_link_deps[dep]) deps.extend(link_deps) # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)? # This hack makes it work: # link_deps.extend(spec.get('libraries', [])) return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) def GetSharedObjectFromSidedeck(self, sidedeck): """Return the shared object files based on sidedeck""" return re.sub(r"\.x$", ".so", sidedeck) def GetUnversionedSidedeckFromSidedeck(self, sidedeck): """Return the shared object files based on sidedeck""" return re.sub(r"\.\d+\.x$", ".x", sidedeck) def WriteDependencyOnExtraOutputs(self, target, extra_outputs): self.WriteMakeRule( [self.output_binary], extra_outputs, comment="Build our special outputs first.", order_only=True, ) def WriteTarget( self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all ): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all' """ self.WriteLn("### Rules for final target.") if extra_outputs: self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs) self.WriteMakeRule( extra_outputs, deps, comment=("Preserve order dependency of " "special output on deps."), order_only=True, ) target_postbuilds = {} if self.type != "none": for configname in sorted(configs.keys()): config = configs[configname] if self.flavor == "mac": ldflags = self.xcode_settings.GetLdflags( configname, generator_default_variables["PRODUCT_DIR"], lambda p: Sourceify(self.Absolutify(p)), arch=config.get("xcode_configuration_platform"), ) # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on. gyp_to_build = gyp.common.InvertRelativePath(self.path) target_postbuild = self.xcode_settings.AddImplicitPostbuilds( configname, QuoteSpaces( os.path.normpath(os.path.join(gyp_to_build, self.output)) ), QuoteSpaces( os.path.normpath( os.path.join(gyp_to_build, self.output_binary) ) ), ) if target_postbuild: target_postbuilds[configname] = target_postbuild else: ldflags = config.get("ldflags", []) # Compute an rpath for this output if needed. if any(dep.endswith(".so") or ".so." in dep for dep in deps): # We want to get the literal string "$ORIGIN" # into the link command, so we need lots of escaping. ldflags.append(r"-Wl,-rpath=\$$ORIGIN/") ldflags.append(r"-Wl,-rpath-link=\$(builddir)/") library_dirs = config.get("library_dirs", []) ldflags += [("-L%s" % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, "LDFLAGS_%s" % configname) if self.flavor == "mac": self.WriteList( self.xcode_settings.GetLibtoolflags(configname), "LIBTOOLFLAGS_%s" % configname, ) libraries = spec.get("libraries") if libraries: # Remove duplicate entries libraries = gyp.common.uniquer(libraries) if self.flavor == "mac": libraries = self.xcode_settings.AdjustLibraries(libraries) self.WriteList(libraries, "LIBS") self.WriteLn( "%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))" % QuoteSpaces(self.output_binary) ) self.WriteLn("%s: LIBS := $(LIBS)" % QuoteSpaces(self.output_binary)) if self.flavor == "mac": self.WriteLn( "%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))" % QuoteSpaces(self.output_binary) ) # Postbuild actions. Like actions, but implicitly depend on the target's # output. postbuilds = [] if self.flavor == "mac": if target_postbuilds: postbuilds.append("$(TARGET_POSTBUILDS_$(BUILDTYPE))") postbuilds.extend(gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) if postbuilds: # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), # so we must output its definition first, since we declare variables # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) for configname in target_postbuilds: self.WriteLn( "%s: TARGET_POSTBUILDS_%s := %s" % ( QuoteSpaces(self.output), configname, gyp.common.EncodePOSIXShellList(target_postbuilds[configname]), ) ) # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList(["cd", self.path])) for i, postbuild in enumerate(postbuilds): if not postbuild.startswith("$"): postbuilds[i] = EscapeShellArgument(postbuild) self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(self.output)) self.WriteLn( "%s: POSTBUILDS := %s" % (QuoteSpaces(self.output), " ".join(postbuilds)) ) # A bundle directory depends on its dependencies such as bundle resources # and bundle binary. When all dependencies have been built, the bundle # needs to be packaged. if self.is_mac_bundle: # If the framework doesn't contain a binary, then nothing depends # on the actions -- make the framework depend on them directly too. self.WriteDependencyOnExtraOutputs(self.output, extra_outputs) # Bundle dependencies. Note that the code below adds actions to this # target, so if you move these two lines, move the lines below as well. self.WriteList([QuoteSpaces(dep) for dep in bundle_deps], "BUNDLE_DEPS") self.WriteLn("%s: $(BUNDLE_DEPS)" % QuoteSpaces(self.output)) # After the framework is built, package it. Needs to happen before # postbuilds, since postbuilds depend on this. if self.type in ("shared_library", "loadable_module"): self.WriteLn( "\t@$(call do_cmd,mac_package_framework,,,%s)" % self.xcode_settings.GetFrameworkVersion() ) # Bundle postbuilds can depend on the whole bundle, so run them after # the bundle is packaged, not already after the bundle binary is done. if postbuilds: self.WriteLn("\t@$(call do_postbuilds)") postbuilds = [] # Don't write postbuilds for target's output. # Needed by test/mac/gyptest-rebuild.py. self.WriteLn("\t@true # No-op, used by tests") # Since this target depends on binary and resources which are in # nested subfolders, the framework directory will be older than # its dependencies usually. To prevent this rule from executing # on every build (expensive, especially with postbuilds), expliclity # update the time on the framework directory. self.WriteLn("\t@touch -c %s" % QuoteSpaces(self.output)) if postbuilds: assert not self.is_mac_bundle, ( "Postbuilds for bundles should be done " "on the bundle, not the binary (target '%s')" % self.target ) assert "product_dir" not in spec, ( "Postbuilds do not work with " "custom product_dir" ) if self.type == "executable": self.WriteLn( "%s: LD_INPUTS := %s" % ( QuoteSpaces(self.output_binary), " ".join(QuoteSpaces(dep) for dep in link_deps), ) ) if self.toolset == "host" and self.flavor == "android": self.WriteDoCmd( [self.output_binary], link_deps, "link_host", part_of_all, postbuilds=postbuilds, ) else: self.WriteDoCmd( [self.output_binary], link_deps, "link", part_of_all, postbuilds=postbuilds, ) elif self.type == "static_library": for link_dep in link_deps: assert " " not in link_dep, ( "Spaces in alink input filenames not supported (%s)" % link_dep ) if ( self.flavor not in ("mac", "openbsd", "netbsd", "win") and not self.is_standalone_static_library ): if self.flavor in ("linux", "android"): self.WriteMakeRule( [self.output_binary], link_deps, actions=["$(call create_thin_archive,$@,$^)"], ) else: self.WriteDoCmd( [self.output_binary], link_deps, "alink_thin", part_of_all, postbuilds=postbuilds, ) else: if self.flavor in ("linux", "android"): self.WriteMakeRule( [self.output_binary], link_deps, actions=["$(call create_archive,$@,$^)"], ) else: self.WriteDoCmd( [self.output_binary], link_deps, "alink", part_of_all, postbuilds=postbuilds, ) elif self.type == "shared_library": self.WriteLn( "%s: LD_INPUTS := %s" % ( QuoteSpaces(self.output_binary), " ".join(QuoteSpaces(dep) for dep in link_deps), ) ) self.WriteDoCmd( [self.output_binary], link_deps, "solink", part_of_all, postbuilds=postbuilds, ) # z/OS has a .so target as well as a sidedeck .x target if self.flavor == "zos": self.WriteLn( "%s: %s" % ( QuoteSpaces( self.GetSharedObjectFromSidedeck(self.output_binary) ), QuoteSpaces(self.output_binary), ) ) elif self.type == "loadable_module": for link_dep in link_deps: assert " " not in link_dep, ( "Spaces in module input filenames not supported (%s)" % link_dep ) if self.toolset == "host" and self.flavor == "android": self.WriteDoCmd( [self.output_binary], link_deps, "solink_module_host", part_of_all, postbuilds=postbuilds, ) else: self.WriteDoCmd( [self.output_binary], link_deps, "solink_module", part_of_all, postbuilds=postbuilds, ) elif self.type == "none": # Write a stamp line. self.WriteDoCmd( [self.output_binary], deps, "touch", part_of_all, postbuilds=postbuilds ) else: print("WARNING: no output for", self.type, self.target) # Add an alias for each target (if there are any outputs). # Installable target aliases are created below. if (self.output and self.output != self.target) and ( self.type not in self._INSTALLABLE_TARGETS ): self.WriteMakeRule( [self.target], [self.output], comment="Add target alias", phony=True ) if part_of_all: self.WriteMakeRule( ["all"], [self.target], comment='Add target alias to "all" target.', phony=True, ) # Add special-case rules for our installable targets. # 1) They need to install to the build dir or "product" dir. # 2) They get shortcuts for building (e.g. "make chrome"). # 3) They are part of "make all". if self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library: if self.type == "shared_library": file_desc = "shared library" elif self.type == "static_library": file_desc = "static library" else: file_desc = "executable" install_path = self._InstallableTargetInstallPath() installable_deps = [] if self.flavor != "zos": installable_deps.append(self.output) if ( self.flavor == "mac" and "product_dir" not in spec and self.toolset == "target" ): # On mac, products are created in install_path immediately. assert install_path == self.output, f"{install_path} != {self.output}" # Point the target alias to the final binary output. self.WriteMakeRule( [self.target], [install_path], comment="Add target alias", phony=True ) if install_path != self.output: assert not self.is_mac_bundle # See comment a few lines above. self.WriteDoCmd( [install_path], [self.output], "copy", comment="Copy this to the %s output path." % file_desc, part_of_all=part_of_all, ) if self.flavor != "zos": installable_deps.append(install_path) if self.flavor == "zos" and self.type == "shared_library": # lib.target/libnode.so has a dependency on $(obj).target/libnode.so self.WriteDoCmd( [self.GetSharedObjectFromSidedeck(install_path)], [self.GetSharedObjectFromSidedeck(self.output)], "copy", comment="Copy this to the %s output path." % file_desc, part_of_all=part_of_all, ) # Create a symlink of libnode.x to libnode.version.x self.WriteDoCmd( [self.GetUnversionedSidedeckFromSidedeck(install_path)], [install_path], "symlink", comment="Symlnk this to the %s output path." % file_desc, part_of_all=part_of_all, ) # Place libnode.version.so and libnode.x symlink in lib.target dir installable_deps.append(self.GetSharedObjectFromSidedeck(install_path)) installable_deps.append( self.GetUnversionedSidedeckFromSidedeck(install_path) ) if self.alias not in (self.output, self.target): self.WriteMakeRule( [self.alias], installable_deps, comment="Short alias for building this %s." % file_desc, phony=True, ) if self.flavor == "zos" and self.type == "shared_library": # Make sure that .x symlink target is run self.WriteMakeRule( ["all"], [ self.GetUnversionedSidedeckFromSidedeck(install_path), self.GetSharedObjectFromSidedeck(install_path), ], comment='Add %s to "all" target.' % file_desc, phony=True, ) elif part_of_all: self.WriteMakeRule( ["all"], [install_path], comment='Add %s to "all" target.' % file_desc, phony=True, ) def WriteList(self, value_list, variable=None, prefix="", quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = "" if value_list: value_list = [replace_sep(quoter(prefix + value)) for value in value_list] values = " \\\n\t" + " \\\n\t".join(value_list) self.fp.write(f"{variable} :={values}\n\n") def WriteDoCmd( self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False ): """Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag. """ suffix = "" if postbuilds: assert "," not in command suffix = ",,1" # Tell do_cmd to honor $POSTBUILDS self.WriteMakeRule( outputs, inputs, actions=[f"$(call do_cmd,{command}{suffix})"], comment=comment, command=command, force=True, ) # Add our outputs to the list of targets we read depfiles from. # all_deps is only used for deps file reading, and for deps files we replace # spaces with ? because escaping doesn't work with make's $(sort) and # other functions. outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs] self.WriteLn("all_deps += %s" % " ".join(outputs)) def WriteMakeRule( self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None, ): """Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels """ outputs = [QuoteSpaces(o) for o in outputs] inputs = [QuoteSpaces(i) for i in inputs] if comment: self.WriteLn("# " + comment) if phony: self.WriteLn(".PHONY: " + " ".join(outputs)) if actions: self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0]) force_append = " FORCE_DO_CMD" if force else "" if order_only: # Order only rule: Just write a simple rule. # TODO(evanm): just make order_only a list of deps instead of this hack. self.WriteLn( "{}: | {}{}".format(" ".join(outputs), " ".join(inputs), force_append) ) elif len(outputs) == 1: # Regular rule, one output: Just write a simple rule. self.WriteLn("{}: {}{}".format(outputs[0], " ".join(inputs), force_append)) else: # Regular rule, more than one output: Multiple outputs are tricky in # make. We will write three rules: # - All outputs depend on an intermediate file. # - Make .INTERMEDIATE depend on the intermediate. # - The intermediate file depends on the inputs and executes the # actual command. # - The intermediate recipe will 'touch' the intermediate file. # - The multi-output rule will have an do-nothing recipe. # Hash the target name to avoid generating overlong filenames. cmddigest = hashlib.sha1( (command or self.target).encode("utf-8") ).hexdigest() intermediate = "%s.intermediate" % cmddigest self.WriteLn("{}: {}".format(" ".join(outputs), intermediate)) self.WriteLn("\t%s" % "@:") self.WriteLn("{}: {}".format(".INTERMEDIATE", intermediate)) self.WriteLn( "{}: {}{}".format(intermediate, " ".join(inputs), force_append) ) actions.insert(0, "$(call do_cmd,touch)") if actions: for action in actions: self.WriteLn("\t%s" % action) self.WriteLn() def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps): """Write a set of LOCAL_XXX definitions for Android NDK. These variable definitions will be used by Android NDK but do nothing for non-Android applications. Arguments: module_name: Android NDK module name, which must be unique among all module names. all_sources: A list of source files (will be filtered by Compilable). link_deps: A list of link dependencies, which must be sorted in the order from dependencies to dependents. """ if self.type not in ("executable", "shared_library", "static_library"): return self.WriteLn("# Variable definitions for Android applications") self.WriteLn("include $(CLEAR_VARS)") self.WriteLn("LOCAL_MODULE := " + module_name) self.WriteLn( "LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) " "$(DEFS_$(BUILDTYPE)) " # LOCAL_CFLAGS is applied to both of C and C++. There is # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C # sources. "$(CFLAGS_C_$(BUILDTYPE)) " # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while # LOCAL_C_INCLUDES does not expect it. So put it in # LOCAL_CFLAGS. "$(INCS_$(BUILDTYPE))" ) # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred. self.WriteLn("LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))") self.WriteLn("LOCAL_C_INCLUDES :=") self.WriteLn("LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)") # Detect the C++ extension. cpp_ext = {".cc": 0, ".cpp": 0, ".cxx": 0} default_cpp_ext = ".cpp" for filename in all_sources: ext = os.path.splitext(filename)[1] if ext in cpp_ext: cpp_ext[ext] += 1 if cpp_ext[ext] > cpp_ext[default_cpp_ext]: default_cpp_ext = ext self.WriteLn("LOCAL_CPP_EXTENSION := " + default_cpp_ext) self.WriteList( list(map(self.Absolutify, filter(Compilable, all_sources))), "LOCAL_SRC_FILES", ) # Filter out those which do not match prefix and suffix and produce # the resulting list without prefix and suffix. def DepsToModules(deps, prefix, suffix): modules = [] for filepath in deps: filename = os.path.basename(filepath) if filename.startswith(prefix) and filename.endswith(suffix): modules.append(filename[len(prefix) : -len(suffix)]) return modules # Retrieve the default value of 'SHARED_LIB_SUFFIX' params = {"flavor": "linux"} default_variables = {} CalculateVariables(default_variables, params) self.WriteList( DepsToModules( link_deps, generator_default_variables["SHARED_LIB_PREFIX"], default_variables["SHARED_LIB_SUFFIX"], ), "LOCAL_SHARED_LIBRARIES", ) self.WriteList( DepsToModules( link_deps, generator_default_variables["STATIC_LIB_PREFIX"], generator_default_variables["STATIC_LIB_SUFFIX"], ), "LOCAL_STATIC_LIBRARIES", ) if self.type == "executable": self.WriteLn("include $(BUILD_EXECUTABLE)") elif self.type == "shared_library": self.WriteLn("include $(BUILD_SHARED_LIBRARY)") elif self.type == "static_library": self.WriteLn("include $(BUILD_STATIC_LIBRARY)") self.WriteLn() def WriteLn(self, text=""): self.fp.write(text + "\n") def GetSortedXcodeEnv(self, additional_settings=None): return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, "$(abs_builddir)", os.path.join("$(abs_srcdir)", self.path), "$(BUILDTYPE)", additional_settings, ) def GetSortedXcodePostbuildEnv(self): # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( "CHROMIUM_STRIP_SAVE_FILE", "" ) # Even if strip_save_file is empty, explicitly write it. Else a postbuild # might pick up an export from an earlier target. return self.GetSortedXcodeEnv( additional_settings={"CHROMIUM_STRIP_SAVE_FILE": strip_save_file} ) def WriteSortedXcodeEnv(self, target, env): for k, v in env: # For # foo := a\ b # the escaped space does the right thing. For # export foo := a\ b # it does not -- the backslash is written to the env as literal character. # So don't escape spaces in |env[k]|. self.WriteLn(f"{QuoteSpaces(target)}: export {k} := {v}") def Objectify(self, path): """Convert a path to its output directory form.""" if "$(" in path: path = path.replace("$(obj)/", "$(obj).%s/$(TARGET)/" % self.toolset) if "$(obj)" not in path: path = f"$(obj).{self.toolset}/$(TARGET)/{path}" return path def Pchify(self, path, lang): """Convert a prefix header path to its output directory form.""" path = self.Absolutify(path) if "$(" in path: path = path.replace( "$(obj)/", f"$(obj).{self.toolset}/$(TARGET)/pch-{lang}" ) return path return f"$(obj).{self.toolset}/$(TARGET)/pch-{lang}/{path}" def Absolutify(self, path): """Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.""" if "$(" in path: # Don't call normpath in this case, as it might collapse the # path too aggressively if it features '..'. However it's still # important to strip trailing slashes. return path.rstrip("/") return os.path.normpath(os.path.join(self.path, path)) def ExpandInputRoot(self, template, expansion, dirname): if "%(INPUT_ROOT)s" not in template and "%(INPUT_DIRNAME)s" not in template: return template path = template % { "INPUT_ROOT": expansion, "INPUT_DIRNAME": dirname, } return path def _InstallableTargetInstallPath(self): """Returns the location of the final output for an installable target.""" # Functionality removed for all platforms to match Xcode and hoist # shared libraries into PRODUCT_DIR for users: # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files # rely on this. Emulate this behavior for mac. # if self.type == "shared_library" and ( # self.flavor != "mac" or self.toolset != "target" # ): # # Install all shared libs into a common directory (per toolset) for # # convenient access with LD_LIBRARY_PATH. # return "$(builddir)/lib.%s/%s" % (self.toolset, self.alias) if self.flavor == "zos" and self.type == "shared_library": return "$(builddir)/lib.%s/%s" % (self.toolset, self.alias) return "$(builddir)/" + self.alias def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files): """Write the target to regenerate the Makefile.""" options = params["options"] build_files_args = [ gyp.common.RelativePath(filename, options.toplevel_dir) for filename in params["build_files_arg"] ] gyp_binary = gyp.common.FixIfRelativePath( params["gyp_binary"], options.toplevel_dir ) if not gyp_binary.startswith(os.sep): gyp_binary = os.path.join(".", gyp_binary) root_makefile.write( "quiet_cmd_regen_makefile = ACTION Regenerating $@\n" "cmd_regen_makefile = cd $(srcdir); %(cmd)s\n" "%(makefile_name)s: %(deps)s\n" "\t$(call do_cmd,regen_makefile)\n\n" % { "makefile_name": makefile_name, "deps": replace_sep( " ".join(SourceifyAndQuoteSpaces(bf) for bf in build_files) ), "cmd": replace_sep(gyp.common.EncodePOSIXShellList( [gyp_binary, "-fmake"] + gyp.RegenerateFlags(options) + build_files_args )), } ) def PerformBuild(data, configurations, params): options = params["options"] for config in configurations: arguments = ["make"] if options.toplevel_dir and options.toplevel_dir != ".": arguments += "-C", options.toplevel_dir arguments.append("BUILDTYPE=" + config) print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) def GenerateOutput(target_list, target_dicts, data, params): options = params["options"] flavor = gyp.common.GetFlavor(params) generator_flags = params.get("generator_flags", {}) builddir_name = generator_flags.get("output_dir", "out") android_ndk_version = generator_flags.get("android_ndk_version", None) default_target = generator_flags.get("default_target", "all") def CalculateMakefilePath(build_file, base_name): """Determine where to write a Makefile for a given gyp file.""" # Paths in gyp files are relative to the .gyp file, but we want # paths relative to the source root for the master makefile. Grab # the path of the .gyp file as the base to relativize against. # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth) # We write the file in the base_path directory. output_file = os.path.join(options.depth, base_path, base_name) if options.generator_output: output_file = os.path.join( options.depth, options.generator_output, base_path, base_name ) base_path = gyp.common.RelativePath( os.path.dirname(build_file), options.toplevel_dir ) return base_path, output_file # TODO: search for the first non-'Default' target. This can go # away when we add verification that all targets have the # necessary configurations. default_configuration = None toolsets = {target_dicts[target]["toolset"] for target in target_list} for target in target_list: spec = target_dicts[target] if spec["default_configuration"] != "Default": default_configuration = spec["default_configuration"] break if not default_configuration: default_configuration = "Default" srcdir = "." makefile_name = "Makefile" + options.suffix makefile_path = os.path.join(options.toplevel_dir, makefile_name) if options.generator_output: global srcdir_prefix makefile_path = os.path.join( options.toplevel_dir, options.generator_output, makefile_name ) srcdir = replace_sep(gyp.common.RelativePath(srcdir, options.generator_output)) srcdir_prefix = "$(srcdir)/" flock_command = "flock" copy_archive_arguments = "-af" makedep_arguments = "-MMD" # wasm-ld doesn't support --start-group/--end-group link_commands = LINK_COMMANDS_LINUX if flavor in ["wasi", "wasm"]: link_commands = link_commands.replace(' -Wl,--start-group', '').replace( ' -Wl,--end-group', '' ) CC_target = replace_sep(GetEnvironFallback(("CC_target", "CC"), "$(CC)")) AR_target = replace_sep(GetEnvironFallback(("AR_target", "AR"), "$(AR)")) CXX_target = replace_sep(GetEnvironFallback(("CXX_target", "CXX"), "$(CXX)")) LINK_target = replace_sep(GetEnvironFallback(("LINK_target", "LINK"), "$(LINK)")) PLI_target = replace_sep(GetEnvironFallback(("PLI_target", "PLI"), "pli")) CC_host = replace_sep(GetEnvironFallback(("CC_host", "CC"), "gcc")) AR_host = replace_sep(GetEnvironFallback(("AR_host", "AR"), "ar")) CXX_host = replace_sep(GetEnvironFallback(("CXX_host", "CXX"), "g++")) LINK_host = replace_sep(GetEnvironFallback(("LINK_host", "LINK"), "$(CXX.host)")) PLI_host = replace_sep(GetEnvironFallback(("PLI_host", "PLI"), "pli")) header_params = { "default_target": default_target, "builddir": builddir_name, "default_configuration": default_configuration, "flock": flock_command, "flock_index": 1, "link_commands": link_commands, "extra_commands": "", "srcdir": srcdir, "copy_archive_args": copy_archive_arguments, "makedep_args": makedep_arguments, "CC.target": CC_target, "AR.target": AR_target, "CXX.target": CXX_target, "LINK.target": LINK_target, "PLI.target": PLI_target, "CC.host": CC_host, "AR.host": AR_host, "CXX.host": CXX_host, "LINK.host": LINK_host, "PLI.host": PLI_host, } if flavor == "mac": flock_command = "./gyp-mac-tool flock" header_params.update( { "flock": flock_command, "flock_index": 2, "link_commands": LINK_COMMANDS_MAC, "extra_commands": SHARED_HEADER_MAC_COMMANDS, } ) elif flavor == "android": header_params.update({"link_commands": LINK_COMMANDS_ANDROID}) elif flavor == "zos": copy_archive_arguments = "-fPR" CC_target = GetEnvironFallback(("CC_target", "CC"), "njsc") makedep_arguments = "-MMD" if CC_target == "clang": CC_host = GetEnvironFallback(("CC_host", "CC"), "clang") CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "clang++") CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "clang++") elif CC_target == "ibm-clang64": CC_host = GetEnvironFallback(("CC_host", "CC"), "ibm-clang64") CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "ibm-clang++64") CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "ibm-clang++64") elif CC_target == "ibm-clang": CC_host = GetEnvironFallback(("CC_host", "CC"), "ibm-clang") CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "ibm-clang++") CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "ibm-clang++") else: # Node.js versions prior to v18: makedep_arguments = "-qmakedep=gcc" CC_host = GetEnvironFallback(("CC_host", "CC"), "njsc") CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "njsc++") CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "njsc++") header_params.update( { "copy_archive_args": copy_archive_arguments, "makedep_args": makedep_arguments, "link_commands": LINK_COMMANDS_OS390, "extra_commands": SHARED_HEADER_OS390_COMMANDS, "CC.target": CC_target, "CXX.target": CXX_target, "CC.host": CC_host, "CXX.host": CXX_host, } ) elif flavor == "solaris": copy_archive_arguments = "-pPRf@" header_params.update( { "copy_archive_args": copy_archive_arguments, "flock": "./gyp-flock-tool flock", "flock_index": 2, } ) elif flavor == "freebsd": # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific. header_params.update({"flock": "lockf"}) elif flavor == "openbsd": copy_archive_arguments = "-pPRf" header_params.update({"copy_archive_args": copy_archive_arguments}) elif flavor == "aix": copy_archive_arguments = "-pPRf" header_params.update( { "copy_archive_args": copy_archive_arguments, "link_commands": LINK_COMMANDS_AIX, "flock": "./gyp-flock-tool flock", "flock_index": 2, } ) elif flavor == "os400": copy_archive_arguments = "-pPRf" header_params.update( { "copy_archive_args": copy_archive_arguments, "link_commands": LINK_COMMANDS_OS400, "flock": "./gyp-flock-tool flock", "flock_index": 2, } ) build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings_array = data[build_file].get("make_global_settings", []) wrappers = {} for key, value in make_global_settings_array: if key.endswith("_wrapper"): wrappers[key[: -len("_wrapper")]] = "$(abspath %s)" % value make_global_settings = "" for key, value in make_global_settings_array: if re.match(".*_wrapper", key): continue if value[0] != "$": value = "$(abspath %s)" % value wrapper = wrappers.get(key) if wrapper: value = f"{wrapper} {value}" del wrappers[key] if key in ("CC", "CC.host", "CXX", "CXX.host"): make_global_settings += ( "ifneq (,$(filter $(origin %s), undefined default))\n" % key ) # Let gyp-time envvars win over global settings. env_key = key.replace(".", "_") # CC.host -> CC_host if env_key in os.environ: value = os.environ[env_key] make_global_settings += f" {key} = {value}\n" make_global_settings += "endif\n" else: make_global_settings += f"{key} ?= {value}\n" # TODO(ukai): define cmd when only wrapper is specified in # make_global_settings. header_params["make_global_settings"] = make_global_settings gyp.common.EnsureDirExists(makefile_path) root_makefile = open(makefile_path, "w") root_makefile.write(SHARED_HEADER % header_params) # Currently any versions have the same effect, but in future the behavior # could be different. if android_ndk_version: root_makefile.write( "# Define LOCAL_PATH for build of Android applications.\n" "LOCAL_PATH := $(call my-dir)\n" "\n" ) for toolset in toolsets: root_makefile.write("TOOLSET := %s\n" % toolset) WriteRootHeaderSuffixRules(root_makefile) # Put build-time support tools next to the root Makefile. dest_path = os.path.dirname(makefile_path) gyp.common.CopyTool(flavor, dest_path) # Find the list of targets that derive from the gyp file(s) being built. needed_targets = set() for build_file in params["build_files"]: for target in gyp.common.AllTargets(target_list, target_dicts, build_file): needed_targets.add(target) build_files = set() include_list = set() for qualified_target in target_list: build_file, target, toolset = gyp.common.ParseQualifiedTarget(qualified_target) this_make_global_settings = data[build_file].get("make_global_settings", []) assert make_global_settings_array == this_make_global_settings, ( "make_global_settings needs to be the same for all targets " f"{this_make_global_settings} vs. {make_global_settings}" ) build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir)) included_files = data[build_file]["included_files"] for included_file in included_files: # The included_files entries are relative to the dir of the build file # that included them, so we have to undo that and then make them relative # to the root dir. relative_include_file = gyp.common.RelativePath( gyp.common.UnrelativePath(included_file, build_file), options.toplevel_dir, ) abs_include_file = os.path.abspath(relative_include_file) # If the include file is from the ~/.gyp dir, we should use absolute path # so that relocating the src dir doesn't break the path. if params["home_dot_gyp"] and abs_include_file.startswith( params["home_dot_gyp"] ): build_files.add(abs_include_file) else: build_files.add(relative_include_file) base_path, output_file = CalculateMakefilePath( build_file, target + "." + toolset + options.suffix + ".mk" ) spec = target_dicts[qualified_target] configs = spec["configurations"] if flavor == "mac": gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) writer = MakefileWriter(generator_flags, flavor) writer.Write( qualified_target, base_path, output_file, spec, configs, part_of_all=qualified_target in needed_targets, ) # Our root_makefile lives at the source root. Compute the relative path # from there to the output_file for including. mkfile_rel_path = gyp.common.RelativePath( output_file, os.path.dirname(makefile_path) ) include_list.add(mkfile_rel_path) # Write out per-gyp (sub-project) Makefiles. depth_rel_path = gyp.common.RelativePath(options.depth, os.getcwd()) for build_file in build_files: # The paths in build_files were relativized above, so undo that before # testing against the non-relativized items in target_list and before # calculating the Makefile path. build_file = os.path.join(depth_rel_path, build_file) gyp_targets = [ target_dicts[qualified_target]["target_name"] for qualified_target in target_list if qualified_target.startswith(build_file) and qualified_target in needed_targets ] # Only generate Makefiles for gyp files with targets. if not gyp_targets: continue base_path, output_file = CalculateMakefilePath( build_file, os.path.splitext(os.path.basename(build_file))[0] + ".Makefile" ) makefile_rel_path = gyp.common.RelativePath( os.path.dirname(makefile_path), os.path.dirname(output_file) ) writer.WriteSubMake(output_file, makefile_rel_path, gyp_targets, builddir_name) # Write out the sorted list of includes. root_makefile.write("\n") for include_file in sorted(include_list): # We wrap each .mk include in an if statement so users can tell make to # not load a file by setting NO_LOAD. The below make code says, only # load the .mk file if the .mk filename doesn't start with a token in # NO_LOAD. root_makefile.write( "ifeq ($(strip $(foreach prefix,$(NO_LOAD),\\\n" " $(findstring $(join ^,$(prefix)),\\\n" " $(join ^," + include_file + ")))),)\n" ) root_makefile.write(" include " + include_file + "\n") root_makefile.write("endif\n") root_makefile.write("\n") if not generator_flags.get("standalone") and generator_flags.get( "auto_regeneration", True ): WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files) root_makefile.write(SHARED_FOOTER) root_makefile.close() # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import ntpath import os import posixpath import re import subprocess import sys from collections import OrderedDict import gyp.common import gyp.easy_xml as easy_xml import gyp.generator.ninja as ninja_generator import gyp.MSVSNew as MSVSNew import gyp.MSVSProject as MSVSProject import gyp.MSVSSettings as MSVSSettings import gyp.MSVSToolFile as MSVSToolFile import gyp.MSVSUserFile as MSVSUserFile import gyp.MSVSUtil as MSVSUtil import gyp.MSVSVersion as MSVSVersion from gyp.common import GypError from gyp.common import OrderedSet # Regular expression for validating Visual Studio GUIDs. If the GUID # contains lowercase hex letters, MSVS will be fine. However, # IncrediBuild BuildConsole will parse the solution file, but then # silently skip building the target causing hard to track down errors. # Note that this only happens with the BuildConsole, and does not occur # if IncrediBuild is executed from inside Visual Studio. This regex # validates that the string looks like a GUID with all uppercase hex # letters. VALID_MSVS_GUID_CHARS = re.compile(r"^[A-F0-9\-]+$") generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() generator_default_variables = { "DRIVER_PREFIX": "", "DRIVER_SUFFIX": ".sys", "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": ".exe", "STATIC_LIB_PREFIX": "", "SHARED_LIB_PREFIX": "", "STATIC_LIB_SUFFIX": ".lib", "SHARED_LIB_SUFFIX": ".dll", "INTERMEDIATE_DIR": "$(IntDir)", "SHARED_INTERMEDIATE_DIR": "$(OutDir)/obj/global_intermediate", "OS": "win", "PRODUCT_DIR": "$(OutDir)", "LIB_DIR": "$(OutDir)lib", "RULE_INPUT_ROOT": "$(InputName)", "RULE_INPUT_DIRNAME": "$(InputDir)", "RULE_INPUT_EXT": "$(InputExt)", "RULE_INPUT_NAME": "$(InputFileName)", "RULE_INPUT_PATH": "$(InputPath)", "CONFIGURATION_NAME": "$(ConfigurationName)", } # The msvs specific sections that hold paths generator_additional_path_sections = [ "msvs_cygwin_dirs", "msvs_props", ] generator_additional_non_configuration_keys = [ "msvs_cygwin_dirs", "msvs_cygwin_shell", "msvs_large_pdb", "msvs_shard", "msvs_external_builder", "msvs_external_builder_out_dir", "msvs_external_builder_build_cmd", "msvs_external_builder_clean_cmd", "msvs_external_builder_clcompile_cmd", "msvs_enable_winrt", "msvs_requires_importlibrary", "msvs_enable_winphone", "msvs_application_type_revision", "msvs_target_platform_version", "msvs_target_platform_minversion", ] generator_filelist_paths = None # List of precompiled header related keys. precomp_keys = [ "msvs_precompiled_header", "msvs_precompiled_source", ] cached_username = None cached_domain = None # TODO(gspencer): Switch the os.environ calls to be # win32api.GetDomainName() and win32api.GetUserName() once the # python version in depot_tools has been updated to work on Vista # 64-bit. def _GetDomainAndUserName(): if sys.platform not in ("win32", "cygwin"): return ("DOMAIN", "USERNAME") global cached_username global cached_domain if not cached_domain or not cached_username: domain = os.environ.get("USERDOMAIN") username = os.environ.get("USERNAME") if not domain or not username: call = subprocess.Popen( ["net", "config", "Workstation"], stdout=subprocess.PIPE ) config = call.communicate()[0].decode("utf-8") username_re = re.compile(r"^User name\s+(\S+)", re.MULTILINE) username_match = username_re.search(config) if username_match: username = username_match.group(1) domain_re = re.compile(r"^Logon domain\s+(\S+)", re.MULTILINE) domain_match = domain_re.search(config) if domain_match: domain = domain_match.group(1) cached_domain = domain cached_username = username return (cached_domain, cached_username) fixpath_prefix = None def _NormalizedSource(source): """Normalize the path. But not if that gets rid of a variable, as this may expand to something larger than one directory. Arguments: source: The path to be normalize.d Returns: The normalized path. """ normalized = os.path.normpath(source) if source.count("$") == normalized.count("$"): source = normalized return source def _FixPath(path, separator="\\"): """Convert paths to a form that will make sense in a vcproj file. Arguments: path: The path to convert, may contain / etc. Returns: The path with all slashes made into backslashes. """ if ( fixpath_prefix and path and not os.path.isabs(path) and path[0] != "$" and not _IsWindowsAbsPath(path) ): path = os.path.join(fixpath_prefix, path) if separator == "\\": path = path.replace("/", "\\") path = _NormalizedSource(path) if separator == "/": path = path.replace("\\", "/") if path and path[-1] == separator: path = path[:-1] return path def _IsWindowsAbsPath(path): """ On Cygwin systems Python needs a little help determining if a path is an absolute Windows path or not, so that it does not treat those as relative, which results in bad paths like: '..\\C:\\\\some_source_code_file.cc' """ return path.startswith("c:") or path.startswith("C:") def _FixPaths(paths, separator="\\"): """Fix each of the paths of the list.""" return [_FixPath(i, separator) for i in paths] def _ConvertSourcesToFilterHierarchy( sources, prefix=None, excluded=None, list_excluded=True, msvs_version=None ): """Converts a list split source file paths into a vcproj folder hierarchy. Arguments: sources: A list of source file paths split. prefix: A list of source file path layers meant to apply to each of sources. excluded: A set of excluded files. msvs_version: A MSVSVersion object. Returns: A hierarchy of filenames and MSVSProject.Filter objects that matches the layout of the source tree. For example: _ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']], prefix=['joe']) --> [MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']), MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])] """ if not prefix: prefix = [] result = [] excluded_result = [] folders = OrderedDict() # Gather files into the final result, excluded, or folders. for s in sources: if len(s) == 1: filename = _NormalizedSource("\\".join(prefix + s)) if filename in excluded: excluded_result.append(filename) else: result.append(filename) elif msvs_version and not msvs_version.UsesVcxproj(): # For MSVS 2008 and earlier, we need to process all files before walking # the sub folders. if not folders.get(s[0]): folders[s[0]] = [] folders[s[0]].append(s[1:]) else: contents = _ConvertSourcesToFilterHierarchy( [s[1:]], prefix + [s[0]], excluded=excluded, list_excluded=list_excluded, msvs_version=msvs_version, ) contents = MSVSProject.Filter(s[0], contents=contents) result.append(contents) # Add a folder for excluded files. if excluded_result and list_excluded: excluded_folder = MSVSProject.Filter( "_excluded_files", contents=excluded_result ) result.append(excluded_folder) if msvs_version and msvs_version.UsesVcxproj(): return result # Populate all the folders. for f in folders: contents = _ConvertSourcesToFilterHierarchy( folders[f], prefix=prefix + [f], excluded=excluded, list_excluded=list_excluded, msvs_version=msvs_version, ) contents = MSVSProject.Filter(f, contents=contents) result.append(contents) return result def _ToolAppend(tools, tool_name, setting, value, only_if_unset=False): if not value: return _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset) def _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset=False): # TODO(bradnelson): ugly hack, fix this more generally!!! if "Directories" in setting or "Dependencies" in setting: if type(value) == str: value = value.replace("/", "\\") else: value = [i.replace("/", "\\") for i in value] if not tools.get(tool_name): tools[tool_name] = {} tool = tools[tool_name] if setting == "CompileAsWinRT": return if tool.get(setting): if only_if_unset: return if type(tool[setting]) == list and type(value) == list: tool[setting] += value else: raise TypeError( 'Appending "%s" to a non-list setting "%s" for tool "%s" is ' "not allowed, previous value: %s" % (value, setting, tool_name, str(tool[setting])) ) else: tool[setting] = value def _ConfigTargetVersion(config_data): return config_data.get("msvs_target_version", "Windows7") def _ConfigPlatform(config_data): return config_data.get("msvs_configuration_platform", "Win32") def _ConfigBaseName(config_name, platform_name): if config_name.endswith("_" + platform_name): return config_name[0 : -len(platform_name) - 1] else: return config_name def _ConfigFullName(config_name, config_data): platform_name = _ConfigPlatform(config_data) return f"{_ConfigBaseName(config_name, platform_name)}|{platform_name}" def _ConfigWindowsTargetPlatformVersion(config_data, version): target_ver = config_data.get("msvs_windows_target_platform_version") if target_ver and re.match(r"^\d+", target_ver): return target_ver config_ver = config_data.get("msvs_windows_sdk_version") vers = [config_ver] if config_ver else version.compatible_sdks for ver in vers: for key in [ r"HKLM\Software\Microsoft\Microsoft SDKs\Windows\%s", r"HKLM\Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows\%s", ]: sdk_dir = MSVSVersion._RegistryGetValue(key % ver, "InstallationFolder") if not sdk_dir: continue version = MSVSVersion._RegistryGetValue(key % ver, "ProductVersion") or "" # Find a matching entry in sdk_dir\include. expected_sdk_dir = r"%s\include" % sdk_dir names = sorted( ( x for x in ( os.listdir(expected_sdk_dir) if os.path.isdir(expected_sdk_dir) else [] ) if x.startswith(version) ), reverse=True, ) if names: return names[0] else: print( "Warning: No include files found for detected " "Windows SDK version %s" % (version), file=sys.stdout, ) def _BuildCommandLineForRuleRaw( spec, cmd, cygwin_shell, has_input_path, quote_cmd, do_setup_env ): if [x for x in cmd if "$(InputDir)" in x]: input_dir_preamble = ( "set INPUTDIR=$(InputDir)\n" "if NOT DEFINED INPUTDIR set INPUTDIR=.\\\n" "set INPUTDIR=%INPUTDIR:~0,-1%\n" ) else: input_dir_preamble = "" if cygwin_shell: # Find path to cygwin. cygwin_dir = _FixPath(spec.get("msvs_cygwin_dirs", ["."])[0]) # Prepare command. direct_cmd = cmd direct_cmd = [ i.replace("$(IntDir)", '`cygpath -m "${INTDIR}"`') for i in direct_cmd ] direct_cmd = [ i.replace("$(OutDir)", '`cygpath -m "${OUTDIR}"`') for i in direct_cmd ] direct_cmd = [ i.replace("$(InputDir)", '`cygpath -m "${INPUTDIR}"`') for i in direct_cmd ] if has_input_path: direct_cmd = [ i.replace("$(InputPath)", '`cygpath -m "${INPUTPATH}"`') for i in direct_cmd ] direct_cmd = ['\\"%s\\"' % i.replace('"', '\\\\\\"') for i in direct_cmd] # direct_cmd = gyp.common.EncodePOSIXShellList(direct_cmd) direct_cmd = " ".join(direct_cmd) # TODO(quote): regularize quoting path names throughout the module cmd = "" if do_setup_env: cmd += 'call "$(ProjectDir)%(cygwin_dir)s\\setup_env.bat" && ' cmd += "set CYGWIN=nontsec&& " if direct_cmd.find("NUMBER_OF_PROCESSORS") >= 0: cmd += "set /a NUMBER_OF_PROCESSORS_PLUS_1=%%NUMBER_OF_PROCESSORS%%+1&& " if direct_cmd.find("INTDIR") >= 0: cmd += "set INTDIR=$(IntDir)&& " if direct_cmd.find("OUTDIR") >= 0: cmd += "set OUTDIR=$(OutDir)&& " if has_input_path and direct_cmd.find("INPUTPATH") >= 0: cmd += "set INPUTPATH=$(InputPath) && " cmd += 'bash -c "%(cmd)s"' cmd = cmd % {"cygwin_dir": cygwin_dir, "cmd": direct_cmd} return input_dir_preamble + cmd else: # Convert cat --> type to mimic unix. command = ["type"] if cmd[0] == "cat" else [cmd[0].replace("/", "\\")] # Add call before command to ensure that commands can be tied together one # after the other without aborting in Incredibuild, since IB makes a bat # file out of the raw command string, and some commands (like python) are # actually batch files themselves. command.insert(0, "call") # Fix the paths # TODO(quote): This is a really ugly heuristic, and will miss path fixing # for arguments like "--arg=path", arg=path, or "/opt:path". # If the argument starts with a slash or dash, or contains an equal sign, # it's probably a command line switch. # Return the path with forward slashes because the command using it might # not support backslashes. arguments = [ i if (i[:1] in "/-" or "=" in i) else _FixPath(i, "/") for i in cmd[1:] ] arguments = [i.replace("$(InputDir)", "%INPUTDIR%") for i in arguments] arguments = [MSVSSettings.FixVCMacroSlashes(i) for i in arguments] if quote_cmd: # Support a mode for using cmd directly. # Convert any paths to native form (first element is used directly). # TODO(quote): regularize quoting path names throughout the module command[1] = '"%s"' % command[1] arguments = ['"%s"' % i for i in arguments] # Collapse into a single command. return input_dir_preamble + " ".join(command + arguments) def _BuildCommandLineForRule(spec, rule, has_input_path, do_setup_env): # Currently this weird argument munging is used to duplicate the way a # python script would need to be run as part of the chrome tree. # Eventually we should add some sort of rule_default option to set this # per project. For now the behavior chrome needs is the default. mcs = rule.get("msvs_cygwin_shell") if mcs is None: mcs = int(spec.get("msvs_cygwin_shell", 1)) elif isinstance(mcs, str): mcs = int(mcs) quote_cmd = int(rule.get("msvs_quote_cmd", 1)) return _BuildCommandLineForRuleRaw( spec, rule["action"], mcs, has_input_path, quote_cmd, do_setup_env=do_setup_env ) def _AddActionStep(actions_dict, inputs, outputs, description, command): """Merge action into an existing list of actions. Care must be taken so that actions which have overlapping inputs either don't get assigned to the same input, or get collapsed into one. Arguments: actions_dict: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. inputs: list of inputs outputs: list of outputs description: description of the action command: command line to execute """ # Require there to be at least one input (call sites will ensure this). assert inputs action = { "inputs": inputs, "outputs": outputs, "description": description, "command": command, } # Pick where to stick this action. # While less than optimal in terms of build time, attach them to the first # input for now. chosen_input = inputs[0] # Add it there. if chosen_input not in actions_dict: actions_dict[chosen_input] = [] actions_dict[chosen_input].append(action) def _AddCustomBuildToolForMSVS( p, spec, primary_input, inputs, outputs, description, cmd ): """Add a custom build tool to execute something. Arguments: p: the target project spec: the target project dict primary_input: input file to attach the build tool to inputs: list of inputs outputs: list of outputs description: description of the action cmd: command line to execute """ inputs = _FixPaths(inputs) outputs = _FixPaths(outputs) tool = MSVSProject.Tool( "VCCustomBuildTool", { "Description": description, "AdditionalDependencies": ";".join(inputs), "Outputs": ";".join(outputs), "CommandLine": cmd, }, ) # Add to the properties of primary input for each config. for config_name, c_data in spec["configurations"].items(): p.AddFileConfig( _FixPath(primary_input), _ConfigFullName(config_name, c_data), tools=[tool] ) def _AddAccumulatedActionsToMSVS(p, spec, actions_dict): """Add actions accumulated into an actions_dict, merging as needed. Arguments: p: the target project spec: the target project dict actions_dict: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. """ for primary_input in actions_dict: inputs = OrderedSet() outputs = OrderedSet() descriptions = [] commands = [] for action in actions_dict[primary_input]: inputs.update(OrderedSet(action["inputs"])) outputs.update(OrderedSet(action["outputs"])) descriptions.append(action["description"]) commands.append(action["command"]) # Add the custom build step for one input file. description = ", and also ".join(descriptions) command = "\r\n".join(commands) _AddCustomBuildToolForMSVS( p, spec, primary_input=primary_input, inputs=inputs, outputs=outputs, description=description, cmd=command, ) def _RuleExpandPath(path, input_file): """Given the input file to which a rule applied, string substitute a path. Arguments: path: a path to string expand input_file: the file to which the rule applied. Returns: The string substituted path. """ path = path.replace( "$(InputName)", os.path.splitext(os.path.split(input_file)[1])[0] ) path = path.replace("$(InputDir)", os.path.dirname(input_file)) path = path.replace( "$(InputExt)", os.path.splitext(os.path.split(input_file)[1])[1] ) path = path.replace("$(InputFileName)", os.path.split(input_file)[1]) path = path.replace("$(InputPath)", input_file) return path def _FindRuleTriggerFiles(rule, sources): """Find the list of files which a particular rule applies to. Arguments: rule: the rule in question sources: the set of all known source files for this project Returns: The list of sources that trigger a particular rule. """ return rule.get("rule_sources", []) def _RuleInputsAndOutputs(rule, trigger_file): """Find the inputs and outputs generated by a rule. Arguments: rule: the rule in question. trigger_file: the main trigger for this rule. Returns: The pair of (inputs, outputs) involved in this rule. """ raw_inputs = _FixPaths(rule.get("inputs", [])) raw_outputs = _FixPaths(rule.get("outputs", [])) inputs = OrderedSet() outputs = OrderedSet() inputs.add(trigger_file) for i in raw_inputs: inputs.add(_RuleExpandPath(i, trigger_file)) for o in raw_outputs: outputs.add(_RuleExpandPath(o, trigger_file)) return (inputs, outputs) def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options): """Generate a native rules file. Arguments: p: the target project rules: the set of rules to include output_dir: the directory in which the project/gyp resides spec: the project dict options: global generator options """ rules_filename = "{}{}.rules".format(spec["target_name"], options.suffix) rules_file = MSVSToolFile.Writer( os.path.join(output_dir, rules_filename), spec["target_name"] ) # Add each rule. for r in rules: rule_name = r["rule_name"] rule_ext = r["extension"] inputs = _FixPaths(r.get("inputs", [])) outputs = _FixPaths(r.get("outputs", [])) # Skip a rule with no action and no inputs. if "action" not in r and not r.get("rule_sources", []): continue cmd = _BuildCommandLineForRule(spec, r, has_input_path=True, do_setup_env=True) rules_file.AddCustomBuildRule( name=rule_name, description=r.get("message", rule_name), extensions=[rule_ext], additional_dependencies=inputs, outputs=outputs, cmd=cmd, ) # Write out rules file. rules_file.WriteIfChanged() # Add rules file to project. p.AddToolFile(rules_filename) def _Cygwinify(path): path = path.replace("$(OutDir)", "$(OutDirCygwin)") path = path.replace("$(IntDir)", "$(IntDirCygwin)") return path def _GenerateExternalRules(rules, output_dir, spec, sources, options, actions_to_add): """Generate an external makefile to do a set of rules. Arguments: rules: the list of rules to include output_dir: path containing project and gyp files spec: project specification data sources: set of sources known options: global generator options actions_to_add: The list of actions we will add to. """ filename = "{}_rules{}.mk".format(spec["target_name"], options.suffix) mk_file = gyp.common.WriteOnDiff(os.path.join(output_dir, filename)) # Find cygwin style versions of some paths. mk_file.write('OutDirCygwin:=$(shell cygpath -u "$(OutDir)")\n') mk_file.write('IntDirCygwin:=$(shell cygpath -u "$(IntDir)")\n') # Gather stuff needed to emit all: target. all_inputs = OrderedSet() all_outputs = OrderedSet() all_output_dirs = OrderedSet() first_outputs = [] for rule in rules: trigger_files = _FindRuleTriggerFiles(rule, sources) for tf in trigger_files: inputs, outputs = _RuleInputsAndOutputs(rule, tf) all_inputs.update(OrderedSet(inputs)) all_outputs.update(OrderedSet(outputs)) # Only use one target from each rule as the dependency for # 'all' so we don't try to build each rule multiple times. first_outputs.append(next(iter(outputs))) # Get the unique output directories for this rule. output_dirs = [os.path.split(i)[0] for i in outputs] for od in output_dirs: all_output_dirs.add(od) first_outputs_cyg = [_Cygwinify(i) for i in first_outputs] # Write out all: target, including mkdir for each output directory. mk_file.write("all: %s\n" % " ".join(first_outputs_cyg)) for od in all_output_dirs: if od: mk_file.write('\tmkdir -p `cygpath -u "%s"`\n' % od) mk_file.write("\n") # Define how each output is generated. for rule in rules: trigger_files = _FindRuleTriggerFiles(rule, sources) for tf in trigger_files: # Get all the inputs and outputs for this rule for this trigger file. inputs, outputs = _RuleInputsAndOutputs(rule, tf) inputs = [_Cygwinify(i) for i in inputs] outputs = [_Cygwinify(i) for i in outputs] # Prepare the command line for this rule. cmd = [_RuleExpandPath(c, tf) for c in rule["action"]] cmd = ['"%s"' % i for i in cmd] cmd = " ".join(cmd) # Add it to the makefile. mk_file.write("{}: {}\n".format(" ".join(outputs), " ".join(inputs))) mk_file.write("\t%s\n\n" % cmd) # Close up the file. mk_file.close() # Add makefile to list of sources. sources.add(filename) # Add a build action to call makefile. cmd = [ "make", "OutDir=$(OutDir)", "IntDir=$(IntDir)", "-j", "${NUMBER_OF_PROCESSORS_PLUS_1}", "-f", filename, ] cmd = _BuildCommandLineForRuleRaw(spec, cmd, True, False, True, True) # Insert makefile as 0'th input, so it gets the action attached there, # as this is easier to understand from in the IDE. all_inputs = list(all_inputs) all_inputs.insert(0, filename) _AddActionStep( actions_to_add, inputs=_FixPaths(all_inputs), outputs=_FixPaths(all_outputs), description="Running external rules for %s" % spec["target_name"], command=cmd, ) def _EscapeEnvironmentVariableExpansion(s): """Escapes % characters. Escapes any % characters so that Windows-style environment variable expansions will leave them alone. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile to understand why we have to do this. Args: s: The string to be escaped. Returns: The escaped string. """ s = s.replace("%", "%%") return s quote_replacer_regex = re.compile(r'(\\*)"') def _EscapeCommandLineArgumentForMSVS(s): """Escapes a Windows command-line argument. So that the Win32 CommandLineToArgv function will turn the escaped result back into the original string. See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx ("Parsing C++ Command-Line Arguments") to understand why we have to do this. Args: s: the string to be escaped. Returns: the escaped string. """ def _Replace(match): # For a literal quote, CommandLineToArgv requires an odd number of # backslashes preceding it, and it produces half as many literal backslashes # (rounded down). So we need to produce 2n+1 backslashes. return 2 * match.group(1) + '\\"' # Escape all quotes so that they are interpreted literally. s = quote_replacer_regex.sub(_Replace, s) # Now add unescaped quotes so that any whitespace is interpreted literally. s = '"' + s + '"' return s delimiters_replacer_regex = re.compile(r"(\\*)([,;]+)") def _EscapeVCProjCommandLineArgListItem(s): """Escapes command line arguments for MSVS. The VCProj format stores string lists in a single string using commas and semi-colons as separators, which must be quoted if they are to be interpreted literally. However, command-line arguments may already have quotes, and the VCProj parser is ignorant of the backslash escaping convention used by CommandLineToArgv, so the command-line quotes and the VCProj quotes may not be the same quotes. So to store a general command-line argument in a VCProj list, we need to parse the existing quoting according to VCProj's convention and quote any delimiters that are not already quoted by that convention. The quotes that we add will also be seen by CommandLineToArgv, so if backslashes precede them then we also have to escape those backslashes according to the CommandLineToArgv convention. Args: s: the string to be escaped. Returns: the escaped string. """ def _Replace(match): # For a non-literal quote, CommandLineToArgv requires an even number of # backslashes preceding it, and it produces half as many literal # backslashes. So we need to produce 2n backslashes. return 2 * match.group(1) + '"' + match.group(2) + '"' segments = s.split('"') # The unquoted segments are at the even-numbered indices. for i in range(0, len(segments), 2): segments[i] = delimiters_replacer_regex.sub(_Replace, segments[i]) # Concatenate back into a single string s = '"'.join(segments) if len(segments) % 2 == 0: # String ends while still quoted according to VCProj's convention. This # means the delimiter and the next list item that follow this one in the # .vcproj file will be misinterpreted as part of this item. There is nothing # we can do about this. Adding an extra quote would correct the problem in # the VCProj but cause the same problem on the final command-line. Moving # the item to the end of the list does works, but that's only possible if # there's only one such item. Let's just warn the user. print( "Warning: MSVS may misinterpret the odd number of " + "quotes in " + s, file=sys.stderr, ) return s def _EscapeCppDefineForMSVS(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = _EscapeEnvironmentVariableExpansion(s) s = _EscapeCommandLineArgumentForMSVS(s) s = _EscapeVCProjCommandLineArgListItem(s) # cl.exe replaces literal # characters with = in preprocessor definitions for # some reason. Octal-encode to work around that. s = s.replace("#", "\\%03o" % ord("#")) return s quote_replacer_regex2 = re.compile(r'(\\+)"') def _EscapeCommandLineArgumentForMSBuild(s): """Escapes a Windows command-line argument for use by MSBuild.""" def _Replace(match): return (len(match.group(1)) / 2 * 4) * "\\" + '\\"' # Escape all quotes so that they are interpreted literally. s = quote_replacer_regex2.sub(_Replace, s) return s def _EscapeMSBuildSpecialCharacters(s): escape_dictionary = { "%": "%25", "$": "%24", "@": "%40", "'": "%27", ";": "%3B", "?": "%3F", "*": "%2A", } result = "".join([escape_dictionary.get(c, c) for c in s]) return result def _EscapeCppDefineForMSBuild(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = _EscapeEnvironmentVariableExpansion(s) s = _EscapeCommandLineArgumentForMSBuild(s) s = _EscapeMSBuildSpecialCharacters(s) # cl.exe replaces literal # characters with = in preprocessor definitions for # some reason. Octal-encode to work around that. s = s.replace("#", "\\%03o" % ord("#")) return s def _GenerateRulesForMSVS( p, output_dir, options, spec, sources, excluded_sources, actions_to_add ): """Generate all the rules for a particular project. Arguments: p: the project output_dir: directory to emit rules to options: global options passed to the generator spec: the specification for this project sources: the set of all known source files in this project excluded_sources: the set of sources excluded from normal processing actions_to_add: deferred list of actions to add in """ rules = spec.get("rules", []) rules_native = [r for r in rules if not int(r.get("msvs_external_rule", 0))] rules_external = [r for r in rules if int(r.get("msvs_external_rule", 0))] # Handle rules that use a native rules file. if rules_native: _GenerateNativeRulesForMSVS(p, rules_native, output_dir, spec, options) # Handle external rules (non-native rules). if rules_external: _GenerateExternalRules( rules_external, output_dir, spec, sources, options, actions_to_add ) _AdjustSourcesForRules(rules, sources, excluded_sources, False) def _AdjustSourcesForRules(rules, sources, excluded_sources, is_msbuild): # Add outputs generated by each rule (if applicable). for rule in rules: # Add in the outputs from this rule. trigger_files = _FindRuleTriggerFiles(rule, sources) for trigger_file in trigger_files: # Remove trigger_file from excluded_sources to let the rule be triggered # (e.g. rule trigger ax_enums.idl is added to excluded_sources # because it's also in an action's inputs in the same project) excluded_sources.discard(_FixPath(trigger_file)) # Done if not processing outputs as sources. if int(rule.get("process_outputs_as_sources", False)): inputs, outputs = _RuleInputsAndOutputs(rule, trigger_file) inputs = OrderedSet(_FixPaths(inputs)) outputs = OrderedSet(_FixPaths(outputs)) inputs.remove(_FixPath(trigger_file)) sources.update(inputs) if not is_msbuild: excluded_sources.update(inputs) sources.update(outputs) def _FilterActionsFromExcluded(excluded_sources, actions_to_add): """Take inputs with actions attached out of the list of exclusions. Arguments: excluded_sources: list of source files not to be built. actions_to_add: dict of actions keyed on source file they're attached to. Returns: excluded_sources with files that have actions attached removed. """ must_keep = OrderedSet(_FixPaths(actions_to_add.keys())) return [s for s in excluded_sources if s not in must_keep] def _GetDefaultConfiguration(spec): return spec["configurations"][spec["default_configuration"]] def _GetGuidOfProject(proj_path, spec): """Get the guid for the project. Arguments: proj_path: Path of the vcproj or vcxproj file to generate. spec: The target dictionary containing the properties of the target. Returns: the guid. Raises: ValueError: if the specified GUID is invalid. """ # Pluck out the default configuration. default_config = _GetDefaultConfiguration(spec) # Decide the guid of the project. guid = default_config.get("msvs_guid") if guid: if VALID_MSVS_GUID_CHARS.match(guid) is None: raise ValueError( 'Invalid MSVS guid: "%s". Must match regex: "%s".' % (guid, VALID_MSVS_GUID_CHARS.pattern) ) guid = "{%s}" % guid guid = guid or MSVSNew.MakeGuid(proj_path) return guid def _GetMsbuildToolsetOfProject(proj_path, spec, version): """Get the platform toolset for the project. Arguments: proj_path: Path of the vcproj or vcxproj file to generate. spec: The target dictionary containing the properties of the target. version: The MSVSVersion object. Returns: the platform toolset string or None. """ # Pluck out the default configuration. default_config = _GetDefaultConfiguration(spec) toolset = default_config.get("msbuild_toolset") if not toolset and version.DefaultToolset(): toolset = version.DefaultToolset() if spec["type"] == "windows_driver": toolset = "WindowsKernelModeDriver10.0" return toolset def _GenerateProject(project, options, version, generator_flags, spec): """Generates a vcproj file. Arguments: project: the MSVSProject object. options: global generator options. version: the MSVSVersion object. generator_flags: dict of generator-specific flags. Returns: A list of source files that cannot be found on disk. """ default_config = _GetDefaultConfiguration(project.spec) # Skip emitting anything if told to with msvs_existing_vcproj option. if default_config.get("msvs_existing_vcproj"): return [] if version.UsesVcxproj(): return _GenerateMSBuildProject(project, options, version, generator_flags, spec) else: return _GenerateMSVSProject(project, options, version, generator_flags) def _GenerateMSVSProject(project, options, version, generator_flags): """Generates a .vcproj file. It may create .rules and .user files too. Arguments: project: The project object we will generate the file for. options: Global options passed to the generator. version: The VisualStudioVersion object. generator_flags: dict of generator-specific flags. """ spec = project.spec gyp.common.EnsureDirExists(project.path) platforms = _GetUniquePlatforms(spec) p = MSVSProject.Writer( project.path, version, spec["target_name"], project.guid, platforms ) # Get directory project file is in. project_dir = os.path.split(project.path)[0] gyp_path = _NormalizedSource(project.build_file) relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir) config_type = _GetMSVSConfigurationType(spec, project.build_file) for config_name, config in spec["configurations"].items(): _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config) # Prepare list of sources and excluded sources. gyp_file = os.path.split(project.build_file)[1] sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, gyp_file) # Add rules. actions_to_add = {} _GenerateRulesForMSVS( p, project_dir, options, spec, sources, excluded_sources, actions_to_add ) list_excluded = generator_flags.get("msvs_list_excluded_files", True) sources, excluded_sources, excluded_idl = _AdjustSourcesAndConvertToFilterHierarchy( spec, options, project_dir, sources, excluded_sources, list_excluded, version ) # Add in files. missing_sources = _VerifySourcesExist(sources, project_dir) p.AddFiles(sources) _AddToolFilesToMSVS(p, spec) _HandlePreCompiledHeaders(p, sources, spec) _AddActions(actions_to_add, spec, relative_path_of_gyp_file) _AddCopies(actions_to_add, spec) _WriteMSVSUserFile(project.path, version, spec) # NOTE: this stanza must appear after all actions have been decided. # Don't excluded sources with actions attached, or they won't run. excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add) _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded) _AddAccumulatedActionsToMSVS(p, spec, actions_to_add) # Write it out. p.WriteIfChanged() return missing_sources def _GetUniquePlatforms(spec): """Returns the list of unique platforms for this spec, e.g ['win32', ...]. Arguments: spec: The target dictionary containing the properties of the target. Returns: The MSVSUserFile object created. """ # Gather list of unique platforms. platforms = OrderedSet() for configuration in spec["configurations"]: platforms.add(_ConfigPlatform(spec["configurations"][configuration])) platforms = list(platforms) return platforms def _CreateMSVSUserFile(proj_path, version, spec): """Generates a .user file for the user running this Gyp program. Arguments: proj_path: The path of the project file being created. The .user file shares the same path (with an appropriate suffix). version: The VisualStudioVersion object. spec: The target dictionary containing the properties of the target. Returns: The MSVSUserFile object created. """ (domain, username) = _GetDomainAndUserName() vcuser_filename = ".".join([proj_path, domain, username, "user"]) user_file = MSVSUserFile.Writer(vcuser_filename, version, spec["target_name"]) return user_file def _GetMSVSConfigurationType(spec, build_file): """Returns the configuration type for this project. It's a number defined by Microsoft. May raise an exception. Args: spec: The target dictionary containing the properties of the target. build_file: The path of the gyp file. Returns: An integer, the configuration type. """ try: config_type = { "executable": "1", # .exe "shared_library": "2", # .dll "loadable_module": "2", # .dll "static_library": "4", # .lib "windows_driver": "5", # .sys "none": "10", # Utility type }[spec["type"]] except KeyError: if spec.get("type"): raise GypError( "Target type %s is not a valid target type for " "target %s in %s." % (spec["type"], spec["target_name"], build_file) ) else: raise GypError( "Missing type field for target %s in %s." % (spec["target_name"], build_file) ) return config_type def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config): """Adds a configuration to the MSVS project. Many settings in a vcproj file are specific to a configuration. This function the main part of the vcproj file that's configuration specific. Arguments: p: The target project being generated. spec: The target dictionary containing the properties of the target. config_type: The configuration type, a number as defined by Microsoft. config_name: The name of the configuration. config: The dictionary that defines the special processing to be done for this configuration. """ # Get the information for this configuration include_dirs, midl_include_dirs, resource_include_dirs = _GetIncludeDirs(config) libraries = _GetLibraries(spec) library_dirs = _GetLibraryDirs(config) out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec, msbuild=False) defines = _GetDefines(config) defines = [_EscapeCppDefineForMSVS(d) for d in defines] disabled_warnings = _GetDisabledWarnings(config) prebuild = config.get("msvs_prebuild") postbuild = config.get("msvs_postbuild") def_file = _GetModuleDefinition(spec) precompiled_header = config.get("msvs_precompiled_header") # Prepare the list of tools as a dictionary. tools = {} # Add in user specified msvs_settings. msvs_settings = config.get("msvs_settings", {}) MSVSSettings.ValidateMSVSSettings(msvs_settings) # Prevent default library inheritance from the environment. _ToolAppend(tools, "VCLinkerTool", "AdditionalDependencies", ["$(NOINHERIT)"]) for tool in msvs_settings: settings = config["msvs_settings"][tool] for setting in settings: _ToolAppend(tools, tool, setting, settings[setting]) # Add the information to the appropriate tool _ToolAppend(tools, "VCCLCompilerTool", "AdditionalIncludeDirectories", include_dirs) _ToolAppend(tools, "VCMIDLTool", "AdditionalIncludeDirectories", midl_include_dirs) _ToolAppend( tools, "VCResourceCompilerTool", "AdditionalIncludeDirectories", resource_include_dirs, ) # Add in libraries. _ToolAppend(tools, "VCLinkerTool", "AdditionalDependencies", libraries) _ToolAppend(tools, "VCLinkerTool", "AdditionalLibraryDirectories", library_dirs) if out_file: _ToolAppend(tools, vc_tool, "OutputFile", out_file, only_if_unset=True) # Add defines. _ToolAppend(tools, "VCCLCompilerTool", "PreprocessorDefinitions", defines) _ToolAppend(tools, "VCResourceCompilerTool", "PreprocessorDefinitions", defines) # Change program database directory to prevent collisions. _ToolAppend( tools, "VCCLCompilerTool", "ProgramDataBaseFileName", "$(IntDir)$(ProjectName)\\vc80.pdb", only_if_unset=True, ) # Add disabled warnings. _ToolAppend(tools, "VCCLCompilerTool", "DisableSpecificWarnings", disabled_warnings) # Add Pre-build. _ToolAppend(tools, "VCPreBuildEventTool", "CommandLine", prebuild) # Add Post-build. _ToolAppend(tools, "VCPostBuildEventTool", "CommandLine", postbuild) # Turn on precompiled headers if appropriate. if precompiled_header: precompiled_header = os.path.split(precompiled_header)[1] _ToolAppend(tools, "VCCLCompilerTool", "UsePrecompiledHeader", "2") _ToolAppend( tools, "VCCLCompilerTool", "PrecompiledHeaderThrough", precompiled_header ) _ToolAppend(tools, "VCCLCompilerTool", "ForcedIncludeFiles", precompiled_header) # Loadable modules don't generate import libraries; # tell dependent projects to not expect one. if spec["type"] == "loadable_module": _ToolAppend(tools, "VCLinkerTool", "IgnoreImportLibrary", "true") # Set the module definition file if any. if def_file: _ToolAppend(tools, "VCLinkerTool", "ModuleDefinitionFile", def_file) _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name) def _GetIncludeDirs(config): """Returns the list of directories to be used for #include directives. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of directory paths. """ # TODO(bradnelson): include_dirs should really be flexible enough not to # require this sort of thing. include_dirs = config.get("include_dirs", []) + config.get( "msvs_system_include_dirs", [] ) midl_include_dirs = config.get("midl_include_dirs", []) + config.get( "msvs_system_include_dirs", [] ) resource_include_dirs = config.get("resource_include_dirs", include_dirs) include_dirs = _FixPaths(include_dirs) midl_include_dirs = _FixPaths(midl_include_dirs) resource_include_dirs = _FixPaths(resource_include_dirs) return include_dirs, midl_include_dirs, resource_include_dirs def _GetLibraryDirs(config): """Returns the list of directories to be used for library search paths. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of directory paths. """ library_dirs = config.get("library_dirs", []) library_dirs = _FixPaths(library_dirs) return library_dirs def _GetLibraries(spec): """Returns the list of libraries for this configuration. Arguments: spec: The target dictionary containing the properties of the target. Returns: The list of directory paths. """ libraries = spec.get("libraries", []) # Strip out -l, as it is not used on windows (but is needed so we can pass # in libraries that are assumed to be in the default library path). # Also remove duplicate entries, leaving only the last duplicate, while # preserving order. found = OrderedSet() unique_libraries_list = [] for entry in reversed(libraries): library = re.sub(r"^\-l", "", entry) if not os.path.splitext(library)[1]: library += ".lib" if library not in found: found.add(library) unique_libraries_list.append(library) unique_libraries_list.reverse() return unique_libraries_list def _GetOutputFilePathAndTool(spec, msbuild): """Returns the path and tool to use for this target. Figures out the path of the file this spec will create and the name of the VC tool that will create it. Arguments: spec: The target dictionary containing the properties of the target. Returns: A triple of (file path, name of the vc tool, name of the msbuild tool) """ # Select a name for the output file. out_file = "" vc_tool = "" msbuild_tool = "" output_file_map = { "executable": ("VCLinkerTool", "Link", "$(OutDir)", ".exe"), "shared_library": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"), "loadable_module": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"), "windows_driver": ("VCLinkerTool", "Link", "$(OutDir)", ".sys"), "static_library": ("VCLibrarianTool", "Lib", "$(OutDir)lib\\", ".lib"), } output_file_props = output_file_map.get(spec["type"]) if output_file_props and int(spec.get("msvs_auto_output_file", 1)): vc_tool, msbuild_tool, out_dir, suffix = output_file_props if spec.get("standalone_static_library", 0): out_dir = "$(OutDir)" out_dir = spec.get("product_dir", out_dir) product_extension = spec.get("product_extension") if product_extension: suffix = "." + product_extension elif msbuild: suffix = "$(TargetExt)" prefix = spec.get("product_prefix", "") product_name = spec.get("product_name", "$(ProjectName)") out_file = ntpath.join(out_dir, prefix + product_name + suffix) return out_file, vc_tool, msbuild_tool def _GetOutputTargetExt(spec): """Returns the extension for this target, including the dot If product_extension is specified, set target_extension to this to avoid MSB8012, returns None otherwise. Ignores any target_extension settings in the input files. Arguments: spec: The target dictionary containing the properties of the target. Returns: A string with the extension, or None """ target_extension = spec.get("product_extension") if target_extension: return "." + target_extension return None def _GetDefines(config): """Returns the list of preprocessor definitions for this configuration. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of preprocessor definitions. """ defines = [] for d in config.get("defines", []): fd = "=".join([str(dpart) for dpart in d]) if isinstance(d, list) else str(d) defines.append(fd) return defines def _GetDisabledWarnings(config): return [str(i) for i in config.get("msvs_disabled_warnings", [])] def _GetModuleDefinition(spec): def_file = "" if spec["type"] in [ "shared_library", "loadable_module", "executable", "windows_driver", ]: def_files = [s for s in spec.get("sources", []) if s.endswith(".def")] if len(def_files) == 1: def_file = _FixPath(def_files[0]) elif def_files: raise ValueError( "Multiple module definition files in one target, target %s lists " "multiple .def files: %s" % (spec["target_name"], " ".join(def_files)) ) return def_file def _ConvertToolsToExpectedForm(tools): """Convert tools to a form expected by Visual Studio. Arguments: tools: A dictionary of settings; the tool name is the key. Returns: A list of Tool objects. """ tool_list = [] for tool, settings in tools.items(): # Collapse settings with lists. settings_fixed = {} for setting, value in settings.items(): if type(value) == list: if ( tool == "VCLinkerTool" and setting == "AdditionalDependencies" ) or setting == "AdditionalOptions": settings_fixed[setting] = " ".join(value) else: settings_fixed[setting] = ";".join(value) else: settings_fixed[setting] = value # Add in this tool. tool_list.append(MSVSProject.Tool(tool, settings_fixed)) return tool_list def _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name): """Add to the project file the configuration specified by config. Arguments: p: The target project being generated. spec: the target project dict. tools: A dictionary of settings; the tool name is the key. config: The dictionary that defines the special processing to be done for this configuration. config_type: The configuration type, a number as defined by Microsoft. config_name: The name of the configuration. """ attributes = _GetMSVSAttributes(spec, config, config_type) # Add in this configuration. tool_list = _ConvertToolsToExpectedForm(tools) p.AddConfig(_ConfigFullName(config_name, config), attrs=attributes, tools=tool_list) def _GetMSVSAttributes(spec, config, config_type): # Prepare configuration attributes. prepared_attrs = {} source_attrs = config.get("msvs_configuration_attributes", {}) for a in source_attrs: prepared_attrs[a] = source_attrs[a] # Add props files. vsprops_dirs = config.get("msvs_props", []) vsprops_dirs = _FixPaths(vsprops_dirs) if vsprops_dirs: prepared_attrs["InheritedPropertySheets"] = ";".join(vsprops_dirs) # Set configuration type. prepared_attrs["ConfigurationType"] = config_type output_dir = prepared_attrs.get( "OutputDirectory", "$(SolutionDir)$(ConfigurationName)" ) prepared_attrs["OutputDirectory"] = _FixPath(output_dir) + "\\" if "IntermediateDirectory" not in prepared_attrs: intermediate = "$(ConfigurationName)\\obj\\$(ProjectName)" prepared_attrs["IntermediateDirectory"] = _FixPath(intermediate) + "\\" else: intermediate = _FixPath(prepared_attrs["IntermediateDirectory"]) + "\\" intermediate = MSVSSettings.FixVCMacroSlashes(intermediate) prepared_attrs["IntermediateDirectory"] = intermediate return prepared_attrs def _AddNormalizedSources(sources_set, sources_array): sources_set.update(_NormalizedSource(s) for s in sources_array) def _PrepareListOfSources(spec, generator_flags, gyp_file): """Prepare list of sources and excluded sources. Besides the sources specified directly in the spec, adds the gyp file so that a change to it will cause a re-compile. Also adds appropriate sources for actions and copies. Assumes later stage will un-exclude files which have custom build steps attached. Arguments: spec: The target dictionary containing the properties of the target. gyp_file: The name of the gyp file. Returns: A pair of (list of sources, list of excluded sources). The sources will be relative to the gyp file. """ sources = OrderedSet() _AddNormalizedSources(sources, spec.get("sources", [])) excluded_sources = OrderedSet() # Add in the gyp file. if not generator_flags.get("standalone"): sources.add(gyp_file) # Add in 'action' inputs and outputs. for a in spec.get("actions", []): inputs = a["inputs"] inputs = [_NormalizedSource(i) for i in inputs] # Add all inputs to sources and excluded sources. inputs = OrderedSet(inputs) sources.update(inputs) if not spec.get("msvs_external_builder"): excluded_sources.update(inputs) if int(a.get("process_outputs_as_sources", False)): _AddNormalizedSources(sources, a.get("outputs", [])) # Add in 'copies' inputs and outputs. for cpy in spec.get("copies", []): _AddNormalizedSources(sources, cpy.get("files", [])) return (sources, excluded_sources) def _AdjustSourcesAndConvertToFilterHierarchy( spec, options, gyp_dir, sources, excluded_sources, list_excluded, version ): """Adjusts the list of sources and excluded sources. Also converts the sets to lists. Arguments: spec: The target dictionary containing the properties of the target. options: Global generator options. gyp_dir: The path to the gyp file being processed. sources: A set of sources to be included for this project. excluded_sources: A set of sources to be excluded for this project. version: A MSVSVersion object. Returns: A trio of (list of sources, list of excluded sources, path of excluded IDL file) """ # Exclude excluded sources coming into the generator. excluded_sources.update(OrderedSet(spec.get("sources_excluded", []))) # Add excluded sources into sources for good measure. sources.update(excluded_sources) # Convert to proper windows form. # NOTE: sources goes from being a set to a list here. # NOTE: excluded_sources goes from being a set to a list here. sources = _FixPaths(sources) # Convert to proper windows form. excluded_sources = _FixPaths(excluded_sources) excluded_idl = _IdlFilesHandledNonNatively(spec, sources) precompiled_related = _GetPrecompileRelatedFiles(spec) # Find the excluded ones, minus the precompiled header related ones. fully_excluded = [i for i in excluded_sources if i not in precompiled_related] # Convert to folders and the right slashes. sources = [i.split("\\") for i in sources] sources = _ConvertSourcesToFilterHierarchy( sources, excluded=fully_excluded, list_excluded=list_excluded, msvs_version=version, ) # Prune filters with a single child to flatten ugly directory structures # such as ../../src/modules/module1 etc. if version.UsesVcxproj(): while ( all(isinstance(s, MSVSProject.Filter) for s in sources) and len({s.name for s in sources}) == 1 ): assert all(len(s.contents) == 1 for s in sources) sources = [s.contents[0] for s in sources] else: while len(sources) == 1 and isinstance(sources[0], MSVSProject.Filter): sources = sources[0].contents return sources, excluded_sources, excluded_idl def _IdlFilesHandledNonNatively(spec, sources): # If any non-native rules use 'idl' as an extension exclude idl files. # Gather a list here to use later. using_idl = False for rule in spec.get("rules", []): if rule["extension"] == "idl" and int(rule.get("msvs_external_rule", 0)): using_idl = True break excluded_idl = [i for i in sources if i.endswith(".idl")] if using_idl else [] return excluded_idl def _GetPrecompileRelatedFiles(spec): # Gather a list of precompiled header related sources. precompiled_related = [] for _, config in spec["configurations"].items(): for k in precomp_keys: f = config.get(k) if f: precompiled_related.append(_FixPath(f)) return precompiled_related def _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded): exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl) for file_name, excluded_configs in exclusions.items(): if not list_excluded and len(excluded_configs) == len(spec["configurations"]): # If we're not listing excluded files, then they won't appear in the # project, so don't try to configure them to be excluded. pass else: for config_name, config in excluded_configs: p.AddFileConfig( file_name, _ConfigFullName(config_name, config), {"ExcludedFromBuild": "true"}, ) def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl): exclusions = {} # Exclude excluded sources from being built. for f in excluded_sources: excluded_configs = [] for config_name, config in spec["configurations"].items(): precomped = [_FixPath(config.get(i, "")) for i in precomp_keys] # Don't do this for ones that are precompiled header related. if f not in precomped: excluded_configs.append((config_name, config)) exclusions[f] = excluded_configs # If any non-native rules use 'idl' as an extension exclude idl files. # Exclude them now. for f in excluded_idl: excluded_configs = [] for config_name, config in spec["configurations"].items(): excluded_configs.append((config_name, config)) exclusions[f] = excluded_configs return exclusions def _AddToolFilesToMSVS(p, spec): # Add in tool files (rules). tool_files = OrderedSet() for _, config in spec["configurations"].items(): for f in config.get("msvs_tool_files", []): tool_files.add(f) for f in tool_files: p.AddToolFile(f) def _HandlePreCompiledHeaders(p, sources, spec): # Pre-compiled header source stubs need a different compiler flag # (generate precompiled header) and any source file not of the same # kind (i.e. C vs. C++) as the precompiled header source stub needs # to have use of precompiled headers disabled. extensions_excluded_from_precompile = [] for config_name, config in spec["configurations"].items(): source = config.get("msvs_precompiled_source") if source: source = _FixPath(source) # UsePrecompiledHeader=1 for if using precompiled headers. tool = MSVSProject.Tool("VCCLCompilerTool", {"UsePrecompiledHeader": "1"}) p.AddFileConfig( source, _ConfigFullName(config_name, config), {}, tools=[tool] ) basename, extension = os.path.splitext(source) if extension == ".c": extensions_excluded_from_precompile = [".cc", ".cpp", ".cxx"] else: extensions_excluded_from_precompile = [".c"] def DisableForSourceTree(source_tree): for source in source_tree: if isinstance(source, MSVSProject.Filter): DisableForSourceTree(source.contents) else: basename, extension = os.path.splitext(source) if extension in extensions_excluded_from_precompile: for config_name, config in spec["configurations"].items(): tool = MSVSProject.Tool( "VCCLCompilerTool", { "UsePrecompiledHeader": "0", "ForcedIncludeFiles": "$(NOINHERIT)", }, ) p.AddFileConfig( _FixPath(source), _ConfigFullName(config_name, config), {}, tools=[tool], ) # Do nothing if there was no precompiled source. if extensions_excluded_from_precompile: DisableForSourceTree(sources) def _AddActions(actions_to_add, spec, relative_path_of_gyp_file): # Add actions. actions = spec.get("actions", []) # Don't setup_env every time. When all the actions are run together in one # batch file in VS, the PATH will grow too long. # Membership in this set means that the cygwin environment has been set up, # and does not need to be set up again. have_setup_env = set() for a in actions: # Attach actions to the gyp file if nothing else is there. inputs = a.get("inputs") or [relative_path_of_gyp_file] attached_to = inputs[0] need_setup_env = attached_to not in have_setup_env cmd = _BuildCommandLineForRule( spec, a, has_input_path=False, do_setup_env=need_setup_env ) have_setup_env.add(attached_to) # Add the action. _AddActionStep( actions_to_add, inputs=inputs, outputs=a.get("outputs", []), description=a.get("message", a["action_name"]), command=cmd, ) def _WriteMSVSUserFile(project_path, version, spec): # Add run_as and test targets. if "run_as" in spec: run_as = spec["run_as"] action = run_as.get("action", []) environment = run_as.get("environment", []) working_directory = run_as.get("working_directory", ".") elif int(spec.get("test", 0)): action = ["$(TargetPath)", "--gtest_print_time"] environment = [] working_directory = "." else: return # Nothing to add # Write out the user file. user_file = _CreateMSVSUserFile(project_path, version, spec) for config_name, c_data in spec["configurations"].items(): user_file.AddDebugSettings( _ConfigFullName(config_name, c_data), action, environment, working_directory ) user_file.WriteIfChanged() def _AddCopies(actions_to_add, spec): copies = _GetCopies(spec) for inputs, outputs, cmd, description in copies: _AddActionStep( actions_to_add, inputs=inputs, outputs=outputs, description=description, command=cmd, ) def _GetCopies(spec): copies = [] # Add copies. for cpy in spec.get("copies", []): for src in cpy.get("files", []): dst = os.path.join(cpy["destination"], os.path.basename(src)) # _AddCustomBuildToolForMSVS() will call _FixPath() on the inputs and # outputs, so do the same for our generated command line. if src.endswith("/"): src_bare = src[:-1] base_dir = posixpath.split(src_bare)[0] outer_dir = posixpath.split(src_bare)[1] fixed_dst = _FixPath(dst) full_dst = f'"{fixed_dst}\\{outer_dir}\\"' cmd = ( f'mkdir {full_dst} 2>nul & cd "{_FixPath(base_dir)}" ' f'&& xcopy /e /f /y "{outer_dir}" {full_dst}' ) copies.append( ( [src], ["dummy_copies", dst], cmd, f"Copying {src} to {fixed_dst}", ) ) else: fix_dst = _FixPath(cpy["destination"]) cmd = ( f'mkdir "{fix_dst}" 2>nul & set ERRORLEVEL=0 & ' f'copy /Y "{_FixPath(src)}" "{_FixPath(dst)}"' ) copies.append(([src], [dst], cmd, f"Copying {src} to {fix_dst}")) return copies def _GetPathDict(root, path): # |path| will eventually be empty (in the recursive calls) if it was initially # relative; otherwise it will eventually end up as '\', 'D:\', etc. if not path or path.endswith(os.sep): return root parent, folder = os.path.split(path) parent_dict = _GetPathDict(root, parent) if folder not in parent_dict: parent_dict[folder] = {} return parent_dict[folder] def _DictsToFolders(base_path, bucket, flat): # Convert to folders recursively. children = [] for folder, contents in bucket.items(): if type(contents) == dict: folder_children = _DictsToFolders( os.path.join(base_path, folder), contents, flat ) if flat: children += folder_children else: folder_children = MSVSNew.MSVSFolder( os.path.join(base_path, folder), name="(" + folder + ")", entries=folder_children, ) children.append(folder_children) else: children.append(contents) return children def _CollapseSingles(parent, node): # Recursively explorer the tree of dicts looking for projects which are # the sole item in a folder which has the same name as the project. Bring # such projects up one level. if type(node) == dict and len(node) == 1 and next(iter(node)) == parent + ".vcproj": return node[next(iter(node))] if type(node) != dict: return node for child in node: node[child] = _CollapseSingles(child, node[child]) return node def _GatherSolutionFolders(sln_projects, project_objects, flat): root = {} # Convert into a tree of dicts on path. for p in sln_projects: gyp_file, target = gyp.common.ParseQualifiedTarget(p)[0:2] if p.endswith("#host"): target += "_host" gyp_dir = os.path.dirname(gyp_file) path_dict = _GetPathDict(root, gyp_dir) path_dict[target + ".vcproj"] = project_objects[p] # Walk down from the top until we hit a folder that has more than one entry. # In practice, this strips the top-level "src/" dir from the hierarchy in # the solution. while len(root) == 1 and type(root[next(iter(root))]) == dict: root = root[next(iter(root))] # Collapse singles. root = _CollapseSingles("", root) # Merge buckets until everything is a root entry. return _DictsToFolders("", root, flat) def _GetPathOfProject(qualified_target, spec, options, msvs_version): default_config = _GetDefaultConfiguration(spec) proj_filename = default_config.get("msvs_existing_vcproj") if not proj_filename: proj_filename = spec["target_name"] if spec["toolset"] == "host": proj_filename += "_host" proj_filename = proj_filename + options.suffix + msvs_version.ProjectExtension() build_file = gyp.common.BuildFile(qualified_target) proj_path = os.path.join(os.path.dirname(build_file), proj_filename) fix_prefix = None if options.generator_output: project_dir_path = os.path.dirname(os.path.abspath(proj_path)) proj_path = os.path.join(options.generator_output, proj_path) fix_prefix = gyp.common.RelativePath( project_dir_path, os.path.dirname(proj_path) ) return proj_path, fix_prefix def _GetPlatformOverridesOfProject(spec): # Prepare a dict indicating which project configurations are used for which # solution configurations for this target. config_platform_overrides = {} for config_name, c in spec["configurations"].items(): config_fullname = _ConfigFullName(config_name, c) platform = c.get("msvs_target_platform", _ConfigPlatform(c)) base_name = _ConfigBaseName(config_name, _ConfigPlatform(c)) fixed_config_fullname = f"{base_name}|{platform}" if spec["toolset"] == "host" and generator_supports_multiple_toolsets: fixed_config_fullname = f"{config_name}|x64" config_platform_overrides[config_fullname] = fixed_config_fullname return config_platform_overrides def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): """Create a MSVSProject object for the targets found in target list. Arguments: target_list: the list of targets to generate project objects for. target_dicts: the dictionary of specifications. options: global generator options. msvs_version: the MSVSVersion object. Returns: A set of created projects, keyed by target. """ global fixpath_prefix # Generate each project. projects = {} for qualified_target in target_list: spec = target_dicts[qualified_target] proj_path, fixpath_prefix = _GetPathOfProject( qualified_target, spec, options, msvs_version ) guid = _GetGuidOfProject(proj_path, spec) overrides = _GetPlatformOverridesOfProject(spec) build_file = gyp.common.BuildFile(qualified_target) # Create object for this project. target_name = spec["target_name"] if spec["toolset"] == "host": target_name += "_host" obj = MSVSNew.MSVSProject( proj_path, name=target_name, guid=guid, spec=spec, build_file=build_file, config_platform_overrides=overrides, fixpath_prefix=fixpath_prefix, ) # Set project toolset if any (MS build only) if msvs_version.UsesVcxproj(): obj.set_msbuild_toolset( _GetMsbuildToolsetOfProject(proj_path, spec, msvs_version) ) projects[qualified_target] = obj # Set all the dependencies, but not if we are using an external builder like # ninja for project in projects.values(): if not project.spec.get("msvs_external_builder"): deps = project.spec.get("dependencies", []) deps = [projects[d] for d in deps] project.set_dependencies(deps) return projects def _InitNinjaFlavor(params, target_list, target_dicts): """Initialize targets for the ninja flavor. This sets up the necessary variables in the targets to generate msvs projects that use ninja as an external builder. The variables in the spec are only set if they have not been set. This allows individual specs to override the default values initialized here. Arguments: params: Params provided to the generator. target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. """ for qualified_target in target_list: spec = target_dicts[qualified_target] if spec.get("msvs_external_builder"): # The spec explicitly defined an external builder, so don't change it. continue path_to_ninja = spec.get("msvs_path_to_ninja", "ninja.exe") spec["msvs_external_builder"] = "ninja" if not spec.get("msvs_external_builder_out_dir"): gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target) gyp_dir = os.path.dirname(gyp_file) configuration = "$(Configuration)" if params.get("target_arch") == "x64": configuration += "_x64" if params.get("target_arch") == "arm64": configuration += "_arm64" spec["msvs_external_builder_out_dir"] = os.path.join( gyp.common.RelativePath(params["options"].toplevel_dir, gyp_dir), ninja_generator.ComputeOutputDir(params), configuration, ) if not spec.get("msvs_external_builder_build_cmd"): spec["msvs_external_builder_build_cmd"] = [ path_to_ninja, "-C", "$(OutDir)", "$(ProjectName)", ] if not spec.get("msvs_external_builder_clean_cmd"): spec["msvs_external_builder_clean_cmd"] = [ path_to_ninja, "-C", "$(OutDir)", "-tclean", "$(ProjectName)", ] def CalculateVariables(default_variables, params): """Generated variables that require params to be known.""" generator_flags = params.get("generator_flags", {}) # Select project file format version (if unset, default to auto detecting). msvs_version = MSVSVersion.SelectVisualStudioVersion( generator_flags.get("msvs_version", "auto") ) # Stash msvs_version for later (so we don't have to probe the system twice). params["msvs_version"] = msvs_version # Set a variable so conditions can be based on msvs_version. default_variables["MSVS_VERSION"] = msvs_version.ShortName() # To determine processor word size on Windows, in addition to checking # PROCESSOR_ARCHITECTURE (which reflects the word size of the current # process), it is also necessary to check PROCESSOR_ARCITEW6432 (which # contains the actual word size of the system when running thru WOW64). if ( os.environ.get("PROCESSOR_ARCHITECTURE", "").find("64") >= 0 or os.environ.get("PROCESSOR_ARCHITEW6432", "").find("64") >= 0 ): default_variables["MSVS_OS_BITS"] = 64 else: default_variables["MSVS_OS_BITS"] = 32 if gyp.common.GetFlavor(params) == "ninja": default_variables["SHARED_INTERMEDIATE_DIR"] = "$(OutDir)gen" def PerformBuild(data, configurations, params): options = params["options"] msvs_version = params["msvs_version"] devenv = os.path.join(msvs_version.path, "Common7", "IDE", "devenv.com") for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != ".gyp": continue sln_path = build_file_root + options.suffix + ".sln" if options.generator_output: sln_path = os.path.join(options.generator_output, sln_path) for config in configurations: arguments = [devenv, sln_path, "/Build", config] print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) def CalculateGeneratorInputInfo(params): if params.get("flavor") == "ninja": toplevel = params["options"].toplevel_dir qualified_out_dir = os.path.normpath( os.path.join( toplevel, ninja_generator.ComputeOutputDir(params), "gypfiles-msvs-ninja", ) ) global generator_filelist_paths generator_filelist_paths = { "toplevel": toplevel, "qualified_out_dir": qualified_out_dir, } def GenerateOutput(target_list, target_dicts, data, params): """Generate .sln and .vcproj files. This is the entry point for this generator. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. data: Dictionary containing per .gyp data. """ global fixpath_prefix options = params["options"] # Get the project file format version back out of where we stashed it in # GeneratorCalculatedVariables. msvs_version = params["msvs_version"] generator_flags = params.get("generator_flags", {}) # Optionally shard targets marked with 'msvs_shard': SHARD_COUNT. (target_list, target_dicts) = MSVSUtil.ShardTargets(target_list, target_dicts) # Optionally use the large PDB workaround for targets marked with # 'msvs_large_pdb': 1. (target_list, target_dicts) = MSVSUtil.InsertLargePdbShims( target_list, target_dicts, generator_default_variables ) # Optionally configure each spec to use ninja as the external builder. if params.get("flavor") == "ninja": _InitNinjaFlavor(params, target_list, target_dicts) # Prepare the set of configurations. configs = set() for qualified_target in target_list: spec = target_dicts[qualified_target] for config_name, config in spec["configurations"].items(): config_name = _ConfigFullName(config_name, config) configs.add(config_name) if config_name == "Release|arm64": configs.add("Release|x64") configs = list(configs) # Figure out all the projects that will be generated and their guids project_objects = _CreateProjectObjects( target_list, target_dicts, options, msvs_version ) # Generate each project. missing_sources = [] for project in project_objects.values(): fixpath_prefix = project.fixpath_prefix missing_sources.extend( _GenerateProject(project, options, msvs_version, generator_flags, spec) ) fixpath_prefix = None for build_file in data: # Validate build_file extension target_only_configs = configs if generator_supports_multiple_toolsets: target_only_configs = [i for i in configs if i.endswith("arm64")] if not build_file.endswith(".gyp"): continue sln_path = os.path.splitext(build_file)[0] + options.suffix + ".sln" if options.generator_output: sln_path = os.path.join(options.generator_output, sln_path) # Get projects in the solution, and their dependents. sln_projects = gyp.common.BuildFileTargets(target_list, build_file) sln_projects += gyp.common.DeepDependencyTargets(target_dicts, sln_projects) # Create folder hierarchy. root_entries = _GatherSolutionFolders( sln_projects, project_objects, flat=msvs_version.FlatSolution() ) # Create solution. sln = MSVSNew.MSVSSolution( sln_path, entries=root_entries, variants=target_only_configs, websiteProperties=False, version=msvs_version, ) sln.Write() if missing_sources: error_message = "Missing input files:\n" + "\n".join(set(missing_sources)) if generator_flags.get("msvs_error_on_missing_sources", False): raise GypError(error_message) else: print("Warning: " + error_message, file=sys.stdout) def _GenerateMSBuildFiltersFile( filters_path, source_files, rule_dependencies, extension_to_rule_name, platforms, toolset, ): """Generate the filters file. This file is used by Visual Studio to organize the presentation of source files into folders. Arguments: filters_path: The path of the file to be created. source_files: The hierarchical structure of all the sources. extension_to_rule_name: A dictionary mapping file extensions to rules. """ filter_group = [] source_group = [] _AppendFiltersForMSBuild( "", source_files, rule_dependencies, extension_to_rule_name, platforms, toolset, filter_group, source_group, ) if filter_group: content = [ "Project", { "ToolsVersion": "4.0", "xmlns": "http://schemas.microsoft.com/developer/msbuild/2003", }, ["ItemGroup"] + filter_group, ["ItemGroup"] + source_group, ] easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True) elif os.path.exists(filters_path): # We don't need this filter anymore. Delete the old filter file. os.unlink(filters_path) def _AppendFiltersForMSBuild( parent_filter_name, sources, rule_dependencies, extension_to_rule_name, platforms, toolset, filter_group, source_group, ): """Creates the list of filters and sources to be added in the filter file. Args: parent_filter_name: The name of the filter under which the sources are found. sources: The hierarchy of filters and sources to process. extension_to_rule_name: A dictionary mapping file extensions to rules. filter_group: The list to which filter entries will be appended. source_group: The list to which source entries will be appended. """ for source in sources: if isinstance(source, MSVSProject.Filter): # We have a sub-filter. Create the name of that sub-filter. if not parent_filter_name: filter_name = source.name else: filter_name = f"{parent_filter_name}\\{source.name}" # Add the filter to the group. filter_group.append( [ "Filter", {"Include": filter_name}, ["UniqueIdentifier", MSVSNew.MakeGuid(source.name)], ] ) # Recurse and add its dependents. _AppendFiltersForMSBuild( filter_name, source.contents, rule_dependencies, extension_to_rule_name, platforms, toolset, filter_group, source_group, ) else: # It's a source. Create a source entry. _, element = _MapFileToMsBuildSourceType( source, rule_dependencies, extension_to_rule_name, platforms, toolset ) source_entry = [element, {"Include": source}] # Specify the filter it is part of, if any. if parent_filter_name: source_entry.append(["Filter", parent_filter_name]) source_group.append(source_entry) def _MapFileToMsBuildSourceType( source, rule_dependencies, extension_to_rule_name, platforms, toolset ): """Returns the group and element type of the source file. Arguments: source: The source file name. extension_to_rule_name: A dictionary mapping file extensions to rules. Returns: A pair of (group this file should be part of, the label of element) """ _, ext = os.path.splitext(source) ext = ext.lower() if ext in extension_to_rule_name: group = "rule" element = extension_to_rule_name[ext] elif ext in [".cc", ".cpp", ".c", ".cxx", ".mm"]: group = "compile" element = "ClCompile" elif ext in [".h", ".hxx"]: group = "include" element = "ClInclude" elif ext == ".rc": group = "resource" element = "ResourceCompile" elif ext in [".s", ".asm"]: group = "masm" element = "MASM" if "arm64" in platforms and toolset == "target": element = "MARMASM" elif ext == ".idl": group = "midl" element = "Midl" elif source in rule_dependencies: group = "rule_dependency" element = "CustomBuild" else: group = "none" element = "None" return (group, element) def _GenerateRulesForMSBuild( output_dir, options, spec, sources, excluded_sources, props_files_of_rules, targets_files_of_rules, actions_to_add, rule_dependencies, extension_to_rule_name, ): # MSBuild rules are implemented using three files: an XML file, a .targets # file and a .props file. # For more details see: # https://devblogs.microsoft.com/cppblog/quick-help-on-vs2010-custom-build-rule/ rules = spec.get("rules", []) rules_native = [r for r in rules if not int(r.get("msvs_external_rule", 0))] rules_external = [r for r in rules if int(r.get("msvs_external_rule", 0))] msbuild_rules = [] for rule in rules_native: # Skip a rule with no action and no inputs. if "action" not in rule and not rule.get("rule_sources", []): continue msbuild_rule = MSBuildRule(rule, spec) msbuild_rules.append(msbuild_rule) rule_dependencies.update(msbuild_rule.additional_dependencies.split(";")) extension_to_rule_name[msbuild_rule.extension] = msbuild_rule.rule_name if msbuild_rules: base = spec["target_name"] + options.suffix props_name = base + ".props" targets_name = base + ".targets" xml_name = base + ".xml" props_files_of_rules.add(props_name) targets_files_of_rules.add(targets_name) props_path = os.path.join(output_dir, props_name) targets_path = os.path.join(output_dir, targets_name) xml_path = os.path.join(output_dir, xml_name) _GenerateMSBuildRulePropsFile(props_path, msbuild_rules) _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules) _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules) if rules_external: _GenerateExternalRules( rules_external, output_dir, spec, sources, options, actions_to_add ) _AdjustSourcesForRules(rules, sources, excluded_sources, True) class MSBuildRule: """Used to store information used to generate an MSBuild rule. Attributes: rule_name: The rule name, sanitized to use in XML. target_name: The name of the target. after_targets: The name of the AfterTargets element. before_targets: The name of the BeforeTargets element. depends_on: The name of the DependsOn element. compute_output: The name of the ComputeOutput element. dirs_to_make: The name of the DirsToMake element. inputs: The name of the _inputs element. tlog: The name of the _tlog element. extension: The extension this rule applies to. description: The message displayed when this rule is invoked. additional_dependencies: A string listing additional dependencies. outputs: The outputs of this rule. command: The command used to run the rule. """ def __init__(self, rule, spec): self.display_name = rule["rule_name"] # Assure that the rule name is only characters and numbers self.rule_name = re.sub(r"\W", "_", self.display_name) # Create the various element names, following the example set by the # Visual Studio 2008 to 2010 conversion. I don't know if VS2010 # is sensitive to the exact names. self.target_name = "_" + self.rule_name self.after_targets = self.rule_name + "AfterTargets" self.before_targets = self.rule_name + "BeforeTargets" self.depends_on = self.rule_name + "DependsOn" self.compute_output = "Compute%sOutput" % self.rule_name self.dirs_to_make = self.rule_name + "DirsToMake" self.inputs = self.rule_name + "_inputs" self.tlog = self.rule_name + "_tlog" self.extension = rule["extension"] if not self.extension.startswith("."): self.extension = "." + self.extension self.description = MSVSSettings.ConvertVCMacrosToMSBuild( rule.get("message", self.rule_name) ) old_additional_dependencies = _FixPaths(rule.get("inputs", [])) self.additional_dependencies = ";".join( [ MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in old_additional_dependencies ] ) old_outputs = _FixPaths(rule.get("outputs", [])) self.outputs = ";".join( [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in old_outputs] ) old_command = _BuildCommandLineForRule( spec, rule, has_input_path=True, do_setup_env=True ) self.command = MSVSSettings.ConvertVCMacrosToMSBuild(old_command) def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules): """Generate the .props file.""" content = [ "Project", {"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"}, ] for rule in msbuild_rules: content.extend( [ [ "PropertyGroup", { "Condition": "'$(%s)' == '' and '$(%s)' == '' and " "'$(ConfigurationType)' != 'Makefile'" % (rule.before_targets, rule.after_targets) }, [rule.before_targets, "Midl"], [rule.after_targets, "CustomBuild"], ], [ "PropertyGroup", [ rule.depends_on, {"Condition": "'$(ConfigurationType)' != 'Makefile'"}, "_SelectedFiles;$(%s)" % rule.depends_on, ], ], [ "ItemDefinitionGroup", [ rule.rule_name, ["CommandLineTemplate", rule.command], ["Outputs", rule.outputs], ["ExecutionDescription", rule.description], ["AdditionalDependencies", rule.additional_dependencies], ], ], ] ) easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True) def _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules): """Generate the .targets file.""" content = [ "Project", {"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"}, ] item_group = [ "ItemGroup", [ "PropertyPageSchema", {"Include": "$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml"}, ], ] for rule in msbuild_rules: item_group.append( [ "AvailableItemName", {"Include": rule.rule_name}, ["Targets", rule.target_name], ] ) content.append(item_group) for rule in msbuild_rules: content.append( [ "UsingTask", { "TaskName": rule.rule_name, "TaskFactory": "XamlTaskFactory", "AssemblyName": "Microsoft.Build.Tasks.v4.0", }, ["Task", "$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml"], ] ) for rule in msbuild_rules: rule_name = rule.rule_name target_outputs = "%%(%s.Outputs)" % rule_name target_inputs = ( "%%(%s.Identity);%%(%s.AdditionalDependencies);" "$(MSBuildProjectFile)" ) % (rule_name, rule_name) rule_inputs = "%%(%s.Identity)" % rule_name extension_condition = ( "'%(Extension)'=='.obj' or " "'%(Extension)'=='.res' or " "'%(Extension)'=='.rsc' or " "'%(Extension)'=='.lib'" ) remove_section = [ "ItemGroup", {"Condition": "'@(SelectedFiles)' != ''"}, [ rule_name, { "Remove": "@(%s)" % rule_name, "Condition": "'%(Identity)' != '@(SelectedFiles)'", }, ], ] inputs_section = [ "ItemGroup", [rule.inputs, {"Include": "%%(%s.AdditionalDependencies)" % rule_name}], ] logging_section = [ "ItemGroup", [ rule.tlog, { "Include": "%%(%s.Outputs)" % rule_name, "Condition": ( "'%%(%s.Outputs)' != '' and " "'%%(%s.ExcludedFromBuild)' != 'true'" % (rule_name, rule_name) ), }, ["Source", "@(%s, '|')" % rule_name], ["Inputs", "@(%s -> '%%(Fullpath)', ';')" % rule.inputs], ], ] message_section = [ "Message", {"Importance": "High", "Text": "%%(%s.ExecutionDescription)" % rule_name}, ] write_tlog_section = [ "WriteLinesToFile", { "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " "'true'" % (rule.tlog, rule.tlog), "File": "$(IntDir)$(ProjectName).write.1.tlog", "Lines": "^%%(%s.Source);@(%s->'%%(Fullpath)')" % (rule.tlog, rule.tlog), }, ] read_tlog_section = [ "WriteLinesToFile", { "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " "'true'" % (rule.tlog, rule.tlog), "File": "$(IntDir)$(ProjectName).read.1.tlog", "Lines": f"^%({rule.tlog}.Source);%({rule.tlog}.Inputs)", }, ] command_and_input_section = [ rule_name, { "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " "'true'" % (rule_name, rule_name), "EchoOff": "true", "StandardOutputImportance": "High", "StandardErrorImportance": "High", "CommandLineTemplate": "%%(%s.CommandLineTemplate)" % rule_name, "AdditionalOptions": "%%(%s.AdditionalOptions)" % rule_name, "Inputs": rule_inputs, }, ] content.extend( [ [ "Target", { "Name": rule.target_name, "BeforeTargets": "$(%s)" % rule.before_targets, "AfterTargets": "$(%s)" % rule.after_targets, "Condition": "'@(%s)' != ''" % rule_name, "DependsOnTargets": "$(%s);%s" % (rule.depends_on, rule.compute_output), "Outputs": target_outputs, "Inputs": target_inputs, }, remove_section, inputs_section, logging_section, message_section, write_tlog_section, read_tlog_section, command_and_input_section, ], [ "PropertyGroup", [ "ComputeLinkInputsTargets", "$(ComputeLinkInputsTargets);", "%s;" % rule.compute_output, ], [ "ComputeLibInputsTargets", "$(ComputeLibInputsTargets);", "%s;" % rule.compute_output, ], ], [ "Target", { "Name": rule.compute_output, "Condition": "'@(%s)' != ''" % rule_name, }, [ "ItemGroup", [ rule.dirs_to_make, { "Condition": "'@(%s)' != '' and " "'%%(%s.ExcludedFromBuild)' != 'true'" % (rule_name, rule_name), "Include": "%%(%s.Outputs)" % rule_name, }, ], [ "Link", { "Include": "%%(%s.Identity)" % rule.dirs_to_make, "Condition": extension_condition, }, ], [ "Lib", { "Include": "%%(%s.Identity)" % rule.dirs_to_make, "Condition": extension_condition, }, ], [ "ImpLib", { "Include": "%%(%s.Identity)" % rule.dirs_to_make, "Condition": extension_condition, }, ], ], [ "MakeDir", { "Directories": ( "@(%s->'%%(RootDir)%%(Directory)')" % rule.dirs_to_make ) }, ], ], ] ) easy_xml.WriteXmlIfChanged(content, targets_path, pretty=True, win32=True) def _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules): # Generate the .xml file content = [ "ProjectSchemaDefinitions", { "xmlns": ( "clr-namespace:Microsoft.Build.Framework.XamlTypes;" "assembly=Microsoft.Build.Framework" ), "xmlns:x": "http://schemas.microsoft.com/winfx/2006/xaml", "xmlns:sys": "clr-namespace:System;assembly=mscorlib", "xmlns:transformCallback": "Microsoft.Cpp.Dev10.ConvertPropertyCallback", }, ] for rule in msbuild_rules: content.extend( [ [ "Rule", { "Name": rule.rule_name, "PageTemplate": "tool", "DisplayName": rule.display_name, "Order": "200", }, [ "Rule.DataSource", [ "DataSource", {"Persistence": "ProjectFile", "ItemType": rule.rule_name}, ], ], [ "Rule.Categories", [ "Category", {"Name": "General"}, ["Category.DisplayName", ["sys:String", "General"]], ], [ "Category", {"Name": "Command Line", "Subtype": "CommandLine"}, ["Category.DisplayName", ["sys:String", "Command Line"]], ], ], [ "StringListProperty", { "Name": "Inputs", "Category": "Command Line", "IsRequired": "true", "Switch": " ", }, [ "StringListProperty.DataSource", [ "DataSource", { "Persistence": "ProjectFile", "ItemType": rule.rule_name, "SourceType": "Item", }, ], ], ], [ "StringProperty", { "Name": "CommandLineTemplate", "DisplayName": "Command Line", "Visible": "False", "IncludeInCommandLine": "False", }, ], [ "DynamicEnumProperty", { "Name": rule.before_targets, "Category": "General", "EnumProvider": "Targets", "IncludeInCommandLine": "False", }, [ "DynamicEnumProperty.DisplayName", ["sys:String", "Execute Before"], ], [ "DynamicEnumProperty.Description", [ "sys:String", "Specifies the targets for the build customization" " to run before.", ], ], [ "DynamicEnumProperty.ProviderSettings", [ "NameValuePair", { "Name": "Exclude", "Value": "^%s|^Compute" % rule.before_targets, }, ], ], [ "DynamicEnumProperty.DataSource", [ "DataSource", { "Persistence": "ProjectFile", "HasConfigurationCondition": "true", }, ], ], ], [ "DynamicEnumProperty", { "Name": rule.after_targets, "Category": "General", "EnumProvider": "Targets", "IncludeInCommandLine": "False", }, [ "DynamicEnumProperty.DisplayName", ["sys:String", "Execute After"], ], [ "DynamicEnumProperty.Description", [ "sys:String", ( "Specifies the targets for the build customization" " to run after." ), ], ], [ "DynamicEnumProperty.ProviderSettings", [ "NameValuePair", { "Name": "Exclude", "Value": "^%s|^Compute" % rule.after_targets, }, ], ], [ "DynamicEnumProperty.DataSource", [ "DataSource", { "Persistence": "ProjectFile", "ItemType": "", "HasConfigurationCondition": "true", }, ], ], ], [ "StringListProperty", { "Name": "Outputs", "DisplayName": "Outputs", "Visible": "False", "IncludeInCommandLine": "False", }, ], [ "StringProperty", { "Name": "ExecutionDescription", "DisplayName": "Execution Description", "Visible": "False", "IncludeInCommandLine": "False", }, ], [ "StringListProperty", { "Name": "AdditionalDependencies", "DisplayName": "Additional Dependencies", "IncludeInCommandLine": "False", "Visible": "false", }, ], [ "StringProperty", { "Subtype": "AdditionalOptions", "Name": "AdditionalOptions", "Category": "Command Line", }, [ "StringProperty.DisplayName", ["sys:String", "Additional Options"], ], [ "StringProperty.Description", ["sys:String", "Additional Options"], ], ], ], [ "ItemType", {"Name": rule.rule_name, "DisplayName": rule.display_name}, ], [ "FileExtension", {"Name": "*" + rule.extension, "ContentType": rule.rule_name}, ], [ "ContentType", { "Name": rule.rule_name, "DisplayName": "", "ItemType": rule.rule_name, }, ], ] ) easy_xml.WriteXmlIfChanged(content, xml_path, pretty=True, win32=True) def _GetConfigurationAndPlatform(name, settings, spec): configuration = name.rsplit("_", 1)[0] platform = settings.get("msvs_configuration_platform", "Win32") if spec["toolset"] == "host" and platform == "arm64": platform = "x64" # Host-only tools are always built for x64 return (configuration, platform) def _GetConfigurationCondition(name, settings, spec): return r"'$(Configuration)|$(Platform)'=='%s|%s'" % _GetConfigurationAndPlatform( name, settings, spec ) def _GetMSBuildProjectConfigurations(configurations, spec): group = ["ItemGroup", {"Label": "ProjectConfigurations"}] for (name, settings) in sorted(configurations.items()): configuration, platform = _GetConfigurationAndPlatform(name, settings, spec) designation = f"{configuration}|{platform}" group.append( [ "ProjectConfiguration", {"Include": designation}, ["Configuration", configuration], ["Platform", platform], ] ) return [group] def _GetMSBuildGlobalProperties(spec, version, guid, gyp_file_name): namespace = os.path.splitext(gyp_file_name)[0] properties = [ [ "PropertyGroup", {"Label": "Globals"}, ["ProjectGuid", guid], ["Keyword", "Win32Proj"], ["RootNamespace", namespace], ["IgnoreWarnCompileDuplicatedFilename", "true"], ] ] if ( os.environ.get("PROCESSOR_ARCHITECTURE") == "AMD64" or os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64" ): properties[0].append(["PreferredToolArchitecture", "x64"]) if spec.get("msvs_target_platform_version"): target_platform_version = spec.get("msvs_target_platform_version") properties[0].append(["WindowsTargetPlatformVersion", target_platform_version]) if spec.get("msvs_target_platform_minversion"): target_platform_minversion = spec.get("msvs_target_platform_minversion") properties[0].append( ["WindowsTargetPlatformMinVersion", target_platform_minversion] ) else: properties[0].append( ["WindowsTargetPlatformMinVersion", target_platform_version] ) if spec.get("msvs_enable_winrt"): properties[0].append(["DefaultLanguage", "en-US"]) properties[0].append(["AppContainerApplication", "true"]) if spec.get("msvs_application_type_revision"): app_type_revision = spec.get("msvs_application_type_revision") properties[0].append(["ApplicationTypeRevision", app_type_revision]) else: properties[0].append(["ApplicationTypeRevision", "8.1"]) if spec.get("msvs_enable_winphone"): properties[0].append(["ApplicationType", "Windows Phone"]) else: properties[0].append(["ApplicationType", "Windows Store"]) platform_name = None msvs_windows_sdk_version = None for configuration in spec["configurations"].values(): platform_name = platform_name or _ConfigPlatform(configuration) msvs_windows_sdk_version = ( msvs_windows_sdk_version or _ConfigWindowsTargetPlatformVersion(configuration, version) ) if platform_name and msvs_windows_sdk_version: break if msvs_windows_sdk_version: properties[0].append( ["WindowsTargetPlatformVersion", str(msvs_windows_sdk_version)] ) elif version.compatible_sdks: raise GypError( "%s requires any SDK of %s version, but none were found" % (version.description, version.compatible_sdks) ) if platform_name == "ARM": properties[0].append(["WindowsSDKDesktopARMSupport", "true"]) return properties def _GetMSBuildConfigurationDetails(spec, build_file): properties = {} for name, settings in spec["configurations"].items(): msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file) condition = _GetConfigurationCondition(name, settings, spec) character_set = msbuild_attributes.get("CharacterSet") vctools_version = msbuild_attributes.get("VCToolsVersion") config_type = msbuild_attributes.get("ConfigurationType") _AddConditionalProperty(properties, condition, "ConfigurationType", config_type) spectre_mitigation = msbuild_attributes.get('SpectreMitigation') if spectre_mitigation: _AddConditionalProperty(properties, condition, "SpectreMitigation", spectre_mitigation) if config_type == "Driver": _AddConditionalProperty(properties, condition, "DriverType", "WDM") _AddConditionalProperty( properties, condition, "TargetVersion", _ConfigTargetVersion(settings) ) if character_set and "msvs_enable_winrt" not in spec: _AddConditionalProperty( properties, condition, "CharacterSet", character_set ) if vctools_version and "msvs_enable_winrt" not in spec: _AddConditionalProperty( properties, condition, "VCToolsVersion", vctools_version ) return _GetMSBuildPropertyGroup(spec, "Configuration", properties) def _GetMSBuildLocalProperties(msbuild_toolset): # Currently the only local property we support is PlatformToolset properties = {} if msbuild_toolset: properties = [ [ "PropertyGroup", {"Label": "Locals"}, ["PlatformToolset", msbuild_toolset], ] ] return properties def _GetMSBuildPropertySheets(configurations, spec): user_props = r"$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" additional_props = {} props_specified = False for name, settings in sorted(configurations.items()): configuration = _GetConfigurationCondition(name, settings, spec) if "msbuild_props" in settings: additional_props[configuration] = _FixPaths(settings["msbuild_props"]) props_specified = True else: additional_props[configuration] = "" if not props_specified: return [ [ "ImportGroup", {"Label": "PropertySheets"}, [ "Import", { "Project": user_props, "Condition": "exists('%s')" % user_props, "Label": "LocalAppDataPlatform", }, ], ] ] else: sheets = [] for condition, props in additional_props.items(): import_group = [ "ImportGroup", {"Label": "PropertySheets", "Condition": condition}, [ "Import", { "Project": user_props, "Condition": "exists('%s')" % user_props, "Label": "LocalAppDataPlatform", }, ], ] for props_file in props: import_group.append(["Import", {"Project": props_file}]) sheets.append(import_group) return sheets def _ConvertMSVSBuildAttributes(spec, config, build_file): config_type = _GetMSVSConfigurationType(spec, build_file) msvs_attributes = _GetMSVSAttributes(spec, config, config_type) msbuild_attributes = {} for a in msvs_attributes: if a in ["IntermediateDirectory", "OutputDirectory"]: directory = MSVSSettings.ConvertVCMacrosToMSBuild(msvs_attributes[a]) if not directory.endswith("\\"): directory += "\\" msbuild_attributes[a] = directory elif a == "CharacterSet": msbuild_attributes[a] = _ConvertMSVSCharacterSet(msvs_attributes[a]) elif a == "ConfigurationType": msbuild_attributes[a] = _ConvertMSVSConfigurationType(msvs_attributes[a]) elif a == "SpectreMitigation": msbuild_attributes[a] = msvs_attributes[a] elif a == "VCToolsVersion": msbuild_attributes[a] = msvs_attributes[a] else: print("Warning: Do not know how to convert MSVS attribute " + a) return msbuild_attributes def _ConvertMSVSCharacterSet(char_set): if char_set.isdigit(): char_set = {"0": "MultiByte", "1": "Unicode", "2": "MultiByte"}[char_set] return char_set def _ConvertMSVSConfigurationType(config_type): if config_type.isdigit(): config_type = { "1": "Application", "2": "DynamicLibrary", "4": "StaticLibrary", "5": "Driver", "10": "Utility", }[config_type] return config_type def _GetMSBuildAttributes(spec, config, build_file): if "msbuild_configuration_attributes" not in config: msbuild_attributes = _ConvertMSVSBuildAttributes(spec, config, build_file) else: config_type = _GetMSVSConfigurationType(spec, build_file) config_type = _ConvertMSVSConfigurationType(config_type) msbuild_attributes = config.get("msbuild_configuration_attributes", {}) msbuild_attributes.setdefault("ConfigurationType", config_type) output_dir = msbuild_attributes.get( "OutputDirectory", "$(SolutionDir)$(Configuration)" ) msbuild_attributes["OutputDirectory"] = _FixPath(output_dir) + "\\" if "IntermediateDirectory" not in msbuild_attributes: intermediate = _FixPath("$(Configuration)") + "\\" msbuild_attributes["IntermediateDirectory"] = intermediate if "CharacterSet" in msbuild_attributes: msbuild_attributes["CharacterSet"] = _ConvertMSVSCharacterSet( msbuild_attributes["CharacterSet"] ) if "TargetName" not in msbuild_attributes: prefix = spec.get("product_prefix", "") product_name = spec.get("product_name", "$(ProjectName)") target_name = prefix + product_name msbuild_attributes["TargetName"] = target_name if "TargetExt" not in msbuild_attributes and "product_extension" in spec: ext = spec.get("product_extension") msbuild_attributes["TargetExt"] = "." + ext if spec.get("msvs_external_builder"): external_out_dir = spec.get("msvs_external_builder_out_dir", ".") msbuild_attributes["OutputDirectory"] = _FixPath(external_out_dir) + "\\" # Make sure that 'TargetPath' matches 'Lib.OutputFile' or 'Link.OutputFile' # (depending on the tool used) to avoid MSB8012 warning. msbuild_tool_map = { "executable": "Link", "shared_library": "Link", "loadable_module": "Link", "windows_driver": "Link", "static_library": "Lib", } msbuild_tool = msbuild_tool_map.get(spec["type"]) if msbuild_tool: msbuild_settings = config["finalized_msbuild_settings"] out_file = msbuild_settings[msbuild_tool].get("OutputFile") if out_file: msbuild_attributes["TargetPath"] = _FixPath(out_file) target_ext = msbuild_settings[msbuild_tool].get("TargetExt") if target_ext: msbuild_attributes["TargetExt"] = target_ext return msbuild_attributes def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): # TODO(jeanluc) We could optimize out the following and do it only if # there are actions. # TODO(jeanluc) Handle the equivalent of setting 'CYGWIN=nontsec'. new_paths = [] cygwin_dirs = spec.get("msvs_cygwin_dirs", ["."])[0] if cygwin_dirs: cyg_path = "$(MSBuildProjectDirectory)\\%s\\bin\\" % _FixPath(cygwin_dirs) new_paths.append(cyg_path) # TODO(jeanluc) Change the convention to have both a cygwin_dir and a # python_dir. python_path = cyg_path.replace("cygwin\\bin", "python_26") new_paths.append(python_path) if new_paths: new_paths = "$(ExecutablePath);" + ";".join(new_paths) properties = {} for (name, configuration) in sorted(configurations.items()): condition = _GetConfigurationCondition(name, configuration, spec) attributes = _GetMSBuildAttributes(spec, configuration, build_file) msbuild_settings = configuration["finalized_msbuild_settings"] _AddConditionalProperty( properties, condition, "IntDir", attributes["IntermediateDirectory"] ) _AddConditionalProperty( properties, condition, "OutDir", attributes["OutputDirectory"] ) _AddConditionalProperty( properties, condition, "TargetName", attributes["TargetName"] ) if "TargetExt" in attributes: _AddConditionalProperty( properties, condition, "TargetExt", attributes["TargetExt"] ) if attributes.get("TargetPath"): _AddConditionalProperty( properties, condition, "TargetPath", attributes["TargetPath"] ) if attributes.get("TargetExt"): _AddConditionalProperty( properties, condition, "TargetExt", attributes["TargetExt"] ) if new_paths: _AddConditionalProperty(properties, condition, "ExecutablePath", new_paths) tool_settings = msbuild_settings.get("", {}) for name, value in sorted(tool_settings.items()): formatted_value = _GetValueFormattedForMSBuild("", name, value) _AddConditionalProperty(properties, condition, name, formatted_value) return _GetMSBuildPropertyGroup(spec, None, properties) def _AddConditionalProperty(properties, condition, name, value): """Adds a property / conditional value pair to a dictionary. Arguments: properties: The dictionary to be modified. The key is the name of the property. The value is itself a dictionary; its key is the value and the value a list of condition for which this value is true. condition: The condition under which the named property has the value. name: The name of the property. value: The value of the property. """ if name not in properties: properties[name] = {} values = properties[name] if value not in values: values[value] = [] conditions = values[value] conditions.append(condition) # Regex for msvs variable references ( i.e. $(FOO) ). MSVS_VARIABLE_REFERENCE = re.compile(r"\$\(([a-zA-Z_][a-zA-Z0-9_]*)\)") def _GetMSBuildPropertyGroup(spec, label, properties): """Returns a PropertyGroup definition for the specified properties. Arguments: spec: The target project dict. label: An optional label for the PropertyGroup. properties: The dictionary to be converted. The key is the name of the property. The value is itself a dictionary; its key is the value and the value a list of condition for which this value is true. """ group = ["PropertyGroup"] if label: group.append({"Label": label}) num_configurations = len(spec["configurations"]) def GetEdges(node): # Use a definition of edges such that user_of_variable -> used_varible. # This happens to be easier in this case, since a variable's # definition contains all variables it references in a single string. edges = set() for value in sorted(properties[node].keys()): # Add to edges all $(...) references to variables. # # Variable references that refer to names not in properties are excluded # These can exist for instance to refer built in definitions like # $(SolutionDir). # # Self references are ignored. Self reference is used in a few places to # append to the default value. I.e. PATH=$(PATH);other_path edges.update( { v for v in MSVS_VARIABLE_REFERENCE.findall(value) if v in properties and v != node } ) return edges properties_ordered = gyp.common.TopologicallySorted(properties.keys(), GetEdges) # Walk properties in the reverse of a topological sort on # user_of_variable -> used_variable as this ensures variables are # defined before they are used. # NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) for name in reversed(properties_ordered): values = properties[name] for value, conditions in sorted(values.items()): if len(conditions) == num_configurations: # If the value is the same all configurations, # just add one unconditional entry. group.append([name, value]) else: for condition in conditions: group.append([name, {"Condition": condition}, value]) return [group] def _GetMSBuildToolSettingsSections(spec, configurations): groups = [] for (name, configuration) in sorted(configurations.items()): msbuild_settings = configuration["finalized_msbuild_settings"] group = [ "ItemDefinitionGroup", {"Condition": _GetConfigurationCondition(name, configuration, spec)}, ] for tool_name, tool_settings in sorted(msbuild_settings.items()): # Skip the tool named '' which is a holder of global settings handled # by _GetMSBuildConfigurationGlobalProperties. if tool_name and tool_settings: tool = [tool_name] for name, value in sorted(tool_settings.items()): formatted_value = _GetValueFormattedForMSBuild( tool_name, name, value ) tool.append([name, formatted_value]) group.append(tool) groups.append(group) return groups def _FinalizeMSBuildSettings(spec, configuration): if "msbuild_settings" in configuration: converted = False msbuild_settings = configuration["msbuild_settings"] MSVSSettings.ValidateMSBuildSettings(msbuild_settings) else: converted = True msvs_settings = configuration.get("msvs_settings", {}) msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(msvs_settings) include_dirs, midl_include_dirs, resource_include_dirs = _GetIncludeDirs( configuration ) libraries = _GetLibraries(spec) library_dirs = _GetLibraryDirs(configuration) out_file, _, msbuild_tool = _GetOutputFilePathAndTool(spec, msbuild=True) target_ext = _GetOutputTargetExt(spec) defines = _GetDefines(configuration) if converted: # Visual Studio 2010 has TR1 defines = [d for d in defines if d != "_HAS_TR1=0"] # Warn of ignored settings ignored_settings = ["msvs_tool_files"] for ignored_setting in ignored_settings: value = configuration.get(ignored_setting) if value: print( "Warning: The automatic conversion to MSBuild does not handle " "%s. Ignoring setting of %s" % (ignored_setting, str(value)) ) defines = [_EscapeCppDefineForMSBuild(d) for d in defines] disabled_warnings = _GetDisabledWarnings(configuration) prebuild = configuration.get("msvs_prebuild") postbuild = configuration.get("msvs_postbuild") def_file = _GetModuleDefinition(spec) precompiled_header = configuration.get("msvs_precompiled_header") # Add the information to the appropriate tool # TODO(jeanluc) We could optimize and generate these settings only if # the corresponding files are found, e.g. don't generate ResourceCompile # if you don't have any resources. _ToolAppend( msbuild_settings, "ClCompile", "AdditionalIncludeDirectories", include_dirs ) _ToolAppend( msbuild_settings, "Midl", "AdditionalIncludeDirectories", midl_include_dirs ) _ToolAppend( msbuild_settings, "ResourceCompile", "AdditionalIncludeDirectories", resource_include_dirs, ) # Add in libraries, note that even for empty libraries, we want this # set, to prevent inheriting default libraries from the environment. _ToolSetOrAppend(msbuild_settings, "Link", "AdditionalDependencies", libraries) _ToolAppend(msbuild_settings, "Link", "AdditionalLibraryDirectories", library_dirs) if out_file: _ToolAppend( msbuild_settings, msbuild_tool, "OutputFile", out_file, only_if_unset=True ) if target_ext: _ToolAppend( msbuild_settings, msbuild_tool, "TargetExt", target_ext, only_if_unset=True ) # Add defines. _ToolAppend(msbuild_settings, "ClCompile", "PreprocessorDefinitions", defines) _ToolAppend(msbuild_settings, "ResourceCompile", "PreprocessorDefinitions", defines) # Add disabled warnings. _ToolAppend( msbuild_settings, "ClCompile", "DisableSpecificWarnings", disabled_warnings ) # Turn on precompiled headers if appropriate. if precompiled_header: precompiled_header = os.path.split(precompiled_header)[1] _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "Use") _ToolAppend( msbuild_settings, "ClCompile", "PrecompiledHeaderFile", precompiled_header ) _ToolAppend( msbuild_settings, "ClCompile", "ForcedIncludeFiles", [precompiled_header] ) else: _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "NotUsing") # Turn off WinRT compilation _ToolAppend(msbuild_settings, "ClCompile", "CompileAsWinRT", "false") # Turn on import libraries if appropriate if spec.get("msvs_requires_importlibrary"): _ToolAppend(msbuild_settings, "", "IgnoreImportLibrary", "false") # Loadable modules don't generate import libraries; # tell dependent projects to not expect one. if spec["type"] == "loadable_module": _ToolAppend(msbuild_settings, "", "IgnoreImportLibrary", "true") # Set the module definition file if any. if def_file: _ToolAppend(msbuild_settings, "Link", "ModuleDefinitionFile", def_file) configuration["finalized_msbuild_settings"] = msbuild_settings if prebuild: _ToolAppend(msbuild_settings, "PreBuildEvent", "Command", prebuild) if postbuild: _ToolAppend(msbuild_settings, "PostBuildEvent", "Command", postbuild) def _GetValueFormattedForMSBuild(tool_name, name, value): if type(value) == list: # For some settings, VS2010 does not automatically extends the settings # TODO(jeanluc) Is this what we want? if name in [ "AdditionalIncludeDirectories", "AdditionalLibraryDirectories", "AdditionalOptions", "DelayLoadDLLs", "DisableSpecificWarnings", "PreprocessorDefinitions", ]: value.append("%%(%s)" % name) # For most tools, entries in a list should be separated with ';' but some # settings use a space. Check for those first. exceptions = { "ClCompile": ["AdditionalOptions"], "Link": ["AdditionalOptions"], "Lib": ["AdditionalOptions"], } char = " " if name in exceptions.get(tool_name, []) else ";" formatted_value = char.join( [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in value] ) else: formatted_value = MSVSSettings.ConvertVCMacrosToMSBuild(value) return formatted_value def _VerifySourcesExist(sources, root_dir): """Verifies that all source files exist on disk. Checks that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation but no otherwise visible errors. Arguments: sources: A recursive list of Filter/file names. root_dir: The root directory for the relative path names. Returns: A list of source files that cannot be found on disk. """ missing_sources = [] for source in sources: if isinstance(source, MSVSProject.Filter): missing_sources.extend(_VerifySourcesExist(source.contents, root_dir)) else: if "$" not in source: full_path = os.path.join(root_dir, source) if not os.path.exists(full_path): missing_sources.append(full_path) return missing_sources def _GetMSBuildSources( spec, sources, exclusions, rule_dependencies, extension_to_rule_name, actions_spec, sources_handled_by_action, list_excluded, ): groups = [ "none", "masm", "midl", "include", "compile", "resource", "rule", "rule_dependency", ] grouped_sources = {} for g in groups: grouped_sources[g] = [] _AddSources2( spec, sources, exclusions, grouped_sources, rule_dependencies, extension_to_rule_name, sources_handled_by_action, list_excluded, ) sources = [] for g in groups: if grouped_sources[g]: sources.append(["ItemGroup"] + grouped_sources[g]) if actions_spec: sources.append(["ItemGroup"] + actions_spec) return sources def _AddSources2( spec, sources, exclusions, grouped_sources, rule_dependencies, extension_to_rule_name, sources_handled_by_action, list_excluded, ): extensions_excluded_from_precompile = [] for source in sources: if isinstance(source, MSVSProject.Filter): _AddSources2( spec, source.contents, exclusions, grouped_sources, rule_dependencies, extension_to_rule_name, sources_handled_by_action, list_excluded, ) else: if source not in sources_handled_by_action: detail = [] excluded_configurations = exclusions.get(source, []) if len(excluded_configurations) == len(spec["configurations"]): detail.append(["ExcludedFromBuild", "true"]) else: for config_name, configuration in sorted(excluded_configurations): condition = _GetConfigurationCondition( config_name, configuration ) detail.append( ["ExcludedFromBuild", {"Condition": condition}, "true"] ) # Add precompile if needed for config_name, configuration in spec["configurations"].items(): precompiled_source = configuration.get( "msvs_precompiled_source", "" ) if precompiled_source != "": precompiled_source = _FixPath(precompiled_source) if not extensions_excluded_from_precompile: # If the precompiled header is generated by a C source, # we must not try to use it for C++ sources, # and vice versa. basename, extension = os.path.splitext(precompiled_source) if extension == ".c": extensions_excluded_from_precompile = [ ".cc", ".cpp", ".cxx", ] else: extensions_excluded_from_precompile = [".c"] if precompiled_source == source: condition = _GetConfigurationCondition( config_name, configuration, spec ) detail.append( ["PrecompiledHeader", {"Condition": condition}, "Create"] ) else: # Turn off precompiled header usage for source files of a # different type than the file that generated the # precompiled header. for extension in extensions_excluded_from_precompile: if source.endswith(extension): detail.append(["PrecompiledHeader", ""]) detail.append(["ForcedIncludeFiles", ""]) group, element = _MapFileToMsBuildSourceType( source, rule_dependencies, extension_to_rule_name, _GetUniquePlatforms(spec), spec["toolset"], ) if group == "compile" and not os.path.isabs(source): # Add an value to support duplicate source # file basenames, except for absolute paths to avoid paths # with more than 260 characters. file_name = os.path.splitext(source)[0] + ".obj" if file_name.startswith("..\\"): file_name = re.sub(r"^(\.\.\\)+", "", file_name) elif file_name.startswith("$("): file_name = re.sub(r"^\$\([^)]+\)\\", "", file_name) detail.append(["ObjectFileName", "$(IntDir)\\" + file_name]) grouped_sources[group].append([element, {"Include": source}] + detail) def _GetMSBuildProjectReferences(project): references = [] if project.dependencies: group = ["ItemGroup"] added_dependency_set = set() for dependency in project.dependencies: dependency_spec = dependency.spec should_skip_dep = False if project.spec["toolset"] == "target": if dependency_spec["toolset"] == "host": if dependency_spec["type"] == "static_library": should_skip_dep = True if dependency.name.startswith("run_"): should_skip_dep = False if should_skip_dep: continue canonical_name = dependency.name.replace("_host", "") added_dependency_set.add(canonical_name) guid = dependency.guid project_dir = os.path.split(project.path)[0] relative_path = gyp.common.RelativePath(dependency.path, project_dir) project_ref = [ "ProjectReference", {"Include": relative_path}, ["Project", guid], ["ReferenceOutputAssembly", "false"], ] for config in dependency.spec.get("configurations", {}).values(): if config.get("msvs_use_library_dependency_inputs", 0): project_ref.append(["UseLibraryDependencyInputs", "true"]) break # If it's disabled in any config, turn it off in the reference. if config.get("msvs_2010_disable_uldi_when_referenced", 0): project_ref.append(["UseLibraryDependencyInputs", "false"]) break group.append(project_ref) references.append(group) return references def _GenerateMSBuildProject(project, options, version, generator_flags, spec): spec = project.spec configurations = spec["configurations"] toolset = spec["toolset"] project_dir, project_file_name = os.path.split(project.path) gyp.common.EnsureDirExists(project.path) # Prepare list of sources and excluded sources. gyp_file = os.path.split(project.build_file)[1] sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, gyp_file) # Add rules. actions_to_add = {} props_files_of_rules = set() targets_files_of_rules = set() rule_dependencies = set() extension_to_rule_name = {} list_excluded = generator_flags.get("msvs_list_excluded_files", True) platforms = _GetUniquePlatforms(spec) # Don't generate rules if we are using an external builder like ninja. if not spec.get("msvs_external_builder"): _GenerateRulesForMSBuild( project_dir, options, spec, sources, excluded_sources, props_files_of_rules, targets_files_of_rules, actions_to_add, rule_dependencies, extension_to_rule_name, ) else: rules = spec.get("rules", []) _AdjustSourcesForRules(rules, sources, excluded_sources, True) sources, excluded_sources, excluded_idl = _AdjustSourcesAndConvertToFilterHierarchy( spec, options, project_dir, sources, excluded_sources, list_excluded, version ) # Don't add actions if we are using an external builder like ninja. if not spec.get("msvs_external_builder"): _AddActions(actions_to_add, spec, project.build_file) _AddCopies(actions_to_add, spec) # NOTE: this stanza must appear after all actions have been decided. # Don't excluded sources with actions attached, or they won't run. excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add) exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl) actions_spec, sources_handled_by_action = _GenerateActionsForMSBuild( spec, actions_to_add ) _GenerateMSBuildFiltersFile( project.path + ".filters", sources, rule_dependencies, extension_to_rule_name, platforms, toolset, ) missing_sources = _VerifySourcesExist(sources, project_dir) for configuration in configurations.values(): _FinalizeMSBuildSettings(spec, configuration) # Add attributes to root element import_default_section = [ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.Default.props"}] ] import_cpp_props_section = [ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.props"}] ] import_cpp_targets_section = [ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.targets"}] ] import_masm_props_section = [ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\masm.props"}] ] import_masm_targets_section = [ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\masm.targets"}] ] import_marmasm_props_section = [ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\marmasm.props"}] ] import_marmasm_targets_section = [ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\marmasm.targets"}] ] macro_section = [["PropertyGroup", {"Label": "UserMacros"}]] content = [ "Project", { "xmlns": "http://schemas.microsoft.com/developer/msbuild/2003", "ToolsVersion": version.ProjectVersion(), "DefaultTargets": "Build", }, ] content += _GetMSBuildProjectConfigurations(configurations, spec) content += _GetMSBuildGlobalProperties( spec, version, project.guid, project_file_name ) content += import_default_section content += _GetMSBuildConfigurationDetails(spec, project.build_file) if spec.get("msvs_enable_winphone"): content += _GetMSBuildLocalProperties("v120_wp81") else: content += _GetMSBuildLocalProperties(project.msbuild_toolset) content += import_cpp_props_section content += import_masm_props_section if "arm64" in platforms and toolset == "target": content += import_marmasm_props_section content += _GetMSBuildExtensions(props_files_of_rules) content += _GetMSBuildPropertySheets(configurations, spec) content += macro_section content += _GetMSBuildConfigurationGlobalProperties( spec, configurations, project.build_file ) content += _GetMSBuildToolSettingsSections(spec, configurations) content += _GetMSBuildSources( spec, sources, exclusions, rule_dependencies, extension_to_rule_name, actions_spec, sources_handled_by_action, list_excluded, ) content += _GetMSBuildProjectReferences(project) content += import_cpp_targets_section content += import_masm_targets_section if "arm64" in platforms and toolset == "target": content += import_marmasm_targets_section content += _GetMSBuildExtensionTargets(targets_files_of_rules) if spec.get("msvs_external_builder"): content += _GetMSBuildExternalBuilderTargets(spec) # TODO(jeanluc) File a bug to get rid of runas. We had in MSVS: # has_run_as = _WriteMSVSUserFile(project.path, version, spec) easy_xml.WriteXmlIfChanged(content, project.path, pretty=True, win32=True) return missing_sources def _GetMSBuildExternalBuilderTargets(spec): """Return a list of MSBuild targets for external builders. The "Build" and "Clean" targets are always generated. If the spec contains 'msvs_external_builder_clcompile_cmd', then the "ClCompile" target will also be generated, to support building selected C/C++ files. Arguments: spec: The gyp target spec. Returns: List of MSBuild 'Target' specs. """ build_cmd = _BuildCommandLineForRuleRaw( spec, spec["msvs_external_builder_build_cmd"], False, False, False, False ) build_target = ["Target", {"Name": "Build"}] build_target.append(["Exec", {"Command": build_cmd}]) clean_cmd = _BuildCommandLineForRuleRaw( spec, spec["msvs_external_builder_clean_cmd"], False, False, False, False ) clean_target = ["Target", {"Name": "Clean"}] clean_target.append(["Exec", {"Command": clean_cmd}]) targets = [build_target, clean_target] if spec.get("msvs_external_builder_clcompile_cmd"): clcompile_cmd = _BuildCommandLineForRuleRaw( spec, spec["msvs_external_builder_clcompile_cmd"], False, False, False, False, ) clcompile_target = ["Target", {"Name": "ClCompile"}] clcompile_target.append(["Exec", {"Command": clcompile_cmd}]) targets.append(clcompile_target) return targets def _GetMSBuildExtensions(props_files_of_rules): extensions = ["ImportGroup", {"Label": "ExtensionSettings"}] for props_file in props_files_of_rules: extensions.append(["Import", {"Project": props_file}]) return [extensions] def _GetMSBuildExtensionTargets(targets_files_of_rules): targets_node = ["ImportGroup", {"Label": "ExtensionTargets"}] for targets_file in sorted(targets_files_of_rules): targets_node.append(["Import", {"Project": targets_file}]) return [targets_node] def _GenerateActionsForMSBuild(spec, actions_to_add): """Add actions accumulated into an actions_to_add, merging as needed. Arguments: spec: the target project dict actions_to_add: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. Returns: A pair of (action specification, the sources handled by this action). """ sources_handled_by_action = OrderedSet() actions_spec = [] for primary_input, actions in actions_to_add.items(): if generator_supports_multiple_toolsets: primary_input = primary_input.replace(".exe", "_host.exe") inputs = OrderedSet() outputs = OrderedSet() descriptions = [] commands = [] for action in actions: def fixup_host_exe(i): if "$(OutDir)" in i: i = i.replace(".exe", "_host.exe") return i if generator_supports_multiple_toolsets: action["inputs"] = [fixup_host_exe(i) for i in action["inputs"]] inputs.update(OrderedSet(action["inputs"])) outputs.update(OrderedSet(action["outputs"])) descriptions.append(action["description"]) cmd = action["command"] if generator_supports_multiple_toolsets: cmd = cmd.replace(".exe", "_host.exe") # For most actions, add 'call' so that actions that invoke batch files # return and continue executing. msbuild_use_call provides a way to # disable this but I have not seen any adverse effect from doing that # for everything. if action.get("msbuild_use_call", True): cmd = "call " + cmd commands.append(cmd) # Add the custom build action for one input file. description = ", and also ".join(descriptions) # We can't join the commands simply with && because the command line will # get too long. See also _AddActions: cygwin's setup_env mustn't be called # for every invocation or the command that sets the PATH will grow too # long. command = "\r\n".join( [c + "\r\nif %errorlevel% neq 0 exit /b %errorlevel%" for c in commands] ) _AddMSBuildAction( spec, primary_input, inputs, outputs, command, description, sources_handled_by_action, actions_spec, ) return actions_spec, sources_handled_by_action def _AddMSBuildAction( spec, primary_input, inputs, outputs, cmd, description, sources_handled_by_action, actions_spec, ): command = MSVSSettings.ConvertVCMacrosToMSBuild(cmd) primary_input = _FixPath(primary_input) inputs_array = _FixPaths(inputs) outputs_array = _FixPaths(outputs) additional_inputs = ";".join([i for i in inputs_array if i != primary_input]) outputs = ";".join(outputs_array) sources_handled_by_action.add(primary_input) action_spec = ["CustomBuild", {"Include": primary_input}] action_spec.extend( # TODO(jeanluc) 'Document' for all or just if as_sources? [ ["FileType", "Document"], ["Command", command], ["Message", description], ["Outputs", outputs], ] ) if additional_inputs: action_spec.append(["AdditionalInputs", additional_inputs]) actions_spec.append(action_spec) #!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Unit tests for the msvs.py file. """ import gyp.generator.msvs as msvs import unittest from io import StringIO class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.stderr = StringIO() def test_GetLibraries(self): self.assertEqual(msvs._GetLibraries({}), []) self.assertEqual(msvs._GetLibraries({"libraries": []}), []) self.assertEqual( msvs._GetLibraries({"other": "foo", "libraries": ["a.lib"]}), ["a.lib"] ) self.assertEqual(msvs._GetLibraries({"libraries": ["-la"]}), ["a.lib"]) self.assertEqual( msvs._GetLibraries( { "libraries": [ "a.lib", "b.lib", "c.lib", "-lb.lib", "-lb.lib", "d.lib", "a.lib", ] } ), ["c.lib", "b.lib", "d.lib", "a.lib"], ) if __name__ == "__main__": unittest.main() # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import copy import hashlib import json import multiprocessing import os.path import re import signal import shutil import subprocess import sys import gyp import gyp.common import gyp.msvs_emulation import gyp.MSVSUtil as MSVSUtil import gyp.xcode_emulation from io import StringIO from gyp.common import GetEnvironFallback import gyp.ninja_syntax as ninja_syntax generator_default_variables = { "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "STATIC_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", "SHARED_LIB_PREFIX": "lib", # Gyp expects the following variables to be expandable by the build # system to the appropriate locations. Ninja prefers paths to be # known at gyp time. To resolve this, introduce special # variables starting with $! and $| (which begin with a $ so gyp knows it # should be treated specially, but is otherwise an invalid # ninja/shell variable) that are passed to gyp here but expanded # before writing out into the target .ninja files; see # ExpandSpecial. # $! is used for variables that represent a path and that can only appear at # the start of a string, while $| is used for variables that can appear # anywhere in a string. "INTERMEDIATE_DIR": "$!INTERMEDIATE_DIR", "SHARED_INTERMEDIATE_DIR": "$!PRODUCT_DIR/gen", "PRODUCT_DIR": "$!PRODUCT_DIR", "CONFIGURATION_NAME": "$|CONFIGURATION_NAME", # Special variables that may be used by gyp 'rule' targets. # We generate definitions for these variables on the fly when processing a # rule. "RULE_INPUT_ROOT": "${root}", "RULE_INPUT_DIRNAME": "${dirname}", "RULE_INPUT_PATH": "${source}", "RULE_INPUT_EXT": "${ext}", "RULE_INPUT_NAME": "${name}", } # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() def StripPrefix(arg, prefix): if arg.startswith(prefix): return arg[len(prefix) :] return arg def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # allow common OK ones and quote anything else. if re.match(r"^[a-zA-Z0-9_=.\\/-]+$", arg): return arg # No quoting necessary. if flavor == "win": return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'" def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == "win": # cl.exe replaces literal # characters with = in preprocessor definitions for # some reason. Octal-encode to work around that. d = d.replace("#", "\\%03o" % ord("#")) return QuoteShellArgument(ninja_syntax.escape("-D" + d), flavor) def AddArch(output, arch): """Adds an arch string to an output path.""" output, extension = os.path.splitext(output) return f"{output}.{arch}{extension}" class Target: """Target represents the paths used within a single gyp target. Conceptually, building a single target A is a series of steps: 1) actions/rules/copies generates source/resources/etc. 2) compiles generates .o files 3) link generates a binary (library/executable) 4) bundle merges the above in a mac bundle (Any of these steps can be optional.) From a build ordering perspective, a dependent target B could just depend on the last output of this series of steps. But some dependent commands sometimes need to reach inside the box. For example, when linking B it needs to get the path to the static library generated by A. This object stores those paths. To keep things simple, member variables only store concrete paths to single files, while methods compute derived values like "the last output of the target". """ def __init__(self, type): # Gyp type ("static_library", etc.) of this target. self.type = type # File representing whether any input dependencies necessary for # dependent actions have completed. self.preaction_stamp = None # File representing whether any input dependencies necessary for # dependent compiles have completed. self.precompile_stamp = None # File representing the completion of actions/rules/copies, if any. self.actions_stamp = None # Path to the output of the link step, if any. self.binary = None # Path to the file representing the completion of building the bundle, # if any. self.bundle = None # On Windows, incremental linking requires linking against all the .objs # that compose a .lib (rather than the .lib itself). That list is stored # here. In this case, we also need to save the compile_deps for the target, # so that the target that directly depends on the .objs can also depend # on those. self.component_objs = None self.compile_deps = None # Windows only. The import .lib is the output of a build step, but # because dependents only link against the lib (not both the lib and the # dll) we keep track of the import library here. self.import_lib = None # Track if this target contains any C++ files, to decide if gcc or g++ # should be used for linking. self.uses_cpp = False def Linkable(self): """Return true if this is a target that can be linked against.""" return self.type in ("static_library", "shared_library") def UsesToc(self, flavor): """Return true if the target should produce a restat rule based on a TOC file.""" # For bundles, the .TOC should be produced for the binary, not for # FinalOutput(). But the naive approach would put the TOC file into the # bundle, so don't do this for bundles for now. if flavor == "win" or self.bundle: return False return self.type in ("shared_library", "loadable_module") def PreActionInput(self, flavor): """Return the path, if any, that should be used as a dependency of any dependent action step.""" if self.UsesToc(flavor): return self.FinalOutput() + ".TOC" return self.FinalOutput() or self.preaction_stamp def PreCompileInput(self): """Return the path, if any, that should be used as a dependency of any dependent compile step.""" return self.actions_stamp or self.precompile_stamp def FinalOutput(self): """Return the last output of the target, which depends on all prior steps.""" return self.bundle or self.binary or self.actions_stamp # A small discourse on paths as used within the Ninja build: # All files we produce (both at gyp and at build time) appear in the # build directory (e.g. out/Debug). # # Paths within a given .gyp file are always relative to the directory # containing the .gyp file. Call these "gyp paths". This includes # sources as well as the starting directory a given gyp rule/action # expects to be run from. We call the path from the source root to # the gyp file the "base directory" within the per-.gyp-file # NinjaWriter code. # # All paths as written into the .ninja files are relative to the build # directory. Call these paths "ninja paths". # # We translate between these two notions of paths with two helper # functions: # # - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file) # into the equivalent ninja path. # # - GypPathToUniqueOutput translates a gyp path into a ninja path to write # an output file; the result can be namespaced such that it is unique # to the input file name as well as the output target name. class NinjaWriter: def __init__( self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, toplevel_dir=None, ): """ base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory """ self.hash_for_rules = hash_for_rules self.target_outputs = target_outputs self.base_dir = base_dir self.build_dir = build_dir self.ninja = ninja_syntax.Writer(output_file) self.toplevel_build = toplevel_build self.output_file_name = output_file_name self.flavor = flavor self.abs_build_dir = None if toplevel_dir is not None: self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir)) self.obj_ext = ".obj" if flavor == "win" else ".o" if flavor == "win": # See docstring of msvs_emulation.GenerateEnvironmentFiles(). self.win_env = {} for arch in ("x86", "x64"): self.win_env[arch] = "environment." + arch # Relative path from build output dir to base dir. build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir) self.build_to_base = os.path.join(build_to_top, base_dir) # Relative path from base dir to build dir. base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir) self.base_to_build = os.path.join(base_to_top, build_dir) def ExpandSpecial(self, path, product_dir=None): """Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir. """ PRODUCT_DIR = "$!PRODUCT_DIR" if PRODUCT_DIR in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: path = path.replace(PRODUCT_DIR + "/", "") path = path.replace(PRODUCT_DIR + "\\", "") path = path.replace(PRODUCT_DIR, ".") INTERMEDIATE_DIR = "$!INTERMEDIATE_DIR" if INTERMEDIATE_DIR in path: int_dir = self.GypPathToUniqueOutput("gen") # GypPathToUniqueOutput generates a path relative to the product dir, # so insert product_dir in front if it is provided. path = path.replace( INTERMEDIATE_DIR, os.path.join(product_dir or "", int_dir) ) CONFIGURATION_NAME = "$|CONFIGURATION_NAME" path = path.replace(CONFIGURATION_NAME, self.config_name) return path def ExpandRuleVariables(self, path, root, dirname, source, ext, name): if self.flavor == "win": path = self.msvs_settings.ConvertVSMacros(path, config=self.config_name) path = path.replace(generator_default_variables["RULE_INPUT_ROOT"], root) path = path.replace(generator_default_variables["RULE_INPUT_DIRNAME"], dirname) path = path.replace(generator_default_variables["RULE_INPUT_PATH"], source) path = path.replace(generator_default_variables["RULE_INPUT_EXT"], ext) path = path.replace(generator_default_variables["RULE_INPUT_NAME"], name) return path def GypPathToNinja(self, path, env=None): """Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|. See the above discourse on path conversions.""" if env: if self.flavor == "mac": path = gyp.xcode_emulation.ExpandEnvVars(path, env) elif self.flavor == "win": path = gyp.msvs_emulation.ExpandMacros(path, env) if path.startswith("$!"): expanded = self.ExpandSpecial(path) if self.flavor == "win": expanded = os.path.normpath(expanded) return expanded if "$|" in path: path = self.ExpandSpecial(path) assert "$" not in path, path return os.path.normpath(os.path.join(self.build_to_base, path)) def GypPathToUniqueOutput(self, path, qualified=True): """Translate a gyp path to a ninja path for writing output. If qualified is True, qualify the resulting filename with the name of the target. This is necessary when e.g. compiling the same path twice for two separate output targets. See the above discourse on path conversions.""" path = self.ExpandSpecial(path) assert not path.startswith("$"), path # Translate the path following this scheme: # Input: foo/bar.gyp, target targ, references baz/out.o # Output: obj/foo/baz/targ.out.o (if qualified) # obj/foo/baz/out.o (otherwise) # (and obj.host instead of obj for cross-compiles) # # Why this scheme and not some other one? # 1) for a given input, you can compute all derived outputs by matching # its path, even if the input is brought via a gyp file with '..'. # 2) simple files like libraries and stamps have a simple filename. obj = "obj" if self.toolset != "target": obj += "." + self.toolset path_dir, path_basename = os.path.split(path) assert not os.path.isabs(path_dir), ( "'%s' can not be absolute path (see crbug.com/462153)." % path_dir ) if qualified: path_basename = self.name + "." + path_basename return os.path.normpath( os.path.join(obj, self.base_dir, path_dir, path_basename) ) def WriteCollapsedDependencies(self, name, targets, order_only=None): """Given a list of targets, return a path for a single file representing the result of building all the targets or None. Uses a stamp file if necessary.""" assert targets == [item for item in targets if item], targets if len(targets) == 0: assert not order_only return None if len(targets) > 1 or order_only: stamp = self.GypPathToUniqueOutput(name + ".stamp") targets = self.ninja.build(stamp, "stamp", targets, order_only=order_only) self.ninja.newline() return targets[0] def _SubninjaNameForArch(self, arch): output_file_base = os.path.splitext(self.output_file_name)[0] return f"{output_file_base}.{arch}.ninja" def WriteSpec(self, spec, config_name, generator_flags): """The main entry point for NinjaWriter: write the build rules for a spec. Returns a Target object, which represents the output paths for this spec. Returns None if there are no outputs (e.g. a settings-only 'none' type target).""" self.config_name = config_name self.name = spec["target_name"] self.toolset = spec["toolset"] config = spec["configurations"][config_name] self.target = Target(spec["type"]) self.is_standalone_static_library = bool( spec.get("standalone_static_library", 0) ) self.target_rpath = generator_flags.get("target_rpath", r"\$$ORIGIN/lib/") self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) self.xcode_settings = self.msvs_settings = None if self.flavor == "mac": self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None) if mac_toolchain_dir: self.xcode_settings.mac_toolchain_dir = mac_toolchain_dir if self.flavor == "win": self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags) arch = self.msvs_settings.GetArch(config_name) self.ninja.variable("arch", self.win_env[arch]) self.ninja.variable("cc", "$cl_" + arch) self.ninja.variable("cxx", "$cl_" + arch) self.ninja.variable("cc_host", "$cl_" + arch) self.ninja.variable("cxx_host", "$cl_" + arch) self.ninja.variable("asm", "$ml_" + arch) if self.flavor == "mac": self.archs = self.xcode_settings.GetActiveArchs(config_name) if len(self.archs) > 1: self.arch_subninjas = { arch: ninja_syntax.Writer( OpenOutput( os.path.join( self.toplevel_build, self._SubninjaNameForArch(arch) ), "w", ) ) for arch in self.archs } # Compute predepends for all rules. # actions_depends is the dependencies this target depends on before running # any of its action/rule/copy steps. # compile_depends is the dependencies this target depends on before running # any of its compile steps. actions_depends = [] compile_depends = [] # TODO(evan): it is rather confusing which things are lists and which # are strings. Fix these. if "dependencies" in spec: for dep in spec["dependencies"]: if dep in self.target_outputs: target = self.target_outputs[dep] actions_depends.append(target.PreActionInput(self.flavor)) compile_depends.append(target.PreCompileInput()) if target.uses_cpp: self.target.uses_cpp = True actions_depends = [item for item in actions_depends if item] compile_depends = [item for item in compile_depends if item] actions_depends = self.WriteCollapsedDependencies( "actions_depends", actions_depends ) compile_depends = self.WriteCollapsedDependencies( "compile_depends", compile_depends ) self.target.preaction_stamp = actions_depends self.target.precompile_stamp = compile_depends # Write out actions, rules, and copies. These must happen before we # compile any sources, so compute a list of predependencies for sources # while we do it. extra_sources = [] mac_bundle_depends = [] self.target.actions_stamp = self.WriteActionsRulesCopies( spec, extra_sources, actions_depends, mac_bundle_depends ) # If we have actions/rules/copies, we depend directly on those, but # otherwise we depend on dependent target's actions/rules/copies etc. # We never need to explicitly depend on previous target's link steps, # because no compile ever depends on them. compile_depends_stamp = self.target.actions_stamp or compile_depends # Write out the compilation steps, if any. link_deps = [] try: sources = extra_sources + spec.get("sources", []) except TypeError: print("extra_sources: ", str(extra_sources)) print('spec.get("sources"): ', str(spec.get("sources"))) raise if sources: if self.flavor == "mac" and len(self.archs) > 1: # Write subninja file containing compile and link commands scoped to # a single arch if a fat binary is being built. for arch in self.archs: self.ninja.subninja(self._SubninjaNameForArch(arch)) pch = None if self.flavor == "win": gyp.msvs_emulation.VerifyMissingSources( sources, self.abs_build_dir, generator_flags, self.GypPathToNinja ) pch = gyp.msvs_emulation.PrecompiledHeader( self.msvs_settings, config_name, self.GypPathToNinja, self.GypPathToUniqueOutput, self.obj_ext, ) else: pch = gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, self.GypPathToNinja, lambda path, lang: self.GypPathToUniqueOutput(path + "-" + lang), ) link_deps = self.WriteSources( self.ninja, config_name, config, sources, compile_depends_stamp, pch, spec, ) # Some actions/rules output 'sources' that are already object files. obj_outputs = [f for f in sources if f.endswith(self.obj_ext)] if obj_outputs: if self.flavor != "mac" or len(self.archs) == 1: link_deps += [self.GypPathToNinja(o) for o in obj_outputs] else: print( "Warning: Actions/rules writing object files don't work with " "multiarch targets, dropping. (target %s)" % spec["target_name"] ) elif self.flavor == "mac" and len(self.archs) > 1: link_deps = collections.defaultdict(list) compile_deps = self.target.actions_stamp or actions_depends if self.flavor == "win" and self.target.type == "static_library": self.target.component_objs = link_deps self.target.compile_deps = compile_deps # Write out a link step, if needed. output = None is_empty_bundle = not link_deps and not mac_bundle_depends if link_deps or self.target.actions_stamp or actions_depends: output = self.WriteTarget( spec, config_name, config, link_deps, compile_deps ) if self.is_mac_bundle: mac_bundle_depends.append(output) # Bundle all of the above together, if needed. if self.is_mac_bundle: output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle) if not output: return None assert self.target.FinalOutput(), output return self.target def _WinIdlRule(self, source, prebuild, outputs): """Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.""" outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData( source, self.config_name ) outdir = self.GypPathToNinja(outdir) def fix_path(path, rel=None): path = os.path.join(outdir, path) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) path = self.ExpandRuleVariables(path, root, dirname, source, ext, basename) if rel: path = os.path.relpath(path, rel) return path vars = [(name, fix_path(value, outdir)) for name, value in vars] output = [fix_path(p) for p in output] vars.append(("outdir", outdir)) vars.append(("idlflags", flags)) input = self.GypPathToNinja(source) self.ninja.build(output, "idl", input, variables=vars, order_only=prebuild) outputs.extend(output) def WriteWinIdlFiles(self, spec, prebuild): """Writes rules to match MSVS's implicit idl handling.""" assert self.flavor == "win" if self.msvs_settings.HasExplicitIdlRulesOrActions(spec): return [] outputs = [] for source in filter(lambda x: x.endswith(".idl"), spec["sources"]): self._WinIdlRule(source, prebuild, outputs) return outputs def WriteActionsRulesCopies( self, spec, extra_sources, prebuild, mac_bundle_depends ): """Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.""" outputs = [] if self.is_mac_bundle: mac_bundle_resources = spec.get("mac_bundle_resources", [])[:] else: mac_bundle_resources = [] extra_mac_bundle_resources = [] if "actions" in spec: outputs += self.WriteActions( spec["actions"], extra_sources, prebuild, extra_mac_bundle_resources ) if "rules" in spec: outputs += self.WriteRules( spec["rules"], extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources, ) if "copies" in spec: outputs += self.WriteCopies(spec["copies"], prebuild, mac_bundle_depends) if "sources" in spec and self.flavor == "win": outputs += self.WriteWinIdlFiles(spec, prebuild) if self.xcode_settings and self.xcode_settings.IsIosFramework(): self.WriteiOSFrameworkHeaders(spec, outputs, prebuild) stamp = self.WriteCollapsedDependencies("actions_rules_copies", outputs) if self.is_mac_bundle: xcassets = self.WriteMacBundleResources( extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends ) partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends) self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends) return stamp def GenerateDescription(self, verb, message, fallback): """Generate and return a description of a build step. |verb| is the short summary, e.g. ACTION or RULE. |message| is a hand-written description, or None if not available. |fallback| is the gyp-level name of the step, usable as a fallback. """ if self.toolset != "target": verb += "(%s)" % self.toolset if message: return f"{verb} {self.ExpandSpecial(message)}" else: return f"{verb} {self.name}: {fallback}" def WriteActions( self, actions, extra_sources, prebuild, extra_mac_bundle_resources ): # Actions cd into the base directory. env = self.GetToolchainEnv() all_outputs = [] for action in actions: # First write out a rule for the action. name = "{}_{}".format(action["action_name"], self.hash_for_rules) description = self.GenerateDescription( "ACTION", action.get("message", None), name ) win_shell_flags = ( self.msvs_settings.GetRuleShellFlags(action) if self.flavor == "win" else None ) args = action["action"] depfile = action.get("depfile", None) if depfile: depfile = self.ExpandSpecial(depfile, self.base_to_build) pool = "console" if int(action.get("ninja_use_console", 0)) else None rule_name, _ = self.WriteNewNinjaRule( name, args, description, win_shell_flags, env, pool, depfile=depfile ) inputs = [self.GypPathToNinja(i, env) for i in action["inputs"]] if int(action.get("process_outputs_as_sources", False)): extra_sources += action["outputs"] if int(action.get("process_outputs_as_mac_bundle_resources", False)): extra_mac_bundle_resources += action["outputs"] outputs = [self.GypPathToNinja(o, env) for o in action["outputs"]] # Then write out an edge using the rule. self.ninja.build(outputs, rule_name, inputs, order_only=prebuild) all_outputs += outputs self.ninja.newline() return all_outputs def WriteRules( self, rules, extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources, ): env = self.GetToolchainEnv() all_outputs = [] for rule in rules: # Skip a rule with no action and no inputs. if "action" not in rule and not rule.get("rule_sources", []): continue # First write out a rule for the rule action. name = "{}_{}".format(rule["rule_name"], self.hash_for_rules) args = rule["action"] description = self.GenerateDescription( "RULE", rule.get("message", None), ("%s " + generator_default_variables["RULE_INPUT_PATH"]) % name, ) win_shell_flags = ( self.msvs_settings.GetRuleShellFlags(rule) if self.flavor == "win" else None ) pool = "console" if int(rule.get("ninja_use_console", 0)) else None rule_name, args = self.WriteNewNinjaRule( name, args, description, win_shell_flags, env, pool ) # TODO: if the command references the outputs directly, we should # simplify it to just use $out. # Rules can potentially make use of some special variables which # must vary per source file. # Compute the list of variables we'll need to provide. special_locals = ("source", "root", "dirname", "ext", "name") needed_variables = {"source"} for argument in args: for var in special_locals: if "${%s}" % var in argument: needed_variables.add(var) needed_variables = sorted(needed_variables) def cygwin_munge(path): # pylint: disable=cell-var-from-loop if win_shell_flags and win_shell_flags.cygwin: return path.replace("\\", "/") return path inputs = [self.GypPathToNinja(i, env) for i in rule.get("inputs", [])] # If there are n source files matching the rule, and m additional rule # inputs, then adding 'inputs' to each build edge written below will # write m * n inputs. Collapsing reduces this to m + n. sources = rule.get("rule_sources", []) num_inputs = len(inputs) if prebuild: num_inputs += 1 if num_inputs > 2 and len(sources) > 2: inputs = [ self.WriteCollapsedDependencies( rule["rule_name"], inputs, order_only=prebuild ) ] prebuild = [] # For each source file, write an edge that generates all the outputs. for source in sources: source = os.path.normpath(source) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) # Gather the list of inputs and outputs, expanding $vars if possible. outputs = [ self.ExpandRuleVariables(o, root, dirname, source, ext, basename) for o in rule["outputs"] ] if int(rule.get("process_outputs_as_sources", False)): extra_sources += outputs was_mac_bundle_resource = source in mac_bundle_resources if was_mac_bundle_resource or int( rule.get("process_outputs_as_mac_bundle_resources", False) ): extra_mac_bundle_resources += outputs # Note: This is n_resources * n_outputs_in_rule. # Put to-be-removed items in a set and # remove them all in a single pass # if this becomes a performance issue. if was_mac_bundle_resource: mac_bundle_resources.remove(source) extra_bindings = [] for var in needed_variables: if var == "root": extra_bindings.append(("root", cygwin_munge(root))) elif var == "dirname": # '$dirname' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. dirname_expanded = self.ExpandSpecial( dirname, self.base_to_build ) extra_bindings.append( ("dirname", cygwin_munge(dirname_expanded)) ) elif var == "source": # '$source' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. source_expanded = self.ExpandSpecial(source, self.base_to_build) extra_bindings.append(("source", cygwin_munge(source_expanded))) elif var == "ext": extra_bindings.append(("ext", ext)) elif var == "name": extra_bindings.append(("name", cygwin_munge(basename))) else: assert var is None, repr(var) outputs = [self.GypPathToNinja(o, env) for o in outputs] if self.flavor == "win": # WriteNewNinjaRule uses unique_name to create a rsp file on win. extra_bindings.append( ("unique_name", hashlib.md5(outputs[0]).hexdigest()) ) self.ninja.build( outputs, rule_name, self.GypPathToNinja(source), implicit=inputs, order_only=prebuild, variables=extra_bindings, ) all_outputs.extend(outputs) return all_outputs def WriteCopies(self, copies, prebuild, mac_bundle_depends): outputs = [] if self.xcode_settings: extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetToolchainEnv(additional_settings=extra_env) else: env = self.GetToolchainEnv() for to_copy in copies: for path in to_copy["files"]: # Normalize the path so trailing slashes don't confuse us. path = os.path.normpath(path) basename = os.path.split(path)[1] src = self.GypPathToNinja(path, env) dst = self.GypPathToNinja( os.path.join(to_copy["destination"], basename), env ) outputs += self.ninja.build(dst, "copy", src, order_only=prebuild) if self.is_mac_bundle: # gyp has mac_bundle_resources to copy things into a bundle's # Resources folder, but there's no built-in way to copy files # to other places in the bundle. # Hence, some targets use copies for this. # Check if this file is copied into the current bundle, # and if so add it to the bundle depends so # that dependent targets get rebuilt if the copy input changes. if dst.startswith( self.xcode_settings.GetBundleContentsFolderPath() ): mac_bundle_depends.append(dst) return outputs def WriteiOSFrameworkHeaders(self, spec, outputs, prebuild): """Prebuild steps to generate hmap files and copy headers to destination.""" framework = self.ComputeMacBundleOutput() all_sources = spec["sources"] copy_headers = spec["mac_framework_headers"] output = self.GypPathToUniqueOutput("headers.hmap") self.xcode_settings.header_map_path = output all_headers = map( self.GypPathToNinja, filter(lambda x: x.endswith(".h"), all_sources) ) variables = [ ("framework", framework), ("copy_headers", map(self.GypPathToNinja, copy_headers)), ] outputs.extend( self.ninja.build( output, "compile_ios_framework_headers", all_headers, variables=variables, order_only=prebuild, ) ) def WriteMacBundleResources(self, resources, bundle_depends): """Writes ninja edges for 'mac_bundle_resources'.""" xcassets = [] extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables["PRODUCT_DIR"], self.xcode_settings, map(self.GypPathToNinja, resources), ): output = self.ExpandSpecial(output) if os.path.splitext(output)[-1] != ".xcassets": self.ninja.build( output, "mac_tool", res, variables=[ ("mactool_cmd", "copy-bundle-resource"), ("env", env), ("binary", isBinary), ], ) bundle_depends.append(output) else: xcassets.append(res) return xcassets def WriteMacXCassets(self, xcassets, bundle_depends): """Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.""" if not xcassets: return extra_arguments = {} settings_to_arg = { "XCASSETS_APP_ICON": "app-icon", "XCASSETS_LAUNCH_IMAGE": "launch-image", } settings = self.xcode_settings.xcode_settings[self.config_name] for settings_key, arg_name in settings_to_arg.items(): value = settings.get(settings_key) if value: extra_arguments[arg_name] = value partial_info_plist = None if extra_arguments: partial_info_plist = self.GypPathToUniqueOutput( "assetcatalog_generated_info.plist" ) extra_arguments["output-partial-info-plist"] = partial_info_plist outputs = [] outputs.append( os.path.join(self.xcode_settings.GetBundleResourceFolder(), "Assets.car") ) if partial_info_plist: outputs.append(partial_info_plist) keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor) extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) bundle_depends.extend( self.ninja.build( outputs, "compile_xcassets", xcassets, variables=[("env", env), ("keys", keys)], ) ) return partial_info_plist def WriteMacInfoPlist(self, partial_info_plist, bundle_depends): """Write build rules for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables["PRODUCT_DIR"], self.xcode_settings, self.GypPathToNinja, ) if not info_plist: return out = self.ExpandSpecial(out) if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = self.GypPathToUniqueOutput( os.path.basename(info_plist) ) defines = " ".join([Define(d, self.flavor) for d in defines]) info_plist = self.ninja.build( intermediate_plist, "preprocess_infoplist", info_plist, variables=[("defines", defines)], ) env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) if partial_info_plist: intermediate_plist = self.GypPathToUniqueOutput("merged_info.plist") info_plist = self.ninja.build( intermediate_plist, "merge_infoplist", [partial_info_plist, info_plist] ) keys = self.xcode_settings.GetExtraPlistItems(self.config_name) keys = QuoteShellArgument(json.dumps(keys), self.flavor) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build( out, "copy_infoplist", info_plist, variables=[("env", env), ("keys", keys), ("binary", isBinary)], ) bundle_depends.append(out) def WriteSources( self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, ): """Write build rules to compile all of |sources|.""" if self.toolset == "host": self.ninja.variable("ar", "$ar_host") self.ninja.variable("cc", "$cc_host") self.ninja.variable("cxx", "$cxx_host") self.ninja.variable("ld", "$ld_host") self.ninja.variable("ldxx", "$ldxx_host") self.ninja.variable("nm", "$nm_host") self.ninja.variable("readelf", "$readelf_host") if self.flavor != "mac" or len(self.archs) == 1: return self.WriteSourcesForArch( self.ninja, config_name, config, sources, predepends, precompiled_header, spec, ) else: return { arch: self.WriteSourcesForArch( self.arch_subninjas[arch], config_name, config, sources, predepends, precompiled_header, spec, arch=arch, ) for arch in self.archs } def WriteSourcesForArch( self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, arch=None, ): """Write build rules to compile all of |sources|.""" extra_defines = [] if self.flavor == "mac": cflags = self.xcode_settings.GetCflags(config_name, arch=arch) cflags_c = self.xcode_settings.GetCflagsC(config_name) cflags_cc = self.xcode_settings.GetCflagsCC(config_name) cflags_objc = ["$cflags_c"] + self.xcode_settings.GetCflagsObjC(config_name) cflags_objcc = ["$cflags_cc"] + self.xcode_settings.GetCflagsObjCC( config_name ) elif self.flavor == "win": asmflags = self.msvs_settings.GetAsmflags(config_name) cflags = self.msvs_settings.GetCflags(config_name) cflags_c = self.msvs_settings.GetCflagsC(config_name) cflags_cc = self.msvs_settings.GetCflagsCC(config_name) extra_defines = self.msvs_settings.GetComputedDefines(config_name) # See comment at cc_command for why there's two .pdb files. pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName( config_name, self.ExpandSpecial ) if not pdbpath_c: obj = "obj" if self.toolset != "target": obj += "." + self.toolset pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name)) pdbpath_c = pdbpath + ".c.pdb" pdbpath_cc = pdbpath + ".cc.pdb" self.WriteVariableList(ninja_file, "pdbname_c", [pdbpath_c]) self.WriteVariableList(ninja_file, "pdbname_cc", [pdbpath_cc]) self.WriteVariableList(ninja_file, "pchprefix", [self.name]) else: cflags = config.get("cflags", []) cflags_c = config.get("cflags_c", []) cflags_cc = config.get("cflags_cc", []) # Respect environment variables related to build, but target-specific # flags can still override them. if self.toolset == "target": cflags_c = ( os.environ.get("CPPFLAGS", "").split() + os.environ.get("CFLAGS", "").split() + cflags_c ) cflags_cc = ( os.environ.get("CPPFLAGS", "").split() + os.environ.get("CXXFLAGS", "").split() + cflags_cc ) elif self.toolset == "host": cflags_c = ( os.environ.get("CPPFLAGS_host", "").split() + os.environ.get("CFLAGS_host", "").split() + cflags_c ) cflags_cc = ( os.environ.get("CPPFLAGS_host", "").split() + os.environ.get("CXXFLAGS_host", "").split() + cflags_cc ) defines = config.get("defines", []) + extra_defines self.WriteVariableList( ninja_file, "defines", [Define(d, self.flavor) for d in defines] ) if self.flavor == "win": self.WriteVariableList( ninja_file, "asmflags", map(self.ExpandSpecial, asmflags) ) self.WriteVariableList( ninja_file, "rcflags", [ QuoteShellArgument(self.ExpandSpecial(f), self.flavor) for f in self.msvs_settings.GetRcflags( config_name, self.GypPathToNinja ) ], ) include_dirs = config.get("include_dirs", []) env = self.GetToolchainEnv() if self.flavor == "win": include_dirs = self.msvs_settings.AdjustIncludeDirs( include_dirs, config_name ) self.WriteVariableList( ninja_file, "includes", [ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor) for i in include_dirs ], ) if self.flavor == "win": midl_include_dirs = config.get("midl_include_dirs", []) midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs( midl_include_dirs, config_name ) self.WriteVariableList( ninja_file, "midl_includes", [ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor) for i in midl_include_dirs ], ) pch_commands = precompiled_header.GetPchBuildCommands(arch) if self.flavor == "mac": # Most targets use no precompiled headers, so only write these if needed. for ext, var in [ ("c", "cflags_pch_c"), ("cc", "cflags_pch_cc"), ("m", "cflags_pch_objc"), ("mm", "cflags_pch_objcc"), ]: include = precompiled_header.GetInclude(ext, arch) if include: ninja_file.variable(var, include) arflags = config.get("arflags", []) self.WriteVariableList(ninja_file, "cflags", map(self.ExpandSpecial, cflags)) self.WriteVariableList( ninja_file, "cflags_c", map(self.ExpandSpecial, cflags_c) ) self.WriteVariableList( ninja_file, "cflags_cc", map(self.ExpandSpecial, cflags_cc) ) if self.flavor == "mac": self.WriteVariableList( ninja_file, "cflags_objc", map(self.ExpandSpecial, cflags_objc) ) self.WriteVariableList( ninja_file, "cflags_objcc", map(self.ExpandSpecial, cflags_objcc) ) self.WriteVariableList(ninja_file, "arflags", map(self.ExpandSpecial, arflags)) ninja_file.newline() outputs = [] has_rc_source = False for source in sources: filename, ext = os.path.splitext(source) ext = ext[1:] obj_ext = self.obj_ext if ext in ("cc", "cpp", "cxx"): command = "cxx" self.target.uses_cpp = True elif ext == "c" or (ext == "S" and self.flavor != "win"): command = "cc" elif ext == "s" and self.flavor != "win": # Doesn't generate .o.d files. command = "cc_s" elif ( self.flavor == "win" and ext in ("asm", "S") and not self.msvs_settings.HasExplicitAsmRules(spec) ): command = "asm" # Add the _asm suffix as msvs is capable of handling .cc and # .asm files of the same name without collision. obj_ext = "_asm.obj" elif self.flavor == "mac" and ext == "m": command = "objc" elif self.flavor == "mac" and ext == "mm": command = "objcxx" self.target.uses_cpp = True elif self.flavor == "win" and ext == "rc": command = "rc" obj_ext = ".res" has_rc_source = True else: # Ignore unhandled extensions. continue input = self.GypPathToNinja(source) output = self.GypPathToUniqueOutput(filename + obj_ext) if arch is not None: output = AddArch(output, arch) implicit = precompiled_header.GetObjDependencies([input], [output], arch) variables = [] if self.flavor == "win": variables, output, implicit = precompiled_header.GetFlagsModifications( input, output, implicit, command, cflags_c, cflags_cc, self.ExpandSpecial, ) ninja_file.build( output, command, input, implicit=[gch for _, _, gch in implicit], order_only=predepends, variables=variables, ) outputs.append(output) if has_rc_source: resource_include_dirs = config.get("resource_include_dirs", include_dirs) self.WriteVariableList( ninja_file, "resource_includes", [ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor) for i in resource_include_dirs ], ) self.WritePchTargets(ninja_file, pch_commands) ninja_file.newline() return outputs def WritePchTargets(self, ninja_file, pch_commands): """Writes ninja rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: var_name = { "c": "cflags_pch_c", "cc": "cflags_pch_cc", "m": "cflags_pch_objc", "mm": "cflags_pch_objcc", }[lang] map = { "c": "cc", "cc": "cxx", "m": "objc", "mm": "objcxx", } cmd = map.get(lang) ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)]) def WriteLink(self, spec, config_name, config, link_deps, compile_deps): """Write out a link step. Fills out target.binary. """ if self.flavor != "mac" or len(self.archs) == 1: return self.WriteLinkForArch( self.ninja, spec, config_name, config, link_deps, compile_deps ) else: output = self.ComputeOutput(spec) inputs = [ self.WriteLinkForArch( self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], compile_deps, arch=arch, ) for arch in self.archs ] extra_bindings = [] build_output = output if not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) # TODO(yyanagisawa): more work needed to fix: # https://code.google.com/p/gyp/issues/detail?id=411 if ( spec["type"] in ("shared_library", "loadable_module") and not self.is_mac_bundle ): extra_bindings.append(("lib", output)) self.ninja.build( [output, output + ".TOC"], "solipo", inputs, variables=extra_bindings, ) else: self.ninja.build(build_output, "lipo", inputs, variables=extra_bindings) return output def WriteLinkForArch( self, ninja_file, spec, config_name, config, link_deps, compile_deps, arch=None ): """Write out a link step. Fills out target.binary. """ command = { "executable": "link", "loadable_module": "solink_module", "shared_library": "solink", }[spec["type"]] command_suffix = "" implicit_deps = set() solibs = set() order_deps = set() if compile_deps: # Normally, the compiles of the target already depend on compile_deps, # but a shared_library target might have no sources and only link together # a few static_library deps, so the link step also needs to depend # on compile_deps to make sure actions in the shared_library target # get run before the link. order_deps.add(compile_deps) if "dependencies" in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec["dependencies"]: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: new_deps = [] if ( self.flavor == "win" and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name) ): new_deps = target.component_objs if target.compile_deps: order_deps.add(target.compile_deps) elif self.flavor == "win" and target.import_lib: new_deps = [target.import_lib] elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + ".TOC") else: new_deps = [target.binary] for new_dep in new_deps: if new_dep not in extra_link_deps: extra_link_deps.add(new_dep) link_deps.append(new_dep) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) extra_bindings = [] if self.target.uses_cpp and self.flavor != "win": extra_bindings.append(("ld", "$ldxx")) output = self.ComputeOutput(spec, arch) if arch is None and not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) is_executable = spec["type"] == "executable" # The ldflags config key is not used on mac or win. On those platforms # linker flags are set via xcode_settings and msvs_settings, respectively. if self.toolset == "target": env_ldflags = os.environ.get("LDFLAGS", "").split() elif self.toolset == "host": env_ldflags = os.environ.get("LDFLAGS_host", "").split() if self.flavor == "mac": ldflags = self.xcode_settings.GetLdflags( config_name, self.ExpandSpecial(generator_default_variables["PRODUCT_DIR"]), self.GypPathToNinja, arch, ) ldflags = env_ldflags + ldflags elif self.flavor == "win": manifest_base_name = self.GypPathToUniqueOutput( self.ComputeOutputFileName(spec) ) ( ldflags, intermediate_manifest, manifest_files, ) = self.msvs_settings.GetLdflags( config_name, self.GypPathToNinja, self.ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build, ) ldflags = env_ldflags + ldflags self.WriteVariableList(ninja_file, "manifests", manifest_files) implicit_deps = implicit_deps.union(manifest_files) if intermediate_manifest: self.WriteVariableList( ninja_file, "intermediatemanifest", [intermediate_manifest] ) command_suffix = _GetWinLinkRuleNameSuffix( self.msvs_settings.IsEmbedManifest(config_name) ) def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja) if def_file: implicit_deps.add(def_file) else: # Respect environment variables related to build, but target-specific # flags can still override them. ldflags = env_ldflags + config.get("ldflags", []) if is_executable and len(solibs): rpath = "lib/" if self.toolset != "target": rpath += self.toolset ldflags.append(r"-Wl,-rpath=\$$ORIGIN/%s" % rpath) else: ldflags.append("-Wl,-rpath=%s" % self.target_rpath) ldflags.append("-Wl,-rpath-link=%s" % rpath) self.WriteVariableList(ninja_file, "ldflags", map(self.ExpandSpecial, ldflags)) library_dirs = config.get("library_dirs", []) if self.flavor == "win": library_dirs = [ self.msvs_settings.ConvertVSMacros(library_dir, config_name) for library_dir in library_dirs ] library_dirs = [ "/LIBPATH:" + QuoteShellArgument(self.GypPathToNinja(library_dir), self.flavor) for library_dir in library_dirs ] else: library_dirs = [ QuoteShellArgument("-L" + self.GypPathToNinja(library_dir), self.flavor) for library_dir in library_dirs ] libraries = gyp.common.uniquer( map(self.ExpandSpecial, spec.get("libraries", [])) ) if self.flavor == "mac": libraries = self.xcode_settings.AdjustLibraries(libraries, config_name) elif self.flavor == "win": libraries = self.msvs_settings.AdjustLibraries(libraries) self.WriteVariableList(ninja_file, "libs", library_dirs + libraries) linked_binary = output if command in ("solink", "solink_module"): extra_bindings.append(("soname", os.path.split(output)[1])) extra_bindings.append(("lib", gyp.common.EncodePOSIXShellArgument(output))) if self.flavor != "win": link_file_list = output if self.is_mac_bundle: # 'Dependency Framework.framework/Versions/A/Dependency Framework' # -> 'Dependency Framework.framework.rsp' link_file_list = self.xcode_settings.GetWrapperName() if arch: link_file_list += "." + arch link_file_list += ".rsp" # If an rspfile contains spaces, ninja surrounds the filename with # quotes around it and then passes it to open(), creating a file with # quotes in its name (and when looking for the rsp file, the name # makes it through bash which strips the quotes) :-/ link_file_list = link_file_list.replace(" ", "_") extra_bindings.append( ( "link_file_list", gyp.common.EncodePOSIXShellArgument(link_file_list), ) ) if self.flavor == "win": extra_bindings.append(("binary", output)) if ( "/NOENTRY" not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name) ): self.target.import_lib = output + ".lib" extra_bindings.append( ("implibflag", "/IMPLIB:%s" % self.target.import_lib) ) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + ".pdb" ) output = [output, self.target.import_lib] if pdbname: output.append(pdbname) elif not self.is_mac_bundle: output = [output, output + ".TOC"] else: command = command + "_notoc" elif self.flavor == "win": extra_bindings.append(("binary", output)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + ".pdb" ) if pdbname: output = [output, pdbname] if len(solibs): extra_bindings.append( ("solibs", gyp.common.EncodePOSIXShellList(sorted(solibs))) ) ninja_file.build( output, command + command_suffix, link_deps, implicit=sorted(implicit_deps), order_only=list(order_deps), variables=extra_bindings, ) return linked_binary def WriteTarget(self, spec, config_name, config, link_deps, compile_deps): extra_link_deps = any( self.target_outputs.get(dep).Linkable() for dep in spec.get("dependencies", []) if dep in self.target_outputs ) if spec["type"] == "none" or (not link_deps and not extra_link_deps): # TODO(evan): don't call this function for 'none' target types, as # it doesn't do anything, and we fake out a 'binary' with a stamp file. self.target.binary = compile_deps self.target.type = "none" elif spec["type"] == "static_library": self.target.binary = self.ComputeOutput(spec) if ( self.flavor not in ("ios", "mac", "netbsd", "openbsd", "win") and not self.is_standalone_static_library ): self.ninja.build( self.target.binary, "alink_thin", link_deps, order_only=compile_deps ) else: variables = [] if self.xcode_settings: libtool_flags = self.xcode_settings.GetLibtoolflags(config_name) if libtool_flags: variables.append(("libtool_flags", libtool_flags)) if self.msvs_settings: libflags = self.msvs_settings.GetLibFlags( config_name, self.GypPathToNinja ) variables.append(("libflags", libflags)) if self.flavor != "mac" or len(self.archs) == 1: self.AppendPostbuildVariable( variables, spec, self.target.binary, self.target.binary ) self.ninja.build( self.target.binary, "alink", link_deps, order_only=compile_deps, variables=variables, ) else: inputs = [] for arch in self.archs: output = self.ComputeOutput(spec, arch) self.arch_subninjas[arch].build( output, "alink", link_deps[arch], order_only=compile_deps, variables=variables, ) inputs.append(output) # TODO: It's not clear if # libtool_flags should be passed to the alink # call that combines single-arch .a files into a fat .a file. self.AppendPostbuildVariable( variables, spec, self.target.binary, self.target.binary ) self.ninja.build( self.target.binary, "alink", inputs, # FIXME: test proving order_only=compile_deps isn't # needed. variables=variables, ) else: self.target.binary = self.WriteLink( spec, config_name, config, link_deps, compile_deps ) return self.target.binary def WriteMacBundle(self, spec, mac_bundle_depends, is_empty): assert self.is_mac_bundle package_framework = spec["type"] in ("shared_library", "loadable_module") output = self.ComputeMacBundleOutput() if is_empty: output += ".stamp" variables = [] self.AppendPostbuildVariable( variables, spec, output, self.target.binary, is_command_start=not package_framework, ) if package_framework and not is_empty: if spec["type"] == "shared_library" and self.xcode_settings.isIOS: self.ninja.build( output, "package_ios_framework", mac_bundle_depends, variables=variables, ) else: variables.append(("version", self.xcode_settings.GetFrameworkVersion())) self.ninja.build( output, "package_framework", mac_bundle_depends, variables=variables ) else: self.ninja.build(output, "stamp", mac_bundle_depends, variables=variables) self.target.bundle = output return output def GetToolchainEnv(self, additional_settings=None): """Returns the variables toolchain would set for build steps.""" env = self.GetSortedXcodeEnv(additional_settings=additional_settings) if self.flavor == "win": env = self.GetMsvsToolchainEnv(additional_settings=additional_settings) return env def GetMsvsToolchainEnv(self, additional_settings=None): """Returns the variables Visual Studio would set for build steps.""" return self.msvs_settings.GetVSMacroEnv( "$!PRODUCT_DIR", config=self.config_name ) def GetSortedXcodeEnv(self, additional_settings=None): """Returns the variables Xcode would set for build steps.""" assert self.abs_build_dir abs_build_dir = self.abs_build_dir return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, abs_build_dir, os.path.join(abs_build_dir, self.build_to_base), self.config_name, additional_settings, ) def GetSortedXcodePostbuildEnv(self): """Returns the variables Xcode would set for postbuild steps.""" postbuild_settings = {} # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( "CHROMIUM_STRIP_SAVE_FILE" ) if strip_save_file: postbuild_settings["CHROMIUM_STRIP_SAVE_FILE"] = strip_save_file return self.GetSortedXcodeEnv(additional_settings=postbuild_settings) def AppendPostbuildVariable( self, variables, spec, output, binary, is_command_start=False ): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.append(("postbuilds", postbuild)) def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec["type"] == "none" or not output: return "" output = QuoteShellArgument(output, self.flavor) postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) if output_binary is not None: postbuilds = self.xcode_settings.AddImplicitPostbuilds( self.config_name, os.path.normpath(os.path.join(self.base_to_build, output)), QuoteShellArgument( os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor, ), postbuilds, quiet=True, ) if not postbuilds: return "" # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert( 0, gyp.common.EncodePOSIXShellList(["cd", self.build_to_base]) ) env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) # G will be non-null if any postbuild fails. Run all postbuilds in a # subshell. commands = ( env + " (" + " && ".join([ninja_syntax.escape(command) for command in postbuilds]) ) command_string = ( commands + "); G=$$?; " # Remove the final output if any postbuild failed. "((exit $$G) || rm -rf %s) " % output + "&& exit $$G)" ) if is_command_start: return "(" + command_string + " && " else: return "$ && (" + command_string def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append( "export %s=%s;" % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v))) ) return " ".join(export_str) def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables["PRODUCT_DIR"] return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName()) ) def ComputeOutputFileName(self, spec, type=None): """Compute the filename of the final output for the current target.""" if not type: type = spec["type"] default_variables = copy.copy(generator_default_variables) CalculateVariables(default_variables, {"flavor": self.flavor}) # Compute filename prefix: the product prefix, or a default for # the product type. DEFAULT_PREFIX = { "loadable_module": default_variables["SHARED_LIB_PREFIX"], "shared_library": default_variables["SHARED_LIB_PREFIX"], "static_library": default_variables["STATIC_LIB_PREFIX"], "executable": default_variables["EXECUTABLE_PREFIX"], } prefix = spec.get("product_prefix", DEFAULT_PREFIX.get(type, "")) # Compute filename extension: the product extension, or a default # for the product type. DEFAULT_EXTENSION = { "loadable_module": default_variables["SHARED_LIB_SUFFIX"], "shared_library": default_variables["SHARED_LIB_SUFFIX"], "static_library": default_variables["STATIC_LIB_SUFFIX"], "executable": default_variables["EXECUTABLE_SUFFIX"], } extension = spec.get("product_extension") extension = "." + extension if extension else DEFAULT_EXTENSION.get(type, "") if "product_name" in spec: # If we were given an explicit name, use that. target = spec["product_name"] else: # Otherwise, derive a name from the target name. target = spec["target_name"] if prefix == "lib": # Snip out an extra 'lib' from libs if appropriate. target = StripPrefix(target, "lib") if type in ( "static_library", "loadable_module", "shared_library", "executable", ): return f"{prefix}{target}{extension}" elif type == "none": return "%s.stamp" % target else: raise Exception("Unhandled output type %s" % type) def ComputeOutput(self, spec, arch=None): """Compute the path for the final output of the spec.""" type = spec["type"] if self.flavor == "win": override = self.msvs_settings.GetOutputName( self.config_name, self.ExpandSpecial ) if override: return override if ( arch is None and self.flavor == "mac" and type in ("static_library", "executable", "shared_library", "loadable_module") ): filename = self.xcode_settings.GetExecutablePath() else: filename = self.ComputeOutputFileName(spec, type) if arch is None and "product_dir" in spec: path = os.path.join(spec["product_dir"], filename) return self.ExpandSpecial(path) # Some products go into the output root, libraries go into shared library # dir, and everything else goes into the normal place. type_in_output_root = ["executable", "loadable_module"] if self.flavor == "mac" and self.toolset == "target": type_in_output_root += ["shared_library", "static_library"] elif self.flavor == "win" and self.toolset == "target": type_in_output_root += ["shared_library"] if arch is not None: # Make sure partial executables don't end up in a bundle or the regular # output directory. archdir = "arch" if self.toolset != "target": archdir = os.path.join("arch", "%s" % self.toolset) return os.path.join(archdir, AddArch(filename, arch)) elif type in type_in_output_root or self.is_standalone_static_library: return filename elif type == "shared_library": libdir = "lib" if self.toolset != "target": libdir = os.path.join("lib", "%s" % self.toolset) return os.path.join(libdir, filename) else: return self.GypPathToUniqueOutput(filename, qualified=False) def WriteVariableList(self, ninja_file, var, values): assert not isinstance(values, str) if values is None: values = [] ninja_file.variable(var, " ".join(values)) def WriteNewNinjaRule( self, name, args, description, win_shell_flags, env, pool, depfile=None ): """Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.""" if self.flavor == "win": args = [ self.msvs_settings.ConvertVSMacros( arg, self.base_to_build, config=self.config_name ) for arg in args ] description = self.msvs_settings.ConvertVSMacros( description, config=self.config_name ) elif self.flavor == "mac": # |env| is an empty list on non-mac. args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args] description = gyp.xcode_emulation.ExpandEnvVars(description, env) # TODO: we shouldn't need to qualify names; we do it because # currently the ninja rule namespace is global, but it really # should be scoped to the subninja. rule_name = self.name if self.toolset == "target": rule_name += "." + self.toolset rule_name += "." + name rule_name = re.sub("[^a-zA-Z0-9_]", "_", rule_name) # Remove variable references, but not if they refer to the magic rule # variables. This is not quite right, as it also protects these for # actions, not just for rules where they are valid. Good enough. protect = ["${root}", "${dirname}", "${source}", "${ext}", "${name}"] protect = "(?!" + "|".join(map(re.escape, protect)) + ")" description = re.sub(protect + r"\$", "_", description) # gyp dictates that commands are run from the base directory. # cd into the directory before running, and adjust paths in # the arguments to point to the proper locations. rspfile = None rspfile_content = None args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] if self.flavor == "win": rspfile = rule_name + ".$unique_name.rsp" # The cygwin case handles this inside the bash sub-shell. run_in = "" if win_shell_flags.cygwin else " " + self.build_to_base if win_shell_flags.cygwin: rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine( args, self.build_to_base ) else: rspfile_content = gyp.msvs_emulation.EncodeRspFileList( args, win_shell_flags.quote) command = ( "%s gyp-win-tool action-wrapper $arch " % sys.executable + rspfile + run_in ) else: env = self.ComputeExportEnvString(env) command = gyp.common.EncodePOSIXShellList(args) command = "cd %s; " % self.build_to_base + env + command # GYP rules/actions express being no-ops by not touching their outputs. # Avoid executing downstream dependencies in this case by specifying # restat=1 to ninja. self.ninja.rule( rule_name, command, description, depfile=depfile, restat=True, pool=pool, rspfile=rspfile, rspfile_content=rspfile_content, ) self.ninja.newline() return rule_name, args def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == "mac": default_variables.setdefault("OS", "mac") default_variables.setdefault("SHARED_LIB_SUFFIX", ".dylib") default_variables.setdefault( "SHARED_LIB_DIR", generator_default_variables["PRODUCT_DIR"] ) default_variables.setdefault( "LIB_DIR", generator_default_variables["PRODUCT_DIR"] ) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr( xcode_generator, "generator_additional_non_configuration_keys", [] ) generator_additional_path_sections = getattr( xcode_generator, "generator_additional_path_sections", [] ) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr( xcode_generator, "generator_extra_sources_for_rules", [] ) elif flavor == "win": exts = gyp.MSVSUtil.TARGET_TYPE_EXT default_variables.setdefault("OS", "win") default_variables["EXECUTABLE_SUFFIX"] = "." + exts["executable"] default_variables["STATIC_LIB_PREFIX"] = "" default_variables["STATIC_LIB_SUFFIX"] = "." + exts["static_library"] default_variables["SHARED_LIB_PREFIX"] = "" default_variables["SHARED_LIB_SUFFIX"] = "." + exts["shared_library"] # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr( msvs_generator, "generator_additional_non_configuration_keys", [] ) generator_additional_path_sections = getattr( msvs_generator, "generator_additional_path_sections", [] ) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == "android": operating_system = "linux" # Keep this legacy behavior for now. default_variables.setdefault("OS", operating_system) default_variables.setdefault("SHARED_LIB_SUFFIX", ".so") default_variables.setdefault( "SHARED_LIB_DIR", os.path.join("$!PRODUCT_DIR", "lib") ) default_variables.setdefault("LIB_DIR", os.path.join("$!PRODUCT_DIR", "obj")) def ComputeOutputDir(params): """Returns the path from the toplevel_dir to the build output directory.""" # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params["options"].generator_output or ".") # output_dir: relative path from generator_dir to the build directory. output_dir = params.get("generator_flags", {}).get("output_dir", "out") # Relative path from source root to our output files. e.g. "out" return os.path.normpath(os.path.join(generator_dir, output_dir)) def CalculateGeneratorInputInfo(params): """Called by __init__ to initialize generator values based on params.""" # E.g. "out/gypfiles" toplevel = params["options"].toplevel_dir qualified_out_dir = os.path.normpath( os.path.join(toplevel, ComputeOutputDir(params), "gypfiles") ) global generator_filelist_paths generator_filelist_paths = { "toplevel": toplevel, "qualified_out_dir": qualified_out_dir, } def OpenOutput(path, mode="w"): """Open |path| for writing, creating directories if necessary.""" gyp.common.EnsureDirExists(path) return open(path, mode) def CommandWithWrapper(cmd, wrappers, prog): wrapper = wrappers.get(cmd, "") if wrapper: return wrapper + " " + prog return prog def GetDefaultConcurrentLinks(): """Returns a best-guess for a number of concurrent links.""" pool_size = int(os.environ.get("GYP_LINK_CONCURRENCY", 0)) if pool_size: return pool_size if sys.platform in ("win32", "cygwin"): import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ] stat = MEMORYSTATUSEX() stat.dwLength = ctypes.sizeof(stat) ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) # VS 2015 uses 20% more working set than VS 2013 and can consume all RAM # on a 64 GiB machine. mem_limit = max(1, stat.ullTotalPhys // (5 * (2 ** 30))) # total / 5GiB hard_cap = max(1, int(os.environ.get("GYP_LINK_CONCURRENCY_MAX", 2 ** 32))) return min(mem_limit, hard_cap) elif sys.platform.startswith("linux"): if os.path.exists("/proc/meminfo"): with open("/proc/meminfo") as meminfo: memtotal_re = re.compile(r"^MemTotal:\s*(\d*)\s*kB") for line in meminfo: match = memtotal_re.match(line) if not match: continue # Allow 8Gb per link on Linux because Gold is quite memory hungry return max(1, int(match.group(1)) // (8 * (2 ** 20))) return 1 elif sys.platform == "darwin": try: avail_bytes = int(subprocess.check_output(["sysctl", "-n", "hw.memsize"])) # A static library debug build of Chromium's unit_tests takes ~2.7GB, so # 4GB per ld process allows for some more bloat. return max(1, avail_bytes // (4 * (2 ** 30))) # total / 4GB except subprocess.CalledProcessError: return 1 else: # TODO(scottmg): Implement this for other platforms. return 1 def _GetWinLinkRuleNameSuffix(embed_manifest): """Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled.""" return "_embed" if embed_manifest else "" def _AddWinLinkRules(master_ninja, embed_manifest): """Adds link rules for Windows platform to |master_ninja|.""" def FullLinkCommand(ldcmd, out, binary_type): resource_name = {"exe": "1", "dll": "2"}[binary_type] return ( "%(python)s gyp-win-tool link-with-manifests $arch %(embed)s " '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' "$manifests" % { "python": sys.executable, "out": out, "ldcmd": ldcmd, "resname": resource_name, "embed": embed_manifest, } ) rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest) use_separate_mspdbsrv = int(os.environ.get("GYP_USE_SEPARATE_MSPDBSRV", "0")) != 0 dlldesc = "LINK%s(DLL) $binary" % rule_name_suffix.upper() dllcmd = ( "%s gyp-win-tool link-wrapper $arch %s " "$ld /nologo $implibflag /DLL /OUT:$binary " "@$binary.rsp" % (sys.executable, use_separate_mspdbsrv) ) dllcmd = FullLinkCommand(dllcmd, "$binary", "dll") master_ninja.rule( "solink" + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile="$binary.rsp", rspfile_content="$libs $in_newline $ldflags", restat=True, pool="link_pool", ) master_ninja.rule( "solink_module" + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile="$binary.rsp", rspfile_content="$libs $in_newline $ldflags", restat=True, pool="link_pool", ) # Note that ldflags goes at the end so that it has the option of # overriding default settings earlier in the command line. exe_cmd = ( "%s gyp-win-tool link-wrapper $arch %s " "$ld /nologo /OUT:$binary @$binary.rsp" % (sys.executable, use_separate_mspdbsrv) ) exe_cmd = FullLinkCommand(exe_cmd, "$binary", "exe") master_ninja.rule( "link" + rule_name_suffix, description="LINK%s $binary" % rule_name_suffix.upper(), command=exe_cmd, rspfile="$binary.rsp", rspfile_content="$in_newline $libs $ldflags", pool="link_pool", ) def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params["options"] flavor = gyp.common.GetFlavor(params) generator_flags = params.get("generator_flags", {}) generate_compile_commands = generator_flags.get("compile_commands", False) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath(os.path.join(ComputeOutputDir(params), config_name)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) master_ninja_file = OpenOutput(os.path.join(toplevel_build, "build.ninja")) master_ninja = ninja_syntax.Writer(master_ninja_file, width=120) # Put build-time support tools in out/{config_name}. gyp.common.CopyTool(flavor, toplevel_build, generator_flags) # Grab make settings for CC/CXX. # The rules are # - The priority from low to high is gcc/g++, the 'make_global_settings' in # gyp, the environment variable. # - If there is no 'make_global_settings' for CC.host/CXX.host or # 'CC_host'/'CXX_host' environment variable, cc_host/cxx_host should be set # to cc/cxx. if flavor == "win": ar = "lib.exe" # cc and cxx must be set to the correct architecture by overriding with one # of cl_x86 or cl_x64 below. cc = "UNSET" cxx = "UNSET" ld = "link.exe" ld_host = "$ld" else: ar = "ar" cc = "cc" cxx = "c++" ld = "$cc" ldxx = "$cxx" ld_host = "$cc_host" ldxx_host = "$cxx_host" ar_host = ar cc_host = None cxx_host = None cc_host_global_setting = None cxx_host_global_setting = None clang_cl = None nm = "nm" nm_host = "nm" readelf = "readelf" readelf_host = "readelf" build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings = data[build_file].get("make_global_settings", []) build_to_root = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) wrappers = {} for key, value in make_global_settings: if key == "AR": ar = os.path.join(build_to_root, value) if key == "AR.host": ar_host = os.path.join(build_to_root, value) if key == "CC": cc = os.path.join(build_to_root, value) if cc.endswith("clang-cl"): clang_cl = cc if key == "CXX": cxx = os.path.join(build_to_root, value) if key == "CC.host": cc_host = os.path.join(build_to_root, value) cc_host_global_setting = value if key == "CXX.host": cxx_host = os.path.join(build_to_root, value) cxx_host_global_setting = value if key == "LD": ld = os.path.join(build_to_root, value) if key == "LD.host": ld_host = os.path.join(build_to_root, value) if key == "LDXX": ldxx = os.path.join(build_to_root, value) if key == "LDXX.host": ldxx_host = os.path.join(build_to_root, value) if key == "NM": nm = os.path.join(build_to_root, value) if key == "NM.host": nm_host = os.path.join(build_to_root, value) if key == "READELF": readelf = os.path.join(build_to_root, value) if key == "READELF.host": readelf_host = os.path.join(build_to_root, value) if key.endswith("_wrapper"): wrappers[key[: -len("_wrapper")]] = os.path.join(build_to_root, value) # Support wrappers from environment variables too. for key, value in os.environ.items(): if key.lower().endswith("_wrapper"): key_prefix = key[: -len("_wrapper")] key_prefix = re.sub(r"\.HOST$", ".host", key_prefix) wrappers[key_prefix] = os.path.join(build_to_root, value) mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None) if mac_toolchain_dir: wrappers["LINK"] = "export DEVELOPER_DIR='%s' &&" % mac_toolchain_dir if flavor == "win": configs = [ target_dicts[qualified_target]["configurations"][config_name] for qualified_target in target_list ] shared_system_includes = None if not generator_flags.get("ninja_use_custom_environment_files", 0): shared_system_includes = gyp.msvs_emulation.ExtractSharedMSVSSystemIncludes( configs, generator_flags ) cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles( toplevel_build, generator_flags, shared_system_includes, OpenOutput ) for arch, path in sorted(cl_paths.items()): if clang_cl: # If we have selected clang-cl, use that instead. path = clang_cl command = CommandWithWrapper( "CC", wrappers, QuoteShellArgument(path, "win") ) if clang_cl: # Use clang-cl to cross-compile for x86 or x86_64. command += " -m32" if arch == "x86" else " -m64" master_ninja.variable("cl_" + arch, command) cc = GetEnvironFallback(["CC_target", "CC"], cc) master_ninja.variable("cc", CommandWithWrapper("CC", wrappers, cc)) cxx = GetEnvironFallback(["CXX_target", "CXX"], cxx) master_ninja.variable("cxx", CommandWithWrapper("CXX", wrappers, cxx)) if flavor == "win": master_ninja.variable("ld", ld) master_ninja.variable("idl", "midl.exe") master_ninja.variable("ar", ar) master_ninja.variable("rc", "rc.exe") master_ninja.variable("ml_x86", "ml.exe") master_ninja.variable("ml_x64", "ml64.exe") master_ninja.variable("mt", "mt.exe") else: master_ninja.variable("ld", CommandWithWrapper("LINK", wrappers, ld)) master_ninja.variable("ldxx", CommandWithWrapper("LINK", wrappers, ldxx)) master_ninja.variable("ar", GetEnvironFallback(["AR_target", "AR"], ar)) if flavor != "mac": # Mac does not use readelf/nm for .TOC generation, so avoiding polluting # the master ninja with extra unused variables. master_ninja.variable("nm", GetEnvironFallback(["NM_target", "NM"], nm)) master_ninja.variable( "readelf", GetEnvironFallback(["READELF_target", "READELF"], readelf) ) if generator_supports_multiple_toolsets: if not cc_host: cc_host = cc if not cxx_host: cxx_host = cxx master_ninja.variable("ar_host", GetEnvironFallback(["AR_host"], ar_host)) master_ninja.variable("nm_host", GetEnvironFallback(["NM_host"], nm_host)) master_ninja.variable( "readelf_host", GetEnvironFallback(["READELF_host"], readelf_host) ) cc_host = GetEnvironFallback(["CC_host"], cc_host) cxx_host = GetEnvironFallback(["CXX_host"], cxx_host) # The environment variable could be used in 'make_global_settings', like # ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here. if "$(CC)" in cc_host and cc_host_global_setting: cc_host = cc_host_global_setting.replace("$(CC)", cc) if "$(CXX)" in cxx_host and cxx_host_global_setting: cxx_host = cxx_host_global_setting.replace("$(CXX)", cxx) master_ninja.variable( "cc_host", CommandWithWrapper("CC.host", wrappers, cc_host) ) master_ninja.variable( "cxx_host", CommandWithWrapper("CXX.host", wrappers, cxx_host) ) if flavor == "win": master_ninja.variable("ld_host", ld_host) else: master_ninja.variable( "ld_host", CommandWithWrapper("LINK", wrappers, ld_host) ) master_ninja.variable( "ldxx_host", CommandWithWrapper("LINK", wrappers, ldxx_host) ) master_ninja.newline() master_ninja.pool("link_pool", depth=GetDefaultConcurrentLinks()) master_ninja.newline() deps = "msvc" if flavor == "win" else "gcc" if flavor != "win": master_ninja.rule( "cc", description="CC $out", command=( "$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c " "$cflags_pch_c -c $in -o $out" ), depfile="$out.d", deps=deps, ) master_ninja.rule( "cc_s", description="CC $out", command=( "$cc $defines $includes $cflags $cflags_c " "$cflags_pch_c -c $in -o $out" ), ) master_ninja.rule( "cxx", description="CXX $out", command=( "$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc " "$cflags_pch_cc -c $in -o $out" ), depfile="$out.d", deps=deps, ) else: # TODO(scottmg) Separate pdb names is a test to see if it works around # http://crbug.com/142362. It seems there's a race between the creation of # the .pdb by the precompiled header step for .cc and the compilation of # .c files. This should be handled by mspdbsrv, but rarely errors out with # c1xx : fatal error C1033: cannot open program database # By making the rules target separate pdb files this might be avoided. cc_command = ( "ninja -t msvc -e $arch " + "-- " "$cc /nologo /showIncludes /FC " "@$out.rsp /c $in /Fo$out /Fd$pdbname_c " ) cxx_command = ( "ninja -t msvc -e $arch " + "-- " "$cxx /nologo /showIncludes /FC " "@$out.rsp /c $in /Fo$out /Fd$pdbname_cc " ) master_ninja.rule( "cc", description="CC $out", command=cc_command, rspfile="$out.rsp", rspfile_content="$defines $includes $cflags $cflags_c", deps=deps, ) master_ninja.rule( "cxx", description="CXX $out", command=cxx_command, rspfile="$out.rsp", rspfile_content="$defines $includes $cflags $cflags_cc", deps=deps, ) master_ninja.rule( "idl", description="IDL $in", command=( "%s gyp-win-tool midl-wrapper $arch $outdir " "$tlb $h $dlldata $iid $proxy $in " "$midl_includes $idlflags" % sys.executable ), ) master_ninja.rule( "rc", description="RC $in", # Note: $in must be last otherwise rc.exe complains. command=( "%s gyp-win-tool rc-wrapper " "$arch $rc $defines $resource_includes $rcflags /fo$out $in" % sys.executable ), ) master_ninja.rule( "asm", description="ASM $out", command=( "%s gyp-win-tool asm-wrapper " "$arch $asm $defines $includes $asmflags /c /Fo $out $in" % sys.executable ), ) if flavor not in ("ios", "mac", "win"): master_ninja.rule( "alink", description="AR $out", command="rm -f $out && $ar rcs $arflags $out $in", ) master_ninja.rule( "alink_thin", description="AR $out", command="rm -f $out && $ar rcsT $arflags $out $in", ) # This allows targets that only need to depend on $lib's API to declare an # order-only dependency on $lib.TOC and avoid relinking such downstream # dependencies when $lib changes only in non-public ways. # The resulting string leaves an uninterpolated %{suffix} which # is used in the final substitution below. mtime_preserving_solink_base = ( "if [ ! -e $lib -o ! -e $lib.TOC ]; then " "%(solink)s && %(extract_toc)s > $lib.TOC; else " "%(solink)s && %(extract_toc)s > $lib.tmp && " "if ! cmp -s $lib.tmp $lib.TOC; then mv $lib.tmp $lib.TOC ; " "fi; fi" % { "solink": "$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s", "extract_toc": ( "{ $readelf -d $lib | grep SONAME ; " "$nm -gD -f p $lib | cut -f1-2 -d' '; }" ), } ) master_ninja.rule( "solink", description="SOLINK $lib", restat=True, command=mtime_preserving_solink_base % {"suffix": "@$link_file_list"}, rspfile="$link_file_list", rspfile_content=( "-Wl,--whole-archive $in $solibs -Wl," "--no-whole-archive $libs" ), pool="link_pool", ) master_ninja.rule( "solink_module", description="SOLINK(module) $lib", restat=True, command=mtime_preserving_solink_base % {"suffix": "@$link_file_list"}, rspfile="$link_file_list", rspfile_content="-Wl,--start-group $in $solibs $libs -Wl,--end-group", pool="link_pool", ) master_ninja.rule( "link", description="LINK $out", command=( "$ld $ldflags -o $out " "-Wl,--start-group $in $solibs $libs -Wl,--end-group" ), pool="link_pool", ) elif flavor == "win": master_ninja.rule( "alink", description="LIB $out", command=( "%s gyp-win-tool link-wrapper $arch False " "$ar /nologo /ignore:4221 /OUT:$out @$out.rsp" % sys.executable ), rspfile="$out.rsp", rspfile_content="$in_newline $libflags", ) _AddWinLinkRules(master_ninja, embed_manifest=True) _AddWinLinkRules(master_ninja, embed_manifest=False) else: master_ninja.rule( "objc", description="OBJC $out", command=( "$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc " "$cflags_pch_objc -c $in -o $out" ), depfile="$out.d", deps=deps, ) master_ninja.rule( "objcxx", description="OBJCXX $out", command=( "$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc " "$cflags_pch_objcc -c $in -o $out" ), depfile="$out.d", deps=deps, ) master_ninja.rule( "alink", description="LIBTOOL-STATIC $out, POSTBUILDS", command="rm -f $out && " "./gyp-mac-tool filter-libtool libtool $libtool_flags " "-static -o $out $in" "$postbuilds", ) master_ninja.rule( "lipo", description="LIPO $out, POSTBUILDS", command="rm -f $out && lipo -create $in -output $out$postbuilds", ) master_ninja.rule( "solipo", description="SOLIPO $out, POSTBUILDS", command=( "rm -f $lib $lib.TOC && lipo -create $in -output $lib$postbuilds &&" "%(extract_toc)s > $lib.TOC" % { "extract_toc": "{ otool -l $lib | grep LC_ID_DYLIB -A 5; " "nm -gP $lib | cut -f1-2 -d' ' | grep -v U$$; true; }" } ), ) # Record the public interface of $lib in $lib.TOC. See the corresponding # comment in the posix section above for details. solink_base = "$ld %(type)s $ldflags -o $lib %(suffix)s" mtime_preserving_solink_base = ( "if [ ! -e $lib -o ! -e $lib.TOC ] || " # Always force dependent targets to relink if this library # reexports something. Handling this correctly would require # recursive TOC dumping but this is rare in practice, so punt. "otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then " "%(solink)s && %(extract_toc)s > $lib.TOC; " "else " "%(solink)s && %(extract_toc)s > $lib.tmp && " "if ! cmp -s $lib.tmp $lib.TOC; then " "mv $lib.tmp $lib.TOC ; " "fi; " "fi" % { "solink": solink_base, "extract_toc": "{ otool -l $lib | grep LC_ID_DYLIB -A 5; " "nm -gP $lib | cut -f1-2 -d' ' | grep -v U$$; true; }", } ) solink_suffix = "@$link_file_list$postbuilds" master_ninja.rule( "solink", description="SOLINK $lib, POSTBUILDS", restat=True, command=mtime_preserving_solink_base % {"suffix": solink_suffix, "type": "-shared"}, rspfile="$link_file_list", rspfile_content="$in $solibs $libs", pool="link_pool", ) master_ninja.rule( "solink_notoc", description="SOLINK $lib, POSTBUILDS", restat=True, command=solink_base % {"suffix": solink_suffix, "type": "-shared"}, rspfile="$link_file_list", rspfile_content="$in $solibs $libs", pool="link_pool", ) master_ninja.rule( "solink_module", description="SOLINK(module) $lib, POSTBUILDS", restat=True, command=mtime_preserving_solink_base % {"suffix": solink_suffix, "type": "-bundle"}, rspfile="$link_file_list", rspfile_content="$in $solibs $libs", pool="link_pool", ) master_ninja.rule( "solink_module_notoc", description="SOLINK(module) $lib, POSTBUILDS", restat=True, command=solink_base % {"suffix": solink_suffix, "type": "-bundle"}, rspfile="$link_file_list", rspfile_content="$in $solibs $libs", pool="link_pool", ) master_ninja.rule( "link", description="LINK $out, POSTBUILDS", command=("$ld $ldflags -o $out " "$in $solibs $libs$postbuilds"), pool="link_pool", ) master_ninja.rule( "preprocess_infoplist", description="PREPROCESS INFOPLIST $out", command=( "$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && " "plutil -convert xml1 $out $out" ), ) master_ninja.rule( "copy_infoplist", description="COPY INFOPLIST $in", command="$env ./gyp-mac-tool copy-info-plist $in $out $binary $keys", ) master_ninja.rule( "merge_infoplist", description="MERGE INFOPLISTS $in", command="$env ./gyp-mac-tool merge-info-plist $out $in", ) master_ninja.rule( "compile_xcassets", description="COMPILE XCASSETS $in", command="$env ./gyp-mac-tool compile-xcassets $keys $in", ) master_ninja.rule( "compile_ios_framework_headers", description="COMPILE HEADER MAPS AND COPY FRAMEWORK HEADERS $in", command="$env ./gyp-mac-tool compile-ios-framework-header-map $out " "$framework $in && $env ./gyp-mac-tool " "copy-ios-framework-headers $framework $copy_headers", ) master_ninja.rule( "mac_tool", description="MACTOOL $mactool_cmd $in", command="$env ./gyp-mac-tool $mactool_cmd $in $out $binary", ) master_ninja.rule( "package_framework", description="PACKAGE FRAMEWORK $out, POSTBUILDS", command="./gyp-mac-tool package-framework $out $version$postbuilds " "&& touch $out", ) master_ninja.rule( "package_ios_framework", description="PACKAGE IOS FRAMEWORK $out, POSTBUILDS", command="./gyp-mac-tool package-ios-framework $out $postbuilds " "&& touch $out", ) if flavor == "win": master_ninja.rule( "stamp", description="STAMP $out", command="%s gyp-win-tool stamp $out" % sys.executable, ) else: master_ninja.rule( "stamp", description="STAMP $out", command="${postbuilds}touch $out" ) if flavor == "win": master_ninja.rule( "copy", description="COPY $in $out", command="%s gyp-win-tool recursive-mirror $in $out" % sys.executable, ) elif flavor == "zos": master_ninja.rule( "copy", description="COPY $in $out", command="rm -rf $out && cp -fRP $in $out", ) else: master_ninja.rule( "copy", description="COPY $in $out", command="ln -f $in $out 2>/dev/null || (rm -rf $out && cp -af $in $out)", ) master_ninja.newline() all_targets = set() for build_file in params["build_files"]: for target in gyp.common.AllTargets( target_list, target_dicts, os.path.normpath(build_file) ): all_targets.add(target) all_outputs = set() # target_outputs is a map from qualified target name to a Target object. target_outputs = {} # target_short_names is a map from target short name to a list of Target # objects. target_short_names = {} # short name of targets that were skipped because they didn't contain anything # interesting. # NOTE: there may be overlap between this an non_empty_target_names. empty_target_names = set() # Set of non-empty short target names. # NOTE: there may be overlap between this an empty_target_names. non_empty_target_names = set() for qualified_target in target_list: # qualified_target is like: third_party/icu/icu.gyp:icui18n#target build_file, name, toolset = gyp.common.ParseQualifiedTarget(qualified_target) this_make_global_settings = data[build_file].get("make_global_settings", []) assert make_global_settings == this_make_global_settings, ( "make_global_settings needs to be the same for all targets. " f"{this_make_global_settings} vs. {make_global_settings}" ) spec = target_dicts[qualified_target] if flavor == "mac": gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) # If build_file is a symlink, we must not follow it because there's a chance # it could point to a path above toplevel_dir, and we cannot correctly deal # with that case at the moment. build_file = gyp.common.RelativePath(build_file, options.toplevel_dir, False) qualified_target_for_hash = gyp.common.QualifiedTarget( build_file, name, toolset ) qualified_target_for_hash = qualified_target_for_hash.encode("utf-8") hash_for_rules = hashlib.md5(qualified_target_for_hash).hexdigest() base_path = os.path.dirname(build_file) obj = "obj" if toolset != "target": obj += "." + toolset output_file = os.path.join(obj, base_path, name + ".ninja") ninja_output = StringIO() writer = NinjaWriter( hash_for_rules, target_outputs, base_path, build_dir, ninja_output, toplevel_build, output_file, flavor, toplevel_dir=options.toplevel_dir, ) target = writer.WriteSpec(spec, config_name, generator_flags) if ninja_output.tell() > 0: # Only create files for ninja files that actually have contents. with OpenOutput(os.path.join(toplevel_build, output_file)) as ninja_file: ninja_file.write(ninja_output.getvalue()) ninja_output.close() master_ninja.subninja(output_file) if target: if name != target.FinalOutput() and spec["toolset"] == "target": target_short_names.setdefault(name, []).append(target) target_outputs[qualified_target] = target if qualified_target in all_targets: all_outputs.add(target.FinalOutput()) non_empty_target_names.add(name) else: empty_target_names.add(name) if target_short_names: # Write a short name to build this target. This benefits both the # "build chrome" case as well as the gyp tests, which expect to be # able to run actions and build libraries by their short name. master_ninja.newline() master_ninja.comment("Short names for targets.") for short_name in sorted(target_short_names): master_ninja.build( short_name, "phony", [x.FinalOutput() for x in target_short_names[short_name]], ) # Write phony targets for any empty targets that weren't written yet. As # short names are not necessarily unique only do this for short names that # haven't already been output for another target. empty_target_names = empty_target_names - non_empty_target_names if empty_target_names: master_ninja.newline() master_ninja.comment("Empty targets (output for completeness).") for name in sorted(empty_target_names): master_ninja.build(name, "phony") if all_outputs: master_ninja.newline() master_ninja.build("all", "phony", sorted(all_outputs)) master_ninja.default(generator_flags.get("default_target", "all")) master_ninja_file.close() if generate_compile_commands: compile_db = GenerateCompileDBWithNinja(toplevel_build) compile_db_file = OpenOutput( os.path.join(toplevel_build, "compile_commands.json") ) compile_db_file.write(json.dumps(compile_db, indent=2)) compile_db_file.close() def GenerateCompileDBWithNinja(path, targets=["all"]): """Generates a compile database using ninja. Args: path: The build directory to generate a compile database for. targets: Additional targets to pass to ninja. Returns: List of the contents of the compile database. """ ninja_path = shutil.which("ninja") if ninja_path is None: raise Exception("ninja not found in PATH") json_compile_db = subprocess.check_output( [ninja_path, "-C", path] + targets + ["-t", "compdb", "cc", "cxx", "objc", "objcxx"] ) return json.loads(json_compile_db) def PerformBuild(data, configurations, params): options = params["options"] for config in configurations: builddir = os.path.join(options.toplevel_dir, "out", config) arguments = ["ninja", "-C", builddir] print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) (target_list, target_dicts, data, params, config_name) = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): # Update target_dicts for iOS device builds. target_dicts = gyp.xcode_emulation.CloneConfigurationForDeviceAndEmulator( target_dicts ) user_config = params.get("generator_flags", {}).get("config", None) if gyp.common.GetFlavor(params) == "win": target_list, target_dicts = MSVSUtil.ShardTargets(target_list, target_dicts) target_list, target_dicts = MSVSUtil.InsertLargePdbShims( target_list, target_dicts, generator_default_variables ) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]["configurations"] if params["parallel"]: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append( (target_list, target_dicts, data, params, config_name) ) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt as e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig( target_list, target_dicts, data, params, config_name ) #!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Unit tests for the ninja.py file. """ from pathlib import Path import sys import unittest import gyp.generator.ninja as ninja class TestPrefixesAndSuffixes(unittest.TestCase): def test_BinaryNamesWindows(self): # These cannot run on non-Windows as they require a VS installation to # correctly handle variable expansion. if sys.platform.startswith("win"): writer = ninja.NinjaWriter( "foo", "wee", ".", ".", "build.ninja", ".", "build.ninja", "win" ) spec = {"target_name": "wee"} self.assertTrue( writer.ComputeOutputFileName(spec, "executable").endswith(".exe") ) self.assertTrue( writer.ComputeOutputFileName(spec, "shared_library").endswith(".dll") ) self.assertTrue( writer.ComputeOutputFileName(spec, "static_library").endswith(".lib") ) def test_BinaryNamesLinux(self): writer = ninja.NinjaWriter( "foo", "wee", ".", ".", "build.ninja", ".", "build.ninja", "linux" ) spec = {"target_name": "wee"} self.assertTrue("." not in writer.ComputeOutputFileName(spec, "executable")) self.assertTrue( writer.ComputeOutputFileName(spec, "shared_library").startswith("lib") ) self.assertTrue( writer.ComputeOutputFileName(spec, "static_library").startswith("lib") ) self.assertTrue( writer.ComputeOutputFileName(spec, "shared_library").endswith(".so") ) self.assertTrue( writer.ComputeOutputFileName(spec, "static_library").endswith(".a") ) def test_GenerateCompileDBWithNinja(self): build_dir = ( Path(__file__).resolve().parent.parent.parent.parent / "data" / "ninja" ) compile_db = ninja.GenerateCompileDBWithNinja(build_dir) assert len(compile_db) == 1 assert compile_db[0]["directory"] == str(build_dir) assert compile_db[0]["command"] == "cc my.in my.out" assert compile_db[0]["file"] == "my.in" assert compile_db[0]["output"] == "my.out" if __name__ == "__main__": unittest.main() # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import filecmp import gyp.common import gyp.xcodeproj_file import gyp.xcode_ninja import errno import os import sys import posixpath import re import shutil import subprocess import tempfile # Project files generated by this module will use _intermediate_var as a # custom Xcode setting whose value is a DerivedSources-like directory that's # project-specific and configuration-specific. The normal choice, # DERIVED_FILE_DIR, is target-specific, which is thought to be too restrictive # as it is likely that multiple targets within a single project file will want # to access the same set of generated files. The other option, # PROJECT_DERIVED_FILE_DIR, is unsuitable because while it is project-specific, # it is not configuration-specific. INTERMEDIATE_DIR is defined as # $(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION). _intermediate_var = "INTERMEDIATE_DIR" # SHARED_INTERMEDIATE_DIR is the same, except that it is shared among all # targets that share the same BUILT_PRODUCTS_DIR. _shared_intermediate_var = "SHARED_INTERMEDIATE_DIR" _library_search_paths_var = "LIBRARY_SEARCH_PATHS" generator_default_variables = { "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "STATIC_LIB_PREFIX": "lib", "SHARED_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", "SHARED_LIB_SUFFIX": ".dylib", # INTERMEDIATE_DIR is a place for targets to build up intermediate products. # It is specific to each build environment. It is only guaranteed to exist # and be constant within the context of a project, corresponding to a single # input file. Some build environments may allow their intermediate directory # to be shared on a wider scale, but this is not guaranteed. "INTERMEDIATE_DIR": "$(%s)" % _intermediate_var, "OS": "mac", "PRODUCT_DIR": "$(BUILT_PRODUCTS_DIR)", "LIB_DIR": "$(BUILT_PRODUCTS_DIR)", "RULE_INPUT_ROOT": "$(INPUT_FILE_BASE)", "RULE_INPUT_EXT": "$(INPUT_FILE_SUFFIX)", "RULE_INPUT_NAME": "$(INPUT_FILE_NAME)", "RULE_INPUT_PATH": "$(INPUT_FILE_PATH)", "RULE_INPUT_DIRNAME": "$(INPUT_FILE_DIRNAME)", "SHARED_INTERMEDIATE_DIR": "$(%s)" % _shared_intermediate_var, "CONFIGURATION_NAME": "$(CONFIGURATION)", } # The Xcode-specific sections that hold paths. generator_additional_path_sections = [ "mac_bundle_resources", "mac_framework_headers", "mac_framework_private_headers", # 'mac_framework_dirs', input already handles _dirs endings. ] # The Xcode-specific keys that exist on targets and aren't moved down to # configurations. generator_additional_non_configuration_keys = [ "ios_app_extension", "ios_watch_app", "ios_watchkit_extension", "mac_bundle", "mac_bundle_resources", "mac_framework_headers", "mac_framework_private_headers", "mac_xctest_bundle", "mac_xcuitest_bundle", "xcode_create_dependents_test_runner", ] # We want to let any rules apply to files that are resources also. generator_extra_sources_for_rules = [ "mac_bundle_resources", "mac_framework_headers", "mac_framework_private_headers", ] generator_filelist_paths = None # Xcode's standard set of library directories, which don't need to be duplicated # in LIBRARY_SEARCH_PATHS. This list is not exhaustive, but that's okay. xcode_standard_library_dirs = frozenset( ["$(SDKROOT)/usr/lib", "$(SDKROOT)/usr/local/lib"] ) def CreateXCConfigurationList(configuration_names): xccl = gyp.xcodeproj_file.XCConfigurationList({"buildConfigurations": []}) if len(configuration_names) == 0: configuration_names = ["Default"] for configuration_name in configuration_names: xcbc = gyp.xcodeproj_file.XCBuildConfiguration({"name": configuration_name}) xccl.AppendProperty("buildConfigurations", xcbc) xccl.SetProperty("defaultConfigurationName", configuration_names[0]) return xccl class XcodeProject: def __init__(self, gyp_path, path, build_file_dict): self.gyp_path = gyp_path self.path = path self.project = gyp.xcodeproj_file.PBXProject(path=path) projectDirPath = gyp.common.RelativePath( os.path.dirname(os.path.abspath(self.gyp_path)), os.path.dirname(path) or ".", ) self.project.SetProperty("projectDirPath", projectDirPath) self.project_file = gyp.xcodeproj_file.XCProjectFile( {"rootObject": self.project} ) self.build_file_dict = build_file_dict # TODO(mark): add destructor that cleans up self.path if created_dir is # True and things didn't complete successfully. Or do something even # better with "try"? self.created_dir = False try: os.makedirs(self.path) self.created_dir = True except OSError as e: if e.errno != errno.EEXIST: raise def Finalize1(self, xcode_targets, serialize_all_tests): # Collect a list of all of the build configuration names used by the # various targets in the file. It is very heavily advised to keep each # target in an entire project (even across multiple project files) using # the same set of configuration names. configurations = [] for xct in self.project.GetProperty("targets"): xccl = xct.GetProperty("buildConfigurationList") xcbcs = xccl.GetProperty("buildConfigurations") for xcbc in xcbcs: name = xcbc.GetProperty("name") if name not in configurations: configurations.append(name) # Replace the XCConfigurationList attached to the PBXProject object with # a new one specifying all of the configuration names used by the various # targets. try: xccl = CreateXCConfigurationList(configurations) self.project.SetProperty("buildConfigurationList", xccl) except Exception: sys.stderr.write("Problem with gyp file %s\n" % self.gyp_path) raise # The need for this setting is explained above where _intermediate_var is # defined. The comments below about wanting to avoid project-wide build # settings apply here too, but this needs to be set on a project-wide basis # so that files relative to the _intermediate_var setting can be displayed # properly in the Xcode UI. # # Note that for configuration-relative files such as anything relative to # _intermediate_var, for the purposes of UI tree view display, Xcode will # only resolve the configuration name once, when the project file is # opened. If the active build configuration is changed, the project file # must be closed and reopened if it is desired for the tree view to update. # This is filed as Apple radar 6588391. xccl.SetBuildSetting( _intermediate_var, "$(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION)" ) xccl.SetBuildSetting( _shared_intermediate_var, "$(SYMROOT)/DerivedSources/$(CONFIGURATION)" ) # Set user-specified project-wide build settings and config files. This # is intended to be used very sparingly. Really, almost everything should # go into target-specific build settings sections. The project-wide # settings are only intended to be used in cases where Xcode attempts to # resolve variable references in a project context as opposed to a target # context, such as when resolving sourceTree references while building up # the tree tree view for UI display. # Any values set globally are applied to all configurations, then any # per-configuration values are applied. for xck, xcv in self.build_file_dict.get("xcode_settings", {}).items(): xccl.SetBuildSetting(xck, xcv) if "xcode_config_file" in self.build_file_dict: config_ref = self.project.AddOrGetFileInRootGroup( self.build_file_dict["xcode_config_file"] ) xccl.SetBaseConfiguration(config_ref) build_file_configurations = self.build_file_dict.get("configurations", {}) if build_file_configurations: for config_name in configurations: build_file_configuration_named = build_file_configurations.get( config_name, {} ) if build_file_configuration_named: xcc = xccl.ConfigurationNamed(config_name) for xck, xcv in build_file_configuration_named.get( "xcode_settings", {} ).items(): xcc.SetBuildSetting(xck, xcv) if "xcode_config_file" in build_file_configuration_named: config_ref = self.project.AddOrGetFileInRootGroup( build_file_configurations[config_name]["xcode_config_file"] ) xcc.SetBaseConfiguration(config_ref) # Sort the targets based on how they appeared in the input. # TODO(mark): Like a lot of other things here, this assumes internal # knowledge of PBXProject - in this case, of its "targets" property. # ordinary_targets are ordinary targets that are already in the project # file. run_test_targets are the targets that run unittests and should be # used for the Run All Tests target. support_targets are the action/rule # targets used by GYP file targets, just kept for the assert check. ordinary_targets = [] run_test_targets = [] support_targets = [] # targets is full list of targets in the project. targets = [] # does the it define it's own "all"? has_custom_all = False # targets_for_all is the list of ordinary_targets that should be listed # in this project's "All" target. It includes each non_runtest_target # that does not have suppress_wildcard set. targets_for_all = [] for target in self.build_file_dict["targets"]: target_name = target["target_name"] toolset = target["toolset"] qualified_target = gyp.common.QualifiedTarget( self.gyp_path, target_name, toolset ) xcode_target = xcode_targets[qualified_target] # Make sure that the target being added to the sorted list is already in # the unsorted list. assert xcode_target in self.project._properties["targets"] targets.append(xcode_target) ordinary_targets.append(xcode_target) if xcode_target.support_target: support_targets.append(xcode_target.support_target) targets.append(xcode_target.support_target) if not int(target.get("suppress_wildcard", False)): targets_for_all.append(xcode_target) if target_name.lower() == "all": has_custom_all = True # If this target has a 'run_as' attribute, add its target to the # targets, and add it to the test targets. if target.get("run_as"): # Make a target to run something. It should have one # dependency, the parent xcode target. xccl = CreateXCConfigurationList(configurations) run_target = gyp.xcodeproj_file.PBXAggregateTarget( { "name": "Run " + target_name, "productName": xcode_target.GetProperty("productName"), "buildConfigurationList": xccl, }, parent=self.project, ) run_target.AddDependency(xcode_target) command = target["run_as"] script = "" if command.get("working_directory"): script = ( script + 'cd "%s"\n' % gyp.xcodeproj_file.ConvertVariablesToShellSyntax( command.get("working_directory") ) ) if command.get("environment"): script = ( script + "\n".join( [ 'export %s="%s"' % ( key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax( val ), ) for (key, val) in command.get("environment").items() ] ) + "\n" ) # Some test end up using sockets, files on disk, etc. and can get # confused if more then one test runs at a time. The generator # flag 'xcode_serialize_all_test_runs' controls the forcing of all # tests serially. It defaults to True. To get serial runs this # little bit of python does the same as the linux flock utility to # make sure only one runs at a time. command_prefix = "" if serialize_all_tests: command_prefix = """python -c "import fcntl, subprocess, sys file = open('$TMPDIR/GYP_serialize_test_runs', 'a') fcntl.flock(file.fileno(), fcntl.LOCK_EX) sys.exit(subprocess.call(sys.argv[1:]))" """ # If we were unable to exec for some reason, we want to exit # with an error, and fixup variable references to be shell # syntax instead of xcode syntax. script = ( script + "exec " + command_prefix + "%s\nexit 1\n" % gyp.xcodeproj_file.ConvertVariablesToShellSyntax( gyp.common.EncodePOSIXShellList(command.get("action")) ) ) ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase( {"shellScript": script, "showEnvVarsInLog": 0} ) run_target.AppendProperty("buildPhases", ssbp) # Add the run target to the project file. targets.append(run_target) run_test_targets.append(run_target) xcode_target.test_runner = run_target # Make sure that the list of targets being replaced is the same length as # the one replacing it, but allow for the added test runner targets. assert len(self.project._properties["targets"]) == len(ordinary_targets) + len( support_targets ) self.project._properties["targets"] = targets # Get rid of unnecessary levels of depth in groups like the Source group. self.project.RootGroupsTakeOverOnlyChildren(True) # Sort the groups nicely. Do this after sorting the targets, because the # Products group is sorted based on the order of the targets. self.project.SortGroups() # Create an "All" target if there's more than one target in this project # file and the project didn't define its own "All" target. Put a generated # "All" target first so that people opening up the project for the first # time will build everything by default. if len(targets_for_all) > 1 and not has_custom_all: xccl = CreateXCConfigurationList(configurations) all_target = gyp.xcodeproj_file.PBXAggregateTarget( {"buildConfigurationList": xccl, "name": "All"}, parent=self.project ) for target in targets_for_all: all_target.AddDependency(target) # TODO(mark): This is evil because it relies on internal knowledge of # PBXProject._properties. It's important to get the "All" target first, # though. self.project._properties["targets"].insert(0, all_target) # The same, but for run_test_targets. if len(run_test_targets) > 1: xccl = CreateXCConfigurationList(configurations) run_all_tests_target = gyp.xcodeproj_file.PBXAggregateTarget( {"buildConfigurationList": xccl, "name": "Run All Tests"}, parent=self.project, ) for run_test_target in run_test_targets: run_all_tests_target.AddDependency(run_test_target) # Insert after the "All" target, which must exist if there is more than # one run_test_target. self.project._properties["targets"].insert(1, run_all_tests_target) def Finalize2(self, xcode_targets, xcode_target_to_target_dict): # Finalize2 needs to happen in a separate step because the process of # updating references to other projects depends on the ordering of targets # within remote project files. Finalize1 is responsible for sorting duty, # and once all project files are sorted, Finalize2 can come in and update # these references. # To support making a "test runner" target that will run all the tests # that are direct dependents of any given target, we look for # xcode_create_dependents_test_runner being set on an Aggregate target, # and generate a second target that will run the tests runners found under # the marked target. for bf_tgt in self.build_file_dict["targets"]: if int(bf_tgt.get("xcode_create_dependents_test_runner", 0)): tgt_name = bf_tgt["target_name"] toolset = bf_tgt["toolset"] qualified_target = gyp.common.QualifiedTarget( self.gyp_path, tgt_name, toolset ) xcode_target = xcode_targets[qualified_target] if isinstance(xcode_target, gyp.xcodeproj_file.PBXAggregateTarget): # Collect all the run test targets. all_run_tests = [] pbxtds = xcode_target.GetProperty("dependencies") for pbxtd in pbxtds: pbxcip = pbxtd.GetProperty("targetProxy") dependency_xct = pbxcip.GetProperty("remoteGlobalIDString") if hasattr(dependency_xct, "test_runner"): all_run_tests.append(dependency_xct.test_runner) # Directly depend on all the runners as they depend on the target # that builds them. if len(all_run_tests) > 0: run_all_target = gyp.xcodeproj_file.PBXAggregateTarget( { "name": "Run %s Tests" % tgt_name, "productName": tgt_name, }, parent=self.project, ) for run_test_target in all_run_tests: run_all_target.AddDependency(run_test_target) # Insert the test runner after the related target. idx = self.project._properties["targets"].index(xcode_target) self.project._properties["targets"].insert( idx + 1, run_all_target ) # Update all references to other projects, to make sure that the lists of # remote products are complete. Otherwise, Xcode will fill them in when # it opens the project file, which will result in unnecessary diffs. # TODO(mark): This is evil because it relies on internal knowledge of # PBXProject._other_pbxprojects. for other_pbxproject in self.project._other_pbxprojects: self.project.AddOrGetProjectReference(other_pbxproject) self.project.SortRemoteProductReferences() # Give everything an ID. self.project_file.ComputeIDs() # Make sure that no two objects in the project file have the same ID. If # multiple objects wind up with the same ID, upon loading the file, Xcode # will only recognize one object (the last one in the file?) and the # results are unpredictable. self.project_file.EnsureNoIDCollisions() def Write(self): # Write the project file to a temporary location first. Xcode watches for # changes to the project file and presents a UI sheet offering to reload # the project when it does change. However, in some cases, especially when # multiple projects are open or when Xcode is busy, things don't work so # seamlessly. Sometimes, Xcode is able to detect that a project file has # changed but can't unload it because something else is referencing it. # To mitigate this problem, and to avoid even having Xcode present the UI # sheet when an open project is rewritten for inconsequential changes, the # project file is written to a temporary file in the xcodeproj directory # first. The new temporary file is then compared to the existing project # file, if any. If they differ, the new file replaces the old; otherwise, # the new project file is simply deleted. Xcode properly detects a file # being renamed over an open project file as a change and so it remains # able to present the "project file changed" sheet under this system. # Writing to a temporary file first also avoids the possible problem of # Xcode rereading an incomplete project file. (output_fd, new_pbxproj_path) = tempfile.mkstemp( suffix=".tmp", prefix="project.pbxproj.gyp.", dir=self.path ) try: output_file = os.fdopen(output_fd, "w") self.project_file.Print(output_file) output_file.close() pbxproj_path = os.path.join(self.path, "project.pbxproj") same = False try: same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False) except OSError as e: if e.errno != errno.ENOENT: raise if same: # The new file is identical to the old one, just get rid of the new # one. os.unlink(new_pbxproj_path) else: # The new file is different from the old one, or there is no old one. # Rename the new file to the permanent name. # # tempfile.mkstemp uses an overly restrictive mode, resulting in a # file that can only be read by the owner, regardless of the umask. # There's no reason to not respect the umask here, which means that # an extra hoop is required to fetch it and reset the new file's mode. # # No way to get the umask without setting a new one? Set a safe one # and then set it back to the old value. umask = os.umask(0o77) os.umask(umask) os.chmod(new_pbxproj_path, 0o666 & ~umask) os.rename(new_pbxproj_path, pbxproj_path) except Exception: # Don't leave turds behind. In fact, if this code was responsible for # creating the xcodeproj directory, get rid of that too. os.unlink(new_pbxproj_path) if self.created_dir: shutil.rmtree(self.path, True) raise def AddSourceToTarget(source, type, pbxp, xct): # TODO(mark): Perhaps source_extensions and library_extensions can be made a # little bit fancier. source_extensions = ["c", "cc", "cpp", "cxx", "m", "mm", "s", "swift"] # .o is conceptually more of a "source" than a "library," but Xcode thinks # of "sources" as things to compile and "libraries" (or "frameworks") as # things to link with. Adding an object file to an Xcode target's frameworks # phase works properly. library_extensions = ["a", "dylib", "framework", "o"] basename = posixpath.basename(source) (root, ext) = posixpath.splitext(basename) if ext: ext = ext[1:].lower() if ext in source_extensions and type != "none": xct.SourcesPhase().AddFile(source) elif ext in library_extensions and type != "none": xct.FrameworksPhase().AddFile(source) else: # Files that aren't added to a sources or frameworks build phase can still # go into the project file, just not as part of a build phase. pbxp.AddOrGetFileInRootGroup(source) def AddResourceToTarget(resource, pbxp, xct): # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call # where it's used. xct.ResourcesPhase().AddFile(resource) def AddHeaderToTarget(header, pbxp, xct, is_public): # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call # where it's used. settings = "{ATTRIBUTES = (%s, ); }" % ("Private", "Public")[is_public] xct.HeadersPhase().AddFile(header, settings) _xcode_variable_re = re.compile(r"(\$\((.*?)\))") def ExpandXcodeVariables(string, expansions): """Expands Xcode-style $(VARIABLES) in string per the expansions dict. In some rare cases, it is appropriate to expand Xcode variables when a project file is generated. For any substring $(VAR) in string, if VAR is a key in the expansions dict, $(VAR) will be replaced with expansions[VAR]. Any $(VAR) substring in string for which VAR is not a key in the expansions dict will remain in the returned string. """ matches = _xcode_variable_re.findall(string) if matches is None: return string matches.reverse() for match in matches: (to_replace, variable) = match if variable not in expansions: continue replacement = expansions[variable] string = re.sub(re.escape(to_replace), replacement, string) return string _xcode_define_re = re.compile(r"([\\\"\' ])") def EscapeXcodeDefine(s): """We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly interpret variables especially $(inherited).""" return re.sub(_xcode_define_re, r"\\\1", s) def PerformBuild(data, configurations, params): options = params["options"] for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != ".gyp": continue xcodeproj_path = build_file_root + options.suffix + ".xcodeproj" if options.generator_output: xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path) for config in configurations: arguments = ["xcodebuild", "-project", xcodeproj_path] arguments += ["-configuration", config] print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) def CalculateGeneratorInputInfo(params): toplevel = params["options"].toplevel_dir if params.get("flavor") == "ninja": generator_dir = os.path.relpath(params["options"].generator_output or ".") output_dir = params.get("generator_flags", {}).get("output_dir", "out") output_dir = os.path.normpath(os.path.join(generator_dir, output_dir)) qualified_out_dir = os.path.normpath( os.path.join(toplevel, output_dir, "gypfiles-xcode-ninja") ) else: output_dir = os.path.normpath(os.path.join(toplevel, "xcodebuild")) qualified_out_dir = os.path.normpath( os.path.join(toplevel, output_dir, "gypfiles") ) global generator_filelist_paths generator_filelist_paths = { "toplevel": toplevel, "qualified_out_dir": qualified_out_dir, } def GenerateOutput(target_list, target_dicts, data, params): # Optionally configure each spec to use ninja as the external builder. ninja_wrapper = params.get("flavor") == "ninja" if ninja_wrapper: (target_list, target_dicts, data) = gyp.xcode_ninja.CreateWrapper( target_list, target_dicts, data, params ) options = params["options"] generator_flags = params.get("generator_flags", {}) parallel_builds = generator_flags.get("xcode_parallel_builds", True) serialize_all_tests = generator_flags.get("xcode_serialize_all_test_runs", True) upgrade_check_project_version = generator_flags.get( "xcode_upgrade_check_project_version", None ) # Format upgrade_check_project_version with leading zeros as needed. if upgrade_check_project_version: upgrade_check_project_version = str(upgrade_check_project_version) while len(upgrade_check_project_version) < 4: upgrade_check_project_version = "0" + upgrade_check_project_version skip_excluded_files = not generator_flags.get("xcode_list_excluded_files", True) xcode_projects = {} for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != ".gyp": continue xcodeproj_path = build_file_root + options.suffix + ".xcodeproj" if options.generator_output: xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path) xcp = XcodeProject(build_file, xcodeproj_path, build_file_dict) xcode_projects[build_file] = xcp pbxp = xcp.project # Set project-level attributes from multiple options project_attributes = {} if parallel_builds: project_attributes["BuildIndependentTargetsInParallel"] = "YES" if upgrade_check_project_version: project_attributes["LastUpgradeCheck"] = upgrade_check_project_version project_attributes[ "LastTestingUpgradeCheck" ] = upgrade_check_project_version project_attributes["LastSwiftUpdateCheck"] = upgrade_check_project_version pbxp.SetProperty("attributes", project_attributes) # Add gyp/gypi files to project if not generator_flags.get("standalone"): main_group = pbxp.GetProperty("mainGroup") build_group = gyp.xcodeproj_file.PBXGroup({"name": "Build"}) main_group.AppendChild(build_group) for included_file in build_file_dict["included_files"]: build_group.AddOrGetFileByPath(included_file, False) xcode_targets = {} xcode_target_to_target_dict = {} for qualified_target in target_list: [build_file, target_name, toolset] = gyp.common.ParseQualifiedTarget( qualified_target ) spec = target_dicts[qualified_target] if spec["toolset"] != "target": raise Exception( "Multiple toolsets not supported in xcode build (target %s)" % qualified_target ) configuration_names = [spec["default_configuration"]] for configuration_name in sorted(spec["configurations"].keys()): if configuration_name not in configuration_names: configuration_names.append(configuration_name) xcp = xcode_projects[build_file] pbxp = xcp.project # Set up the configurations for the target according to the list of names # supplied. xccl = CreateXCConfigurationList(configuration_names) # Create an XCTarget subclass object for the target. The type with # "+bundle" appended will be used if the target has "mac_bundle" set. # loadable_modules not in a mac_bundle are mapped to # com.googlecode.gyp.xcode.bundle, a pseudo-type that xcode.py interprets # to create a single-file mh_bundle. _types = { "executable": "com.apple.product-type.tool", "loadable_module": "com.googlecode.gyp.xcode.bundle", "shared_library": "com.apple.product-type.library.dynamic", "static_library": "com.apple.product-type.library.static", "mac_kernel_extension": "com.apple.product-type.kernel-extension", "executable+bundle": "com.apple.product-type.application", "loadable_module+bundle": "com.apple.product-type.bundle", "loadable_module+xctest": "com.apple.product-type.bundle.unit-test", "loadable_module+xcuitest": "com.apple.product-type.bundle.ui-testing", "shared_library+bundle": "com.apple.product-type.framework", "executable+extension+bundle": "com.apple.product-type.app-extension", "executable+watch+extension+bundle": "com.apple.product-type.watchkit-extension", "executable+watch+bundle": "com.apple.product-type.application.watchapp", "mac_kernel_extension+bundle": "com.apple.product-type.kernel-extension", } target_properties = { "buildConfigurationList": xccl, "name": target_name, } type = spec["type"] is_xctest = int(spec.get("mac_xctest_bundle", 0)) is_xcuitest = int(spec.get("mac_xcuitest_bundle", 0)) is_bundle = int(spec.get("mac_bundle", 0)) or is_xctest is_app_extension = int(spec.get("ios_app_extension", 0)) is_watchkit_extension = int(spec.get("ios_watchkit_extension", 0)) is_watch_app = int(spec.get("ios_watch_app", 0)) if type != "none": type_bundle_key = type if is_xcuitest: type_bundle_key += "+xcuitest" assert type == "loadable_module", ( "mac_xcuitest_bundle targets must have type loadable_module " "(target %s)" % target_name ) elif is_xctest: type_bundle_key += "+xctest" assert type == "loadable_module", ( "mac_xctest_bundle targets must have type loadable_module " "(target %s)" % target_name ) elif is_app_extension: assert is_bundle, ( "ios_app_extension flag requires mac_bundle " "(target %s)" % target_name ) type_bundle_key += "+extension+bundle" elif is_watchkit_extension: assert is_bundle, ( "ios_watchkit_extension flag requires mac_bundle " "(target %s)" % target_name ) type_bundle_key += "+watch+extension+bundle" elif is_watch_app: assert is_bundle, ( "ios_watch_app flag requires mac_bundle " "(target %s)" % target_name ) type_bundle_key += "+watch+bundle" elif is_bundle: type_bundle_key += "+bundle" xctarget_type = gyp.xcodeproj_file.PBXNativeTarget try: target_properties["productType"] = _types[type_bundle_key] except KeyError as e: gyp.common.ExceptionAppend( e, "-- unknown product type while " "writing target %s" % target_name, ) raise else: xctarget_type = gyp.xcodeproj_file.PBXAggregateTarget assert not is_bundle, ( 'mac_bundle targets cannot have type none (target "%s")' % target_name ) assert not is_xcuitest, ( 'mac_xcuitest_bundle targets cannot have type none (target "%s")' % target_name ) assert not is_xctest, ( 'mac_xctest_bundle targets cannot have type none (target "%s")' % target_name ) target_product_name = spec.get("product_name") if target_product_name is not None: target_properties["productName"] = target_product_name xct = xctarget_type( target_properties, parent=pbxp, force_outdir=spec.get("product_dir"), force_prefix=spec.get("product_prefix"), force_extension=spec.get("product_extension"), ) pbxp.AppendProperty("targets", xct) xcode_targets[qualified_target] = xct xcode_target_to_target_dict[xct] = spec spec_actions = spec.get("actions", []) spec_rules = spec.get("rules", []) # Xcode has some "issues" with checking dependencies for the "Compile # sources" step with any source files/headers generated by actions/rules. # To work around this, if a target is building anything directly (not # type "none"), then a second target is used to run the GYP actions/rules # and is made a dependency of this target. This way the work is done # before the dependency checks for what should be recompiled. support_xct = None # The Xcode "issues" don't affect xcode-ninja builds, since the dependency # logic all happens in ninja. Don't bother creating the extra targets in # that case. if type != "none" and (spec_actions or spec_rules) and not ninja_wrapper: support_xccl = CreateXCConfigurationList(configuration_names) support_target_suffix = generator_flags.get( "support_target_suffix", " Support" ) support_target_properties = { "buildConfigurationList": support_xccl, "name": target_name + support_target_suffix, } if target_product_name: support_target_properties["productName"] = ( target_product_name + " Support" ) support_xct = gyp.xcodeproj_file.PBXAggregateTarget( support_target_properties, parent=pbxp ) pbxp.AppendProperty("targets", support_xct) xct.AddDependency(support_xct) # Hang the support target off the main target so it can be tested/found # by the generator during Finalize. xct.support_target = support_xct prebuild_index = 0 # Add custom shell script phases for "actions" sections. for action in spec_actions: # There's no need to write anything into the script to ensure that the # output directories already exist, because Xcode will look at the # declared outputs and automatically ensure that they exist for us. # Do we have a message to print when this action runs? message = action.get("message") if message: message = "echo note: " + gyp.common.EncodePOSIXShellArgument(message) else: message = "" # Turn the list into a string that can be passed to a shell. action_string = gyp.common.EncodePOSIXShellList(action["action"]) # Convert Xcode-type variable references to sh-compatible environment # variable references. message_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(message) action_string_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax( action_string ) script = "" # Include the optional message if message_sh: script += message_sh + "\n" # Be sure the script runs in exec, and that if exec fails, the script # exits signalling an error. script += "exec " + action_string_sh + "\nexit 1\n" ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase( { "inputPaths": action["inputs"], "name": 'Action "' + action["action_name"] + '"', "outputPaths": action["outputs"], "shellScript": script, "showEnvVarsInLog": 0, } ) if support_xct: support_xct.AppendProperty("buildPhases", ssbp) else: # TODO(mark): this assumes too much knowledge of the internals of # xcodeproj_file; some of these smarts should move into xcodeproj_file # itself. xct._properties["buildPhases"].insert(prebuild_index, ssbp) prebuild_index = prebuild_index + 1 # TODO(mark): Should verify that at most one of these is specified. if int(action.get("process_outputs_as_sources", False)): for output in action["outputs"]: AddSourceToTarget(output, type, pbxp, xct) if int(action.get("process_outputs_as_mac_bundle_resources", False)): for output in action["outputs"]: AddResourceToTarget(output, pbxp, xct) # tgt_mac_bundle_resources holds the list of bundle resources so # the rule processing can check against it. if is_bundle: tgt_mac_bundle_resources = spec.get("mac_bundle_resources", []) else: tgt_mac_bundle_resources = [] # Add custom shell script phases driving "make" for "rules" sections. # # Xcode's built-in rule support is almost powerful enough to use directly, # but there are a few significant deficiencies that render them unusable. # There are workarounds for some of its inadequacies, but in aggregate, # the workarounds added complexity to the generator, and some workarounds # actually require input files to be crafted more carefully than I'd like. # Consequently, until Xcode rules are made more capable, "rules" input # sections will be handled in Xcode output by shell script build phases # performed prior to the compilation phase. # # The following problems with Xcode rules were found. The numbers are # Apple radar IDs. I hope that these shortcomings are addressed, I really # liked having the rules handled directly in Xcode during the period that # I was prototyping this. # # 6588600 Xcode compiles custom script rule outputs too soon, compilation # fails. This occurs when rule outputs from distinct inputs are # interdependent. The only workaround is to put rules and their # inputs in a separate target from the one that compiles the rule # outputs. This requires input file cooperation and it means that # process_outputs_as_sources is unusable. # 6584932 Need to declare that custom rule outputs should be excluded from # compilation. A possible workaround is to lie to Xcode about a # rule's output, giving it a dummy file it doesn't know how to # compile. The rule action script would need to touch the dummy. # 6584839 I need a way to declare additional inputs to a custom rule. # A possible workaround is a shell script phase prior to # compilation that touches a rule's primary input files if any # would-be additional inputs are newer than the output. Modifying # the source tree - even just modification times - feels dirty. # 6564240 Xcode "custom script" build rules always dump all environment # variables. This is a low-prioroty problem and is not a # show-stopper. rules_by_ext = {} for rule in spec_rules: rules_by_ext[rule["extension"]] = rule # First, some definitions: # # A "rule source" is a file that was listed in a target's "sources" # list and will have a rule applied to it on the basis of matching the # rule's "extensions" attribute. Rule sources are direct inputs to # rules. # # Rule definitions may specify additional inputs in their "inputs" # attribute. These additional inputs are used for dependency tracking # purposes. # # A "concrete output" is a rule output with input-dependent variables # resolved. For example, given a rule with: # 'extension': 'ext', 'outputs': ['$(INPUT_FILE_BASE).cc'], # if the target's "sources" list contained "one.ext" and "two.ext", # the "concrete output" for rule input "two.ext" would be "two.cc". If # a rule specifies multiple outputs, each input file that the rule is # applied to will have the same number of concrete outputs. # # If any concrete outputs are outdated or missing relative to their # corresponding rule_source or to any specified additional input, the # rule action must be performed to generate the concrete outputs. # concrete_outputs_by_rule_source will have an item at the same index # as the rule['rule_sources'] that it corresponds to. Each item is a # list of all of the concrete outputs for the rule_source. concrete_outputs_by_rule_source = [] # concrete_outputs_all is a flat list of all concrete outputs that this # rule is able to produce, given the known set of input files # (rule_sources) that apply to it. concrete_outputs_all = [] # messages & actions are keyed by the same indices as rule['rule_sources'] # and concrete_outputs_by_rule_source. They contain the message and # action to perform after resolving input-dependent variables. The # message is optional, in which case None is stored for each rule source. messages = [] actions = [] for rule_source in rule.get("rule_sources", []): rule_source_dirname, rule_source_basename = posixpath.split(rule_source) (rule_source_root, rule_source_ext) = posixpath.splitext( rule_source_basename ) # These are the same variable names that Xcode uses for its own native # rule support. Because Xcode's rule engine is not being used, they # need to be expanded as they are written to the makefile. rule_input_dict = { "INPUT_FILE_BASE": rule_source_root, "INPUT_FILE_SUFFIX": rule_source_ext, "INPUT_FILE_NAME": rule_source_basename, "INPUT_FILE_PATH": rule_source, "INPUT_FILE_DIRNAME": rule_source_dirname, } concrete_outputs_for_this_rule_source = [] for output in rule.get("outputs", []): # Fortunately, Xcode and make both use $(VAR) format for their # variables, so the expansion is the only transformation necessary. # Any remaining $(VAR)-type variables in the string can be given # directly to make, which will pick up the correct settings from # what Xcode puts into the environment. concrete_output = ExpandXcodeVariables(output, rule_input_dict) concrete_outputs_for_this_rule_source.append(concrete_output) # Add all concrete outputs to the project. pbxp.AddOrGetFileInRootGroup(concrete_output) concrete_outputs_by_rule_source.append( concrete_outputs_for_this_rule_source ) concrete_outputs_all.extend(concrete_outputs_for_this_rule_source) # TODO(mark): Should verify that at most one of these is specified. if int(rule.get("process_outputs_as_sources", False)): for output in concrete_outputs_for_this_rule_source: AddSourceToTarget(output, type, pbxp, xct) # If the file came from the mac_bundle_resources list or if the rule # is marked to process outputs as bundle resource, do so. was_mac_bundle_resource = rule_source in tgt_mac_bundle_resources if was_mac_bundle_resource or int( rule.get("process_outputs_as_mac_bundle_resources", False) ): for output in concrete_outputs_for_this_rule_source: AddResourceToTarget(output, pbxp, xct) # Do we have a message to print when this rule runs? message = rule.get("message") if message: message = gyp.common.EncodePOSIXShellArgument(message) message = ExpandXcodeVariables(message, rule_input_dict) messages.append(message) # Turn the list into a string that can be passed to a shell. action_string = gyp.common.EncodePOSIXShellList(rule["action"]) action = ExpandXcodeVariables(action_string, rule_input_dict) actions.append(action) if len(concrete_outputs_all) > 0: # TODO(mark): There's a possibility for collision here. Consider # target "t" rule "A_r" and target "t_A" rule "r". makefile_name = "%s.make" % re.sub( "[^a-zA-Z0-9_]", "_", "{}_{}".format(target_name, rule["rule_name"]) ) makefile_path = os.path.join( xcode_projects[build_file].path, makefile_name ) # TODO(mark): try/close? Write to a temporary file and swap it only # if it's got changes? makefile = open(makefile_path, "w") # make will build the first target in the makefile by default. By # convention, it's called "all". List all (or at least one) # concrete output for each rule source as a prerequisite of the "all" # target. makefile.write("all: \\\n") for concrete_output_index, concrete_output_by_rule_source in enumerate( concrete_outputs_by_rule_source ): # Only list the first (index [0]) concrete output of each input # in the "all" target. Otherwise, a parallel make (-j > 1) would # attempt to process each input multiple times simultaneously. # Otherwise, "all" could just contain the entire list of # concrete_outputs_all. concrete_output = concrete_output_by_rule_source[0] if ( concrete_output_index == len(concrete_outputs_by_rule_source) - 1 ): eol = "" else: eol = " \\" makefile.write(f" {concrete_output}{eol}\n") for (rule_source, concrete_outputs, message, action) in zip( rule["rule_sources"], concrete_outputs_by_rule_source, messages, actions, ): makefile.write("\n") # Add a rule that declares it can build each concrete output of a # rule source. Collect the names of the directories that are # required. concrete_output_dirs = [] for concrete_output_index, concrete_output in enumerate( concrete_outputs ): bol = "" if concrete_output_index == 0 else " " makefile.write(f"{bol}{concrete_output} \\\n") concrete_output_dir = posixpath.dirname(concrete_output) if ( concrete_output_dir and concrete_output_dir not in concrete_output_dirs ): concrete_output_dirs.append(concrete_output_dir) makefile.write(" : \\\n") # The prerequisites for this rule are the rule source itself and # the set of additional rule inputs, if any. prerequisites = [rule_source] prerequisites.extend(rule.get("inputs", [])) for prerequisite_index, prerequisite in enumerate(prerequisites): if prerequisite_index == len(prerequisites) - 1: eol = "" else: eol = " \\" makefile.write(f" {prerequisite}{eol}\n") # Make sure that output directories exist before executing the rule # action. if len(concrete_output_dirs) > 0: makefile.write( '\t@mkdir -p "%s"\n' % '" "'.join(concrete_output_dirs) ) # The rule message and action have already had # the necessary variable substitutions performed. if message: # Mark it with note: so Xcode picks it up in build output. makefile.write("\t@echo note: %s\n" % message) makefile.write("\t%s\n" % action) makefile.close() # It might be nice to ensure that needed output directories exist # here rather than in each target in the Makefile, but that wouldn't # work if there ever was a concrete output that had an input-dependent # variable anywhere other than in the leaf position. # Don't declare any inputPaths or outputPaths. If they're present, # Xcode will provide a slight optimization by only running the script # phase if any output is missing or outdated relative to any input. # Unfortunately, it will also assume that all outputs are touched by # the script, and if the outputs serve as files in a compilation # phase, they will be unconditionally rebuilt. Since make might not # rebuild everything that could be declared here as an output, this # extra compilation activity is unnecessary. With inputPaths and # outputPaths not supplied, make will always be called, but it knows # enough to not do anything when everything is up-to-date. # To help speed things up, pass -j COUNT to make so it does some work # in parallel. Don't use ncpus because Xcode will build ncpus targets # in parallel and if each target happens to have a rules step, there # would be ncpus^2 things going. With a machine that has 2 quad-core # Xeons, a build can quickly run out of processes based on # scheduling/other tasks, and randomly failing builds are no good. script = ( """JOB_COUNT="$(/usr/sbin/sysctl -n hw.ncpu)" if [ "${JOB_COUNT}" -gt 4 ]; then JOB_COUNT=4 fi exec xcrun make -f "${PROJECT_FILE_PATH}/%s" -j "${JOB_COUNT}" exit 1 """ % makefile_name ) ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase( { "name": 'Rule "' + rule["rule_name"] + '"', "shellScript": script, "showEnvVarsInLog": 0, } ) if support_xct: support_xct.AppendProperty("buildPhases", ssbp) else: # TODO(mark): this assumes too much knowledge of the internals of # xcodeproj_file; some of these smarts should move # into xcodeproj_file itself. xct._properties["buildPhases"].insert(prebuild_index, ssbp) prebuild_index = prebuild_index + 1 # Extra rule inputs also go into the project file. Concrete outputs were # already added when they were computed. groups = ["inputs", "inputs_excluded"] if skip_excluded_files: groups = [x for x in groups if not x.endswith("_excluded")] for group in groups: for item in rule.get(group, []): pbxp.AddOrGetFileInRootGroup(item) # Add "sources". for source in spec.get("sources", []): (source_root, source_extension) = posixpath.splitext(source) if source_extension[1:] not in rules_by_ext: # AddSourceToTarget will add the file to a root group if it's not # already there. AddSourceToTarget(source, type, pbxp, xct) else: pbxp.AddOrGetFileInRootGroup(source) # Add "mac_bundle_resources" and "mac_framework_private_headers" if # it's a bundle of any type. if is_bundle: for resource in tgt_mac_bundle_resources: (resource_root, resource_extension) = posixpath.splitext(resource) if resource_extension[1:] not in rules_by_ext: AddResourceToTarget(resource, pbxp, xct) else: pbxp.AddOrGetFileInRootGroup(resource) for header in spec.get("mac_framework_private_headers", []): AddHeaderToTarget(header, pbxp, xct, False) # Add "mac_framework_headers". These can be valid for both frameworks # and static libraries. if is_bundle or type == "static_library": for header in spec.get("mac_framework_headers", []): AddHeaderToTarget(header, pbxp, xct, True) # Add "copies". pbxcp_dict = {} for copy_group in spec.get("copies", []): dest = copy_group["destination"] if dest[0] not in ("/", "$"): # Relative paths are relative to $(SRCROOT). dest = "$(SRCROOT)/" + dest code_sign = int(copy_group.get("xcode_code_sign", 0)) settings = (None, "{ATTRIBUTES = (CodeSignOnCopy, ); }")[code_sign] # Coalesce multiple "copies" sections in the same target with the same # "destination" property into the same PBXCopyFilesBuildPhase, otherwise # they'll wind up with ID collisions. pbxcp = pbxcp_dict.get(dest, None) if pbxcp is None: pbxcp = gyp.xcodeproj_file.PBXCopyFilesBuildPhase( {"name": "Copy to " + copy_group["destination"]}, parent=xct ) pbxcp.SetDestination(dest) # TODO(mark): The usual comment about this knowing too much about # gyp.xcodeproj_file internals applies. xct._properties["buildPhases"].insert(prebuild_index, pbxcp) pbxcp_dict[dest] = pbxcp for file in copy_group["files"]: pbxcp.AddFile(file, settings) # Excluded files can also go into the project file. if not skip_excluded_files: for key in [ "sources", "mac_bundle_resources", "mac_framework_headers", "mac_framework_private_headers", ]: excluded_key = key + "_excluded" for item in spec.get(excluded_key, []): pbxp.AddOrGetFileInRootGroup(item) # So can "inputs" and "outputs" sections of "actions" groups. groups = ["inputs", "inputs_excluded", "outputs", "outputs_excluded"] if skip_excluded_files: groups = [x for x in groups if not x.endswith("_excluded")] for action in spec.get("actions", []): for group in groups: for item in action.get(group, []): # Exclude anything in BUILT_PRODUCTS_DIR. They're products, not # sources. if not item.startswith("$(BUILT_PRODUCTS_DIR)/"): pbxp.AddOrGetFileInRootGroup(item) for postbuild in spec.get("postbuilds", []): action_string_sh = gyp.common.EncodePOSIXShellList(postbuild["action"]) script = "exec " + action_string_sh + "\nexit 1\n" # Make the postbuild step depend on the output of ld or ar from this # target. Apparently putting the script step after the link step isn't # sufficient to ensure proper ordering in all cases. With an input # declared but no outputs, the script step should run every time, as # desired. ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase( { "inputPaths": ["$(BUILT_PRODUCTS_DIR)/$(EXECUTABLE_PATH)"], "name": 'Postbuild "' + postbuild["postbuild_name"] + '"', "shellScript": script, "showEnvVarsInLog": 0, } ) xct.AppendProperty("buildPhases", ssbp) # Add dependencies before libraries, because adding a dependency may imply # adding a library. It's preferable to keep dependencies listed first # during a link phase so that they can override symbols that would # otherwise be provided by libraries, which will usually include system # libraries. On some systems, ld is finicky and even requires the # libraries to be ordered in such a way that unresolved symbols in # earlier-listed libraries may only be resolved by later-listed libraries. # The Mac linker doesn't work that way, but other platforms do, and so # their linker invocations need to be constructed in this way. There's # no compelling reason for Xcode's linker invocations to differ. if "dependencies" in spec: for dependency in spec["dependencies"]: xct.AddDependency(xcode_targets[dependency]) # The support project also gets the dependencies (in case they are # needed for the actions/rules to work). if support_xct: support_xct.AddDependency(xcode_targets[dependency]) if "libraries" in spec: for library in spec["libraries"]: xct.FrameworksPhase().AddFile(library) # Add the library's directory to LIBRARY_SEARCH_PATHS if necessary. # I wish Xcode handled this automatically. library_dir = posixpath.dirname(library) if library_dir not in xcode_standard_library_dirs and ( not xct.HasBuildSetting(_library_search_paths_var) or library_dir not in xct.GetBuildSetting(_library_search_paths_var) ): xct.AppendBuildSetting(_library_search_paths_var, library_dir) for configuration_name in configuration_names: configuration = spec["configurations"][configuration_name] xcbc = xct.ConfigurationNamed(configuration_name) for include_dir in configuration.get("mac_framework_dirs", []): xcbc.AppendBuildSetting("FRAMEWORK_SEARCH_PATHS", include_dir) for include_dir in configuration.get("include_dirs", []): xcbc.AppendBuildSetting("HEADER_SEARCH_PATHS", include_dir) for library_dir in configuration.get("library_dirs", []): if library_dir not in xcode_standard_library_dirs and ( not xcbc.HasBuildSetting(_library_search_paths_var) or library_dir not in xcbc.GetBuildSetting(_library_search_paths_var) ): xcbc.AppendBuildSetting(_library_search_paths_var, library_dir) if "defines" in configuration: for define in configuration["defines"]: set_define = EscapeXcodeDefine(define) xcbc.AppendBuildSetting("GCC_PREPROCESSOR_DEFINITIONS", set_define) if "xcode_settings" in configuration: for xck, xcv in configuration["xcode_settings"].items(): xcbc.SetBuildSetting(xck, xcv) if "xcode_config_file" in configuration: config_ref = pbxp.AddOrGetFileInRootGroup( configuration["xcode_config_file"] ) xcbc.SetBaseConfiguration(config_ref) build_files = [] for build_file, build_file_dict in data.items(): if build_file.endswith(".gyp"): build_files.append(build_file) for build_file in build_files: xcode_projects[build_file].Finalize1(xcode_targets, serialize_all_tests) for build_file in build_files: xcode_projects[build_file].Finalize2(xcode_targets, xcode_target_to_target_dict) for build_file in build_files: xcode_projects[build_file].Write() #!/usr/bin/env python3 # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Unit tests for the xcode.py file. """ import gyp.generator.xcode as xcode import unittest import sys class TestEscapeXcodeDefine(unittest.TestCase): if sys.platform == "darwin": def test_InheritedRemainsUnescaped(self): self.assertEqual(xcode.EscapeXcodeDefine("$(inherited)"), "$(inherited)") def test_Escaping(self): self.assertEqual(xcode.EscapeXcodeDefine('a b"c\\'), 'a\\ b\\"c\\\\') if __name__ == "__main__": unittest.main() # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import ast import gyp.common import gyp.simple_copy import multiprocessing import os.path import re import shlex import signal import subprocess import sys import threading import traceback from gyp.common import GypError from gyp.common import OrderedSet from packaging.version import Version # A list of types that are treated as linkable. linkable_types = [ "executable", "shared_library", "loadable_module", "mac_kernel_extension", "windows_driver", ] # A list of sections that contain links to other targets. dependency_sections = ["dependencies", "export_dependent_settings"] # base_path_sections is a list of sections defined by GYP that contain # pathnames. The generators can provide more keys, the two lists are merged # into path_sections, but you should call IsPathSection instead of using either # list directly. base_path_sections = [ "destination", "files", "include_dirs", "inputs", "libraries", "outputs", "sources", ] path_sections = set() # These per-process dictionaries are used to cache build file data when loading # in parallel mode. per_process_data = {} per_process_aux_data = {} def IsPathSection(section): # If section ends in one of the '=+?!' characters, it's applied to a section # without the trailing characters. '/' is notably absent from this list, # because there's no way for a regular expression to be treated as a path. while section and section[-1:] in "=+?!": section = section[:-1] if section in path_sections: return True # Sections matching the regexp '_(dir|file|path)s?$' are also # considered PathSections. Using manual string matching since that # is much faster than the regexp and this can be called hundreds of # thousands of times so micro performance matters. if "_" in section: tail = section[-6:] if tail[-1] == "s": tail = tail[:-1] if tail[-5:] in ("_file", "_path"): return True return tail[-4:] == "_dir" return False # base_non_configuration_keys is a list of key names that belong in the target # itself and should not be propagated into its configurations. It is merged # with a list that can come from the generator to # create non_configuration_keys. base_non_configuration_keys = [ # Sections that must exist inside targets and not configurations. "actions", "configurations", "copies", "default_configuration", "dependencies", "dependencies_original", "libraries", "postbuilds", "product_dir", "product_extension", "product_name", "product_prefix", "rules", "run_as", "sources", "standalone_static_library", "suppress_wildcard", "target_name", "toolset", "toolsets", "type", # Sections that can be found inside targets or configurations, but that # should not be propagated from targets into their configurations. "variables", ] non_configuration_keys = [] # Keys that do not belong inside a configuration dictionary. invalid_configuration_keys = [ "actions", "all_dependent_settings", "configurations", "dependencies", "direct_dependent_settings", "libraries", "link_settings", "sources", "standalone_static_library", "target_name", "type", ] # Controls whether or not the generator supports multiple toolsets. multiple_toolsets = False # Paths for converting filelist paths to output paths: { # toplevel, # qualified_output_dir, # } generator_filelist_paths = None def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory. """ if included is None: included = [] if build_file_path in included: return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get("included", []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ syntax_tree = ast.parse(file_contents) assert isinstance(syntax_tree, ast.Module) c1 = syntax_tree.body assert len(c1) == 1 c2 = c1[0] assert isinstance(c2, ast.Expr) return CheckNode(c2.value, []) def CheckNode(node, keypath): if isinstance(node, ast.Dict): dict = {} for key, value in zip(node.keys, node.values): assert isinstance(key, ast.Str) key = key.s if key in dict: raise GypError( "Key '" + key + "' repeated at level " + repr(len(keypath) + 1) + " with key path '" + ".".join(keypath) + "'" ) kp = list(keypath) # Make a copy of the list for descending this node. kp.append(key) dict[key] = CheckNode(value, kp) return dict elif isinstance(node, ast.List): children = [] for index, child in enumerate(node.elts): kp = list(keypath) # Copy list. kp.append(repr(index)) children.append(CheckNode(child, kp)) return children elif isinstance(node, ast.Str): return node.s else: raise TypeError( "Unknown AST node at key path '" + ".".join(keypath) + "': " + repr(node) ) def LoadOneBuildFile(build_file_path, data, aux_data, includes, is_target, check): if build_file_path in data: return data[build_file_path] if os.path.exists(build_file_path): build_file_contents = open(build_file_path, encoding="utf-8").read() else: raise GypError(f"{build_file_path} not found (cwd: {os.getcwd()})") build_file_data = None try: if check: build_file_data = CheckedEval(build_file_contents) else: build_file_data = eval(build_file_contents, {"__builtins__": {}}, None) except SyntaxError as e: e.filename = build_file_path raise except Exception as e: gyp.common.ExceptionAppend(e, "while reading " + build_file_path) raise if type(build_file_data) is not dict: raise GypError("%s does not evaluate to a dictionary." % build_file_path) data[build_file_path] = build_file_data aux_data[build_file_path] = {} # Scan for includes and merge them in. if "skip_includes" not in build_file_data or not build_file_data["skip_includes"]: try: if is_target: LoadBuildFileIncludesIntoDict( build_file_data, build_file_path, data, aux_data, includes, check ) else: LoadBuildFileIncludesIntoDict( build_file_data, build_file_path, data, aux_data, None, check ) except Exception as e: gyp.common.ExceptionAppend( e, "while reading includes of " + build_file_path ) raise return build_file_data def LoadBuildFileIncludesIntoDict( subdict, subdict_path, data, aux_data, includes, check ): includes_list = [] if includes is not None: includes_list.extend(includes) if "includes" in subdict: for include in subdict["includes"]: # "include" is specified relative to subdict_path, so compute the real # path to include by appending the provided "include" to the directory # in which subdict_path resides. relative_include = os.path.normpath( os.path.join(os.path.dirname(subdict_path), include) ) includes_list.append(relative_include) # Unhook the includes list, it's no longer needed. del subdict["includes"] # Merge in the included files. for include in includes_list: if "included" not in aux_data[subdict_path]: aux_data[subdict_path]["included"] = [] aux_data[subdict_path]["included"].append(include) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'", include) MergeDicts( subdict, LoadOneBuildFile(include, data, aux_data, None, False, check), subdict_path, include, ) # Recurse into subdictionaries. for k, v in subdict.items(): if type(v) is dict: LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, None, check) elif type(v) is list: LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, check) # This recurses into lists so that it can look for dicts. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, check): for item in sublist: if type(item) is dict: LoadBuildFileIncludesIntoDict( item, sublist_path, data, aux_data, None, check ) elif type(item) is list: LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, check) # Processes toolsets in all the targets. This recurses into condition entries # since they can contain toolsets as well. def ProcessToolsetsInDict(data): if "targets" in data: target_list = data["targets"] new_target_list = [] for target in target_list: # If this target already has an explicit 'toolset', and no 'toolsets' # list, don't modify it further. if "toolset" in target and "toolsets" not in target: new_target_list.append(target) continue if multiple_toolsets: toolsets = target.get("toolsets", ["target"]) else: toolsets = ["target"] # Make sure this 'toolsets' definition is only processed once. if "toolsets" in target: del target["toolsets"] if len(toolsets) > 0: # Optimization: only do copies if more than one toolset is specified. for build in toolsets[1:]: new_target = gyp.simple_copy.deepcopy(target) new_target["toolset"] = build new_target_list.append(new_target) target["toolset"] = toolsets[0] new_target_list.append(target) data["targets"] = new_target_list if "conditions" in data: for condition in data["conditions"]: if type(condition) is list: for condition_dict in condition[1:]: if type(condition_dict) is dict: ProcessToolsetsInDict(condition_dict) # TODO(mark): I don't love this name. It just means that it's going to load # a build file that contains targets and is expected to provide a targets dict # that contains the targets... def LoadTargetBuildFile( build_file_path, data, aux_data, variables, includes, depth, check, load_dependencies, ): # If depth is set, predefine the DEPTH variable to be a relative path from # this build file's directory to the directory identified by depth. if depth: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path)) if d == "": variables["DEPTH"] = "." else: variables["DEPTH"] = d.replace("\\", "/") # The 'target_build_files' key is only set when loading target build files in # the non-parallel code path, where LoadTargetBuildFile is called # recursively. In the parallel code path, we don't need to check whether the # |build_file_path| has already been loaded, because the 'scheduled' set in # ParallelState guarantees that we never load the same |build_file_path| # twice. if "target_build_files" in data: if build_file_path in data["target_build_files"]: # Already loaded. return False data["target_build_files"].add(build_file_path) gyp.DebugOutput( gyp.DEBUG_INCLUDES, "Loading Target Build File '%s'", build_file_path ) build_file_data = LoadOneBuildFile( build_file_path, data, aux_data, includes, True, check ) # Store DEPTH for later use in generators. build_file_data["_DEPTH"] = depth # Set up the included_files key indicating which .gyp files contributed to # this target dict. if "included_files" in build_file_data: raise GypError(build_file_path + " must not contain included_files key") included = GetIncludedBuildFiles(build_file_path, aux_data) build_file_data["included_files"] = [] for included_file in included: # included_file is relative to the current directory, but it needs to # be made relative to build_file_path's directory. included_relative = gyp.common.RelativePath( included_file, os.path.dirname(build_file_path) ) build_file_data["included_files"].append(included_relative) # Do a first round of toolsets expansion so that conditions can be defined # per toolset. ProcessToolsetsInDict(build_file_data) # Apply "pre"/"early" variable expansions and condition evaluations. ProcessVariablesAndConditionsInDict( build_file_data, PHASE_EARLY, variables, build_file_path ) # Since some toolsets might have been defined conditionally, perform # a second round of toolsets expansion now. ProcessToolsetsInDict(build_file_data) # Look at each project's target_defaults dict, and merge settings into # targets. if "target_defaults" in build_file_data: if "targets" not in build_file_data: raise GypError("Unable to find targets in build file %s" % build_file_path) index = 0 while index < len(build_file_data["targets"]): # This procedure needs to give the impression that target_defaults is # used as defaults, and the individual targets inherit from that. # The individual targets need to be merged into the defaults. Make # a deep copy of the defaults for each target, merge the target dict # as found in the input file into that copy, and then hook up the # copy with the target-specific data merged into it as the replacement # target dict. old_target_dict = build_file_data["targets"][index] new_target_dict = gyp.simple_copy.deepcopy( build_file_data["target_defaults"] ) MergeDicts( new_target_dict, old_target_dict, build_file_path, build_file_path ) build_file_data["targets"][index] = new_target_dict index += 1 # No longer needed. del build_file_data["target_defaults"] # Look for dependencies. This means that dependency resolution occurs # after "pre" conditionals and variable expansion, but before "post" - # in other words, you can't put a "dependencies" section inside a "post" # conditional within a target. dependencies = [] if "targets" in build_file_data: for target_dict in build_file_data["targets"]: if "dependencies" not in target_dict: continue for dependency in target_dict["dependencies"]: dependencies.append( gyp.common.ResolveTarget(build_file_path, dependency, None)[0] ) if load_dependencies: for dependency in dependencies: try: LoadTargetBuildFile( dependency, data, aux_data, variables, includes, depth, check, load_dependencies, ) except Exception as e: gyp.common.ExceptionAppend( e, "while loading dependencies of %s" % build_file_path ) raise else: return (build_file_path, dependencies) def CallLoadTargetBuildFile( global_flags, build_file_path, variables, includes, depth, check, generator_input_info, ): """Wrapper around LoadTargetBuildFile for parallel processing. This wrapper is used when LoadTargetBuildFile is executed in a worker process. """ try: signal.signal(signal.SIGINT, signal.SIG_IGN) # Apply globals so that the worker process behaves the same. for key, value in global_flags.items(): globals()[key] = value SetGeneratorGlobals(generator_input_info) result = LoadTargetBuildFile( build_file_path, per_process_data, per_process_aux_data, variables, includes, depth, check, False, ) if not result: return result (build_file_path, dependencies) = result # We can safely pop the build_file_data from per_process_data because it # will never be referenced by this process again, so we don't need to keep # it in the cache. build_file_data = per_process_data.pop(build_file_path) # This gets serialized and sent back to the main process via a pipe. # It's handled in LoadTargetBuildFileCallback. return (build_file_path, build_file_data, dependencies) except GypError as e: sys.stderr.write("gyp: %s\n" % e) return None except Exception as e: print("Exception:", e, file=sys.stderr) print(traceback.format_exc(), file=sys.stderr) return None class ParallelProcessingError(Exception): pass class ParallelState: """Class to keep track of state when processing input files in parallel. If build files are loaded in parallel, use this to keep track of state during farming out and processing parallel jobs. It's stored in a global so that the callback function can have access to it. """ def __init__(self): # The multiprocessing pool. self.pool = None # The condition variable used to protect this object and notify # the main loop when there might be more data to process. self.condition = None # The "data" dict that was passed to LoadTargetBuildFileParallel self.data = None # The number of parallel calls outstanding; decremented when a response # was received. self.pending = 0 # The set of all build files that have been scheduled, so we don't # schedule the same one twice. self.scheduled = set() # A list of dependency build file paths that haven't been scheduled yet. self.dependencies = [] # Flag to indicate if there was an error in a child process. self.error = False def LoadTargetBuildFileCallback(self, result): """Handle the results of running LoadTargetBuildFile in another process. """ self.condition.acquire() if not result: self.error = True self.condition.notify() self.condition.release() return (build_file_path0, build_file_data0, dependencies0) = result self.data[build_file_path0] = build_file_data0 self.data["target_build_files"].add(build_file_path0) for new_dependency in dependencies0: if new_dependency not in self.scheduled: self.scheduled.add(new_dependency) self.dependencies.append(new_dependency) self.pending -= 1 self.condition.notify() self.condition.release() def LoadTargetBuildFilesParallel( build_files, data, variables, includes, depth, check, generator_input_info ): parallel_state = ParallelState() parallel_state.condition = threading.Condition() # Make copies of the build_files argument that we can modify while working. parallel_state.dependencies = list(build_files) parallel_state.scheduled = set(build_files) parallel_state.pending = 0 parallel_state.data = data try: parallel_state.condition.acquire() while parallel_state.dependencies or parallel_state.pending: if parallel_state.error: break if not parallel_state.dependencies: parallel_state.condition.wait() continue dependency = parallel_state.dependencies.pop() parallel_state.pending += 1 global_flags = { "path_sections": globals()["path_sections"], "non_configuration_keys": globals()["non_configuration_keys"], "multiple_toolsets": globals()["multiple_toolsets"], } if not parallel_state.pool: parallel_state.pool = multiprocessing.Pool(multiprocessing.cpu_count()) parallel_state.pool.apply_async( CallLoadTargetBuildFile, args=( global_flags, dependency, variables, includes, depth, check, generator_input_info, ), callback=parallel_state.LoadTargetBuildFileCallback, ) except KeyboardInterrupt as e: parallel_state.pool.terminate() raise e parallel_state.condition.release() parallel_state.pool.close() parallel_state.pool.join() parallel_state.pool = None if parallel_state.error: sys.exit(1) # Look for the bracket that matches the first bracket seen in a # string, and return the start and end as a tuple. For example, if # the input is something like "<(foo <(bar)) blah", then it would # return (1, 13), indicating the entire string except for the leading # "<" and trailing " blah". LBRACKETS = set("{[(") BRACKETS = {"}": "{", "]": "[", ")": "("} def FindEnclosingBracketGroup(input_str): stack = [] start = -1 for index, char in enumerate(input_str): if char in LBRACKETS: stack.append(char) if start == -1: start = index elif char in BRACKETS: if not stack: return (-1, -1) if stack.pop() != BRACKETS[char]: return (-1, -1) if not stack: return (start, index + 1) return (-1, -1) def IsStrCanonicalInt(string): """Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string. """ if type(string) is str: # This function is called a lot so for maximum performance, avoid # involving regexps which would otherwise make the code much # shorter. Regexps would need twice the time of this function. if string: if string == "0": return True if string[0] == "-": string = string[1:] if not string: return False if "1" <= string[0] <= "9": return string.isdigit() return False # This matches things like "<(asdf)", "(?P<(?:(?:!?@?)|\|)?)" r"(?P[-a-zA-Z0-9_.]+)?" r"\((?P\s*\[?)" r"(?P.*?)(\]?)\))" ) # This matches the same as early_variable_re, but with '>' instead of '<'. late_variable_re = re.compile( r"(?P(?P>(?:(?:!?@?)|\|)?)" r"(?P[-a-zA-Z0-9_.]+)?" r"\((?P\s*\[?)" r"(?P.*?)(\]?)\))" ) # This matches the same as early_variable_re, but with '^' instead of '<'. latelate_variable_re = re.compile( r"(?P(?P[\^](?:(?:!?@?)|\|)?)" r"(?P[-a-zA-Z0-9_.]+)?" r"\((?P\s*\[?)" r"(?P.*?)(\]?)\))" ) # Global cache of results from running commands so they don't have to be run # more then once. cached_command_results = {} def FixupPlatformCommand(cmd): if sys.platform == "win32": if type(cmd) is list: cmd = [re.sub("^cat ", "type ", cmd[0])] + cmd[1:] else: cmd = re.sub("^cat ", "type ", cmd) return cmd PHASE_EARLY = 0 PHASE_LATE = 1 PHASE_LATELATE = 2 def ExpandVariables(input, phase, variables, build_file): # Look for the pattern that gets expanded into variables if phase == PHASE_EARLY: variable_re = early_variable_re expansion_symbol = "<" elif phase == PHASE_LATE: variable_re = late_variable_re expansion_symbol = ">" elif phase == PHASE_LATELATE: variable_re = latelate_variable_re expansion_symbol = "^" else: assert False input_str = str(input) if IsStrCanonicalInt(input_str): return int(input_str) # Do a quick scan to determine if an expensive regex search is warranted. if expansion_symbol not in input_str: return input_str # Get the entire list of matches as a list of MatchObject instances. # (using findall here would return strings instead of MatchObjects). matches = list(variable_re.finditer(input_str)) if not matches: return input_str output = input_str # Reverse the list of matches so that replacements are done right-to-left. # That ensures that earlier replacements won't mess up the string in a # way that causes later calls to find the earlier substituted text instead # of what's intended for replacement. matches.reverse() for match_group in matches: match = match_group.groupdict() gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %r", match) # match['replace'] is the substring to look for, match['type'] # is the character code for the replacement type (< > ! <| >| <@ # >@ !@), match['is_array'] contains a '[' for command # arrays, and match['content'] is the name of the variable (< >) # or command to run (!). match['command_string'] is an optional # command string. Currently, only 'pymod_do_main' is supported. # run_command is true if a ! variant is used. run_command = "!" in match["type"] command_string = match["command_string"] # file_list is true if a | variant is used. file_list = "|" in match["type"] # Capture these now so we can adjust them later. replace_start = match_group.start("replace") replace_end = match_group.end("replace") # Find the ending paren, and re-evaluate the contained string. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:]) # Adjust the replacement range to match the entire command # found by FindEnclosingBracketGroup (since the variable_re # probably doesn't match the entire command if it contained # nested variables). replace_end = replace_start + c_end # Find the "real" replacement, matching the appropriate closing # paren, and adjust the replacement start and end. replacement = input_str[replace_start:replace_end] # Figure out what the contents of the variable parens are. contents_start = replace_start + c_start + 1 contents_end = replace_end - 1 contents = input_str[contents_start:contents_end] # Do filter substitution now for <|(). # Admittedly, this is different than the evaluation order in other # contexts. However, since filtration has no chance to run on <|(), # this seems like the only obvious way to give them access to filters. if file_list: processed_variables = gyp.simple_copy.deepcopy(variables) ProcessListFiltersInDict(contents, processed_variables) # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, processed_variables, build_file) else: # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, variables, build_file) # Strip off leading/trailing whitespace so that variable matches are # simpler below (and because they are rarely needed). contents = contents.strip() # expand_to_list is true if an @ variant is used. In that case, # the expansion should result in a list. Note that the caller # is to be expecting a list in return, and not all callers do # because not all are working in list context. Also, for list # expansions, there can be no other text besides the variable # expansion in the input string. expand_to_list = "@" in match["type"] and input_str == replacement if run_command or file_list: # Find the build file's directory, so commands can be run or file lists # generated relative to it. build_file_dir = os.path.dirname(build_file) if build_file_dir == "" and not file_list: # If build_file is just a leaf filename indicating a file in the # current directory, build_file_dir might be an empty string. Set # it to None to signal to subprocess.Popen that it should run the # command in the current directory. build_file_dir = None # Support <|(listfile.txt ...) which generates a file # containing items from a gyp list, generated at gyp time. # This works around actions/rules which have more inputs than will # fit on the command line. if file_list: contents_list = contents if type(contents) is list else contents.split(" ") replacement = contents_list[0] if os.path.isabs(replacement): raise GypError('| cannot handle absolute paths, got "%s"' % replacement) if not generator_filelist_paths: path = os.path.join(build_file_dir, replacement) else: if os.path.isabs(build_file_dir): toplevel = generator_filelist_paths["toplevel"] rel_build_file_dir = gyp.common.RelativePath( build_file_dir, toplevel ) else: rel_build_file_dir = build_file_dir qualified_out_dir = generator_filelist_paths["qualified_out_dir"] path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement) gyp.common.EnsureDirExists(path) replacement = gyp.common.RelativePath(path, build_file_dir) f = gyp.common.WriteOnDiff(path) for i in contents_list[1:]: f.write("%s\n" % i) f.close() elif run_command: use_shell = True if match["is_array"]: contents = eval(contents) use_shell = False # Check for a cached value to avoid executing commands, or generating # file lists more than once. The cache key contains the command to be # run as well as the directory to run it from, to account for commands # that depend on their current directory. # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory, # someone could author a set of GYP files where each time the command # is invoked it produces different output by design. When the need # arises, the syntax should be extended to support no caching off a # command's output so it is run every time. cache_key = (str(contents), build_file_dir) cached_value = cached_command_results.get(cache_key, None) if cached_value is None: gyp.DebugOutput( gyp.DEBUG_VARIABLES, "Executing command '%s' in directory '%s'", contents, build_file_dir, ) replacement = "" if command_string == "pymod_do_main": # 0: raise GypError( "Call to '%s' returned exit status %d while in %s." % (contents, result.returncode, build_file) ) replacement = result.stdout.decode("utf-8").rstrip() cached_command_results[cache_key] = replacement else: gyp.DebugOutput( gyp.DEBUG_VARIABLES, "Had cache value for command '%s' in directory '%s'", contents, build_file_dir, ) replacement = cached_value else: if contents not in variables: if contents[-1] in ["!", "/"]: # In order to allow cross-compiles (nacl) to happen more naturally, # we will allow references to >(sources/) etc. to resolve to # and empty list if undefined. This allows actions to: # 'action!': [ # '>@(_sources!)', # ], # 'action/': [ # '>@(_sources/)', # ], replacement = [] else: raise GypError( "Undefined variable " + contents + " in " + build_file ) else: replacement = variables[contents] if isinstance(replacement, bytes) and not isinstance(replacement, str): replacement = replacement.decode("utf-8") # done on Python 3 only if type(replacement) is list: for item in replacement: if isinstance(item, bytes) and not isinstance(item, str): item = item.decode("utf-8") # done on Python 3 only if not contents[-1] == "/" and type(item) not in (str, int): raise GypError( "Variable " + contents + " must expand to a string or list of strings; " + "list contains a " + item.__class__.__name__ ) # Run through the list and handle variable expansions in it. Since # the list is guaranteed not to contain dicts, this won't do anything # with conditions sections. ProcessVariablesAndConditionsInList( replacement, phase, variables, build_file ) elif type(replacement) not in (str, int): raise GypError( "Variable " + contents + " must expand to a string or list of strings; " + "found a " + replacement.__class__.__name__ ) if expand_to_list: # Expanding in list context. It's guaranteed that there's only one # replacement to do in |input_str| and that it's this replacement. See # above. if type(replacement) is list: # If it's already a list, make a copy. output = replacement[:] else: # Split it the same way sh would split arguments. output = shlex.split(str(replacement)) else: # Expanding in string context. encoded_replacement = "" if type(replacement) is list: # When expanding a list into string context, turn the list items # into a string in a way that will work with a subprocess call. # # TODO(mark): This isn't completely correct. This should # call a generator-provided function that observes the # proper list-to-argument quoting rules on a specific # platform instead of just calling the POSIX encoding # routine. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement) else: encoded_replacement = replacement output = ( output[:replace_start] + str(encoded_replacement) + output[replace_end:] ) # Prepare for the next match iteration. input_str = output if output == input: gyp.DebugOutput( gyp.DEBUG_VARIABLES, "Found only identity matches on %r, avoiding infinite " "recursion.", output, ) else: # Look for more matches now that we've replaced some, to deal with # expanding local variables (variables defined in the same # variables block as this one). gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output) if type(output) is list: if output and type(output[0]) is list: # Leave output alone if it's a list of lists. # We don't want such lists to be stringified. pass else: new_output = [] for item in output: new_output.append( ExpandVariables(item, phase, variables, build_file) ) output = new_output else: output = ExpandVariables(output, phase, variables, build_file) # Convert all strings that are canonically-represented integers into integers. if type(output) is list: for index, outstr in enumerate(output): if IsStrCanonicalInt(outstr): output[index] = int(outstr) elif IsStrCanonicalInt(output): output = int(output) return output # The same condition is often evaluated over and over again so it # makes sense to cache as much as possible between evaluations. cached_conditions_asts = {} def EvalCondition(condition, conditions_key, phase, variables, build_file): """Returns the dict that should be used or None if the result was that nothing should be used.""" if type(condition) is not list: raise GypError(conditions_key + " must be a list") if len(condition) < 2: # It's possible that condition[0] won't work in which case this # attempt will raise its own IndexError. That's probably fine. raise GypError( conditions_key + " " + condition[0] + " must be at least length 2, not " + str(len(condition)) ) i = 0 result = None while i < len(condition): cond_expr = condition[i] true_dict = condition[i + 1] if type(true_dict) is not dict: raise GypError( f"{conditions_key} {cond_expr} must be followed by a dictionary, " f"not {type(true_dict)}" ) if len(condition) > i + 2 and type(condition[i + 2]) is dict: false_dict = condition[i + 2] i = i + 3 if i != len(condition): raise GypError( f"{conditions_key} {cond_expr} has " f"{len(condition) - i} unexpected trailing items" ) else: false_dict = None i = i + 2 if result is None: result = EvalSingleCondition( cond_expr, true_dict, false_dict, phase, variables, build_file ) return result def EvalSingleCondition(cond_expr, true_dict, false_dict, phase, variables, build_file): """Returns true_dict if cond_expr evaluates to true, and false_dict otherwise.""" # Do expansions on the condition itself. Since the condition can naturally # contain variable references without needing to resort to GYP expansion # syntax, this is of dubious value for variables, but someone might want to # use a command expansion directly inside a condition. cond_expr_expanded = ExpandVariables(cond_expr, phase, variables, build_file) if type(cond_expr_expanded) not in (str, int): raise ValueError( "Variable expansion in this context permits str and int " + "only, found " + cond_expr_expanded.__class__.__name__ ) try: if cond_expr_expanded in cached_conditions_asts: ast_code = cached_conditions_asts[cond_expr_expanded] else: ast_code = compile(cond_expr_expanded, "", "eval") cached_conditions_asts[cond_expr_expanded] = ast_code env = {"__builtins__": {}, "v": Version} if eval(ast_code, env, variables): return true_dict return false_dict except SyntaxError as e: syntax_error = SyntaxError( "%s while evaluating condition '%s' in %s " "at character %d." % (str(e.args[0]), e.text, build_file, e.offset), e.filename, e.lineno, e.offset, e.text, ) raise syntax_error except NameError as e: gyp.common.ExceptionAppend( e, f"while evaluating condition '{cond_expr_expanded}' in {build_file}", ) raise GypError(e) def ProcessConditionsInDict(the_dict, phase, variables, build_file): # Process a 'conditions' or 'target_conditions' section in the_dict, # depending on phase. # early -> conditions # late -> target_conditions # latelate -> no conditions # # Each item in a conditions list consists of cond_expr, a string expression # evaluated as the condition, and true_dict, a dict that will be merged into # the_dict if cond_expr evaluates to true. Optionally, a third item, # false_dict, may be present. false_dict is merged into the_dict if # cond_expr evaluates to false. # # Any dict merged into the_dict will be recursively processed for nested # conditionals and other expansions, also according to phase, immediately # prior to being merged. if phase == PHASE_EARLY: conditions_key = "conditions" elif phase == PHASE_LATE: conditions_key = "target_conditions" elif phase == PHASE_LATELATE: return else: assert False if conditions_key not in the_dict: return conditions_list = the_dict[conditions_key] # Unhook the conditions list, it's no longer needed. del the_dict[conditions_key] for condition in conditions_list: merge_dict = EvalCondition( condition, conditions_key, phase, variables, build_file ) if merge_dict is not None: # Expand variables and nested conditinals in the merge_dict before # merging it. ProcessVariablesAndConditionsInDict( merge_dict, phase, variables, build_file ) MergeDicts(the_dict, merge_dict, build_file, build_file) def LoadAutomaticVariablesFromDict(variables, the_dict): # Any keys with plain string values in the_dict become automatic variables. # The variable name is the key name with a "_" character prepended. for key, value in the_dict.items(): if type(value) in (str, int, list): variables["_" + key] = value def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): # Any keys in the_dict's "variables" dict, if it has one, becomes a # variable. The variable name is the key name in the "variables" dict. # Variables that end with the % character are set only if they are unset in # the variables dict. the_dict_key is the name of the key that accesses # the_dict in the_dict's parent dict. If the_dict's parent is not a dict # (it could be a list or it could be parentless because it is a root dict), # the_dict_key will be None. for key, value in the_dict.get("variables", {}).items(): if type(value) not in (str, int, list): continue if key.endswith("%"): variable_name = key[:-1] if variable_name in variables: # If the variable is already set, don't set it. continue if the_dict_key == "variables" and variable_name in the_dict: # If the variable is set without a % in the_dict, and the_dict is a # variables dict (making |variables| a variables sub-dict of a # variables dict), use the_dict's definition. value = the_dict[variable_name] else: variable_name = key variables[variable_name] = value def ProcessVariablesAndConditionsInDict( the_dict, phase, variables_in, build_file, the_dict_key=None ): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function. """ # Make a copy of the variables_in dict that can be modified during the # loading of automatics and the loading of the variables dict. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) if "variables" in the_dict: # Make sure all the local variables are added to the variables # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. for key, value in the_dict["variables"].items(): variables[key] = value # Handle the associated variables dict first, so that any variable # references within can be resolved prior to using them as variables. # Pass a copy of the variables dict to avoid having it be tainted. # Otherwise, it would have extra automatics added for everything that # should just be an ordinary variable in this scope. ProcessVariablesAndConditionsInDict( the_dict["variables"], phase, variables, build_file, "variables" ) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) for key, value in the_dict.items(): # Skip "variables", which was already processed if present. if key != "variables" and type(value) is str: expanded = ExpandVariables(value, phase, variables, build_file) if type(expanded) not in (str, int): raise ValueError( "Variable expansion in this context permits str and int " + "only, found " + expanded.__class__.__name__ + " for " + key ) the_dict[key] = expanded # Variable expansion may have resulted in changes to automatics. Reload. # TODO(mark): Optimization: only reload if no changes were made. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Process conditions in this dict. This is done after variable expansion # so that conditions may take advantage of expanded variables. For example, # if the_dict contains: # {'type': '<(library_type)', # 'conditions': [['_type=="static_library"', { ... }]]}, # _type, as used in the condition, will only be set to the value of # library_type if variable expansion is performed before condition # processing. However, condition processing should occur prior to recursion # so that variables (both automatic and "variables" dict type) may be # adjusted by conditions sections, merged into the_dict, and have the # intended impact on contained dicts. # # This arrangement means that a "conditions" section containing a "variables" # section will only have those variables effective in subdicts, not in # the_dict. The workaround is to put a "conditions" section within a # "variables" section. For example: # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will not result in "IS_MAC" being appended to the "defines" list in the # current scope but would result in it being appended to the "defines" list # within "my_subdict". By comparison: # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will append "IS_MAC" to both "defines" lists. # Evaluate conditions sections, allowing variable expansions within them # as well as nested conditionals. This will process a 'conditions' or # 'target_conditions' section, perform appropriate merging and recursive # conditional and variable processing, and then remove the conditions section # from the_dict if it is present. ProcessConditionsInDict(the_dict, phase, variables, build_file) # Conditional processing may have resulted in changes to automatics or the # variables dict. Reload. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. for key, value in the_dict.items(): # Skip "variables" and string values, which were already processed if # present. if key == "variables" or type(value) is str: continue if type(value) is dict: # Pass a copy of the variables dict so that subdicts can't influence # parents. ProcessVariablesAndConditionsInDict( value, phase, variables, build_file, key ) elif type(value) is list: # The list itself can't influence the variables dict, and # ProcessVariablesAndConditionsInList will make copies of the variables # dict if it needs to pass it to something that can influence it. No # copy is necessary here. ProcessVariablesAndConditionsInList(value, phase, variables, build_file) elif type(value) is not int: raise TypeError("Unknown type " + value.__class__.__name__ + " for " + key) def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file): # Iterate using an index so that new values can be assigned into the_list. index = 0 while index < len(the_list): item = the_list[index] if type(item) is dict: # Make a copy of the variables dict so that it won't influence anything # outside of its own scope. ProcessVariablesAndConditionsInDict(item, phase, variables, build_file) elif type(item) is list: ProcessVariablesAndConditionsInList(item, phase, variables, build_file) elif type(item) is str: expanded = ExpandVariables(item, phase, variables, build_file) if type(expanded) in (str, int): the_list[index] = expanded elif type(expanded) is list: the_list[index : index + 1] = expanded index += len(expanded) # index now identifies the next item to examine. Continue right now # without falling into the index increment below. continue else: raise ValueError( "Variable expansion in this context permits strings and " + "lists only, found " + expanded.__class__.__name__ + " at " + index ) elif type(item) is not int: raise TypeError( "Unknown type " + item.__class__.__name__ + " at index " + index ) index = index + 1 def BuildTargetsDict(data): """Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" key is taken as a list containing target dicts. Each target's fully-qualified name is constructed from the pathname of the build file (|data| key) and its "target_name" property. These fully-qualified names are used as the keys in the returned dict. These keys provide access to the target dicts, the dicts in the "targets" lists. """ targets = {} for build_file in data["target_build_files"]: for target in data[build_file].get("targets", []): target_name = gyp.common.QualifiedTarget( build_file, target["target_name"], target["toolset"] ) if target_name in targets: raise GypError("Duplicate target definitions for " + target_name) targets[target_name] = target return targets def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict. """ all_dependency_sections = [ dep + op for dep in dependency_sections for op in ("", "!", "/") ] for target, target_dict in targets.items(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict["toolset"] for dependency_key in all_dependency_sections: dependencies = target_dict.get(dependency_key, []) for index, dep in enumerate(dependencies): dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( target_build_file, dep, toolset ) if not multiple_toolsets: # Ignore toolset specification in the dependency if it is specified. dep_toolset = toolset dependency = gyp.common.QualifiedTarget( dep_file, dep_target, dep_toolset ) dependencies[index] = dependency # Make sure anything appearing in a list other than "dependencies" also # appears in the "dependencies" list. if ( dependency_key != "dependencies" and dependency not in target_dict["dependencies"] ): raise GypError( "Found " + dependency + " in " + dependency_key + " of " + target + ", but not in dependencies" ) def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called. """ for target, target_dict in targets.items(): target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) # Loop this way instead of "for dependency in" or "for index in range" # because the dependencies list will be modified within the loop body. index = 0 while index < len(dependencies): ( dependency_build_file, dependency_target, dependency_toolset, ) = gyp.common.ParseQualifiedTarget(dependencies[index]) if dependency_target != "*" and dependency_toolset != "*": # Not a wildcard. Keep it moving. index = index + 1 continue if dependency_build_file == target_build_file: # It's an error for a target to depend on all other targets in # the same file, because a target cannot depend on itself. raise GypError( "Found wildcard in " + dependency_key + " of " + target + " referring to same build file" ) # Take the wildcard out and adjust the index so that the next # dependency in the list will be processed the next time through the # loop. del dependencies[index] index = index - 1 # Loop through the targets in the other build file, adding them to # this target's list of dependencies in place of the removed # wildcard. dependency_target_dicts = data[dependency_build_file]["targets"] for dependency_target_dict in dependency_target_dicts: if int(dependency_target_dict.get("suppress_wildcard", False)): continue dependency_target_name = dependency_target_dict["target_name"] if ( dependency_target not in {"*", dependency_target_name} ): continue dependency_target_toolset = dependency_target_dict["toolset"] if ( dependency_toolset not in {"*", dependency_target_toolset} ): continue dependency = gyp.common.QualifiedTarget( dependency_build_file, dependency_target_name, dependency_target_toolset, ) index = index + 1 dependencies.insert(index, dependency) index = index + 1 def Unify(items): """Removes duplicate elements from items, keeping the first element.""" seen = {} return [seen.setdefault(e, e) for e in items if e not in seen] def RemoveDuplicateDependencies(targets): """Makes sure every dependency appears only once in all targets's dependency lists.""" for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: target_dict[dependency_key] = Unify(dependencies) def Filter(items, item): """Removes item from items.""" res = {} return [res.setdefault(e, e) for e in items if e != item] def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency variable set.""" for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if t == target_name and ( targets[t] .get("variables", {}) .get("prune_self_dependency", 0) ): target_dict[dependency_key] = Filter( dependencies, target_name ) def RemoveLinkDependenciesFromNoneTargets(targets): """Remove dependencies having the 'link_dependency' attribute from the 'none' targets.""" for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if target_dict.get("type", None) == "none": if targets[t].get("variables", {}).get("link_dependency", 0): target_dict[dependency_key] = Filter( target_dict[dependency_key], t ) class DependencyGraphNode: """ Attributes: ref: A reference to an object that this DependencyGraphNode represents. dependencies: List of DependencyGraphNodes on which this one depends. dependents: List of DependencyGraphNodes that depend on this one. """ class CircularException(GypError): pass def __init__(self, ref): self.ref = ref self.dependencies = [] self.dependents = [] def __repr__(self): return "" % self.ref def FlattenToList(self): # flat_list is the sorted list of dependencies - actually, the list items # are the "ref" attributes of DependencyGraphNodes. Every target will # appear in flat_list after all of its dependencies, and before all of its # dependents. flat_list = OrderedSet() def ExtractNodeRef(node): """Extracts the object that the node represents from the given node.""" return node.ref # in_degree_zeros is the list of DependencyGraphNodes that have no # dependencies not in flat_list. Initially, it is a copy of the children # of this node, because when the graph was built, nodes with no # dependencies were made implicit dependents of the root node. in_degree_zeros = sorted(self.dependents[:], key=ExtractNodeRef) while in_degree_zeros: # Nodes in in_degree_zeros have no dependencies not in flat_list, so they # can be appended to flat_list. Take these nodes out of in_degree_zeros # as work progresses, so that the next node to process from the list can # always be accessed at a consistent position. node = in_degree_zeros.pop() flat_list.add(node.ref) # Look at dependents of the node just added to flat_list. Some of them # may now belong in in_degree_zeros. for node_dependent in sorted(node.dependents, key=ExtractNodeRef): is_in_degree_zero = True # TODO: We want to check through the # node_dependent.dependencies list but if it's long and we # always start at the beginning, then we get O(n^2) behaviour. for node_dependent_dependency in sorted( node_dependent.dependencies, key=ExtractNodeRef ): if node_dependent_dependency.ref not in flat_list: # The dependent one or more dependencies not in flat_list. # There will be more chances to add it to flat_list # when examining it again as a dependent of those other # dependencies, provided that there are no cycles. is_in_degree_zero = False break if is_in_degree_zero: # All of the dependent's dependencies are already in flat_list. Add # it to in_degree_zeros where it will be processed in a future # iteration of the outer loop. in_degree_zeros += [node_dependent] return list(flat_list) def FindCycles(self): """ Returns a list of cycles in the graph, where each cycle is its own list. """ results = [] visited = set() def Visit(node, path): for child in node.dependents: if child in path: results.append([child] + path[: path.index(child) + 1]) elif child not in visited: visited.add(child) Visit(child, [child] + path) visited.add(self) Visit(self, [self]) return results def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies is None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref and dependency.ref not in dependencies: dependencies.append(dependency.ref) return dependencies def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point. """ if dependencies is None: dependencies = [] index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Add any dependencies whose settings should be imported to the list # if not already present. Newly-added items will be checked for # their own imports when the list iteration reaches them. # Rather than simply appending new items, insert them after the # dependency that exported them. This is done to more closely match # the depth-first method used by DeepDependencies. add_index = 1 for imported_dependency in dependency_dict.get( "export_dependent_settings", [] ): if imported_dependency not in dependencies: dependencies.insert(index + add_index, imported_dependency) add_index = add_index + 1 index = index + 1 return dependencies def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies) def DeepDependencies(self, dependencies=None): """Returns an OrderedSet of all of a target's dependencies, recursively.""" if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref is None: continue if dependency.ref not in dependencies: dependency.DeepDependencies(dependencies) dependencies.add(dependency.ref) return dependencies def _LinkDependenciesInternal( self, targets, include_shared_libraries, dependencies=None, initial=True ): """Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect dependencies that are linked into the linkable target for which the list is being built. If |include_shared_libraries| is False, the resulting dependencies will not include shared_library targets that are linked into this target. """ if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() # Check for None, corresponding to the root node. if self.ref is None: return dependencies # It's kind of sucky that |targets| has to be passed into this function, # but that's presently the easiest way to access the target dicts so that # this function can find target types. if "target_name" not in targets[self.ref]: raise GypError("Missing 'target_name' field in target.") if "type" not in targets[self.ref]: raise GypError( "Missing 'type' field in target %s" % targets[self.ref]["target_name"] ) target_type = targets[self.ref]["type"] is_linkable = target_type in linkable_types if initial and not is_linkable: # If this is the first target being examined and it's not linkable, # return an empty list of link dependencies, because the link # dependencies are intended to apply to the target itself (initial is # True) and this target won't be linked. return dependencies # Don't traverse 'none' targets if explicitly excluded. if target_type == "none" and not targets[self.ref].get( "dependencies_traverse", True ): dependencies.add(self.ref) return dependencies # Executables, mac kernel extensions, windows drivers and loadable modules # are already fully and finally linked. Nothing else can be a link # dependency of them, there can only be dependencies in the sense that a # dependent target might run an executable or load the loadable_module. if not initial and target_type in ( "executable", "loadable_module", "mac_kernel_extension", "windows_driver", ): return dependencies # Shared libraries are already fully linked. They should only be included # in |dependencies| when adjusting static library dependencies (in order to # link against the shared_library's import lib), but should not be included # in |dependencies| when propagating link_settings. # The |include_shared_libraries| flag controls which of these two cases we # are handling. if ( not initial and target_type == "shared_library" and not include_shared_libraries ): return dependencies # The target is linkable, add it to the list of link dependencies. if self.ref not in dependencies: dependencies.add(self.ref) if initial or not is_linkable: # If this is a subsequent target and it's linkable, don't look any # further for linkable dependencies, as they'll already be linked into # this target linkable. Always look at dependencies of the initial # target, and always look at dependencies of non-linkables. for dependency in self.dependencies: dependency._LinkDependenciesInternal( targets, include_shared_libraries, dependencies, False ) return dependencies def DependenciesForLinkSettings(self, targets): """ Returns a list of dependency targets whose link_settings should be merged into this target. """ # TODO(sbaig) Currently, chrome depends on the bug that shared libraries' # link_settings are propagated. So for now, we will allow it, unless the # 'allow_sharedlib_linksettings_propagation' flag is explicitly set to # False. Once chrome is fixed, we can remove this flag. include_shared_libraries = targets[self.ref].get( "allow_sharedlib_linksettings_propagation", True ) return self._LinkDependenciesInternal(targets, include_shared_libraries) def DependenciesToLinkAgainst(self, targets): """ Returns a list of dependency targets that are linked into this target. """ return self._LinkDependenciesInternal(targets, True) def BuildDependencyList(targets): # Create a DependencyGraphNode for each target. Put it into a dict for easy # access. dependency_nodes = {} for target, spec in targets.items(): if target not in dependency_nodes: dependency_nodes[target] = DependencyGraphNode(target) # Set up the dependency links. Targets that have no dependencies are treated # as dependent on root_node. root_node = DependencyGraphNode(None) for target, spec in targets.items(): target_node = dependency_nodes[target] dependencies = spec.get("dependencies") if not dependencies: target_node.dependencies = [root_node] root_node.dependents.append(target_node) else: for dependency in dependencies: dependency_node = dependency_nodes.get(dependency) if not dependency_node: raise GypError( "Dependency '%s' not found while " "trying to load target %s" % (dependency, target) ) target_node.dependencies.append(dependency_node) dependency_node.dependents.append(target_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(targets): if not root_node.dependents: # If all targets have dependencies, add the first target as a dependent # of root_node so that the cycle can be discovered from root_node. target = next(iter(targets)) target_node = dependency_nodes[target] target_node.dependencies.append(root_node) root_node.dependents.append(target_node) cycles = [] for cycle in root_node.FindCycles(): paths = [node.ref for node in cycle] cycles.append("Cycle: %s" % " -> ".join(paths)) raise DependencyGraphNode.CircularException( "Cycles in dependency graph detected:\n" + "\n".join(cycles) ) return [dependency_nodes, flat_list] def VerifyNoGYPFileCircularDependencies(targets): # Create a DependencyGraphNode for each gyp file containing a target. Put # it into a dict for easy access. dependency_nodes = {} for target in targets: build_file = gyp.common.BuildFile(target) if build_file not in dependency_nodes: dependency_nodes[build_file] = DependencyGraphNode(build_file) # Set up the dependency links. for target, spec in targets.items(): build_file = gyp.common.BuildFile(target) build_file_node = dependency_nodes[build_file] target_dependencies = spec.get("dependencies", []) for dependency in target_dependencies: try: dependency_build_file = gyp.common.BuildFile(dependency) except GypError as e: gyp.common.ExceptionAppend( e, "while computing dependencies of .gyp file %s" % build_file ) raise if dependency_build_file == build_file: # A .gyp file is allowed to refer back to itself. continue dependency_node = dependency_nodes.get(dependency_build_file) if not dependency_node: raise GypError("Dependency '%s' not found" % dependency_build_file) if dependency_node not in build_file_node.dependencies: build_file_node.dependencies.append(dependency_node) dependency_node.dependents.append(build_file_node) # Files that have no dependencies are treated as dependent on root_node. root_node = DependencyGraphNode(None) for build_file_node in dependency_nodes.values(): if len(build_file_node.dependencies) == 0: build_file_node.dependencies.append(root_node) root_node.dependents.append(build_file_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(dependency_nodes): if not root_node.dependents: # If all files have dependencies, add the first file as a dependent # of root_node so that the cycle can be discovered from root_node. file_node = next(iter(dependency_nodes.values())) file_node.dependencies.append(root_node) root_node.dependents.append(file_node) cycles = [] for cycle in root_node.FindCycles(): paths = [node.ref for node in cycle] cycles.append("Cycle: %s" % " -> ".join(paths)) raise DependencyGraphNode.CircularException( "Cycles in .gyp file dependency graph detected:\n" + "\n".join(cycles) ) def DoDependentSettings(key, flat_list, targets, dependency_nodes): # key should be one of all_dependent_settings, direct_dependent_settings, # or link_settings. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) if key == "all_dependent_settings": dependencies = dependency_nodes[target].DeepDependencies() elif key == "direct_dependent_settings": dependencies = dependency_nodes[target].DirectAndImportedDependencies( targets ) elif key == "link_settings": dependencies = dependency_nodes[target].DependenciesForLinkSettings(targets) else: raise GypError( "DoDependentSettings doesn't know how to determine " "dependencies for " + key ) for dependency in dependencies: dependency_dict = targets[dependency] if key not in dependency_dict: continue dependency_build_file = gyp.common.BuildFile(dependency) MergeDicts( target_dict, dependency_dict[key], build_file, dependency_build_file ) def AdjustStaticLibraryDependencies( flat_list, targets, dependency_nodes, sort_dependencies ): # Recompute target "dependencies" properties. For each static library # target, remove "dependencies" entries referring to other static libraries, # unless the dependency has the "hard_dependency" attribute set. For each # linkable target, add a "dependencies" entry referring to all of the # target's computed list of link dependencies (including static libraries # if no such entry is already present. for target in flat_list: target_dict = targets[target] target_type = target_dict["type"] if target_type == "static_library": if "dependencies" not in target_dict: continue target_dict["dependencies_original"] = target_dict.get("dependencies", [])[ : ] # A static library should not depend on another static library unless # the dependency relationship is "hard," which should only be done when # a dependent relies on some side effect other than just the build # product, like a rule or action output. Further, if a target has a # non-hard dependency, but that dependency exports a hard dependency, # the non-hard dependency can safely be removed, but the exported hard # dependency must be added to the target to keep the same dependency # ordering. dependencies = dependency_nodes[target].DirectAndImportedDependencies( targets ) index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Remove every non-hard static library dependency and remove every # non-static library dependency that isn't a direct dependency. if ( dependency_dict["type"] == "static_library" and not dependency_dict.get("hard_dependency", False) ) or ( dependency_dict["type"] != "static_library" and dependency not in target_dict["dependencies"] ): # Take the dependency out of the list, and don't increment index # because the next dependency to analyze will shift into the index # formerly occupied by the one being removed. del dependencies[index] else: index = index + 1 # Update the dependencies. If the dependencies list is empty, it's not # needed, so unhook it. if len(dependencies) > 0: target_dict["dependencies"] = dependencies else: del target_dict["dependencies"] elif target_type in linkable_types: # Get a list of dependency targets that should be linked into this # target. Add them to the dependencies list if they're not already # present. link_dependencies = dependency_nodes[target].DependenciesToLinkAgainst( targets ) for dependency in link_dependencies: if dependency == target: continue if "dependencies" not in target_dict: target_dict["dependencies"] = [] if dependency not in target_dict["dependencies"]: target_dict["dependencies"].append(dependency) # Sort the dependencies list in the order from dependents to dependencies. # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D. # Note: flat_list is already sorted in the order from dependencies to # dependents. if sort_dependencies and "dependencies" in target_dict: target_dict["dependencies"] = [ dep for dep in reversed(flat_list) if dep in target_dict["dependencies"] ] # Initialize this here to speed up MakePathRelative. exception_re = re.compile(r"""["']?[-/$<>^]""") def MakePathRelative(to_file, fro_file, item): # If item is a relative path, it's relative to the build file dict that it's # coming from. Fix it up to make it relative to the build file dict that # it's going into. # Exception: any |item| that begins with these special characters is # returned without modification. # / Used when a path is already absolute (shortcut optimization; # such paths would be returned as absolute anyway) # $ Used for build environment variables # - Used for some build environment flags (such as -lapr-1 in a # "libraries" section) # < Used for our own variable and command expansions (see ExpandVariables) # > Used for our own variable and command expansions (see ExpandVariables) # ^ Used for our own variable and command expansions (see ExpandVariables) # # "/' Used when a value is quoted. If these are present, then we # check the second character instead. # if to_file == fro_file or exception_re.match(item): return item else: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. ret = os.path.normpath( os.path.join( gyp.common.RelativePath( os.path.dirname(fro_file), os.path.dirname(to_file) ), item, ) ).replace("\\", "/") if item.endswith("/"): ret += "/" return ret def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): # Python documentation recommends objects which do not support hash # set this value to None. Python library objects follow this rule. def is_hashable(val): return val.__hash__ # If x is hashable, returns whether x is in s. Else returns whether x is in items. def is_in_set_or_list(x, s, items): if is_hashable(x): return x in s return x in items prepend_index = 0 # Make membership testing of hashables in |to| (in particular, strings) # faster. hashable_to_set = {x for x in to if is_hashable(x)} for item in fro: singleton = False if type(item) in (str, int): # The cheap and easy case. to_item = MakePathRelative(to_file, fro_file, item) if is_paths else item if not (type(item) is str and item.startswith("-")): # Any string that doesn't begin with a "-" is a singleton - it can # only appear once in a list, to be enforced by the list merge append # or prepend. singleton = True elif type(item) is dict: # Make a copy of the dictionary, continuing to look for paths to fix. # The other intelligent aspects of merge processing won't apply because # item is being merged into an empty dict. to_item = {} MergeDicts(to_item, item, to_file, fro_file) elif type(item) is list: # Recurse, making a copy of the list. If the list contains any # descendant dicts, path fixing will occur. Note that here, custom # values for is_paths and append are dropped; those are only to be # applied to |to| and |fro|, not sublists of |fro|. append shouldn't # matter anyway because the new |to_item| list is empty. to_item = [] MergeLists(to_item, item, to_file, fro_file) else: raise TypeError( "Attempt to merge list item of unsupported type " + item.__class__.__name__ ) if append: # If appending a singleton that's already in the list, don't append. # This ensures that the earliest occurrence of the item will stay put. if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to): to.append(to_item) if is_hashable(to_item): hashable_to_set.add(to_item) else: # If prepending a singleton that's already in the list, remove the # existing instance and proceed with the prepend. This ensures that the # item appears at the earliest possible position in the list. while singleton and to_item in to: to.remove(to_item) # Don't just insert everything at index 0. That would prepend the new # items to the list in reverse order, which would be an unwelcome # surprise. to.insert(prepend_index, to_item) if is_hashable(to_item): hashable_to_set.add(to_item) prepend_index = prepend_index + 1 def MergeDicts(to, fro, to_file, fro_file): # I wanted to name the parameter "from" but it's a Python keyword... for k, v in fro.items(): # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give # copy semantics. Something else may want to merge from the |fro| dict # later, and having the same dict ref pointed to twice in the tree isn't # what anyone wants considering that the dicts may subsequently be # modified. if k in to: bad_merge = False if type(v) in (str, int): if type(to[k]) not in (str, int): bad_merge = True elif not isinstance(v, type(to[k])): bad_merge = True if bad_merge: raise TypeError( "Attempt to merge dict value of type " + v.__class__.__name__ + " into incompatible type " + to[k].__class__.__name__ + " for key " + k ) if type(v) in (str, int): # Overwrite the existing value, if any. Cheap and easy. is_path = IsPathSection(k) if is_path: to[k] = MakePathRelative(to_file, fro_file, v) else: to[k] = v elif type(v) is dict: # Recurse, guaranteeing copies will be made of objects that require it. if k not in to: to[k] = {} MergeDicts(to[k], v, to_file, fro_file) elif type(v) is list: # Lists in dicts can be merged with different policies, depending on # how the key in the "from" dict (k, the from-key) is written. # # If the from-key has ...the to-list will have this action # this character appended:... applied when receiving the from-list: # = replace # + prepend # ? set, only if to-list does not yet exist # (none) append # # This logic is list-specific, but since it relies on the associated # dict key, it's checked in this dict-oriented function. ext = k[-1] append = True if ext == "=": list_base = k[:-1] lists_incompatible = [list_base, list_base + "?"] to[list_base] = [] elif ext == "+": list_base = k[:-1] lists_incompatible = [list_base + "=", list_base + "?"] append = False elif ext == "?": list_base = k[:-1] lists_incompatible = [list_base, list_base + "=", list_base + "+"] else: list_base = k lists_incompatible = [list_base + "=", list_base + "?"] # Some combinations of merge policies appearing together are meaningless. # It's stupid to replace and append simultaneously, for example. Append # and prepend are the only policies that can coexist. for list_incompatible in lists_incompatible: if list_incompatible in fro: raise GypError( "Incompatible list policies " + k + " and " + list_incompatible ) if list_base in to: if ext == "?": # If the key ends in "?", the list will only be merged if it doesn't # already exist. continue elif type(to[list_base]) is not list: # This may not have been checked above if merging in a list with an # extension character. raise TypeError( "Attempt to merge dict value of type " + v.__class__.__name__ + " into incompatible type " + to[list_base].__class__.__name__ + " for key " + list_base + "(" + k + ")" ) else: to[list_base] = [] # Call MergeLists, which will make copies of objects that require it. # MergeLists can recurse back into MergeDicts, although this will be # to make copies of dicts (with paths fixed), there will be no # subsequent dict "merging" once entering a list because lists are # always replaced, appended to, or prepended to. is_paths = IsPathSection(list_base) MergeLists(to[list_base], v, to_file, fro_file, is_paths, append) else: raise TypeError( "Attempt to merge dict value of unsupported type " + v.__class__.__name__ + " for key " + k ) def MergeConfigWithInheritance( new_configuration_dict, build_file, target_dict, configuration, visited ): # Skip if previously visited. if configuration in visited: return # Look at this configuration. configuration_dict = target_dict["configurations"][configuration] # Merge in parents. for parent in configuration_dict.get("inherit_from", []): MergeConfigWithInheritance( new_configuration_dict, build_file, target_dict, parent, visited + [configuration], ) # Merge it into the new config. MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file) # Drop abstract. if "abstract" in new_configuration_dict: del new_configuration_dict["abstract"] def SetUpConfigurations(target, target_dict): # key_suffixes is a list of key suffixes that might appear on key names. # These suffixes are handled in conditional evaluations (for =, +, and ?) # and rules/exclude processing (for ! and /). Keys with these suffixes # should be treated the same as keys without. key_suffixes = ["=", "+", "?", "!", "/"] build_file = gyp.common.BuildFile(target) # Provide a single configuration by default if none exists. # TODO(mark): Signal an error if default_configurations exists but # configurations does not. if "configurations" not in target_dict: target_dict["configurations"] = {"Default": {}} if "default_configuration" not in target_dict: concrete = [ i for (i, config) in target_dict["configurations"].items() if not config.get("abstract") ] target_dict["default_configuration"] = sorted(concrete)[0] merged_configurations = {} configs = target_dict["configurations"] for (configuration, old_configuration_dict) in configs.items(): # Skip abstract configurations (saves work only). if old_configuration_dict.get("abstract"): continue # Configurations inherit (most) settings from the enclosing target scope. # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = {} for (key, target_val) in target_dict.items(): key_ext = key[-1:] key_base = key[:-1] if key_ext in key_suffixes else key if key_base not in non_configuration_keys: new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val) # Merge in configuration (with all its parents first). MergeConfigWithInheritance( new_configuration_dict, build_file, target_dict, configuration, [] ) merged_configurations[configuration] = new_configuration_dict # Put the new configurations back into the target dict as a configuration. for configuration in merged_configurations: target_dict["configurations"][configuration] = merged_configurations[ configuration ] # Now drop all the abstract ones. configs = target_dict["configurations"] target_dict["configurations"] = { k: v for k, v in configs.items() if not v.get("abstract") } # Now that all of the target's configurations have been built, go through # the target dict's keys and remove everything that's been moved into a # "configurations" section. delete_keys = [] for key in target_dict: key_ext = key[-1:] key_base = key[:-1] if key_ext in key_suffixes else key if key_base not in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del target_dict[key] # Check the configurations to see if they contain invalid keys. for configuration in target_dict["configurations"]: configuration_dict = target_dict["configurations"][configuration] for key in configuration_dict: if key in invalid_configuration_keys: raise GypError( "%s not allowed in the %s configuration, found in " "target %s" % (key, configuration, target) ) def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include". """ # Look through the dictionary for any lists whose keys end in "!" or "/". # These are lists that will be treated as exclude lists and regular # expression-based exclude/include lists. Collect the lists that are # needed first, looking for the lists that they operate on, and assemble # then into |lists|. This is done in a separate loop up front, because # the _included and _excluded keys need to be added to the_dict, and that # can't be done while iterating through it. lists = [] del_lists = [] for key, value in the_dict.items(): if not key: continue operation = key[-1] if operation not in {"!", "/"}: continue if type(value) is not list: raise ValueError( name + " key " + key + " must be list, not " + value.__class__.__name__ ) list_key = key[:-1] if list_key not in the_dict: # This happens when there's a list like "sources!" but no corresponding # "sources" list. Since there's nothing for it to operate on, queue up # the "sources!" list for deletion now. del_lists.append(key) continue if type(the_dict[list_key]) is not list: value = the_dict[list_key] raise ValueError( name + " key " + list_key + " must be list, not " + value.__class__.__name__ + " when applying " + {"!": "exclusion", "/": "regex"}[operation] ) if list_key not in lists: lists.append(list_key) # Delete the lists that are known to be unneeded at this point. for del_list in del_lists: del the_dict[del_list] for list_key in lists: the_list = the_dict[list_key] # Initialize the list_actions list, which is parallel to the_list. Each # item in list_actions identifies whether the corresponding item in # the_list should be excluded, unconditionally preserved (included), or # whether no exclusion or inclusion has been applied. Items for which # no exclusion or inclusion has been applied (yet) have value -1, items # excluded have value 0, and items included have value 1. Includes and # excludes override previous actions. All items in list_actions are # initialized to -1 because no excludes or includes have been processed # yet. list_actions = list((-1,) * len(the_list)) exclude_key = list_key + "!" if exclude_key in the_dict: for exclude_item in the_dict[exclude_key]: for index, list_item in enumerate(the_list): if exclude_item == list_item: # This item matches the exclude_item, so set its action to 0 # (exclude). list_actions[index] = 0 # The "whatever!" list is no longer needed, dump it. del the_dict[exclude_key] regex_key = list_key + "/" if regex_key in the_dict: for regex_item in the_dict[regex_key]: [action, pattern] = regex_item pattern_re = re.compile(pattern) if action == "exclude": # This item matches an exclude regex, set its value to 0 (exclude). action_value = 0 elif action == "include": # This item matches an include regex, set its value to 1 (include). action_value = 1 else: # This is an action that doesn't make any sense. raise ValueError( "Unrecognized action " + action + " in " + name + " key " + regex_key ) for index, list_item in enumerate(the_list): if list_actions[index] == action_value: # Even if the regex matches, nothing will change so continue # (regex searches are expensive). continue if pattern_re.search(list_item): # Regular expression match. list_actions[index] = action_value # The "whatever/" list is no longer needed, dump it. del the_dict[regex_key] # Add excluded items to the excluded list. # # Note that exclude_key ("sources!") is different from excluded_key # ("sources_excluded"). The exclude_key list is input and it was already # processed and deleted; the excluded_key list is output and it's about # to be created. excluded_key = list_key + "_excluded" if excluded_key in the_dict: raise GypError( name + " key " + excluded_key + " must not be present prior " " to applying exclusion/regex filters for " + list_key ) excluded_list = [] # Go backwards through the list_actions list so that as items are deleted, # the indices of items that haven't been seen yet don't shift. That means # that things need to be prepended to excluded_list to maintain them in the # same order that they existed in the_list. for index in range(len(list_actions) - 1, -1, -1): if list_actions[index] == 0: # Dump anything with action 0 (exclude). Keep anything with action 1 # (include) or -1 (no include or exclude seen for the item). excluded_list.insert(0, the_list[index]) del the_list[index] # If anything was excluded, put the excluded list into the_dict at # excluded_key. if len(excluded_list) > 0: the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.items(): if type(value) is dict: ProcessListFiltersInDict(key, value) elif type(value) is list: ProcessListFiltersInList(key, value) def ProcessListFiltersInList(name, the_list): for item in the_list: if type(item) is dict: ProcessListFiltersInDict(name, item) elif type(item) is list: ProcessListFiltersInList(name, item) def ValidateTargetType(target, target_dict): """Ensures the 'type' field on the target is one of the known types. Arguments: target: string, name of target. target_dict: dict, target spec. Raises an exception on error. """ VALID_TARGET_TYPES = ( "executable", "loadable_module", "static_library", "shared_library", "mac_kernel_extension", "none", "windows_driver", ) target_type = target_dict.get("type", None) if target_type not in VALID_TARGET_TYPES: raise GypError( "Target %s has an invalid target type '%s'. " "Must be one of %s." % (target, target_type, "/".join(VALID_TARGET_TYPES)) ) if ( target_dict.get("standalone_static_library", 0) and not target_type == "static_library" ): raise GypError( "Target %s has type %s but standalone_static_library flag is" " only valid for static_library type." % (target, target_type) ) def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): """Ensures that the rules sections in target_dict are valid and consistent, and determines which sources they apply to. Arguments: target: string, name of target. target_dict: dict, target spec containing "rules" and "sources" lists. extra_sources_for_rules: a list of keys to scan for rule matches in addition to 'sources'. """ # Dicts to map between values found in rules' 'rule_name' and 'extension' # keys and the rule dicts themselves. rule_names = {} rule_extensions = {} rules = target_dict.get("rules", []) for rule in rules: # Make sure that there's no conflict among rule names and extensions. rule_name = rule["rule_name"] if rule_name in rule_names: raise GypError( f"rule {rule_name} exists in duplicate, target {target}" ) rule_names[rule_name] = rule rule_extension = rule["extension"] if rule_extension.startswith("."): rule_extension = rule_extension[1:] if rule_extension in rule_extensions: raise GypError( ( "extension %s associated with multiple rules, " + "target %s rules %s and %s" ) % ( rule_extension, target, rule_extensions[rule_extension]["rule_name"], rule_name, ) ) rule_extensions[rule_extension] = rule # Make sure rule_sources isn't already there. It's going to be # created below if needed. if "rule_sources" in rule: raise GypError( "rule_sources must not exist in input, target %s rule %s" % (target, rule_name) ) rule_sources = [] source_keys = ["sources"] source_keys.extend(extra_sources_for_rules) for source_key in source_keys: for source in target_dict.get(source_key, []): (source_root, source_extension) = os.path.splitext(source) if source_extension.startswith("."): source_extension = source_extension[1:] if source_extension == rule_extension: rule_sources.append(source) if len(rule_sources) > 0: rule["rule_sources"] = rule_sources def ValidateRunAsInTarget(target, target_dict, build_file): target_name = target_dict.get("target_name") run_as = target_dict.get("run_as") if not run_as: return if type(run_as) is not dict: raise GypError( "The 'run_as' in target %s from file %s should be a " "dictionary." % (target_name, build_file) ) action = run_as.get("action") if not action: raise GypError( "The 'run_as' in target %s from file %s must have an " "'action' section." % (target_name, build_file) ) if type(action) is not list: raise GypError( "The 'action' for 'run_as' in target %s from file %s " "must be a list." % (target_name, build_file) ) working_directory = run_as.get("working_directory") if working_directory and type(working_directory) is not str: raise GypError( "The 'working_directory' for 'run_as' in target %s " "in file %s should be a string." % (target_name, build_file) ) environment = run_as.get("environment") if environment and type(environment) is not dict: raise GypError( "The 'environment' for 'run_as' in target %s " "in file %s should be a dictionary." % (target_name, build_file) ) def ValidateActionsInTarget(target, target_dict, build_file): """Validates the inputs to the actions in a target.""" target_name = target_dict.get("target_name") actions = target_dict.get("actions", []) for action in actions: action_name = action.get("action_name") if not action_name: raise GypError( "Anonymous action in target %s. " "An action must have an 'action_name' field." % target_name ) inputs = action.get("inputs", None) if inputs is None: raise GypError("Action in target %s has no inputs." % target_name) action_command = action.get("action") if action_command and not action_command[0]: raise GypError("Empty action as command in target %s." % target_name) def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if type(v) is int: v = str(v) the_dict[k] = v elif type(v) is dict: TurnIntIntoStrInDict(v) elif type(v) is list: TurnIntIntoStrInList(v) if type(k) is int: del the_dict[k] the_dict[str(k)] = v def TurnIntIntoStrInList(the_list): """Given list the_list, recursively converts all integers into strings. """ for index, item in enumerate(the_list): if type(item) is int: the_list[index] = str(item) elif type(item) is dict: TurnIntIntoStrInDict(item) elif type(item) is list: TurnIntIntoStrInList(item) def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data): """Return only the targets that are deep dependencies of |root_targets|.""" qualified_root_targets = [] for target in root_targets: target = target.strip() qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list) if not qualified_targets: raise GypError("Could not find target %s" % target) qualified_root_targets.extend(qualified_targets) wanted_targets = {} for target in qualified_root_targets: wanted_targets[target] = targets[target] for dependency in dependency_nodes[target].DeepDependencies(): wanted_targets[dependency] = targets[dependency] wanted_flat_list = [t for t in flat_list if t in wanted_targets] # Prune unwanted targets from each build_file's data dict. for build_file in data["target_build_files"]: if "targets" not in data[build_file]: continue new_targets = [] for target in data[build_file]["targets"]: qualified_name = gyp.common.QualifiedTarget( build_file, target["target_name"], target["toolset"] ) if qualified_name in wanted_targets: new_targets.append(target) data[build_file]["targets"] = new_targets return wanted_targets, wanted_flat_list def VerifyNoCollidingTargets(targets): """Verify that no two targets in the same directory share the same name. Arguments: targets: A list of targets in the form 'path/to/file.gyp:target_name'. """ # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'. used = {} for target in targets: # Separate out 'path/to/file.gyp, 'target_name' from # 'path/to/file.gyp:target_name'. path, name = target.rsplit(":", 1) # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'. subdir, gyp = os.path.split(path) # Use '.' for the current directory '', so that the error messages make # more sense. if not subdir: subdir = "." # Prepare a key like 'path/to:target_name'. key = subdir + ":" + name if key in used: # Complain if this target is already used. raise GypError( 'Duplicate target name "%s" in directory "%s" used both ' 'in "%s" and "%s".' % (name, subdir, gyp, used[key]) ) used[key] = gyp def SetGeneratorGlobals(generator_input_info): # Set up path_sections and non_configuration_keys with the default data plus # the generator-specific data. global path_sections path_sections = set(base_path_sections) path_sections.update(generator_input_info["path_sections"]) global non_configuration_keys non_configuration_keys = base_non_configuration_keys[:] non_configuration_keys.extend(generator_input_info["non_configuration_keys"]) global multiple_toolsets multiple_toolsets = generator_input_info["generator_supports_multiple_toolsets"] global generator_filelist_paths generator_filelist_paths = generator_input_info["generator_filelist_paths"] def Load( build_files, variables, includes, depth, generator_input_info, check, circular_check, parallel, root_targets, ): SetGeneratorGlobals(generator_input_info) # A generator can have other lists (in addition to sources) be processed # for rules. extra_sources_for_rules = generator_input_info["extra_sources_for_rules"] # Load build files. This loads every target-containing build file into # the |data| dictionary such that the keys to |data| are build file names, # and the values are the entire build file contents after "early" or "pre" # processing has been done and includes have been resolved. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps # track of the keys corresponding to "target" files. data = {"target_build_files": set()} # Normalize paths everywhere. This is important because paths will be # used as keys to the data dict and for references between input files. build_files = set(map(os.path.normpath, build_files)) if parallel: LoadTargetBuildFilesParallel( build_files, data, variables, includes, depth, check, generator_input_info ) else: aux_data = {} for build_file in build_files: try: LoadTargetBuildFile( build_file, data, aux_data, variables, includes, depth, check, True ) except Exception as e: gyp.common.ExceptionAppend(e, "while trying to load %s" % build_file) raise # Build a dict to access each target's subdict by qualified name. targets = BuildTargetsDict(data) # Fully qualify all dependency links. QualifyDependencies(targets) # Remove self-dependencies from targets that have 'prune_self_dependencies' # set to 1. RemoveSelfDependencies(targets) # Expand dependencies specified as build_file:*. ExpandWildcardDependencies(targets, data) # Remove all dependencies marked as 'link_dependency' from the targets of # type 'none'. RemoveLinkDependenciesFromNoneTargets(targets) # Apply exclude (!) and regex (/) list filters only for dependency_sections. for target_name, target_dict in targets.items(): tmp_dict = {} for key_base in dependency_sections: for op in ("", "!", "/"): key = key_base + op if key in target_dict: tmp_dict[key] = target_dict[key] del target_dict[key] ProcessListFiltersInDict(target_name, tmp_dict) # Write the results back to |target_dict|. for key in tmp_dict: target_dict[key] = tmp_dict[key] # Make sure every dependency appears at most once. RemoveDuplicateDependencies(targets) if circular_check: # Make sure that any targets in a.gyp don't contain dependencies in other # .gyp files that further depend on a.gyp. VerifyNoGYPFileCircularDependencies(targets) [dependency_nodes, flat_list] = BuildDependencyList(targets) if root_targets: # Remove, from |targets| and |flat_list|, the targets that are not deep # dependencies of the targets specified in |root_targets|. targets, flat_list = PruneUnwantedTargets( targets, flat_list, dependency_nodes, root_targets, data ) # Check that no two targets in the same directory have the same name. VerifyNoCollidingTargets(flat_list) # Handle dependent settings of various types. for settings_type in [ "all_dependent_settings", "direct_dependent_settings", "link_settings", ]: DoDependentSettings(settings_type, flat_list, targets, dependency_nodes) # Take out the dependent settings now that they've been published to all # of the targets that require them. for target in flat_list: if settings_type in targets[target]: del targets[target][settings_type] # Make sure static libraries don't declare dependencies on other static # libraries, but that linkables depend on all unlinked static libraries # that they need so that their link steps will be correct. gii = generator_input_info if gii["generator_wants_static_library_dependencies_adjusted"]: AdjustStaticLibraryDependencies( flat_list, targets, dependency_nodes, gii["generator_wants_sorted_dependencies"], ) # Apply "post"/"late"/"target" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATE, variables, build_file ) # Move everything that can go into a "configurations" section into one. for target in flat_list: target_dict = targets[target] SetUpConfigurations(target, target_dict) # Apply exclude (!) and regex (/) list filters. for target in flat_list: target_dict = targets[target] ProcessListFiltersInDict(target, target_dict) # Apply "latelate" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATELATE, variables, build_file ) # Make sure that the rules make sense, and build up rule_sources lists as # needed. Not all generators will need to use the rule_sources lists, but # some may, and it seems best to build the list in a common spot. # Also validate actions and run_as elements in targets. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ValidateTargetType(target, target_dict) ValidateRulesInTarget(target, target_dict, extra_sources_for_rules) ValidateRunAsInTarget(target, target_dict, build_file) ValidateActionsInTarget(target, target_dict, build_file) # Generators might not expect ints. Turn them into strs. TurnIntIntoStrInDict(data) # TODO(mark): Return |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. return [flat_list, targets, data] #!/usr/bin/env python3 # Copyright 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for the input.py file.""" import gyp.input import unittest class TestFindCycles(unittest.TestCase): def setUp(self): self.nodes = {} for x in ("a", "b", "c", "d", "e"): self.nodes[x] = gyp.input.DependencyGraphNode(x) def _create_dependency(self, dependent, dependency): dependent.dependencies.append(dependency) dependency.dependents.append(dependent) def test_no_cycle_empty_graph(self): for label, node in self.nodes.items(): self.assertEqual([], node.FindCycles()) def test_no_cycle_line(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["b"], self.nodes["c"]) self._create_dependency(self.nodes["c"], self.nodes["d"]) for label, node in self.nodes.items(): self.assertEqual([], node.FindCycles()) def test_no_cycle_dag(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["a"], self.nodes["c"]) self._create_dependency(self.nodes["b"], self.nodes["c"]) for label, node in self.nodes.items(): self.assertEqual([], node.FindCycles()) def test_cycle_self_reference(self): self._create_dependency(self.nodes["a"], self.nodes["a"]) self.assertEqual( [[self.nodes["a"], self.nodes["a"]]], self.nodes["a"].FindCycles() ) def test_cycle_two_nodes(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["b"], self.nodes["a"]) self.assertEqual( [[self.nodes["a"], self.nodes["b"], self.nodes["a"]]], self.nodes["a"].FindCycles(), ) self.assertEqual( [[self.nodes["b"], self.nodes["a"], self.nodes["b"]]], self.nodes["b"].FindCycles(), ) def test_two_cycles(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["b"], self.nodes["a"]) self._create_dependency(self.nodes["b"], self.nodes["c"]) self._create_dependency(self.nodes["c"], self.nodes["b"]) cycles = self.nodes["a"].FindCycles() self.assertTrue([self.nodes["a"], self.nodes["b"], self.nodes["a"]] in cycles) self.assertTrue([self.nodes["b"], self.nodes["c"], self.nodes["b"]] in cycles) self.assertEqual(2, len(cycles)) def test_big_cycle(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["b"], self.nodes["c"]) self._create_dependency(self.nodes["c"], self.nodes["d"]) self._create_dependency(self.nodes["d"], self.nodes["e"]) self._create_dependency(self.nodes["e"], self.nodes["a"]) self.assertEqual( [ [ self.nodes["a"], self.nodes["b"], self.nodes["c"], self.nodes["d"], self.nodes["e"], self.nodes["a"], ] ], self.nodes["a"].FindCycles(), ) if __name__ == "__main__": unittest.main() #!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions to perform Xcode-style build steps. These functions are executed via gyp-mac-tool when using the Makefile generator. """ import fcntl import fnmatch import glob import json import os import plistlib import re import shutil import struct import subprocess import sys import tempfile def main(args): executor = MacTool() exit_code = executor.Dispatch(args) if exit_code is not None: sys.exit(exit_code) class MacTool: """This class performs all the Mac tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like copy-info-plist to CopyInfoPlist""" return name_string.title().replace("-", "") def ExecCopyBundleResource(self, source, dest, convert_to_binary): """Copies a resource file to the bundle/Resources directory, performing any necessary compilation on each resource.""" convert_to_binary = convert_to_binary == "True" extension = os.path.splitext(source)[1].lower() if os.path.isdir(source): # Copy tree. # TODO(thakis): This copies file attributes like mtime, while the # single-file branch below doesn't. This should probably be changed to # be consistent with the single-file branch. if os.path.exists(dest): shutil.rmtree(dest) shutil.copytree(source, dest) elif extension == ".xib": return self._CopyXIBFile(source, dest) elif extension == ".storyboard": return self._CopyXIBFile(source, dest) elif extension == ".strings" and not convert_to_binary: self._CopyStringsFile(source, dest) else: if os.path.exists(dest): os.unlink(dest) shutil.copy(source, dest) if convert_to_binary and extension in (".plist", ".strings"): self._ConvertToBinary(dest) def _CopyXIBFile(self, source, dest): """Compiles a XIB file with ibtool into a binary plist in the bundle.""" # ibtool sometimes crashes with relative paths. See crbug.com/314728. base = os.path.dirname(os.path.realpath(__file__)) if os.path.relpath(source): source = os.path.join(base, source) if os.path.relpath(dest): dest = os.path.join(base, dest) args = ["xcrun", "ibtool", "--errors", "--warnings", "--notices"] if os.environ["XCODE_VERSION_ACTUAL"] > "0700": args.extend(["--auto-activate-custom-fonts"]) if "IPHONEOS_DEPLOYMENT_TARGET" in os.environ: args.extend( [ "--target-device", "iphone", "--target-device", "ipad", "--minimum-deployment-target", os.environ["IPHONEOS_DEPLOYMENT_TARGET"], ] ) else: args.extend( [ "--target-device", "mac", "--minimum-deployment-target", os.environ["MACOSX_DEPLOYMENT_TARGET"], ] ) args.extend( ["--output-format", "human-readable-text", "--compile", dest, source] ) ibtool_section_re = re.compile(r"/\*.*\*/") ibtool_re = re.compile(r".*note:.*is clipping its content") try: stdout = subprocess.check_output(args) except subprocess.CalledProcessError as e: print(e.output) raise current_section_header = None for line in stdout.splitlines(): if ibtool_section_re.match(line): current_section_header = line elif not ibtool_re.match(line): if current_section_header: print(current_section_header) current_section_header = None print(line) return 0 def _ConvertToBinary(self, dest): subprocess.check_call( ["xcrun", "plutil", "-convert", "binary1", "-o", dest, dest] ) def _CopyStringsFile(self, source, dest): """Copies a .strings file using iconv to reconvert the input into UTF-16.""" input_code = self._DetectInputEncoding(source) or "UTF-8" # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing # semicolon in dictionary. # on invalid files. Do the same kind of validation. import CoreFoundation with open(source, "rb") as in_file: s = in_file.read() d = CoreFoundation.CFDataCreate(None, s, len(s)) _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) if error: return with open(dest, "wb") as fp: fp.write(s.decode(input_code).encode("UTF-16")) def _DetectInputEncoding(self, file_name): """Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.""" with open(file_name, "rb") as fp: try: header = fp.read(3) except Exception: return None if header.startswith(b"\xFE\xFF"): return "UTF-16" elif header.startswith(b"\xFF\xFE"): return "UTF-16" elif header.startswith(b"\xEF\xBB\xBF"): return "UTF-8" else: return None def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys): """Copies the |source| Info.plist to the destination directory |dest|.""" # Read the source Info.plist into memory. with open(source) as fd: lines = fd.read() # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). plist = plistlib.readPlistFromString(lines) if keys: plist.update(json.loads(keys[0])) lines = plistlib.writePlistToString(plist) # Go through all the environment variables and replace them as variables in # the file. IDENT_RE = re.compile(r"[_/\s]") for key in os.environ: if key.startswith("_"): continue evar = "${%s}" % key evalue = os.environ[key] lines = lines.replace(lines, evar, evalue) # Xcode supports various suffices on environment variables, which are # all undocumented. :rfc1034identifier is used in the standard project # template these days, and :identifier was used earlier. They are used to # convert non-url characters into things that look like valid urls -- # except that the replacement character for :identifier, '_' isn't valid # in a URL either -- oops, hence :rfc1034identifier was born. evar = "${%s:identifier}" % key evalue = IDENT_RE.sub("_", os.environ[key]) lines = lines.replace(lines, evar, evalue) evar = "${%s:rfc1034identifier}" % key evalue = IDENT_RE.sub("-", os.environ[key]) lines = lines.replace(lines, evar, evalue) # Remove any keys with values that haven't been replaced. lines = lines.splitlines() for i in range(len(lines)): if lines[i].strip().startswith("${"): lines[i] = None lines[i - 1] = None lines = "\n".join(line for line in lines if line is not None) # Write out the file with variables replaced. with open(dest, "w") as fd: fd.write(lines) # Now write out PkgInfo file now that the Info.plist file has been # "compiled". self._WritePkgInfo(dest) if convert_to_binary == "True": self._ConvertToBinary(dest) def _WritePkgInfo(self, info_plist): """This writes the PkgInfo file from the data stored in Info.plist.""" plist = plistlib.readPlist(info_plist) if not plist: return # Only create PkgInfo for executable types. package_type = plist["CFBundlePackageType"] if package_type != "APPL": return # The format of PkgInfo is eight characters, representing the bundle type # and bundle signature, each four characters. If that is missing, four # '?' characters are used instead. signature_code = plist.get("CFBundleSignature", "????") if len(signature_code) != 4: # Wrong length resets everything, too. signature_code = "?" * 4 dest = os.path.join(os.path.dirname(info_plist), "PkgInfo") with open(dest, "w") as fp: fp.write(f"{package_type}{signature_code}") def ExecFlock(self, lockfile, *cmd_list): """Emulates the most basic behavior of Linux's flock(1).""" # Rely on exception handling to report errors. fd = os.open(lockfile, os.O_RDONLY | os.O_NOCTTY | os.O_CREAT, 0o666) fcntl.flock(fd, fcntl.LOCK_EX) return subprocess.call(cmd_list) def ExecFilterLibtool(self, *cmd_list): """Calls libtool and filters out '/path/to/libtool: file: foo.o has no symbols'.""" libtool_re = re.compile( r"^.*libtool: (?:for architecture: \S* )?" r"file: .* has no symbols$" ) libtool_re5 = re.compile( r"^.*libtool: warning for library: " + r".* the table of contents is empty " + r"\(no object file members in the library define global symbols\)$" ) env = os.environ.copy() # Ref: # http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c # The problem with this flag is that it resets the file mtime on the file to # epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone. env["ZERO_AR_DATE"] = "1" libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env) err = libtoolout.communicate()[1].decode("utf-8") for line in err.splitlines(): if not libtool_re.match(line) and not libtool_re5.match(line): print(line, file=sys.stderr) # Unconditionally touch the output .a file on the command line if present # and the command succeeded. A bit hacky. if not libtoolout.returncode: for i in range(len(cmd_list) - 1): if cmd_list[i] == "-o" and cmd_list[i + 1].endswith(".a"): os.utime(cmd_list[i + 1], None) break return libtoolout.returncode def ExecPackageIosFramework(self, framework): # Find the name of the binary based on the part before the ".framework". binary = os.path.basename(framework).split(".")[0] module_path = os.path.join(framework, "Modules") if not os.path.exists(module_path): os.mkdir(module_path) module_template = ( "framework module %s {\n" ' umbrella header "%s.h"\n' "\n" " export *\n" " module * { export * }\n" "}\n" % (binary, binary) ) with open(os.path.join(module_path, "module.modulemap"), "w") as module_file: module_file.write(module_template) def ExecPackageFramework(self, framework, version): """Takes a path to Something.framework and the Current version of that and sets up all the symlinks.""" # Find the name of the binary based on the part before the ".framework". binary = os.path.basename(framework).split(".")[0] CURRENT = "Current" RESOURCES = "Resources" VERSIONS = "Versions" if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): # Binary-less frameworks don't seem to contain symlinks (see e.g. # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). return # Move into the framework directory to set the symlinks correctly. pwd = os.getcwd() os.chdir(framework) # Set up the Current version. self._Relink(version, os.path.join(VERSIONS, CURRENT)) # Set up the root symlinks. self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) # Back to where we were before! os.chdir(pwd) def _Relink(self, dest, link): """Creates a symlink to |dest| named |link|. If |link| already exists, it is overwritten.""" if os.path.lexists(link): os.remove(link) os.symlink(dest, link) def ExecCompileIosFrameworkHeaderMap(self, out, framework, *all_headers): framework_name = os.path.basename(framework).split(".")[0] all_headers = [os.path.abspath(header) for header in all_headers] filelist = {} for header in all_headers: filename = os.path.basename(header) filelist[filename] = header filelist[os.path.join(framework_name, filename)] = header WriteHmap(out, filelist) def ExecCopyIosFrameworkHeaders(self, framework, *copy_headers): header_path = os.path.join(framework, "Headers") if not os.path.exists(header_path): os.makedirs(header_path) for header in copy_headers: shutil.copy(header, os.path.join(header_path, os.path.basename(header))) def ExecCompileXcassets(self, keys, *inputs): """Compiles multiple .xcassets files into a single .car file. This invokes 'actool' to compile all the inputs .xcassets files. The |keys| arguments is a json-encoded dictionary of extra arguments to pass to 'actool' when the asset catalogs contains an application icon or a launch image. Note that 'actool' does not create the Assets.car file if the asset catalogs does not contains imageset. """ command_line = [ "xcrun", "actool", "--output-format", "human-readable-text", "--compress-pngs", "--notices", "--warnings", "--errors", ] is_iphone_target = "IPHONEOS_DEPLOYMENT_TARGET" in os.environ if is_iphone_target: platform = os.environ["CONFIGURATION"].split("-")[-1] if platform not in ("iphoneos", "iphonesimulator"): platform = "iphonesimulator" command_line.extend( [ "--platform", platform, "--target-device", "iphone", "--target-device", "ipad", "--minimum-deployment-target", os.environ["IPHONEOS_DEPLOYMENT_TARGET"], "--compile", os.path.abspath(os.environ["CONTENTS_FOLDER_PATH"]), ] ) else: command_line.extend( [ "--platform", "macosx", "--target-device", "mac", "--minimum-deployment-target", os.environ["MACOSX_DEPLOYMENT_TARGET"], "--compile", os.path.abspath(os.environ["UNLOCALIZED_RESOURCES_FOLDER_PATH"]), ] ) if keys: keys = json.loads(keys) for key, value in keys.items(): arg_name = "--" + key if isinstance(value, bool): if value: command_line.append(arg_name) elif isinstance(value, list): for v in value: command_line.append(arg_name) command_line.append(str(v)) else: command_line.append(arg_name) command_line.append(str(value)) # Note: actool crashes if inputs path are relative, so use os.path.abspath # to get absolute path name for inputs. command_line.extend(map(os.path.abspath, inputs)) subprocess.check_call(command_line) def ExecMergeInfoPlist(self, output, *inputs): """Merge multiple .plist files into a single .plist file.""" merged_plist = {} for path in inputs: plist = self._LoadPlistMaybeBinary(path) self._MergePlist(merged_plist, plist) plistlib.writePlist(merged_plist, output) def ExecCodeSignBundle(self, key, entitlements, provisioning, path, preserve): """Code sign a bundle. This function tries to code sign an iOS bundle, following the same algorithm as Xcode: 1. pick the provisioning profile that best match the bundle identifier, and copy it into the bundle as embedded.mobileprovision, 2. copy Entitlements.plist from user or SDK next to the bundle, 3. code sign the bundle. """ substitutions, overrides = self._InstallProvisioningProfile( provisioning, self._GetCFBundleIdentifier() ) entitlements_path = self._InstallEntitlements( entitlements, substitutions, overrides ) args = ["codesign", "--force", "--sign", key] if preserve == "True": args.extend(["--deep", "--preserve-metadata=identifier,entitlements"]) else: args.extend(["--entitlements", entitlements_path]) args.extend(["--timestamp=none", path]) subprocess.check_call(args) def _InstallProvisioningProfile(self, profile, bundle_identifier): """Installs embedded.mobileprovision into the bundle. Args: profile: string, optional, short name of the .mobileprovision file to use, if empty or the file is missing, the best file installed will be used bundle_identifier: string, value of CFBundleIdentifier from Info.plist Returns: A tuple containing two dictionary: variables substitutions and values to overrides when generating the entitlements file. """ source_path, provisioning_data, team_id = self._FindProvisioningProfile( profile, bundle_identifier ) target_path = os.path.join( os.environ["BUILT_PRODUCTS_DIR"], os.environ["CONTENTS_FOLDER_PATH"], "embedded.mobileprovision", ) shutil.copy2(source_path, target_path) substitutions = self._GetSubstitutions(bundle_identifier, team_id + ".") return substitutions, provisioning_data["Entitlements"] def _FindProvisioningProfile(self, profile, bundle_identifier): """Finds the .mobileprovision file to use for signing the bundle. Checks all the installed provisioning profiles (or if the user specified the PROVISIONING_PROFILE variable, only consult it) and select the most specific that correspond to the bundle identifier. Args: profile: string, optional, short name of the .mobileprovision file to use, if empty or the file is missing, the best file installed will be used bundle_identifier: string, value of CFBundleIdentifier from Info.plist Returns: A tuple of the path to the selected provisioning profile, the data of the embedded plist in the provisioning profile and the team identifier to use for code signing. Raises: SystemExit: if no .mobileprovision can be used to sign the bundle. """ profiles_dir = os.path.join( os.environ["HOME"], "Library", "MobileDevice", "Provisioning Profiles" ) if not os.path.isdir(profiles_dir): print( "cannot find mobile provisioning for %s" % (bundle_identifier), file=sys.stderr, ) sys.exit(1) provisioning_profiles = None if profile: profile_path = os.path.join(profiles_dir, profile + ".mobileprovision") if os.path.exists(profile_path): provisioning_profiles = [profile_path] if not provisioning_profiles: provisioning_profiles = glob.glob( os.path.join(profiles_dir, "*.mobileprovision") ) valid_provisioning_profiles = {} for profile_path in provisioning_profiles: profile_data = self._LoadProvisioningProfile(profile_path) app_id_pattern = profile_data.get("Entitlements", {}).get( "application-identifier", "" ) for team_identifier in profile_data.get("TeamIdentifier", []): app_id = f"{team_identifier}.{bundle_identifier}" if fnmatch.fnmatch(app_id, app_id_pattern): valid_provisioning_profiles[app_id_pattern] = ( profile_path, profile_data, team_identifier, ) if not valid_provisioning_profiles: print( "cannot find mobile provisioning for %s" % (bundle_identifier), file=sys.stderr, ) sys.exit(1) # If the user has multiple provisioning profiles installed that can be # used for ${bundle_identifier}, pick the most specific one (ie. the # provisioning profile whose pattern is the longest). selected_key = max(valid_provisioning_profiles, key=lambda v: len(v)) return valid_provisioning_profiles[selected_key] def _LoadProvisioningProfile(self, profile_path): """Extracts the plist embedded in a provisioning profile. Args: profile_path: string, path to the .mobileprovision file Returns: Content of the plist embedded in the provisioning profile as a dictionary. """ with tempfile.NamedTemporaryFile() as temp: subprocess.check_call( ["security", "cms", "-D", "-i", profile_path, "-o", temp.name] ) return self._LoadPlistMaybeBinary(temp.name) def _MergePlist(self, merged_plist, plist): """Merge |plist| into |merged_plist|.""" for key, value in plist.items(): if isinstance(value, dict): merged_value = merged_plist.get(key, {}) if isinstance(merged_value, dict): self._MergePlist(merged_value, value) merged_plist[key] = merged_value else: merged_plist[key] = value else: merged_plist[key] = value def _LoadPlistMaybeBinary(self, plist_path): """Loads into a memory a plist possibly encoded in binary format. This is a wrapper around plistlib.readPlist that tries to convert the plist to the XML format if it can't be parsed (assuming that it is in the binary format). Args: plist_path: string, path to a plist file, in XML or binary format Returns: Content of the plist as a dictionary. """ try: # First, try to read the file using plistlib that only supports XML, # and if an exception is raised, convert a temporary copy to XML and # load that copy. return plistlib.readPlist(plist_path) except Exception: pass with tempfile.NamedTemporaryFile() as temp: shutil.copy2(plist_path, temp.name) subprocess.check_call(["plutil", "-convert", "xml1", temp.name]) return plistlib.readPlist(temp.name) def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix): """Constructs a dictionary of variable substitutions for Entitlements.plist. Args: bundle_identifier: string, value of CFBundleIdentifier from Info.plist app_identifier_prefix: string, value for AppIdentifierPrefix Returns: Dictionary of substitutions to apply when generating Entitlements.plist. """ return { "CFBundleIdentifier": bundle_identifier, "AppIdentifierPrefix": app_identifier_prefix, } def _GetCFBundleIdentifier(self): """Extracts CFBundleIdentifier value from Info.plist in the bundle. Returns: Value of CFBundleIdentifier in the Info.plist located in the bundle. """ info_plist_path = os.path.join( os.environ["TARGET_BUILD_DIR"], os.environ["INFOPLIST_PATH"] ) info_plist_data = self._LoadPlistMaybeBinary(info_plist_path) return info_plist_data["CFBundleIdentifier"] def _InstallEntitlements(self, entitlements, substitutions, overrides): """Generates and install the ${BundleName}.xcent entitlements file. Expands variables "$(variable)" pattern in the source entitlements file, add extra entitlements defined in the .mobileprovision file and the copy the generated plist to "${BundlePath}.xcent". Args: entitlements: string, optional, path to the Entitlements.plist template to use, defaults to "${SDKROOT}/Entitlements.plist" substitutions: dictionary, variable substitutions overrides: dictionary, values to add to the entitlements Returns: Path to the generated entitlements file. """ source_path = entitlements target_path = os.path.join( os.environ["BUILT_PRODUCTS_DIR"], os.environ["PRODUCT_NAME"] + ".xcent" ) if not source_path: source_path = os.path.join(os.environ["SDKROOT"], "Entitlements.plist") shutil.copy2(source_path, target_path) data = self._LoadPlistMaybeBinary(target_path) data = self._ExpandVariables(data, substitutions) if overrides: for key in overrides: if key not in data: data[key] = overrides[key] plistlib.writePlist(data, target_path) return target_path def _ExpandVariables(self, data, substitutions): """Expands variables "$(variable)" in data. Args: data: object, can be either string, list or dictionary substitutions: dictionary, variable substitutions to perform Returns: Copy of data where each references to "$(variable)" has been replaced by the corresponding value found in substitutions, or left intact if the key was not found. """ if isinstance(data, str): for key, value in substitutions.items(): data = data.replace("$(%s)" % key, value) return data if isinstance(data, list): return [self._ExpandVariables(v, substitutions) for v in data] if isinstance(data, dict): return {k: self._ExpandVariables(data[k], substitutions) for k in data} return data def NextGreaterPowerOf2(x): return 2 ** (x).bit_length() def WriteHmap(output_name, filelist): """Generates a header map based on |filelist|. Per Mark Mentovai: A header map is structured essentially as a hash table, keyed by names used in #includes, and providing pathnames to the actual files. The implementation below and the comment above comes from inspecting: http://www.opensource.apple.com/source/distcc/distcc-2503/distcc_dist/include_server/headermap.py?txt while also looking at the implementation in clang in: https://llvm.org/svn/llvm-project/cfe/trunk/lib/Lex/HeaderMap.cpp """ magic = 1751998832 version = 1 _reserved = 0 count = len(filelist) capacity = NextGreaterPowerOf2(count) strings_offset = 24 + (12 * capacity) max_value_length = max(len(value) for value in filelist.values()) out = open(output_name, "wb") out.write( struct.pack( " 0 or arg.count("/") > 1: arg = os.path.normpath(arg) # For a literal quote, CommandLineToArgvW requires 2n+1 backslashes # preceding it, and results in n backslashes + the quote. So we substitute # in 2* what we match, +1 more, plus the quote. if quote_cmd: arg = windows_quoter_regex.sub(lambda mo: 2 * mo.group(1) + '\\"', arg) # %'s also need to be doubled otherwise they're interpreted as batch # positional arguments. Also make sure to escape the % so that they're # passed literally through escaping so they can be singled to just the # original %. Otherwise, trying to pass the literal representation that # looks like an environment variable to the shell (e.g. %PATH%) would fail. arg = arg.replace("%", "%%") # These commands are used in rsp files, so no escaping for the shell (via ^) # is necessary. # As a workaround for programs that don't use CommandLineToArgvW, gyp # supports msvs_quote_cmd=0, which simply disables all quoting. if quote_cmd: # Finally, wrap the whole thing in quotes so that the above quote rule # applies and whitespace isn't a word break. return f'"{arg}"' return arg def EncodeRspFileList(args, quote_cmd): """Process a list of arguments using QuoteCmdExeArgument.""" # Note that the first argument is assumed to be the command. Don't add # quotes around it because then built-ins like 'echo', etc. won't work. # Take care to normpath only the path in the case of 'call ../x.bat' because # otherwise the whole thing is incorrectly interpreted as a path and not # normalized correctly. if not args: return "" if args[0].startswith("call "): call, program = args[0].split(" ", 1) program = call + " " + os.path.normpath(program) else: program = os.path.normpath(args[0]) return (program + " " + " ".join(QuoteForRspFile(arg, quote_cmd) for arg in args[1:])) def _GenericRetrieve(root, default, path): """Given a list of dictionary keys |path| and a tree of dicts |root|, find value at path, or return |default| if any of the path doesn't exist.""" if not root: return default if not path: return root return _GenericRetrieve(root.get(path[0]), default, path[1:]) def _AddPrefix(element, prefix): """Add |prefix| to |element| or each subelement if element is iterable.""" if element is None: return element # Note, not Iterable because we don't want to handle strings like that. if isinstance(element, (list, tuple)): return [prefix + e for e in element] else: return prefix + element def _DoRemapping(element, map): """If |element| then remap it through |map|. If |element| is iterable then each item will be remapped. Any elements not found will be removed.""" if map is not None and element is not None: if not callable(map): map = map.get # Assume it's a dict, otherwise a callable to do the remap. if isinstance(element, (list, tuple)): element = filter(None, [map(elem) for elem in element]) else: element = map(element) return element def _AppendOrReturn(append, element): """If |append| is None, simply return |element|. If |append| is not None, then add |element| to it, adding each item in |element| if it's a list or tuple.""" if append is not None and element is not None: if isinstance(element, (list, tuple)): append.extend(element) else: append.append(element) else: return element def _FindDirectXInstallation(): """Try to find an installation location for the DirectX SDK. Check for the standard environment variable, and if that doesn't exist, try to find via the registry. May return None if not found in either location.""" # Return previously calculated value, if there is one if hasattr(_FindDirectXInstallation, "dxsdk_dir"): return _FindDirectXInstallation.dxsdk_dir dxsdk_dir = os.environ.get("DXSDK_DIR") if not dxsdk_dir: # Setup params to pass to and attempt to launch reg.exe. cmd = ["reg.exe", "query", r"HKLM\Software\Microsoft\DirectX", "/s"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = p.communicate()[0].decode("utf-8") for line in stdout.splitlines(): if "InstallPath" in line: dxsdk_dir = line.split(" ")[3] + "\\" # Cache return value _FindDirectXInstallation.dxsdk_dir = dxsdk_dir return dxsdk_dir def GetGlobalVSMacroEnv(vs_version): """Get a dict of variables mapping internal VS macro names to their gyp equivalents. Returns all variables that are independent of the target.""" env = {} # '$(VSInstallDir)' and '$(VCInstallDir)' are available when and only when # Visual Studio is actually installed. if vs_version.Path(): env["$(VSInstallDir)"] = vs_version.Path() env["$(VCInstallDir)"] = os.path.join(vs_version.Path(), "VC") + "\\" # Chromium uses DXSDK_DIR in include/lib paths, but it may or may not be # set. This happens when the SDK is sync'd via src-internal, rather than # by typical end-user installation of the SDK. If it's not set, we don't # want to leave the unexpanded variable in the path, so simply strip it. dxsdk_dir = _FindDirectXInstallation() env["$(DXSDK_DIR)"] = dxsdk_dir if dxsdk_dir else "" # Try to find an installation location for the Windows DDK by checking # the WDK_DIR environment variable, may be None. env["$(WDK_DIR)"] = os.environ.get("WDK_DIR", "") return env def ExtractSharedMSVSSystemIncludes(configs, generator_flags): """Finds msvs_system_include_dirs that are common to all targets, removes them from all targets, and returns an OrderedSet containing them.""" all_system_includes = OrderedSet(configs[0].get("msvs_system_include_dirs", [])) for config in configs[1:]: system_includes = config.get("msvs_system_include_dirs", []) all_system_includes = all_system_includes & OrderedSet(system_includes) if not all_system_includes: return None # Expand macros in all_system_includes. env = GetGlobalVSMacroEnv(GetVSVersion(generator_flags)) expanded_system_includes = OrderedSet( [ExpandMacros(include, env) for include in all_system_includes] ) if any("$" in include for include in expanded_system_includes): # Some path relies on target-specific variables, bail. return None # Remove system includes shared by all targets from the targets. for config in configs: includes = config.get("msvs_system_include_dirs", []) if includes: # Don't insert a msvs_system_include_dirs key if not needed. # This must check the unexpanded includes list: new_includes = [i for i in includes if i not in all_system_includes] config["msvs_system_include_dirs"] = new_includes return expanded_system_includes class MsvsSettings: """A class that understands the gyp 'msvs_...' values (especially the msvs_settings field). They largely correpond to the VS2008 IDE DOM. This class helps map those settings to command line options.""" def __init__(self, spec, generator_flags): self.spec = spec self.vs_version = GetVSVersion(generator_flags) supported_fields = [ ("msvs_configuration_attributes", dict), ("msvs_settings", dict), ("msvs_system_include_dirs", list), ("msvs_disabled_warnings", list), ("msvs_precompiled_header", str), ("msvs_precompiled_source", str), ("msvs_configuration_platform", str), ("msvs_target_platform", str), ] configs = spec["configurations"] for field, default in supported_fields: setattr(self, field, {}) for configname, config in configs.items(): getattr(self, field)[configname] = config.get(field, default()) self.msvs_cygwin_dirs = spec.get("msvs_cygwin_dirs", ["."]) unsupported_fields = [ "msvs_prebuild", "msvs_postbuild", ] unsupported = [] for field in unsupported_fields: for config in configs.values(): if field in config: unsupported += [ "{} not supported (target {}).".format( field, spec["target_name"] ) ] if unsupported: raise Exception("\n".join(unsupported)) def GetExtension(self): """Returns the extension for the target, with no leading dot. Uses 'product_extension' if specified, otherwise uses MSVS defaults based on the target type. """ ext = self.spec.get("product_extension", None) if ext: return ext return gyp.MSVSUtil.TARGET_TYPE_EXT.get(self.spec["type"], "") def GetVSMacroEnv(self, base_to_build=None, config=None): """Get a dict of variables mapping internal VS macro names to their gyp equivalents.""" target_arch = self.GetArch(config) target_platform = "Win32" if target_arch == "x86" else target_arch target_name = self.spec.get("product_prefix", "") + self.spec.get( "product_name", self.spec["target_name"] ) target_dir = base_to_build + "\\" if base_to_build else "" target_ext = "." + self.GetExtension() target_file_name = target_name + target_ext replacements = { "$(InputName)": "${root}", "$(InputPath)": "${source}", "$(IntDir)": "$!INTERMEDIATE_DIR", "$(OutDir)\\": target_dir, "$(PlatformName)": target_platform, "$(ProjectDir)\\": "", "$(ProjectName)": self.spec["target_name"], "$(TargetDir)\\": target_dir, "$(TargetExt)": target_ext, "$(TargetFileName)": target_file_name, "$(TargetName)": target_name, "$(TargetPath)": os.path.join(target_dir, target_file_name), } replacements.update(GetGlobalVSMacroEnv(self.vs_version)) return replacements def ConvertVSMacros(self, s, base_to_build=None, config=None): """Convert from VS macro names to something equivalent.""" env = self.GetVSMacroEnv(base_to_build, config=config) return ExpandMacros(s, env) def AdjustLibraries(self, libraries): """Strip -l from library if it's specified with that.""" libs = [lib[2:] if lib.startswith("-l") else lib for lib in libraries] return [ lib + ".lib" if not lib.lower().endswith(".lib") and not lib.lower().endswith(".obj") else lib for lib in libs ] def _GetAndMunge(self, field, path, default, prefix, append, map): """Retrieve a value from |field| at |path| or return |default|. If |append| is specified, and the item is found, it will be appended to that object instead of returned. If |map| is specified, results will be remapped through |map| before being returned or appended.""" result = _GenericRetrieve(field, default, path) result = _DoRemapping(result, map) result = _AddPrefix(result, prefix) return _AppendOrReturn(append, result) class _GetWrapper: def __init__(self, parent, field, base_path, append=None): self.parent = parent self.field = field self.base_path = [base_path] self.append = append def __call__(self, name, map=None, prefix="", default=None): return self.parent._GetAndMunge( self.field, self.base_path + [name], default=default, prefix=prefix, append=self.append, map=map, ) def GetArch(self, config): """Get architecture based on msvs_configuration_platform and msvs_target_platform. Returns either 'x86' or 'x64'.""" configuration_platform = self.msvs_configuration_platform.get(config, "") platform = self.msvs_target_platform.get(config, "") if not platform: # If no specific override, use the configuration's. platform = configuration_platform # Map from platform to architecture. return {"Win32": "x86", "x64": "x64", "ARM64": "arm64"}.get(platform, "x86") def _TargetConfig(self, config): """Returns the target-specific configuration.""" # There's two levels of architecture/platform specification in VS. The # first level is globally for the configuration (this is what we consider # "the" config at the gyp level, which will be something like 'Debug' or # 'Release'), VS2015 and later only use this level if int(self.vs_version.short_name) >= 2015: return config # and a second target-specific configuration, which is an # override for the global one. |config| is remapped here to take into # account the local target-specific overrides to the global configuration. arch = self.GetArch(config) if arch == "x64" and not config.endswith("_x64"): config += "_x64" if arch == "x86" and config.endswith("_x64"): config = config.rsplit("_", 1)[0] return config def _Setting(self, path, config, default=None, prefix="", append=None, map=None): """_GetAndMunge for msvs_settings.""" return self._GetAndMunge( self.msvs_settings[config], path, default, prefix, append, map ) def _ConfigAttrib( self, path, config, default=None, prefix="", append=None, map=None ): """_GetAndMunge for msvs_configuration_attributes.""" return self._GetAndMunge( self.msvs_configuration_attributes[config], path, default, prefix, append, map, ) def AdjustIncludeDirs(self, include_dirs, config): """Updates include_dirs to expand VS specific paths, and adds the system include dirs used for platform SDK and similar.""" config = self._TargetConfig(config) includes = include_dirs + self.msvs_system_include_dirs[config] includes.extend( self._Setting( ("VCCLCompilerTool", "AdditionalIncludeDirectories"), config, default=[] ) ) return [self.ConvertVSMacros(p, config=config) for p in includes] def AdjustMidlIncludeDirs(self, midl_include_dirs, config): """Updates midl_include_dirs to expand VS specific paths, and adds the system include dirs used for platform SDK and similar.""" config = self._TargetConfig(config) includes = midl_include_dirs + self.msvs_system_include_dirs[config] includes.extend( self._Setting( ("VCMIDLTool", "AdditionalIncludeDirectories"), config, default=[] ) ) return [self.ConvertVSMacros(p, config=config) for p in includes] def GetComputedDefines(self, config): """Returns the set of defines that are injected to the defines list based on other VS settings.""" config = self._TargetConfig(config) defines = [] if self._ConfigAttrib(["CharacterSet"], config) == "1": defines.extend(("_UNICODE", "UNICODE")) if self._ConfigAttrib(["CharacterSet"], config) == "2": defines.append("_MBCS") defines.extend( self._Setting( ("VCCLCompilerTool", "PreprocessorDefinitions"), config, default=[] ) ) return defines def GetCompilerPdbName(self, config, expand_special): """Get the pdb file name that should be used for compiler invocations, or None if there's no explicit name specified.""" config = self._TargetConfig(config) pdbname = self._Setting(("VCCLCompilerTool", "ProgramDataBaseFileName"), config) if pdbname: pdbname = expand_special(self.ConvertVSMacros(pdbname)) return pdbname def GetMapFileName(self, config, expand_special): """Gets the explicitly overridden map file name for a target or returns None if it's not set.""" config = self._TargetConfig(config) map_file = self._Setting(("VCLinkerTool", "MapFileName"), config) if map_file: map_file = expand_special(self.ConvertVSMacros(map_file, config=config)) return map_file def GetOutputName(self, config, expand_special): """Gets the explicitly overridden output name for a target or returns None if it's not overridden.""" config = self._TargetConfig(config) type = self.spec["type"] root = "VCLibrarianTool" if type == "static_library" else "VCLinkerTool" # TODO(scottmg): Handle OutputDirectory without OutputFile. output_file = self._Setting((root, "OutputFile"), config) if output_file: output_file = expand_special( self.ConvertVSMacros(output_file, config=config) ) return output_file def GetPDBName(self, config, expand_special, default): """Gets the explicitly overridden pdb name for a target or returns default if it's not overridden, or if no pdb will be generated.""" config = self._TargetConfig(config) output_file = self._Setting(("VCLinkerTool", "ProgramDatabaseFile"), config) generate_debug_info = self._Setting( ("VCLinkerTool", "GenerateDebugInformation"), config ) if generate_debug_info == "true": if output_file: return expand_special(self.ConvertVSMacros(output_file, config=config)) else: return default else: return None def GetNoImportLibrary(self, config): """If NoImportLibrary: true, ninja will not expect the output to include an import library.""" config = self._TargetConfig(config) noimplib = self._Setting(("NoImportLibrary",), config) return noimplib == "true" def GetAsmflags(self, config): """Returns the flags that need to be added to ml invocations.""" config = self._TargetConfig(config) asmflags = [] safeseh = self._Setting(("MASM", "UseSafeExceptionHandlers"), config) if safeseh == "true": asmflags.append("/safeseh") return asmflags def GetCflags(self, config): """Returns the flags that need to be added to .c and .cc compilations.""" config = self._TargetConfig(config) cflags = [] cflags.extend(["/wd" + w for w in self.msvs_disabled_warnings[config]]) cl = self._GetWrapper( self, self.msvs_settings[config], "VCCLCompilerTool", append=cflags ) cl( "Optimization", map={"0": "d", "1": "1", "2": "2", "3": "x"}, prefix="/O", default="2", ) cl("InlineFunctionExpansion", prefix="/Ob") cl("DisableSpecificWarnings", prefix="/wd") cl("StringPooling", map={"true": "/GF"}) cl("EnableFiberSafeOptimizations", map={"true": "/GT"}) cl("OmitFramePointers", map={"false": "-", "true": ""}, prefix="/Oy") cl("EnableIntrinsicFunctions", map={"false": "-", "true": ""}, prefix="/Oi") cl("FavorSizeOrSpeed", map={"1": "t", "2": "s"}, prefix="/O") cl( "FloatingPointModel", map={"0": "precise", "1": "strict", "2": "fast"}, prefix="/fp:", default="0", ) cl("CompileAsManaged", map={"false": "", "true": "/clr"}) cl("WholeProgramOptimization", map={"true": "/GL"}) cl("WarningLevel", prefix="/W") cl("WarnAsError", map={"true": "/WX"}) cl( "CallingConvention", map={"0": "d", "1": "r", "2": "z", "3": "v"}, prefix="/G", ) cl("DebugInformationFormat", map={"1": "7", "3": "i", "4": "I"}, prefix="/Z") cl("RuntimeTypeInfo", map={"true": "/GR", "false": "/GR-"}) cl("EnableFunctionLevelLinking", map={"true": "/Gy", "false": "/Gy-"}) cl("MinimalRebuild", map={"true": "/Gm"}) cl("BufferSecurityCheck", map={"true": "/GS", "false": "/GS-"}) cl("BasicRuntimeChecks", map={"1": "s", "2": "u", "3": "1"}, prefix="/RTC") cl( "RuntimeLibrary", map={"0": "T", "1": "Td", "2": "D", "3": "Dd"}, prefix="/M", ) cl("ExceptionHandling", map={"1": "sc", "2": "a"}, prefix="/EH") cl("DefaultCharIsUnsigned", map={"true": "/J"}) cl( "TreatWChar_tAsBuiltInType", map={"false": "-", "true": ""}, prefix="/Zc:wchar_t", ) cl("EnablePREfast", map={"true": "/analyze"}) cl("AdditionalOptions", prefix="") cl( "EnableEnhancedInstructionSet", map={"1": "SSE", "2": "SSE2", "3": "AVX", "4": "IA32", "5": "AVX2"}, prefix="/arch:", ) cflags.extend( [ "/FI" + f for f in self._Setting( ("VCCLCompilerTool", "ForcedIncludeFiles"), config, default=[] ) ] ) if float(self.vs_version.project_version) >= 12.0: # New flag introduced in VS2013 (project version 12.0) Forces writes to # the program database (PDB) to be serialized through MSPDBSRV.EXE. # https://msdn.microsoft.com/en-us/library/dn502518.aspx cflags.append("/FS") # ninja handles parallelism by itself, don't have the compiler do it too. cflags = [x for x in cflags if not x.startswith("/MP")] return cflags def _GetPchFlags(self, config, extension): """Get the flags to be added to the cflags for precompiled header support.""" config = self._TargetConfig(config) # The PCH is only built once by a particular source file. Usage of PCH must # only be for the same language (i.e. C vs. C++), so only include the pch # flags when the language matches. if self.msvs_precompiled_header[config]: source_ext = os.path.splitext(self.msvs_precompiled_source[config])[1] if _LanguageMatchesForPch(source_ext, extension): pch = self.msvs_precompiled_header[config] pchbase = os.path.split(pch)[1] return ["/Yu" + pch, "/FI" + pch, "/Fp${pchprefix}." + pchbase + ".pch"] return [] def GetCflagsC(self, config): """Returns the flags that need to be added to .c compilations.""" config = self._TargetConfig(config) return self._GetPchFlags(config, ".c") def GetCflagsCC(self, config): """Returns the flags that need to be added to .cc compilations.""" config = self._TargetConfig(config) return ["/TP"] + self._GetPchFlags(config, ".cc") def _GetAdditionalLibraryDirectories(self, root, config, gyp_to_build_path): """Get and normalize the list of paths in AdditionalLibraryDirectories setting.""" config = self._TargetConfig(config) libpaths = self._Setting( (root, "AdditionalLibraryDirectories"), config, default=[] ) libpaths = [ os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(p, config=config))) for p in libpaths ] return ['/LIBPATH:"' + p + '"' for p in libpaths] def GetLibFlags(self, config, gyp_to_build_path): """Returns the flags that need to be added to lib commands.""" config = self._TargetConfig(config) libflags = [] lib = self._GetWrapper( self, self.msvs_settings[config], "VCLibrarianTool", append=libflags ) libflags.extend( self._GetAdditionalLibraryDirectories( "VCLibrarianTool", config, gyp_to_build_path ) ) lib("LinkTimeCodeGeneration", map={"true": "/LTCG"}) lib( "TargetMachine", map={"1": "X86", "17": "X64", "3": "ARM"}, prefix="/MACHINE:", ) lib("AdditionalOptions") return libflags def GetDefFile(self, gyp_to_build_path): """Returns the .def file from sources, if any. Otherwise returns None.""" spec = self.spec if spec["type"] in ("shared_library", "loadable_module", "executable"): def_files = [ s for s in spec.get("sources", []) if s.lower().endswith(".def") ] if len(def_files) == 1: return gyp_to_build_path(def_files[0]) elif len(def_files) > 1: raise Exception("Multiple .def files") return None def _GetDefFileAsLdflags(self, ldflags, gyp_to_build_path): """.def files get implicitly converted to a ModuleDefinitionFile for the linker in the VS generator. Emulate that behaviour here.""" def_file = self.GetDefFile(gyp_to_build_path) if def_file: ldflags.append('/DEF:"%s"' % def_file) def GetPGDName(self, config, expand_special): """Gets the explicitly overridden pgd name for a target or returns None if it's not overridden.""" config = self._TargetConfig(config) output_file = self._Setting(("VCLinkerTool", "ProfileGuidedDatabase"), config) if output_file: output_file = expand_special( self.ConvertVSMacros(output_file, config=config) ) return output_file def GetLdflags( self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir, ): """Returns the flags that need to be added to link commands, and the manifest files.""" config = self._TargetConfig(config) ldflags = [] ld = self._GetWrapper( self, self.msvs_settings[config], "VCLinkerTool", append=ldflags ) self._GetDefFileAsLdflags(ldflags, gyp_to_build_path) ld("GenerateDebugInformation", map={"true": "/DEBUG"}) # TODO: These 'map' values come from machineTypeOption enum, # and does not have an official value for ARM64 in VS2017 (yet). # It needs to verify the ARM64 value when machineTypeOption is updated. ld( "TargetMachine", map={"1": "X86", "17": "X64", "3": "ARM", "18": "ARM64"}, prefix="/MACHINE:", ) ldflags.extend( self._GetAdditionalLibraryDirectories( "VCLinkerTool", config, gyp_to_build_path ) ) ld("DelayLoadDLLs", prefix="/DELAYLOAD:") ld("TreatLinkerWarningAsErrors", prefix="/WX", map={"true": "", "false": ":NO"}) out = self.GetOutputName(config, expand_special) if out: ldflags.append("/OUT:" + out) pdb = self.GetPDBName(config, expand_special, output_name + ".pdb") if pdb: ldflags.append("/PDB:" + pdb) pgd = self.GetPGDName(config, expand_special) if pgd: ldflags.append("/PGD:" + pgd) map_file = self.GetMapFileName(config, expand_special) ld("GenerateMapFile", map={"true": "/MAP:" + map_file if map_file else "/MAP"}) ld("MapExports", map={"true": "/MAPINFO:EXPORTS"}) ld("AdditionalOptions", prefix="") minimum_required_version = self._Setting( ("VCLinkerTool", "MinimumRequiredVersion"), config, default="" ) if minimum_required_version: minimum_required_version = "," + minimum_required_version ld( "SubSystem", map={ "1": "CONSOLE%s" % minimum_required_version, "2": "WINDOWS%s" % minimum_required_version, }, prefix="/SUBSYSTEM:", ) stack_reserve_size = self._Setting( ("VCLinkerTool", "StackReserveSize"), config, default="" ) if stack_reserve_size: stack_commit_size = self._Setting( ("VCLinkerTool", "StackCommitSize"), config, default="" ) if stack_commit_size: stack_commit_size = "," + stack_commit_size ldflags.append(f"/STACK:{stack_reserve_size}{stack_commit_size}") ld("TerminalServerAware", map={"1": ":NO", "2": ""}, prefix="/TSAWARE") ld("LinkIncremental", map={"1": ":NO", "2": ""}, prefix="/INCREMENTAL") ld("BaseAddress", prefix="/BASE:") ld("FixedBaseAddress", map={"1": ":NO", "2": ""}, prefix="/FIXED") ld("RandomizedBaseAddress", map={"1": ":NO", "2": ""}, prefix="/DYNAMICBASE") ld("DataExecutionPrevention", map={"1": ":NO", "2": ""}, prefix="/NXCOMPAT") ld("OptimizeReferences", map={"1": "NOREF", "2": "REF"}, prefix="/OPT:") ld("ForceSymbolReferences", prefix="/INCLUDE:") ld("EnableCOMDATFolding", map={"1": "NOICF", "2": "ICF"}, prefix="/OPT:") ld( "LinkTimeCodeGeneration", map={"1": "", "2": ":PGINSTRUMENT", "3": ":PGOPTIMIZE", "4": ":PGUPDATE"}, prefix="/LTCG", ) ld("IgnoreDefaultLibraryNames", prefix="/NODEFAULTLIB:") ld("ResourceOnlyDLL", map={"true": "/NOENTRY"}) ld("EntryPointSymbol", prefix="/ENTRY:") ld("Profile", map={"true": "/PROFILE"}) ld("LargeAddressAware", map={"1": ":NO", "2": ""}, prefix="/LARGEADDRESSAWARE") # TODO(scottmg): This should sort of be somewhere else (not really a flag). ld("AdditionalDependencies", prefix="") safeseh_default = "true" if self.GetArch(config) == "x86" else None ld( "ImageHasSafeExceptionHandlers", map={"false": ":NO", "true": ""}, prefix="/SAFESEH", default=safeseh_default, ) # If the base address is not specifically controlled, DYNAMICBASE should # be on by default. if not any("DYNAMICBASE" in flag or flag == "/FIXED" for flag in ldflags): ldflags.append("/DYNAMICBASE") # If the NXCOMPAT flag has not been specified, default to on. Despite the # documentation that says this only defaults to on when the subsystem is # Vista or greater (which applies to the linker), the IDE defaults it on # unless it's explicitly off. if not any("NXCOMPAT" in flag for flag in ldflags): ldflags.append("/NXCOMPAT") have_def_file = any(flag.startswith("/DEF:") for flag in ldflags) ( manifest_flags, intermediate_manifest, manifest_files, ) = self._GetLdManifestFlags( config, manifest_base_name, gyp_to_build_path, is_executable and not have_def_file, build_dir, ) ldflags.extend(manifest_flags) return ldflags, intermediate_manifest, manifest_files def _GetLdManifestFlags( self, config, name, gyp_to_build_path, allow_isolation, build_dir ): """Returns a 3-tuple: - the set of flags that need to be added to the link to generate a default manifest - the intermediate manifest that the linker will generate that should be used to assert it doesn't add anything to the merged one. - the list of all the manifest files to be merged by the manifest tool and included into the link.""" generate_manifest = self._Setting( ("VCLinkerTool", "GenerateManifest"), config, default="true" ) if generate_manifest != "true": # This means not only that the linker should not generate the intermediate # manifest but also that the manifest tool should do nothing even when # additional manifests are specified. return ["/MANIFEST:NO"], [], [] output_name = name + ".intermediate.manifest" flags = [ "/MANIFEST", "/ManifestFile:" + output_name, ] # Instead of using the MANIFESTUAC flags, we generate a .manifest to # include into the list of manifests. This allows us to avoid the need to # do two passes during linking. The /MANIFEST flag and /ManifestFile are # still used, and the intermediate manifest is used to assert that the # final manifest we get from merging all the additional manifest files # (plus the one we generate here) isn't modified by merging the # intermediate into it. # Always NO, because we generate a manifest file that has what we want. flags.append("/MANIFESTUAC:NO") config = self._TargetConfig(config) enable_uac = self._Setting( ("VCLinkerTool", "EnableUAC"), config, default="true" ) manifest_files = [] generated_manifest_outer = ( "" "" "%s" ) if enable_uac == "true": execution_level = self._Setting( ("VCLinkerTool", "UACExecutionLevel"), config, default="0" ) execution_level_map = { "0": "asInvoker", "1": "highestAvailable", "2": "requireAdministrator", } ui_access = self._Setting( ("VCLinkerTool", "UACUIAccess"), config, default="false" ) level = execution_level_map[execution_level] inner = f""" """ else: inner = "" generated_manifest_contents = generated_manifest_outer % inner generated_name = name + ".generated.manifest" # Need to join with the build_dir here as we're writing it during # generation time, but we return the un-joined version because the build # will occur in that directory. We only write the file if the contents # have changed so that simply regenerating the project files doesn't # cause a relink. build_dir_generated_name = os.path.join(build_dir, generated_name) gyp.common.EnsureDirExists(build_dir_generated_name) f = gyp.common.WriteOnDiff(build_dir_generated_name) f.write(generated_manifest_contents) f.close() manifest_files = [generated_name] if allow_isolation: flags.append("/ALLOWISOLATION") manifest_files += self._GetAdditionalManifestFiles(config, gyp_to_build_path) return flags, output_name, manifest_files def _GetAdditionalManifestFiles(self, config, gyp_to_build_path): """Gets additional manifest files that are added to the default one generated by the linker.""" files = self._Setting( ("VCManifestTool", "AdditionalManifestFiles"), config, default=[] ) if isinstance(files, str): files = files.split(";") return [ os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(f, config=config))) for f in files ] def IsUseLibraryDependencyInputs(self, config): """Returns whether the target should be linked via Use Library Dependency Inputs (using component .objs of a given .lib).""" config = self._TargetConfig(config) uldi = self._Setting(("VCLinkerTool", "UseLibraryDependencyInputs"), config) return uldi == "true" def IsEmbedManifest(self, config): """Returns whether manifest should be linked into binary.""" config = self._TargetConfig(config) embed = self._Setting( ("VCManifestTool", "EmbedManifest"), config, default="true" ) return embed == "true" def IsLinkIncremental(self, config): """Returns whether the target should be linked incrementally.""" config = self._TargetConfig(config) link_inc = self._Setting(("VCLinkerTool", "LinkIncremental"), config) return link_inc != "1" def GetRcflags(self, config, gyp_to_ninja_path): """Returns the flags that need to be added to invocations of the resource compiler.""" config = self._TargetConfig(config) rcflags = [] rc = self._GetWrapper( self, self.msvs_settings[config], "VCResourceCompilerTool", append=rcflags ) rc("AdditionalIncludeDirectories", map=gyp_to_ninja_path, prefix="/I") rcflags.append("/I" + gyp_to_ninja_path(".")) rc("PreprocessorDefinitions", prefix="/d") # /l arg must be in hex without leading '0x' rc("Culture", prefix="/l", map=lambda x: hex(int(x))[2:]) return rcflags def BuildCygwinBashCommandLine(self, args, path_to_base): """Build a command line that runs args via cygwin bash. We assume that all incoming paths are in Windows normpath'd form, so they need to be converted to posix style for the part of the command line that's passed to bash. We also have to do some Visual Studio macro emulation here because various rules use magic VS names for things. Also note that rules that contain ninja variables cannot be fixed here (for example ${source}), so the outer generator needs to make sure that the paths that are written out are in posix style, if the command line will be used here.""" cygwin_dir = os.path.normpath( os.path.join(path_to_base, self.msvs_cygwin_dirs[0]) ) cd = ("cd %s" % path_to_base).replace("\\", "/") args = [a.replace("\\", "/").replace('"', '\\"') for a in args] args = ["'%s'" % a.replace("'", "'\\''") for a in args] bash_cmd = " ".join(args) cmd = ( 'call "%s\\setup_env.bat" && set CYGWIN=nontsec && ' % cygwin_dir + f'bash -c "{cd} ; {bash_cmd}"' ) return cmd RuleShellFlags = collections.namedtuple("RuleShellFlags", ["cygwin", "quote"]) def GetRuleShellFlags(self, rule): """Return RuleShellFlags about how the given rule should be run. This includes whether it should run under cygwin (msvs_cygwin_shell), and whether the commands should be quoted (msvs_quote_cmd).""" # If the variable is unset, or set to 1 we use cygwin cygwin = int(rule.get("msvs_cygwin_shell", self.spec.get("msvs_cygwin_shell", 1))) != 0 # Default to quoting. There's only a few special instances where the # target command uses non-standard command line parsing and handle quotes # and quote escaping differently. quote_cmd = int(rule.get("msvs_quote_cmd", 1)) assert quote_cmd != 0 or cygwin != 1, \ "msvs_quote_cmd=0 only applicable for msvs_cygwin_shell=0" return MsvsSettings.RuleShellFlags(cygwin, quote_cmd) def _HasExplicitRuleForExtension(self, spec, extension): """Determine if there's an explicit rule for a particular extension.""" return any(rule["extension"] == extension for rule in spec.get("rules", [])) def _HasExplicitIdlActions(self, spec): """Determine if an action should not run midl for .idl files.""" return any( action.get("explicit_idl_action", 0) for action in spec.get("actions", []) ) def HasExplicitIdlRulesOrActions(self, spec): """Determine if there's an explicit rule or action for idl files. When there isn't we need to generate implicit rules to build MIDL .idl files.""" return self._HasExplicitRuleForExtension( spec, "idl" ) or self._HasExplicitIdlActions(spec) def HasExplicitAsmRules(self, spec): """Determine if there's an explicit rule for asm files. When there isn't we need to generate implicit rules to assemble .asm files.""" return self._HasExplicitRuleForExtension(spec, "asm") def GetIdlBuildData(self, source, config): """Determine the implicit outputs for an idl file. Returns output directory, outputs, and variables and flags that are required.""" config = self._TargetConfig(config) midl_get = self._GetWrapper(self, self.msvs_settings[config], "VCMIDLTool") def midl(name, default=None): return self.ConvertVSMacros(midl_get(name, default=default), config=config) tlb = midl("TypeLibraryName", default="${root}.tlb") header = midl("HeaderFileName", default="${root}.h") dlldata = midl("DLLDataFileName", default="dlldata.c") iid = midl("InterfaceIdentifierFileName", default="${root}_i.c") proxy = midl("ProxyFileName", default="${root}_p.c") # Note that .tlb is not included in the outputs as it is not always # generated depending on the content of the input idl file. outdir = midl("OutputDirectory", default="") output = [header, dlldata, iid, proxy] variables = [ ("tlb", tlb), ("h", header), ("dlldata", dlldata), ("iid", iid), ("proxy", proxy), ] # TODO(scottmg): Are there configuration settings to set these flags? target_platform = self.GetArch(config) if target_platform == "x86": target_platform = "win32" flags = ["/char", "signed", "/env", target_platform, "/Oicf"] return outdir, output, variables, flags def _LanguageMatchesForPch(source_ext, pch_source_ext): c_exts = (".c",) cc_exts = (".cc", ".cxx", ".cpp") return (source_ext in c_exts and pch_source_ext in c_exts) or ( source_ext in cc_exts and pch_source_ext in cc_exts ) class PrecompiledHeader: """Helper to generate dependencies and build rules to handle generation of precompiled headers. Interface matches the GCH handler in xcode_emulation.py. """ def __init__( self, settings, config, gyp_to_build_path, gyp_to_unique_output, obj_ext ): self.settings = settings self.config = config pch_source = self.settings.msvs_precompiled_source[self.config] self.pch_source = gyp_to_build_path(pch_source) filename, _ = os.path.splitext(pch_source) self.output_obj = gyp_to_unique_output(filename + obj_ext).lower() def _PchHeader(self): """Get the header that will appear in an #include line for all source files.""" return self.settings.msvs_precompiled_header[self.config] def GetObjDependencies(self, sources, objs, arch): """Given a list of sources files and the corresponding object files, returns a list of the pch files that should be depended upon. The additional wrapping in the return value is for interface compatibility with make.py on Mac, and xcode_emulation.py.""" assert arch is None if not self._PchHeader(): return [] pch_ext = os.path.splitext(self.pch_source)[1] for source in sources: if _LanguageMatchesForPch(os.path.splitext(source)[1], pch_ext): return [(None, None, self.output_obj)] return [] def GetPchBuildCommands(self, arch): """Not used on Windows as there are no additional build steps required (instead, existing steps are modified in GetFlagsModifications below).""" return [] def GetFlagsModifications( self, input, output, implicit, command, cflags_c, cflags_cc, expand_special ): """Get the modified cflags and implicit dependencies that should be used for the pch compilation step.""" if input == self.pch_source: pch_output = ["/Yc" + self._PchHeader()] if command == "cxx": return ( [("cflags_cc", map(expand_special, cflags_cc + pch_output))], self.output_obj, [], ) elif command == "cc": return ( [("cflags_c", map(expand_special, cflags_c + pch_output))], self.output_obj, [], ) return [], output, implicit vs_version = None def GetVSVersion(generator_flags): global vs_version if not vs_version: vs_version = gyp.MSVSVersion.SelectVisualStudioVersion( generator_flags.get("msvs_version", "auto"), allow_fallback=False ) return vs_version def _GetVsvarsSetupArgs(generator_flags, arch): vs = GetVSVersion(generator_flags) return vs.SetupScript() def ExpandMacros(string, expansions): """Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv for the canonical way to retrieve a suitable dict.""" if "$" in string: for old, new in expansions.items(): assert "$(" not in new, new string = string.replace(old, new) return string def _ExtractImportantEnvironment(output_of_set): """Extracts environment variables required for the toolchain to run from a textual dump output by the cmd.exe 'set' command.""" envvars_to_save = ( "goma_.*", # TODO(scottmg): This is ugly, but needed for goma. "include", "lib", "libpath", "path", "pathext", "systemroot", "temp", "tmp", ) env = {} # This occasionally happens and leads to misleading SYSTEMROOT error messages # if not caught here. if output_of_set.count("=") == 0: raise Exception("Invalid output_of_set. Value is:\n%s" % output_of_set) for line in output_of_set.splitlines(): for envvar in envvars_to_save: if re.match(envvar + "=", line.lower()): var, setting = line.split("=", 1) if envvar == "path": # Our own rules (for running gyp-win-tool) and other actions in # Chromium rely on python being in the path. Add the path to this # python here so that if it's not in the path when ninja is run # later, python will still be found. setting = os.path.dirname(sys.executable) + os.pathsep + setting env[var.upper()] = setting break for required in ("SYSTEMROOT", "TEMP", "TMP"): if required not in env: raise Exception( 'Environment variable "%s" ' "required to be set to valid path" % required ) return env def _FormatAsEnvironmentBlock(envvar_dict): """Format as an 'environment block' directly suitable for CreateProcess. Briefly this is a list of key=value\0, terminated by an additional \0. See CreateProcess documentation for more details.""" block = "" nul = "\0" for key, value in envvar_dict.items(): block += key + "=" + value + nul block += nul return block def _ExtractCLPath(output_of_where): """Gets the path to cl.exe based on the output of calling the environment setup batch file, followed by the equivalent of `where`.""" # Take the first line, as that's the first found in the PATH. for line in output_of_where.strip().splitlines(): if line.startswith("LOC:"): return line[len("LOC:") :].strip() def GenerateEnvironmentFiles( toplevel_build_dir, generator_flags, system_includes, open_out ): """It's not sufficient to have the absolute path to the compiler, linker, etc. on Windows, as those tools rely on .dlls being in the PATH. We also need to support both x86 and x64 compilers within the same build (to support msvs_target_platform hackery). Different architectures require a different compiler binary, and different supporting environment variables (INCLUDE, LIB, LIBPATH). So, we extract the environment here, wrap all invocations of compiler tools (cl, link, lib, rc, midl, etc.) via win_tool.py which sets up the environment, and then we do not prefix the compiler with an absolute path, instead preferring something like "cl.exe" in the rule which will then run whichever the environment setup has put in the path. When the following procedure to generate environment files does not meet your requirement (e.g. for custom toolchains), you can pass "-G ninja_use_custom_environment_files" to the gyp to suppress file generation and use custom environment files prepared by yourself.""" archs = ("x86", "x64") if generator_flags.get("ninja_use_custom_environment_files", 0): cl_paths = {} for arch in archs: cl_paths[arch] = "cl.exe" return cl_paths vs = GetVSVersion(generator_flags) cl_paths = {} for arch in archs: # Extract environment variables for subprocesses. args = vs.SetupScript(arch) args.extend(("&&", "set")) popen = subprocess.Popen( args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) variables = popen.communicate()[0].decode("utf-8") if popen.returncode != 0: raise Exception('"%s" failed with error %d' % (args, popen.returncode)) env = _ExtractImportantEnvironment(variables) # Inject system includes from gyp files into INCLUDE. if system_includes: system_includes = system_includes | OrderedSet( env.get("INCLUDE", "").split(";") ) env["INCLUDE"] = ";".join(system_includes) env_block = _FormatAsEnvironmentBlock(env) f = open_out(os.path.join(toplevel_build_dir, "environment." + arch), "w") f.write(env_block) f.close() # Find cl.exe location for this architecture. args = vs.SetupScript(arch) args.extend( ("&&", "for", "%i", "in", "(cl.exe)", "do", "@echo", "LOC:%~$PATH:i") ) popen = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE) output = popen.communicate()[0].decode("utf-8") cl_paths[arch] = _ExtractCLPath(output) return cl_paths def VerifyMissingSources(sources, build_dir, generator_flags, gyp_to_ninja): """Emulate behavior of msvs_error_on_missing_sources present in the msvs generator: Check that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation when building via VS, and we want this check to match for people/bots that build using ninja, so they're not surprised when the VS build fails.""" if int(generator_flags.get("msvs_error_on_missing_sources", 0)): no_specials = filter(lambda x: "$" not in x, sources) relative = [os.path.join(build_dir, gyp_to_ninja(s)) for s in no_specials] missing = [x for x in relative if not os.path.exists(x)] if missing: # They'll look like out\Release\..\..\stuff\things.cc, so normalize the # path for a slightly less crazy looking output. cleaned_up = [os.path.normpath(x) for x in missing] raise Exception("Missing input files:\n%s" % "\n".join(cleaned_up)) # Sets some values in default_variables, which are required for many # generators, run on Windows. def CalculateCommonVariables(default_variables, params): generator_flags = params.get("generator_flags", {}) # Set a variable so conditions can be based on msvs_version. msvs_version = gyp.msvs_emulation.GetVSVersion(generator_flags) default_variables["MSVS_VERSION"] = msvs_version.ShortName() # To determine processor word size on Windows, in addition to checking # PROCESSOR_ARCHITECTURE (which reflects the word size of the current # process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which # contains the actual word size of the system when running thru WOW64). if "64" in os.environ.get("PROCESSOR_ARCHITECTURE", "") or "64" in os.environ.get( "PROCESSOR_ARCHITEW6432", "" ): default_variables["MSVS_OS_BITS"] = 64 else: default_variables["MSVS_OS_BITS"] = 32 # This file comes from # https://github.com/martine/ninja/blob/master/misc/ninja_syntax.py # Do not edit! Edit the upstream one instead. """Python module for generating .ninja files. Note that this is emphatically not a required piece of Ninja; it's just a helpful utility for build-file-generation systems that already use Python. """ import textwrap def escape_path(word): return word.replace("$ ", "$$ ").replace(" ", "$ ").replace(":", "$:") class Writer: def __init__(self, output, width=78): self.output = output self.width = width def newline(self): self.output.write("\n") def comment(self, text): for line in textwrap.wrap(text, self.width - 2): self.output.write("# " + line + "\n") def variable(self, key, value, indent=0): if value is None: return if isinstance(value, list): value = " ".join(filter(None, value)) # Filter out empty strings. self._line(f"{key} = {value}", indent) def pool(self, name, depth): self._line("pool %s" % name) self.variable("depth", depth, indent=1) def rule( self, name, command, description=None, depfile=None, generator=False, pool=None, restat=False, rspfile=None, rspfile_content=None, deps=None, ): self._line("rule %s" % name) self.variable("command", command, indent=1) if description: self.variable("description", description, indent=1) if depfile: self.variable("depfile", depfile, indent=1) if generator: self.variable("generator", "1", indent=1) if pool: self.variable("pool", pool, indent=1) if restat: self.variable("restat", "1", indent=1) if rspfile: self.variable("rspfile", rspfile, indent=1) if rspfile_content: self.variable("rspfile_content", rspfile_content, indent=1) if deps: self.variable("deps", deps, indent=1) def build( self, outputs, rule, inputs=None, implicit=None, order_only=None, variables=None ): outputs = self._as_list(outputs) all_inputs = self._as_list(inputs)[:] out_outputs = list(map(escape_path, outputs)) all_inputs = list(map(escape_path, all_inputs)) if implicit: implicit = map(escape_path, self._as_list(implicit)) all_inputs.append("|") all_inputs.extend(implicit) if order_only: order_only = map(escape_path, self._as_list(order_only)) all_inputs.append("||") all_inputs.extend(order_only) self._line( "build {}: {}".format(" ".join(out_outputs), " ".join([rule] + all_inputs)) ) if variables: if isinstance(variables, dict): iterator = iter(variables.items()) else: iterator = iter(variables) for key, val in iterator: self.variable(key, val, indent=1) return outputs def include(self, path): self._line("include %s" % path) def subninja(self, path): self._line("subninja %s" % path) def default(self, paths): self._line("default %s" % " ".join(self._as_list(paths))) def _count_dollars_before_index(self, s, i): """Returns the number of '$' characters right in front of s[i].""" dollar_count = 0 dollar_index = i - 1 while dollar_index > 0 and s[dollar_index] == "$": dollar_count += 1 dollar_index -= 1 return dollar_count def _line(self, text, indent=0): """Write 'text' word-wrapped at self.width characters.""" leading_space = " " * indent while len(leading_space) + len(text) > self.width: # The text is too wide; wrap if possible. # Find the rightmost space that would obey our width constraint and # that's not an escaped space. available_space = self.width - len(leading_space) - len(" $") space = available_space while True: space = text.rfind(" ", 0, space) if space < 0 or self._count_dollars_before_index(text, space) % 2 == 0: break if space < 0: # No such space; just use the first unescaped space we can find. space = available_space - 1 while True: space = text.find(" ", space + 1) if ( space < 0 or self._count_dollars_before_index(text, space) % 2 == 0 ): break if space < 0: # Give up on breaking. break self.output.write(leading_space + text[0:space] + " $\n") text = text[space + 1 :] # Subsequent lines are continuations, so indent them. leading_space = " " * (indent + 2) self.output.write(leading_space + text + "\n") def _as_list(self, input): if input is None: return [] if isinstance(input, list): return input return [input] def escape(string): """Escape a string such that it can be embedded into a Ninja file without further interpretation.""" assert "\n" not in string, "Ninja syntax does not allow newlines" # We only have one special metacharacter: '$'. return string.replace("$", "$$") # Copyright 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A clone of the default copy.deepcopy that doesn't handle cyclic structures or complex types except for dicts and lists. This is because gyp copies so large structure that small copy overhead ends up taking seconds in a project the size of Chromium.""" class Error(Exception): pass __all__ = ["Error", "deepcopy"] def deepcopy(x): """Deep copy operation on gyp objects such as strings, ints, dicts and lists. More than twice as fast as copy.deepcopy but much less generic.""" try: return _deepcopy_dispatch[type(x)](x) except KeyError: raise Error( "Unsupported type %s for deepcopy. Use copy.deepcopy " + "or expand simple_copy support." % type(x) ) _deepcopy_dispatch = d = {} def _deepcopy_atomic(x): return x types = bool, float, int, str, type, type(None) for x in types: d[x] = _deepcopy_atomic def _deepcopy_list(x): return [deepcopy(a) for a in x] d[list] = _deepcopy_list def _deepcopy_dict(x): y = {} for key, value in x.items(): y[deepcopy(key)] = deepcopy(value) return y d[dict] = _deepcopy_dict del d #!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for Windows builds. These functions are executed via gyp-win-tool when using the ninja generator. """ import os import re import shutil import subprocess import stat import string import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # A regex matching an argument corresponding to the output filename passed to # link.exe. _LINK_EXE_OUT_ARG = re.compile("/OUT:(?P.+)$", re.IGNORECASE) def main(args): executor = WinTool() exit_code = executor.Dispatch(args) if exit_code is not None: sys.exit(exit_code) class WinTool: """This class performs all the Windows tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" def _UseSeparateMspdbsrv(self, env, args): """Allows to use a unique instance of mspdbsrv.exe per linker instead of a shared one.""" if len(args) < 1: raise Exception("Not enough arguments") if args[0] != "link.exe": return # Use the output filename passed to the linker to generate an endpoint name # for mspdbsrv.exe. endpoint_name = None for arg in args: m = _LINK_EXE_OUT_ARG.match(arg) if m: endpoint_name = re.sub( r"\W+", "", "%s_%d" % (m.group("out"), os.getpid()) ) break if endpoint_name is None: return # Adds the appropriate environment variable. This will be read by link.exe # to know which instance of mspdbsrv.exe it should connect to (if it's # not set then the default endpoint is used). env["_MSPDBSRV_ENDPOINT_"] = endpoint_name def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like recursive-mirror to RecursiveMirror.""" return name_string.title().replace("-", "") def _GetEnv(self, arch): """Gets the saved environment from a file for a given architecture.""" # The environment is saved as an "environment block" (see CreateProcess # and msvs_emulation for details). We convert to a dict here. # Drop last 2 NULs, one for list terminator, one for trailing vs. separator. pairs = open(arch).read()[:-2].split("\0") kvs = [item.split("=", 1) for item in pairs] return dict(kvs) def ExecStamp(self, path): """Simple stamp command.""" open(path, "w").close() def ExecRecursiveMirror(self, source, dest): """Emulation of rm -rf out && cp -af in out.""" if os.path.exists(dest): if os.path.isdir(dest): def _on_error(fn, path, excinfo): # The operation failed, possibly because the file is set to # read-only. If that's why, make it writable and try the op again. if not os.access(path, os.W_OK): os.chmod(path, stat.S_IWRITE) fn(path) shutil.rmtree(dest, onerror=_on_error) else: if not os.access(dest, os.W_OK): # Attempt to make the file writable before deleting it. os.chmod(dest, stat.S_IWRITE) os.unlink(dest) if os.path.isdir(source): shutil.copytree(source, dest) else: shutil.copy2(source, dest) def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args): """Filter diagnostic output from link that looks like: ' Creating library ui.dll.lib and object ui.dll.exp' This happens when there are exports from the dll or exe. """ env = self._GetEnv(arch) if use_separate_mspdbsrv == "True": self._UseSeparateMspdbsrv(env, args) if sys.platform == "win32": args = list(args) # *args is a tuple by default, which is read-only. args[0] = args[0].replace("/", "\\") # https://docs.python.org/2/library/subprocess.html: # "On Unix with shell=True [...] if args is a sequence, the first item # specifies the command string, and any additional items will be treated as # additional arguments to the shell itself. That is to say, Popen does the # equivalent of: # Popen(['/bin/sh', '-c', args[0], args[1], ...])" # For that reason, since going through the shell doesn't seem necessary on # non-Windows don't do that there. link = subprocess.Popen( args, shell=sys.platform == "win32", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) out = link.communicate()[0].decode("utf-8") for line in out.splitlines(): if ( not line.startswith(" Creating library ") and not line.startswith("Generating code") and not line.startswith("Finished generating code") ): print(line) return link.returncode def ExecLinkWithManifests( self, arch, embed_manifest, out, ldcmd, resname, mt, rc, intermediate_manifest, *manifests ): """A wrapper for handling creating a manifest resource and then executing a link command.""" # The 'normal' way to do manifests is to have link generate a manifest # based on gathering dependencies from the object files, then merge that # manifest with other manifests supplied as sources, convert the merged # manifest to a resource, and then *relink*, including the compiled # version of the manifest resource. This breaks incremental linking, and # is generally overly complicated. Instead, we merge all the manifests # provided (along with one that includes what would normally be in the # linker-generated one, see msvs_emulation.py), and include that into the # first and only link. We still tell link to generate a manifest, but we # only use that to assert that our simpler process did not miss anything. variables = { "python": sys.executable, "arch": arch, "out": out, "ldcmd": ldcmd, "resname": resname, "mt": mt, "rc": rc, "intermediate_manifest": intermediate_manifest, "manifests": " ".join(manifests), } add_to_ld = "" if manifests: subprocess.check_call( "%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo " "-manifest %(manifests)s -out:%(out)s.manifest" % variables ) if embed_manifest == "True": subprocess.check_call( "%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest" " %(out)s.manifest.rc %(resname)s" % variables ) subprocess.check_call( "%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s " "%(out)s.manifest.rc" % variables ) add_to_ld = " %(out)s.manifest.res" % variables subprocess.check_call(ldcmd + add_to_ld) # Run mt.exe on the theoretically complete manifest we generated, merging # it with the one the linker generated to confirm that the linker # generated one does not add anything. This is strictly unnecessary for # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not # used in a #pragma comment. if manifests: # Merge the intermediate one with ours to .assert.manifest, then check # that .assert.manifest is identical to ours. subprocess.check_call( "%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo " "-manifest %(out)s.manifest %(intermediate_manifest)s " "-out:%(out)s.assert.manifest" % variables ) assert_manifest = "%(out)s.assert.manifest" % variables our_manifest = "%(out)s.manifest" % variables # Load and normalize the manifests. mt.exe sometimes removes whitespace, # and sometimes doesn't unfortunately. with open(our_manifest) as our_f, open(assert_manifest) as assert_f: translator = str.maketrans("", "", string.whitespace) our_data = our_f.read().translate(translator) assert_data = assert_f.read().translate(translator) if our_data != assert_data: os.unlink(out) def dump(filename): print(filename, file=sys.stderr) print("-----", file=sys.stderr) with open(filename) as f: print(f.read(), file=sys.stderr) print("-----", file=sys.stderr) dump(intermediate_manifest) dump(our_manifest) dump(assert_manifest) sys.stderr.write( 'Linker generated manifest "%s" added to final manifest "%s" ' '(result in "%s"). ' "Were /MANIFEST switches used in #pragma statements? " % (intermediate_manifest, our_manifest, assert_manifest) ) return 1 def ExecManifestWrapper(self, arch, *args): """Run manifest tool with environment set. Strip out undesirable warning (some XML blocks are recognized by the OS loader, but not the manifest tool).""" env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out = popen.communicate()[0].decode("utf-8") for line in out.splitlines(): if line and "manifest authoring warning 81010002" not in line: print(line) return popen.returncode def ExecManifestToRc(self, arch, *args): """Creates a resource file pointing a SxS assembly manifest. |args| is tuple containing path to resource file, path to manifest file and resource name which can be "1" (for executables) or "2" (for DLLs).""" manifest_path, resource_path, resource_name = args with open(resource_path, "w") as output: output.write( '#include \n%s RT_MANIFEST "%s"' % (resource_name, os.path.abspath(manifest_path).replace("\\", "/")) ) def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags): """Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags. """ args = ( ["midl", "/nologo"] + list(flags) + [ "/out", outdir, "/tlb", tlb, "/h", h, "/dlldata", dlldata, "/iid", iid, "/proxy", proxy, idl, ] ) env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out = popen.communicate()[0].decode("utf-8") # Filter junk out of stdout, and write filtered versions. Output we want # to filter is pairs of lines that look like this: # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl # objidl.idl lines = out.splitlines() prefixes = ("Processing ", "64 bit Processing ") processing = {os.path.basename(x) for x in lines if x.startswith(prefixes)} for line in lines: if not line.startswith(prefixes) and line not in processing: print(line) return popen.returncode def ExecAsmWrapper(self, arch, *args): """Filter logo banner from invocations of asm.exe.""" env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out = popen.communicate()[0].decode("utf-8") for line in out.splitlines(): if ( not line.startswith("Copyright (C) Microsoft Corporation") and not line.startswith("Microsoft (R) Macro Assembler") and not line.startswith(" Assembling: ") and line ): print(line) return popen.returncode def ExecRcWrapper(self, arch, *args): """Filter logo banner from invocations of rc.exe. Older versions of RC don't support the /nologo flag.""" env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out = popen.communicate()[0].decode("utf-8") for line in out.splitlines(): if ( not line.startswith("Microsoft (R) Windows (R) Resource Compiler") and not line.startswith("Copyright (C) Microsoft Corporation") and line ): print(line) return popen.returncode def ExecActionWrapper(self, arch, rspfile, *dir): """Runs an action command line from a response file using the environment for |arch|. If |dir| is supplied, use that as the working directory.""" env = self._GetEnv(arch) # TODO(scottmg): This is a temporary hack to get some specific variables # through to actions that are set after gyp-time. http://crbug.com/333738. for k, v in os.environ.items(): if k not in env: env[k] = v args = open(rspfile).read() dir = dir[0] if dir else None return subprocess.call(args, shell=True, env=env, cwd=dir) def ExecClCompile(self, project_dir, selected_files): """Executed by msvs-ninja projects when the 'ClCompile' target is used to build selected C/C++ files.""" project_dir = os.path.relpath(project_dir, BASE_DIR) selected_files = selected_files.split(";") ninja_targets = [ os.path.join(project_dir, filename) + "^^" for filename in selected_files ] cmd = ["ninja.exe"] cmd.extend(ninja_targets) return subprocess.call(cmd, shell=True, cwd=BASE_DIR) if __name__ == "__main__": sys.exit(main(sys.argv[1:])) # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This module contains classes that help to emulate xcodebuild behavior on top of other build systems, such as make and ninja. """ import copy import gyp.common import os import os.path import re import shlex import subprocess import sys from gyp.common import GypError # Populated lazily by XcodeVersion, for efficiency, and to fix an issue when # "xcodebuild" is called too quickly (it has been found to return incorrect # version number). XCODE_VERSION_CACHE = None # Populated lazily by GetXcodeArchsDefault, to an |XcodeArchsDefault| instance # corresponding to the installed version of Xcode. XCODE_ARCHS_DEFAULT_CACHE = None def XcodeArchsVariableMapping(archs, archs_including_64_bit=None): """Constructs a dictionary with expansion for $(ARCHS_STANDARD) variable, and optionally for $(ARCHS_STANDARD_INCLUDING_64_BIT).""" mapping = {"$(ARCHS_STANDARD)": archs} if archs_including_64_bit: mapping["$(ARCHS_STANDARD_INCLUDING_64_BIT)"] = archs_including_64_bit return mapping class XcodeArchsDefault: """A class to resolve ARCHS variable from xcode_settings, resolving Xcode macros and implementing filtering by VALID_ARCHS. The expansion of macros depends on the SDKROOT used ("macosx", "iphoneos", "iphonesimulator") and on the version of Xcode. """ # Match variable like $(ARCHS_STANDARD). variable_pattern = re.compile(r"\$\([a-zA-Z_][a-zA-Z0-9_]*\)$") def __init__(self, default, mac, iphonesimulator, iphoneos): self._default = (default,) self._archs = {"mac": mac, "ios": iphoneos, "iossim": iphonesimulator} def _VariableMapping(self, sdkroot): """Returns the dictionary of variable mapping depending on the SDKROOT.""" sdkroot = sdkroot.lower() if "iphoneos" in sdkroot: return self._archs["ios"] elif "iphonesimulator" in sdkroot: return self._archs["iossim"] else: return self._archs["mac"] def _ExpandArchs(self, archs, sdkroot): """Expands variables references in ARCHS, and remove duplicates.""" variable_mapping = self._VariableMapping(sdkroot) expanded_archs = [] for arch in archs: if self.variable_pattern.match(arch): variable = arch try: variable_expansion = variable_mapping[variable] for arch in variable_expansion: if arch not in expanded_archs: expanded_archs.append(arch) except KeyError: print('Warning: Ignoring unsupported variable "%s".' % variable) elif arch not in expanded_archs: expanded_archs.append(arch) return expanded_archs def ActiveArchs(self, archs, valid_archs, sdkroot): """Expands variables references in ARCHS, and filter by VALID_ARCHS if it is defined (if not set, Xcode accept any value in ARCHS, otherwise, only values present in VALID_ARCHS are kept).""" expanded_archs = self._ExpandArchs(archs or self._default, sdkroot or "") if valid_archs: filtered_archs = [] for arch in expanded_archs: if arch in valid_archs: filtered_archs.append(arch) expanded_archs = filtered_archs return expanded_archs def GetXcodeArchsDefault(): """Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used. For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses $(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0 and deprecated with Xcode 5.1. For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit architecture as part of $(ARCHS_STANDARD) and default to only building it. For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they are also part of $(ARCHS_STANDARD). All these rules are coded in the construction of the |XcodeArchsDefault| object to use depending on the version of Xcode detected. The object is for performance reason.""" global XCODE_ARCHS_DEFAULT_CACHE if XCODE_ARCHS_DEFAULT_CACHE: return XCODE_ARCHS_DEFAULT_CACHE xcode_version, _ = XcodeVersion() if xcode_version < "0500": XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( "$(ARCHS_STANDARD)", XcodeArchsVariableMapping(["i386"]), XcodeArchsVariableMapping(["i386"]), XcodeArchsVariableMapping(["armv7"]), ) elif xcode_version < "0510": XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( "$(ARCHS_STANDARD_INCLUDING_64_BIT)", XcodeArchsVariableMapping(["x86_64"], ["x86_64"]), XcodeArchsVariableMapping(["i386"], ["i386", "x86_64"]), XcodeArchsVariableMapping( ["armv7", "armv7s"], ["armv7", "armv7s", "arm64"] ), ) else: XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( "$(ARCHS_STANDARD)", XcodeArchsVariableMapping(["x86_64"], ["x86_64"]), XcodeArchsVariableMapping(["i386", "x86_64"], ["i386", "x86_64"]), XcodeArchsVariableMapping( ["armv7", "armv7s", "arm64"], ["armv7", "armv7s", "arm64"] ), ) return XCODE_ARCHS_DEFAULT_CACHE class XcodeSettings: """A class that understands the gyp 'xcode_settings' object.""" # Populated lazily by _SdkPath(). Shared by all XcodeSettings, so cached # at class-level for efficiency. _sdk_path_cache = {} _platform_path_cache = {} _sdk_root_cache = {} # Populated lazily by GetExtraPlistItems(). Shared by all XcodeSettings, so # cached at class-level for efficiency. _plist_cache = {} # Populated lazily by GetIOSPostbuilds. Shared by all XcodeSettings, so # cached at class-level for efficiency. _codesigning_key_cache = {} def __init__(self, spec): self.spec = spec self.isIOS = False self.mac_toolchain_dir = None self.header_map_path = None # Per-target 'xcode_settings' are pushed down into configs earlier by gyp. # This means self.xcode_settings[config] always contains all settings # for that config -- the per-target settings as well. Settings that are # the same for all configs are implicitly per-target settings. self.xcode_settings = {} configs = spec["configurations"] for configname, config in configs.items(): self.xcode_settings[configname] = config.get("xcode_settings", {}) self._ConvertConditionalKeys(configname) if self.xcode_settings[configname].get("IPHONEOS_DEPLOYMENT_TARGET", None): self.isIOS = True # This is only non-None temporarily during the execution of some methods. self.configname = None # Used by _AdjustLibrary to match .a and .dylib entries in libraries. self.library_re = re.compile(r"^lib([^/]+)\.(a|dylib)$") def _ConvertConditionalKeys(self, configname): """Converts or warns on conditional keys. Xcode supports conditional keys, such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation with some keys converted while the rest force a warning.""" settings = self.xcode_settings[configname] conditional_keys = [key for key in settings if key.endswith("]")] for key in conditional_keys: # If you need more, speak up at http://crbug.com/122592 if key.endswith("[sdk=iphoneos*]"): if configname.endswith("iphoneos"): new_key = key.split("[")[0] settings[new_key] = settings[key] else: print( "Warning: Conditional keys not implemented, ignoring:", " ".join(conditional_keys), ) del settings[key] def _Settings(self): assert self.configname return self.xcode_settings[self.configname] def _Test(self, test_key, cond_key, default): return self._Settings().get(test_key, default) == cond_key def _Appendf(self, lst, test_key, format_str, default=None): if test_key in self._Settings(): lst.append(format_str % str(self._Settings()[test_key])) elif default: lst.append(format_str % str(default)) def _WarnUnimplemented(self, test_key): if test_key in self._Settings(): print('Warning: Ignoring not yet implemented key "%s".' % test_key) def IsBinaryOutputFormat(self, configname): default = "binary" if self.isIOS else "xml" format = self.xcode_settings[configname].get("INFOPLIST_OUTPUT_FORMAT", default) return format == "binary" def IsIosFramework(self): return self.spec["type"] == "shared_library" and self._IsBundle() and self.isIOS def _IsBundle(self): return ( int(self.spec.get("mac_bundle", 0)) != 0 or self._IsXCTest() or self._IsXCUiTest() ) def _IsXCTest(self): return int(self.spec.get("mac_xctest_bundle", 0)) != 0 def _IsXCUiTest(self): return int(self.spec.get("mac_xcuitest_bundle", 0)) != 0 def _IsIosAppExtension(self): return int(self.spec.get("ios_app_extension", 0)) != 0 def _IsIosWatchKitExtension(self): return int(self.spec.get("ios_watchkit_extension", 0)) != 0 def _IsIosWatchApp(self): return int(self.spec.get("ios_watch_app", 0)) != 0 def GetFrameworkVersion(self): """Returns the framework version of the current target. Only valid for bundles.""" assert self._IsBundle() return self.GetPerTargetSetting("FRAMEWORK_VERSION", default="A") def GetWrapperExtension(self): """Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.""" assert self._IsBundle() if self.spec["type"] in ("loadable_module", "shared_library"): default_wrapper_extension = { "loadable_module": "bundle", "shared_library": "framework", }[self.spec["type"]] wrapper_extension = self.GetPerTargetSetting( "WRAPPER_EXTENSION", default=default_wrapper_extension ) return "." + self.spec.get("product_extension", wrapper_extension) elif self.spec["type"] == "executable": if self._IsIosAppExtension() or self._IsIosWatchKitExtension(): return "." + self.spec.get("product_extension", "appex") else: return "." + self.spec.get("product_extension", "app") else: assert False, "Don't know extension for '{}', target '{}'".format( self.spec["type"], self.spec["target_name"], ) def GetProductName(self): """Returns PRODUCT_NAME.""" return self.spec.get("product_name", self.spec["target_name"]) def GetFullProductName(self): """Returns FULL_PRODUCT_NAME.""" if self._IsBundle(): return self.GetWrapperName() else: return self._GetStandaloneBinaryPath() def GetWrapperName(self): """Returns the directory name of the bundle represented by this target. Only valid for bundles.""" assert self._IsBundle() return self.GetProductName() + self.GetWrapperExtension() def GetBundleContentsFolderPath(self): """Returns the qualified path to the bundle's contents folder. E.g. Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.""" if self.isIOS: return self.GetWrapperName() assert self._IsBundle() if self.spec["type"] == "shared_library": return os.path.join( self.GetWrapperName(), "Versions", self.GetFrameworkVersion() ) else: # loadable_modules have a 'Contents' folder like executables. return os.path.join(self.GetWrapperName(), "Contents") def GetBundleResourceFolder(self): """Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.""" assert self._IsBundle() if self.isIOS: return self.GetBundleContentsFolderPath() return os.path.join(self.GetBundleContentsFolderPath(), "Resources") def GetBundleExecutableFolderPath(self): """Returns the qualified path to the bundle's executables folder. E.g. Chromium.app/Contents/MacOS. Only valid for bundles.""" assert self._IsBundle() if self.spec["type"] in ("shared_library") or self.isIOS: return self.GetBundleContentsFolderPath() elif self.spec["type"] in ("executable", "loadable_module"): return os.path.join(self.GetBundleContentsFolderPath(), "MacOS") def GetBundleJavaFolderPath(self): """Returns the qualified path to the bundle's Java resource folder. E.g. Chromium.app/Contents/Resources/Java. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleResourceFolder(), "Java") def GetBundleFrameworksFolderPath(self): """Returns the qualified path to the bundle's frameworks folder. E.g, Chromium.app/Contents/Frameworks. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), "Frameworks") def GetBundleSharedFrameworksFolderPath(self): """Returns the qualified path to the bundle's frameworks folder. E.g, Chromium.app/Contents/SharedFrameworks. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), "SharedFrameworks") def GetBundleSharedSupportFolderPath(self): """Returns the qualified path to the bundle's shared support folder. E.g, Chromium.app/Contents/SharedSupport. Only valid for bundles.""" assert self._IsBundle() if self.spec["type"] == "shared_library": return self.GetBundleResourceFolder() else: return os.path.join(self.GetBundleContentsFolderPath(), "SharedSupport") def GetBundlePlugInsFolderPath(self): """Returns the qualified path to the bundle's plugins folder. E.g, Chromium.app/Contents/PlugIns. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), "PlugIns") def GetBundleXPCServicesFolderPath(self): """Returns the qualified path to the bundle's XPC services folder. E.g, Chromium.app/Contents/XPCServices. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), "XPCServices") def GetBundlePlistPath(self): """Returns the qualified path to the bundle's plist file. E.g. Chromium.app/Contents/Info.plist. Only valid for bundles.""" assert self._IsBundle() if ( self.spec["type"] in ("executable", "loadable_module") or self.IsIosFramework() ): return os.path.join(self.GetBundleContentsFolderPath(), "Info.plist") else: return os.path.join( self.GetBundleContentsFolderPath(), "Resources", "Info.plist" ) def GetProductType(self): """Returns the PRODUCT_TYPE of this target.""" if self._IsIosAppExtension(): assert self._IsBundle(), ( "ios_app_extension flag requires mac_bundle " "(target %s)" % self.spec["target_name"] ) return "com.apple.product-type.app-extension" if self._IsIosWatchKitExtension(): assert self._IsBundle(), ( "ios_watchkit_extension flag requires " "mac_bundle (target %s)" % self.spec["target_name"] ) return "com.apple.product-type.watchkit-extension" if self._IsIosWatchApp(): assert self._IsBundle(), ( "ios_watch_app flag requires mac_bundle " "(target %s)" % self.spec["target_name"] ) return "com.apple.product-type.application.watchapp" if self._IsXCUiTest(): assert self._IsBundle(), ( "mac_xcuitest_bundle flag requires mac_bundle " "(target %s)" % self.spec["target_name"] ) return "com.apple.product-type.bundle.ui-testing" if self._IsBundle(): return { "executable": "com.apple.product-type.application", "loadable_module": "com.apple.product-type.bundle", "shared_library": "com.apple.product-type.framework", }[self.spec["type"]] else: return { "executable": "com.apple.product-type.tool", "loadable_module": "com.apple.product-type.library.dynamic", "shared_library": "com.apple.product-type.library.dynamic", "static_library": "com.apple.product-type.library.static", }[self.spec["type"]] def GetMachOType(self): """Returns the MACH_O_TYPE of this target.""" # Weird, but matches Xcode. if not self._IsBundle() and self.spec["type"] == "executable": return "" return { "executable": "mh_execute", "static_library": "staticlib", "shared_library": "mh_dylib", "loadable_module": "mh_bundle", }[self.spec["type"]] def _GetBundleBinaryPath(self): """Returns the name of the bundle binary of by this target. E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.""" assert self._IsBundle() return os.path.join( self.GetBundleExecutableFolderPath(), self.GetExecutableName() ) def _GetStandaloneExecutableSuffix(self): if "product_extension" in self.spec: return "." + self.spec["product_extension"] return { "executable": "", "static_library": ".a", "shared_library": ".dylib", "loadable_module": ".so", }[self.spec["type"]] def _GetStandaloneExecutablePrefix(self): return self.spec.get( "product_prefix", { "executable": "", "static_library": "lib", "shared_library": "lib", # Non-bundled loadable_modules are called foo.so for some reason # (that is, .so and no prefix) with the xcode build -- match that. "loadable_module": "", }[self.spec["type"]], ) def _GetStandaloneBinaryPath(self): """Returns the name of the non-bundle binary represented by this target. E.g. hello_world. Only valid for non-bundles.""" assert not self._IsBundle() assert self.spec["type"] in ( "executable", "shared_library", "static_library", "loadable_module", ), ("Unexpected type %s" % self.spec["type"]) target = self.spec["target_name"] if self.spec["type"] == "static_library": if target[:3] == "lib": target = target[3:] elif self.spec["type"] in ("loadable_module", "shared_library"): if target[:3] == "lib": target = target[3:] target_prefix = self._GetStandaloneExecutablePrefix() target = self.spec.get("product_name", target) target_ext = self._GetStandaloneExecutableSuffix() return target_prefix + target + target_ext def GetExecutableName(self): """Returns the executable name of the bundle represented by this target. E.g. Chromium.""" if self._IsBundle(): return self.spec.get("product_name", self.spec["target_name"]) else: return self._GetStandaloneBinaryPath() def GetExecutablePath(self): """Returns the qualified path to the primary executable of the bundle represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium.""" if self._IsBundle(): return self._GetBundleBinaryPath() else: return self._GetStandaloneBinaryPath() def GetActiveArchs(self, configname): """Returns the architectures this target should be built for.""" config_settings = self.xcode_settings[configname] xcode_archs_default = GetXcodeArchsDefault() return xcode_archs_default.ActiveArchs( config_settings.get("ARCHS"), config_settings.get("VALID_ARCHS"), config_settings.get("SDKROOT"), ) def _GetSdkVersionInfoItem(self, sdk, infoitem): # xcodebuild requires Xcode and can't run on Command Line Tools-only # systems from 10.7 onward. # Since the CLT has no SDK paths anyway, returning None is the # most sensible route and should still do the right thing. try: return GetStdoutQuiet(["xcrun", "--sdk", sdk, infoitem]) except GypError: pass def _SdkRoot(self, configname): if configname is None: configname = self.configname return self.GetPerConfigSetting("SDKROOT", configname, default="") def _XcodePlatformPath(self, configname=None): sdk_root = self._SdkRoot(configname) if sdk_root not in XcodeSettings._platform_path_cache: platform_path = self._GetSdkVersionInfoItem( sdk_root, "--show-sdk-platform-path" ) XcodeSettings._platform_path_cache[sdk_root] = platform_path return XcodeSettings._platform_path_cache[sdk_root] def _SdkPath(self, configname=None): sdk_root = self._SdkRoot(configname) if sdk_root.startswith("/"): return sdk_root return self._XcodeSdkPath(sdk_root) def _XcodeSdkPath(self, sdk_root): if sdk_root not in XcodeSettings._sdk_path_cache: sdk_path = self._GetSdkVersionInfoItem(sdk_root, "--show-sdk-path") XcodeSettings._sdk_path_cache[sdk_root] = sdk_path if sdk_root: XcodeSettings._sdk_root_cache[sdk_path] = sdk_root return XcodeSettings._sdk_path_cache[sdk_root] def _AppendPlatformVersionMinFlags(self, lst): self._Appendf(lst, "MACOSX_DEPLOYMENT_TARGET", "-mmacosx-version-min=%s") if "IPHONEOS_DEPLOYMENT_TARGET" in self._Settings(): # TODO: Implement this better? sdk_path_basename = os.path.basename(self._SdkPath()) if sdk_path_basename.lower().startswith("iphonesimulator"): self._Appendf( lst, "IPHONEOS_DEPLOYMENT_TARGET", "-mios-simulator-version-min=%s" ) else: self._Appendf( lst, "IPHONEOS_DEPLOYMENT_TARGET", "-miphoneos-version-min=%s" ) def GetCflags(self, configname, arch=None): """Returns flags that need to be added to .c, .cc, .m, and .mm compilations.""" # This functions (and the similar ones below) do not offer complete # emulation of all xcode_settings keys. They're implemented on demand. self.configname = configname cflags = [] sdk_root = self._SdkPath() if "SDKROOT" in self._Settings() and sdk_root: cflags.append("-isysroot") cflags.append(sdk_root) if self.header_map_path: cflags.append("-I%s" % self.header_map_path) if self._Test("CLANG_WARN_CONSTANT_CONVERSION", "YES", default="NO"): cflags.append("-Wconstant-conversion") if self._Test("GCC_CHAR_IS_UNSIGNED_CHAR", "YES", default="NO"): cflags.append("-funsigned-char") if self._Test("GCC_CW_ASM_SYNTAX", "YES", default="YES"): cflags.append("-fasm-blocks") if "GCC_DYNAMIC_NO_PIC" in self._Settings(): if self._Settings()["GCC_DYNAMIC_NO_PIC"] == "YES": cflags.append("-mdynamic-no-pic") else: pass # TODO: In this case, it depends on the target. xcode passes # mdynamic-no-pic by default for executable and possibly static lib # according to mento if self._Test("GCC_ENABLE_PASCAL_STRINGS", "YES", default="YES"): cflags.append("-mpascal-strings") self._Appendf(cflags, "GCC_OPTIMIZATION_LEVEL", "-O%s", default="s") if self._Test("GCC_GENERATE_DEBUGGING_SYMBOLS", "YES", default="YES"): dbg_format = self._Settings().get("DEBUG_INFORMATION_FORMAT", "dwarf") if dbg_format == "dwarf": cflags.append("-gdwarf-2") elif dbg_format == "stabs": raise NotImplementedError("stabs debug format is not supported yet.") elif dbg_format == "dwarf-with-dsym": cflags.append("-gdwarf-2") else: raise NotImplementedError("Unknown debug format %s" % dbg_format) if self._Settings().get("GCC_STRICT_ALIASING") == "YES": cflags.append("-fstrict-aliasing") elif self._Settings().get("GCC_STRICT_ALIASING") == "NO": cflags.append("-fno-strict-aliasing") if self._Test("GCC_SYMBOLS_PRIVATE_EXTERN", "YES", default="NO"): cflags.append("-fvisibility=hidden") if self._Test("GCC_TREAT_WARNINGS_AS_ERRORS", "YES", default="NO"): cflags.append("-Werror") if self._Test("GCC_WARN_ABOUT_MISSING_NEWLINE", "YES", default="NO"): cflags.append("-Wnewline-eof") # In Xcode, this is only activated when GCC_COMPILER_VERSION is clang or # llvm-gcc. It also requires a fairly recent libtool, and # if the system clang isn't used, DYLD_LIBRARY_PATH needs to contain the # path to the libLTO.dylib that matches the used clang. if self._Test("LLVM_LTO", "YES", default="NO"): cflags.append("-flto") self._AppendPlatformVersionMinFlags(cflags) # TODO: if self._Test("COPY_PHASE_STRIP", "YES", default="NO"): self._WarnUnimplemented("COPY_PHASE_STRIP") self._WarnUnimplemented("GCC_DEBUGGING_SYMBOLS") self._WarnUnimplemented("GCC_ENABLE_OBJC_EXCEPTIONS") # TODO: This is exported correctly, but assigning to it is not supported. self._WarnUnimplemented("MACH_O_TYPE") self._WarnUnimplemented("PRODUCT_TYPE") # If GYP_CROSSCOMPILE (--cross-compiling), disable architecture-specific # additions and assume these will be provided as required via CC_host, # CXX_host, CC_target and CXX_target. if not gyp.common.CrossCompileRequested(): if arch is not None: archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if len(archs) != 1: # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented("ARCHS") archs = ["i386"] cflags.append("-arch") cflags.append(archs[0]) if archs[0] in ("i386", "x86_64"): if self._Test("GCC_ENABLE_SSE3_EXTENSIONS", "YES", default="NO"): cflags.append("-msse3") if self._Test( "GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS", "YES", default="NO" ): cflags.append("-mssse3") # Note 3rd 's'. if self._Test("GCC_ENABLE_SSE41_EXTENSIONS", "YES", default="NO"): cflags.append("-msse4.1") if self._Test("GCC_ENABLE_SSE42_EXTENSIONS", "YES", default="NO"): cflags.append("-msse4.2") cflags += self._Settings().get("WARNING_CFLAGS", []) if self._IsXCTest(): platform_root = self._XcodePlatformPath(configname) if platform_root: cflags.append("-F" + platform_root + "/Developer/Library/Frameworks/") framework_root = sdk_root if sdk_root else "" config = self.spec["configurations"][self.configname] framework_dirs = config.get("mac_framework_dirs", []) for directory in framework_dirs: cflags.append("-F" + directory.replace("$(SDKROOT)", framework_root)) self.configname = None return cflags def GetCflagsC(self, configname): """Returns flags that need to be added to .c, and .m compilations.""" self.configname = configname cflags_c = [] if self._Settings().get("GCC_C_LANGUAGE_STANDARD", "") == "ansi": cflags_c.append("-ansi") else: self._Appendf(cflags_c, "GCC_C_LANGUAGE_STANDARD", "-std=%s") cflags_c += self._Settings().get("OTHER_CFLAGS", []) self.configname = None return cflags_c def GetCflagsCC(self, configname): """Returns flags that need to be added to .cc, and .mm compilations.""" self.configname = configname cflags_cc = [] clang_cxx_language_standard = self._Settings().get( "CLANG_CXX_LANGUAGE_STANDARD" ) # Note: Don't make c++0x to c++11 so that c++0x can be used with older # clangs that don't understand c++11 yet (like Xcode 4.2's). if clang_cxx_language_standard: cflags_cc.append("-std=%s" % clang_cxx_language_standard) self._Appendf(cflags_cc, "CLANG_CXX_LIBRARY", "-stdlib=%s") if self._Test("GCC_ENABLE_CPP_RTTI", "NO", default="YES"): cflags_cc.append("-fno-rtti") if self._Test("GCC_ENABLE_CPP_EXCEPTIONS", "NO", default="YES"): cflags_cc.append("-fno-exceptions") if self._Test("GCC_INLINES_ARE_PRIVATE_EXTERN", "YES", default="NO"): cflags_cc.append("-fvisibility-inlines-hidden") if self._Test("GCC_THREADSAFE_STATICS", "NO", default="YES"): cflags_cc.append("-fno-threadsafe-statics") # Note: This flag is a no-op for clang, it only has an effect for gcc. if self._Test("GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO", "NO", default="YES"): cflags_cc.append("-Wno-invalid-offsetof") other_ccflags = [] for flag in self._Settings().get("OTHER_CPLUSPLUSFLAGS", ["$(inherited)"]): # TODO: More general variable expansion. Missing in many other places too. if flag in ("$inherited", "$(inherited)", "${inherited}"): flag = "$OTHER_CFLAGS" if flag in ("$OTHER_CFLAGS", "$(OTHER_CFLAGS)", "${OTHER_CFLAGS}"): other_ccflags += self._Settings().get("OTHER_CFLAGS", []) else: other_ccflags.append(flag) cflags_cc += other_ccflags self.configname = None return cflags_cc def _AddObjectiveCGarbageCollectionFlags(self, flags): gc_policy = self._Settings().get("GCC_ENABLE_OBJC_GC", "unsupported") if gc_policy == "supported": flags.append("-fobjc-gc") elif gc_policy == "required": flags.append("-fobjc-gc-only") def _AddObjectiveCARCFlags(self, flags): if self._Test("CLANG_ENABLE_OBJC_ARC", "YES", default="NO"): flags.append("-fobjc-arc") def _AddObjectiveCMissingPropertySynthesisFlags(self, flags): if self._Test( "CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS", "YES", default="NO" ): flags.append("-Wobjc-missing-property-synthesis") def GetCflagsObjC(self, configname): """Returns flags that need to be added to .m compilations.""" self.configname = configname cflags_objc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objc) self._AddObjectiveCARCFlags(cflags_objc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objc) self.configname = None return cflags_objc def GetCflagsObjCC(self, configname): """Returns flags that need to be added to .mm compilations.""" self.configname = configname cflags_objcc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objcc) self._AddObjectiveCARCFlags(cflags_objcc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objcc) if self._Test("GCC_OBJC_CALL_CXX_CDTORS", "YES", default="NO"): cflags_objcc.append("-fobjc-call-cxx-cdtors") self.configname = None return cflags_objcc def GetInstallNameBase(self): """Return DYLIB_INSTALL_NAME_BASE for this target.""" # Xcode sets this for shared_libraries, and for nonbundled loadable_modules. if self.spec["type"] != "shared_library" and ( self.spec["type"] != "loadable_module" or self._IsBundle() ): return None install_base = self.GetPerTargetSetting( "DYLIB_INSTALL_NAME_BASE", default="/Library/Frameworks" if self._IsBundle() else "/usr/local/lib", ) return install_base def _StandardizePath(self, path): """Do :standardizepath processing for path.""" # I'm not quite sure what :standardizepath does. Just call normpath(), # but don't let @executable_path/../foo collapse to foo. if "/" in path: prefix, rest = "", path if path.startswith("@"): prefix, rest = path.split("/", 1) rest = os.path.normpath(rest) # :standardizepath path = os.path.join(prefix, rest) return path def GetInstallName(self): """Return LD_DYLIB_INSTALL_NAME for this target.""" # Xcode sets this for shared_libraries, and for nonbundled loadable_modules. if self.spec["type"] != "shared_library" and ( self.spec["type"] != "loadable_module" or self._IsBundle() ): return None default_install_name = ( "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)" ) install_name = self.GetPerTargetSetting( "LD_DYLIB_INSTALL_NAME", default=default_install_name ) # Hardcode support for the variables used in chromium for now, to # unblock people using the make build. if "$" in install_name: assert install_name in ( "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/" "$(WRAPPER_NAME)/$(PRODUCT_NAME)", default_install_name, ), ( "Variables in LD_DYLIB_INSTALL_NAME are not generally supported " "yet in target '%s' (got '%s')" % (self.spec["target_name"], install_name) ) install_name = install_name.replace( "$(DYLIB_INSTALL_NAME_BASE:standardizepath)", self._StandardizePath(self.GetInstallNameBase()), ) if self._IsBundle(): # These are only valid for bundles, hence the |if|. install_name = install_name.replace( "$(WRAPPER_NAME)", self.GetWrapperName() ) install_name = install_name.replace( "$(PRODUCT_NAME)", self.GetProductName() ) else: assert "$(WRAPPER_NAME)" not in install_name assert "$(PRODUCT_NAME)" not in install_name install_name = install_name.replace( "$(EXECUTABLE_PATH)", self.GetExecutablePath() ) return install_name def _MapLinkerFlagFilename(self, ldflag, gyp_to_build_path): """Checks if ldflag contains a filename and if so remaps it from gyp-directory-relative to build-directory-relative.""" # This list is expanded on demand. # They get matched as: # -exported_symbols_list file # -Wl,exported_symbols_list file # -Wl,exported_symbols_list,file LINKER_FILE = r"(\S+)" WORD = r"\S+" linker_flags = [ ["-exported_symbols_list", LINKER_FILE], # Needed for NaCl. ["-unexported_symbols_list", LINKER_FILE], ["-reexported_symbols_list", LINKER_FILE], ["-sectcreate", WORD, WORD, LINKER_FILE], # Needed for remoting. ] for flag_pattern in linker_flags: regex = re.compile("(?:-Wl,)?" + "[ ,]".join(flag_pattern)) m = regex.match(ldflag) if m: ldflag = ( ldflag[: m.start(1)] + gyp_to_build_path(m.group(1)) + ldflag[m.end(1) :] ) # Required for ffmpeg (no idea why they don't use LIBRARY_SEARCH_PATHS, # TODO(thakis): Update ffmpeg.gyp): if ldflag.startswith("-L"): ldflag = "-L" + gyp_to_build_path(ldflag[len("-L") :]) return ldflag def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): """Returns flags that need to be passed to the linker. Args: configname: The name of the configuration to get ld flags for. product_dir: The directory where products such static and dynamic libraries are placed. This is added to the library search path. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build directory. """ self.configname = configname ldflags = [] # The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS # can contain entries that depend on this. Explicitly absolutify these. for ldflag in self._Settings().get("OTHER_LDFLAGS", []): ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path)) if self._Test("DEAD_CODE_STRIPPING", "YES", default="NO"): ldflags.append("-Wl,-dead_strip") if self._Test("PREBINDING", "YES", default="NO"): ldflags.append("-Wl,-prebind") self._Appendf( ldflags, "DYLIB_COMPATIBILITY_VERSION", "-compatibility_version %s" ) self._Appendf(ldflags, "DYLIB_CURRENT_VERSION", "-current_version %s") self._AppendPlatformVersionMinFlags(ldflags) if "SDKROOT" in self._Settings() and self._SdkPath(): ldflags.append("-isysroot") ldflags.append(self._SdkPath()) for library_path in self._Settings().get("LIBRARY_SEARCH_PATHS", []): ldflags.append("-L" + gyp_to_build_path(library_path)) if "ORDER_FILE" in self._Settings(): ldflags.append("-Wl,-order_file") ldflags.append("-Wl," + gyp_to_build_path(self._Settings()["ORDER_FILE"])) if not gyp.common.CrossCompileRequested(): if arch is not None: archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if len(archs) != 1: # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented("ARCHS") archs = ["i386"] # Avoid quoting the space between -arch and the arch name ldflags.append("-arch") ldflags.append(archs[0]) # Xcode adds the product directory by default. # Rewrite -L. to -L./ to work around http://www.openradar.me/25313838 ldflags.append("-L" + (product_dir if product_dir != "." else "./")) install_name = self.GetInstallName() if install_name and self.spec["type"] != "loadable_module": ldflags.append("-install_name") ldflags.append(install_name.replace(" ", r"\ ")) for rpath in self._Settings().get("LD_RUNPATH_SEARCH_PATHS", []): ldflags.append("-Wl,-rpath," + rpath) sdk_root = self._SdkPath() if not sdk_root: sdk_root = "" config = self.spec["configurations"][self.configname] framework_dirs = config.get("mac_framework_dirs", []) for directory in framework_dirs: ldflags.append("-F" + directory.replace("$(SDKROOT)", sdk_root)) if self._IsXCTest(): platform_root = self._XcodePlatformPath(configname) if sdk_root and platform_root: ldflags.append("-F" + platform_root + "/Developer/Library/Frameworks/") ldflags.append("-framework") ldflags.append("XCTest") is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension() if sdk_root and is_extension: # Adds the link flags for extensions. These flags are common for all # extensions and provide loader and main function. # These flags reflect the compilation options used by xcode to compile # extensions. xcode_version, _ = XcodeVersion() if xcode_version < "0900": ldflags.append("-lpkstart") ldflags.append( sdk_root + "/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit" ) else: ldflags.append("-e") ldflags.append("_NSExtensionMain") ldflags.append("-fapplication-extension") self._Appendf(ldflags, "CLANG_CXX_LIBRARY", "-stdlib=%s") self.configname = None return ldflags def GetLibtoolflags(self, configname): """Returns flags that need to be passed to the static linker. Args: configname: The name of the configuration to get ld flags for. """ self.configname = configname libtoolflags = [] for libtoolflag in self._Settings().get("OTHER_LDFLAGS", []): libtoolflags.append(libtoolflag) # TODO(thakis): ARCHS? self.configname = None return libtoolflags def GetPerTargetSettings(self): """Gets a list of all the per-target settings. This will only fetch keys whose values are the same across all configurations.""" first_pass = True result = {} for configname in sorted(self.xcode_settings.keys()): if first_pass: result = dict(self.xcode_settings[configname]) first_pass = False else: for key, value in self.xcode_settings[configname].items(): if key not in result: continue elif result[key] != value: del result[key] return result def GetPerConfigSetting(self, setting, configname, default=None): if configname in self.xcode_settings: return self.xcode_settings[configname].get(setting, default) else: return self.GetPerTargetSetting(setting, default) def GetPerTargetSetting(self, setting, default=None): """Tries to get xcode_settings.setting from spec. Assumes that the setting has the same value in all configurations and throws otherwise.""" is_first_pass = True result = None for configname in sorted(self.xcode_settings.keys()): if is_first_pass: result = self.xcode_settings[configname].get(setting, None) is_first_pass = False else: assert result == self.xcode_settings[configname].get(setting, None), ( "Expected per-target setting for '%s', got per-config setting " "(target %s)" % (setting, self.spec["target_name"]) ) if result is None: return default return result def _GetStripPostbuilds(self, configname, output_binary, quiet): """Returns a list of shell commands that contain the shell commands necessary to strip this target's binary. These should be run as postbuilds before the actual postbuilds run.""" self.configname = configname result = [] if self._Test("DEPLOYMENT_POSTPROCESSING", "YES", default="NO") and self._Test( "STRIP_INSTALLED_PRODUCT", "YES", default="NO" ): default_strip_style = "debugging" if ( self.spec["type"] == "loadable_module" or self._IsIosAppExtension() ) and self._IsBundle(): default_strip_style = "non-global" elif self.spec["type"] == "executable": default_strip_style = "all" strip_style = self._Settings().get("STRIP_STYLE", default_strip_style) strip_flags = {"all": "", "non-global": "-x", "debugging": "-S"}[ strip_style ] explicit_strip_flags = self._Settings().get("STRIPFLAGS", "") if explicit_strip_flags: strip_flags += " " + _NormalizeEnvVarReferences(explicit_strip_flags) if not quiet: result.append("echo STRIP\\(%s\\)" % self.spec["target_name"]) result.append(f"strip {strip_flags} {output_binary}") self.configname = None return result def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet): """Returns a list of shell commands that contain the shell commands necessary to massage this target's debug information. These should be run as postbuilds before the actual postbuilds run.""" self.configname = configname # For static libraries, no dSYMs are created. result = [] if ( self._Test("GCC_GENERATE_DEBUGGING_SYMBOLS", "YES", default="YES") and self._Test( "DEBUG_INFORMATION_FORMAT", "dwarf-with-dsym", default="dwarf" ) and self.spec["type"] != "static_library" ): if not quiet: result.append("echo DSYMUTIL\\(%s\\)" % self.spec["target_name"]) result.append("dsymutil {} -o {}".format(output_binary, output + ".dSYM")) self.configname = None return result def _GetTargetPostbuilds(self, configname, output, output_binary, quiet=False): """Returns a list of shell commands that contain the shell commands to run as postbuilds for this target, before the actual postbuilds.""" # dSYMs need to build before stripping happens. return self._GetDebugInfoPostbuilds( configname, output, output_binary, quiet ) + self._GetStripPostbuilds(configname, output_binary, quiet) def _GetIOSPostbuilds(self, configname, output_binary): """Return a shell command to codesign the iOS output binary so it can be deployed to a device. This should be run as the very last step of the build.""" if not ( self.isIOS and (self.spec["type"] == "executable" or self._IsXCTest()) or self.IsIosFramework() ): return [] postbuilds = [] product_name = self.GetFullProductName() settings = self.xcode_settings[configname] # Xcode expects XCTests to be copied into the TEST_HOST dir. if self._IsXCTest(): source = os.path.join("${BUILT_PRODUCTS_DIR}", product_name) test_host = os.path.dirname(settings.get("TEST_HOST")) xctest_destination = os.path.join(test_host, "PlugIns", product_name) postbuilds.extend([f"ditto {source} {xctest_destination}"]) key = self._GetIOSCodeSignIdentityKey(settings) if not key: return postbuilds # Warn for any unimplemented signing xcode keys. unimpl = ["OTHER_CODE_SIGN_FLAGS"] unimpl = set(unimpl) & set(self.xcode_settings[configname].keys()) if unimpl: print( "Warning: Some codesign keys not implemented, ignoring: %s" % ", ".join(sorted(unimpl)) ) if self._IsXCTest(): # For device xctests, Xcode copies two extra frameworks into $TEST_HOST. test_host = os.path.dirname(settings.get("TEST_HOST")) frameworks_dir = os.path.join(test_host, "Frameworks") platform_root = self._XcodePlatformPath(configname) frameworks = [ "Developer/Library/PrivateFrameworks/IDEBundleInjection.framework", "Developer/Library/Frameworks/XCTest.framework", ] for framework in frameworks: source = os.path.join(platform_root, framework) destination = os.path.join(frameworks_dir, os.path.basename(framework)) postbuilds.extend([f"ditto {source} {destination}"]) # Then re-sign everything with 'preserve=True' postbuilds.extend( [ '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), settings.get("PROVISIONING_PROFILE", ""), destination, True, ) ] ) plugin_dir = os.path.join(test_host, "PlugIns") targets = [os.path.join(plugin_dir, product_name), test_host] for target in targets: postbuilds.extend( [ '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), settings.get("PROVISIONING_PROFILE", ""), target, True, ) ] ) postbuilds.extend( [ '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), settings.get("PROVISIONING_PROFILE", ""), os.path.join("${BUILT_PRODUCTS_DIR}", product_name), False, ) ] ) return postbuilds def _GetIOSCodeSignIdentityKey(self, settings): identity = settings.get("CODE_SIGN_IDENTITY") if not identity: return None if identity not in XcodeSettings._codesigning_key_cache: output = subprocess.check_output( ["security", "find-identity", "-p", "codesigning", "-v"] ) for line in output.splitlines(): if identity in line: fingerprint = line.split()[1] cache = XcodeSettings._codesigning_key_cache assert identity not in cache or fingerprint == cache[identity], ( "Multiple codesigning fingerprints for identity: %s" % identity ) XcodeSettings._codesigning_key_cache[identity] = fingerprint return XcodeSettings._codesigning_key_cache.get(identity, "") def AddImplicitPostbuilds( self, configname, output, output_binary, postbuilds=[], quiet=False ): """Returns a list of shell commands that should run before and after |postbuilds|.""" assert output_binary is not None pre = self._GetTargetPostbuilds(configname, output, output_binary, quiet) post = self._GetIOSPostbuilds(configname, output_binary) return pre + postbuilds + post def _AdjustLibrary(self, library, config_name=None): if library.endswith(".framework"): l_flag = "-framework " + os.path.splitext(os.path.basename(library))[0] else: m = self.library_re.match(library) l_flag = "-l" + m.group(1) if m else library sdk_root = self._SdkPath(config_name) if not sdk_root: sdk_root = "" # Xcode 7 started shipping with ".tbd" (text based stubs) files instead of # ".dylib" without providing a real support for them. What it does, for # "/usr/lib" libraries, is do "-L/usr/lib -lname" which is dependent on the # library order and cause collision when building Chrome. # # Instead substitute ".tbd" to ".dylib" in the generated project when the # following conditions are both true: # - library is referenced in the gyp file as "$(SDKROOT)/**/*.dylib", # - the ".dylib" file does not exists but a ".tbd" file do. library = l_flag.replace("$(SDKROOT)", sdk_root) if l_flag.startswith("$(SDKROOT)"): basename, ext = os.path.splitext(library) if ext == ".dylib" and not os.path.exists(library): tbd_library = basename + ".tbd" if os.path.exists(tbd_library): library = tbd_library return library def AdjustLibraries(self, libraries, config_name=None): """Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. """ libraries = [self._AdjustLibrary(library, config_name) for library in libraries] return libraries def _BuildMachineOSBuild(self): return GetStdout(["sw_vers", "-buildVersion"]) def _XcodeIOSDeviceFamily(self, configname): family = self.xcode_settings[configname].get("TARGETED_DEVICE_FAMILY", "1") return [int(x) for x in family.split(",")] def GetExtraPlistItems(self, configname=None): """Returns a dictionary with extra items to insert into Info.plist.""" if configname not in XcodeSettings._plist_cache: cache = {} cache["BuildMachineOSBuild"] = self._BuildMachineOSBuild() xcode_version, xcode_build = XcodeVersion() cache["DTXcode"] = xcode_version cache["DTXcodeBuild"] = xcode_build compiler = self.xcode_settings[configname].get("GCC_VERSION") if compiler is not None: cache["DTCompiler"] = compiler sdk_root = self._SdkRoot(configname) if not sdk_root: sdk_root = self._DefaultSdkRoot() sdk_version = self._GetSdkVersionInfoItem(sdk_root, "--show-sdk-version") cache["DTSDKName"] = sdk_root + (sdk_version or "") if xcode_version >= "0720": cache["DTSDKBuild"] = self._GetSdkVersionInfoItem( sdk_root, "--show-sdk-build-version" ) elif xcode_version >= "0430": cache["DTSDKBuild"] = sdk_version else: cache["DTSDKBuild"] = cache["BuildMachineOSBuild"] if self.isIOS: cache["MinimumOSVersion"] = self.xcode_settings[configname].get( "IPHONEOS_DEPLOYMENT_TARGET" ) cache["DTPlatformName"] = sdk_root cache["DTPlatformVersion"] = sdk_version if configname.endswith("iphoneos"): cache["CFBundleSupportedPlatforms"] = ["iPhoneOS"] cache["DTPlatformBuild"] = cache["DTSDKBuild"] else: cache["CFBundleSupportedPlatforms"] = ["iPhoneSimulator"] # This is weird, but Xcode sets DTPlatformBuild to an empty field # for simulator builds. cache["DTPlatformBuild"] = "" XcodeSettings._plist_cache[configname] = cache # Include extra plist items that are per-target, not per global # XcodeSettings. items = dict(XcodeSettings._plist_cache[configname]) if self.isIOS: items["UIDeviceFamily"] = self._XcodeIOSDeviceFamily(configname) return items def _DefaultSdkRoot(self): """Returns the default SDKROOT to use. Prior to version 5.0.0, if SDKROOT was not explicitly set in the Xcode project, then the environment variable was empty. Starting with this version, Xcode uses the name of the newest SDK installed. """ xcode_version, _ = XcodeVersion() if xcode_version < "0500": return "" default_sdk_path = self._XcodeSdkPath("") default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path) if default_sdk_root: return default_sdk_root try: all_sdks = GetStdout(["xcodebuild", "-showsdks"]) except GypError: # If xcodebuild fails, there will be no valid SDKs return "" for line in all_sdks.splitlines(): items = line.split() if len(items) >= 3 and items[-2] == "-sdk": sdk_root = items[-1] sdk_path = self._XcodeSdkPath(sdk_root) if sdk_path == default_sdk_path: return sdk_root return "" class MacPrefixHeader: """A class that helps with emulating Xcode's GCC_PREFIX_HEADER feature. This feature consists of several pieces: * If GCC_PREFIX_HEADER is present, all compilations in that project get an additional |-include path_to_prefix_header| cflag. * If GCC_PRECOMPILE_PREFIX_HEADER is present too, then the prefix header is instead compiled, and all other compilations in the project get an additional |-include path_to_compiled_header| instead. + Compiled prefix headers have the extension gch. There is one gch file for every language used in the project (c, cc, m, mm), since gch files for different languages aren't compatible. + gch files themselves are built with the target's normal cflags, but they obviously don't get the |-include| flag. Instead, they need a -x flag that describes their language. + All o files in the target need to depend on the gch file, to make sure it's built before any o file is built. This class helps with some of these tasks, but it needs help from the build system for writing dependencies to the gch files, for writing build commands for the gch files, and for figuring out the location of the gch files. """ def __init__( self, xcode_settings, gyp_path_to_build_path, gyp_path_to_build_output ): """If xcode_settings is None, all methods on this class are no-ops. Args: gyp_path_to_build_path: A function that takes a gyp-relative path, and returns a path relative to the build directory. gyp_path_to_build_output: A function that takes a gyp-relative path and a language code ('c', 'cc', 'm', or 'mm'), and that returns a path to where the output of precompiling that path for that language should be placed (without the trailing '.gch'). """ # This doesn't support per-configuration prefix headers. Good enough # for now. self.header = None self.compile_headers = False if xcode_settings: self.header = xcode_settings.GetPerTargetSetting("GCC_PREFIX_HEADER") self.compile_headers = ( xcode_settings.GetPerTargetSetting( "GCC_PRECOMPILE_PREFIX_HEADER", default="NO" ) != "NO" ) self.compiled_headers = {} if self.header: if self.compile_headers: for lang in ["c", "cc", "m", "mm"]: self.compiled_headers[lang] = gyp_path_to_build_output( self.header, lang ) self.header = gyp_path_to_build_path(self.header) def _CompiledHeader(self, lang, arch): assert self.compile_headers h = self.compiled_headers[lang] if arch: h += "." + arch return h def GetInclude(self, lang, arch=None): """Gets the cflags to include the prefix header for language |lang|.""" if self.compile_headers and lang in self.compiled_headers: return "-include %s" % self._CompiledHeader(lang, arch) elif self.header: return "-include %s" % self.header else: return "" def _Gch(self, lang, arch): """Returns the actual file name of the prefix header for language |lang|.""" assert self.compile_headers return self._CompiledHeader(lang, arch) + ".gch" def GetObjDependencies(self, sources, objs, arch=None): """Given a list of source files and the corresponding object files, returns a list of (source, object, gch) tuples, where |gch| is the build-directory relative path to the gch file each object file depends on. |compilable[i]| has to be the source file belonging to |objs[i]|.""" if not self.header or not self.compile_headers: return [] result = [] for source, obj in zip(sources, objs): ext = os.path.splitext(source)[1] lang = { ".c": "c", ".cpp": "cc", ".cc": "cc", ".cxx": "cc", ".m": "m", ".mm": "mm", }.get(ext, None) if lang: result.append((source, obj, self._Gch(lang, arch))) return result def GetPchBuildCommands(self, arch=None): """Returns [(path_to_gch, language_flag, language, header)]. |path_to_gch| and |header| are relative to the build directory. """ if not self.header or not self.compile_headers: return [] return [ (self._Gch("c", arch), "-x c-header", "c", self.header), (self._Gch("cc", arch), "-x c++-header", "cc", self.header), (self._Gch("m", arch), "-x objective-c-header", "m", self.header), (self._Gch("mm", arch), "-x objective-c++-header", "mm", self.header), ] def XcodeVersion(): """Returns a tuple of version and build version of installed Xcode.""" # `xcodebuild -version` output looks like # Xcode 4.6.3 # Build version 4H1503 # or like # Xcode 3.2.6 # Component versions: DevToolsCore-1809.0; DevToolsSupport-1806.0 # BuildVersion: 10M2518 # Convert that to ('0463', '4H1503') or ('0326', '10M2518'). global XCODE_VERSION_CACHE if XCODE_VERSION_CACHE: return XCODE_VERSION_CACHE version = "" build = "" try: version_list = GetStdoutQuiet(["xcodebuild", "-version"]).splitlines() # In some circumstances xcodebuild exits 0 but doesn't return # the right results; for example, a user on 10.7 or 10.8 with # a bogus path set via xcode-select # In that case this may be a CLT-only install so fall back to # checking that version. if len(version_list) < 2: raise GypError("xcodebuild returned unexpected results") version = version_list[0].split()[-1] # Last word on first line build = version_list[-1].split()[-1] # Last word on last line except GypError: # Xcode not installed so look for XCode Command Line Tools version = CLTVersion() # macOS Catalina returns 11.0.0.0.1.1567737322 if not version: raise GypError("No Xcode or CLT version detected!") # Be careful to convert "4.2.3" to "0423" and "11.0.0" to "1100": version = version.split(".")[:3] # Just major, minor, micro version[0] = version[0].zfill(2) # Add a leading zero if major is one digit version = ("".join(version) + "00")[:4] # Limit to exactly four characters XCODE_VERSION_CACHE = (version, build) return XCODE_VERSION_CACHE # This function ported from the logic in Homebrew's CLT version check def CLTVersion(): """Returns the version of command-line tools from pkgutil.""" # pkgutil output looks like # package-id: com.apple.pkg.CLTools_Executables # version: 5.0.1.0.1.1382131676 # volume: / # location: / # install-time: 1382544035 # groups: com.apple.FindSystemFiles.pkg-group # com.apple.DevToolsBoth.pkg-group # com.apple.DevToolsNonRelocatableShared.pkg-group STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo" FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI" MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables" regex = re.compile("version: (?P.+)") for key in [MAVERICKS_PKG_ID, STANDALONE_PKG_ID, FROM_XCODE_PKG_ID]: try: output = GetStdout(["/usr/sbin/pkgutil", "--pkg-info", key]) return re.search(regex, output).groupdict()["version"] except GypError: continue regex = re.compile(r"Command Line Tools for Xcode\s+(?P\S+)") try: output = GetStdout(["/usr/sbin/softwareupdate", "--history"]) return re.search(regex, output).groupdict()["version"] except GypError: return None def GetStdoutQuiet(cmdlist): """Returns the content of standard output returned by invoking |cmdlist|. Ignores the stderr. Raises |GypError| if the command return with a non-zero return code.""" job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out = job.communicate()[0].decode("utf-8") if job.returncode != 0: raise GypError("Error %d running %s" % (job.returncode, cmdlist[0])) return out.rstrip("\n") def GetStdout(cmdlist): """Returns the content of standard output returned by invoking |cmdlist|. Raises |GypError| if the command return with a non-zero return code.""" job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) out = job.communicate()[0].decode("utf-8") if job.returncode != 0: sys.stderr.write(out + "\n") raise GypError("Error %d running %s" % (job.returncode, cmdlist[0])) return out.rstrip("\n") def MergeGlobalXcodeSettingsToSpec(global_dict, spec): """Merges the global xcode_settings dictionary into each configuration of the target represented by spec. For keys that are both in the global and the local xcode_settings dict, the local key gets precedence. """ # The xcode generator special-cases global xcode_settings and does something # that amounts to merging in the global xcode_settings into each local # xcode_settings dict. global_xcode_settings = global_dict.get("xcode_settings", {}) for config in spec["configurations"].values(): if "xcode_settings" in config: new_settings = global_xcode_settings.copy() new_settings.update(config["xcode_settings"]) config["xcode_settings"] = new_settings def IsMacBundle(flavor, spec): """Returns if |spec| should be treated as a bundle. Bundles are directories with a certain subdirectory structure, instead of just a single file. Bundle rules do not produce a binary but also package resources into that directory.""" is_mac_bundle = ( int(spec.get("mac_xctest_bundle", 0)) != 0 or int(spec.get("mac_xcuitest_bundle", 0)) != 0 or (int(spec.get("mac_bundle", 0)) != 0 and flavor == "mac") ) if is_mac_bundle: assert spec["type"] != "none", ( 'mac_bundle targets cannot have type none (target "%s")' % spec["target_name"] ) return is_mac_bundle def GetMacBundleResources(product_dir, xcode_settings, resources): """Yields (output, resource) pairs for every resource in |resources|. Only call this for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. resources: A list of bundle resources, relative to the build directory. """ dest = os.path.join(product_dir, xcode_settings.GetBundleResourceFolder()) for res in resources: output = dest # The make generator doesn't support it, so forbid it everywhere # to keep the generators more interchangeable. assert " " not in res, "Spaces in resource filenames not supported (%s)" % res # Split into (path,file). res_parts = os.path.split(res) # Now split the path into (prefix,maybe.lproj). lproj_parts = os.path.split(res_parts[0]) # If the resource lives in a .lproj bundle, add that to the destination. if lproj_parts[1].endswith(".lproj"): output = os.path.join(output, lproj_parts[1]) output = os.path.join(output, res_parts[1]) # Compiled XIB files are referred to by .nib. if output.endswith(".xib"): output = os.path.splitext(output)[0] + ".nib" # Compiled storyboard files are referred to by .storyboardc. if output.endswith(".storyboard"): output = os.path.splitext(output)[0] + ".storyboardc" yield output, res def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path): """Returns (info_plist, dest_plist, defines, extra_env), where: * |info_plist| is the source plist path, relative to the build directory, * |dest_plist| is the destination plist path, relative to the build directory, * |defines| is a list of preprocessor defines (empty if the plist shouldn't be preprocessed, * |extra_env| is a dict of env variables that should be exported when invoking |mac_tool copy-info-plist|. Only call this for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build directory. """ info_plist = xcode_settings.GetPerTargetSetting("INFOPLIST_FILE") if not info_plist: return None, None, [], {} # The make generator doesn't support it, so forbid it everywhere # to keep the generators more interchangeable. assert " " not in info_plist, ( "Spaces in Info.plist filenames not supported (%s)" % info_plist ) info_plist = gyp_path_to_build_path(info_plist) # If explicitly set to preprocess the plist, invoke the C preprocessor and # specify any defines as -D flags. if ( xcode_settings.GetPerTargetSetting("INFOPLIST_PREPROCESS", default="NO") == "YES" ): # Create an intermediate file based on the path. defines = shlex.split( xcode_settings.GetPerTargetSetting( "INFOPLIST_PREPROCESSOR_DEFINITIONS", default="" ) ) else: defines = [] dest_plist = os.path.join(product_dir, xcode_settings.GetBundlePlistPath()) extra_env = xcode_settings.GetPerTargetSettings() return info_plist, dest_plist, defines, extra_env def _GetXcodeEnv( xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None ): """Return the environment variables that Xcode would set. See http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW153 for a full list. Args: xcode_settings: An XcodeSettings object. If this is None, this function returns an empty dict. built_products_dir: Absolute path to the built products dir. srcroot: Absolute path to the source root. configuration: The build configuration name. additional_settings: An optional dict with more values to add to the result. """ if not xcode_settings: return {} # This function is considered a friend of XcodeSettings, so let it reach into # its implementation details. spec = xcode_settings.spec # These are filled in on an as-needed basis. env = { "BUILT_FRAMEWORKS_DIR": built_products_dir, "BUILT_PRODUCTS_DIR": built_products_dir, "CONFIGURATION": configuration, "PRODUCT_NAME": xcode_settings.GetProductName(), # For FULL_PRODUCT_NAME see: # /Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications/MacOSX\ Product\ Types.xcspec # noqa: E501 "SRCROOT": srcroot, "SOURCE_ROOT": "${SRCROOT}", # This is not true for static libraries, but currently the env is only # written for bundles: "TARGET_BUILD_DIR": built_products_dir, "TEMP_DIR": "${TMPDIR}", "XCODE_VERSION_ACTUAL": XcodeVersion()[0], } if xcode_settings.GetPerConfigSetting("SDKROOT", configuration): env["SDKROOT"] = xcode_settings._SdkPath(configuration) else: env["SDKROOT"] = "" if xcode_settings.mac_toolchain_dir: env["DEVELOPER_DIR"] = xcode_settings.mac_toolchain_dir if spec["type"] in ( "executable", "static_library", "shared_library", "loadable_module", ): env["EXECUTABLE_NAME"] = xcode_settings.GetExecutableName() env["EXECUTABLE_PATH"] = xcode_settings.GetExecutablePath() env["FULL_PRODUCT_NAME"] = xcode_settings.GetFullProductName() mach_o_type = xcode_settings.GetMachOType() if mach_o_type: env["MACH_O_TYPE"] = mach_o_type env["PRODUCT_TYPE"] = xcode_settings.GetProductType() if xcode_settings._IsBundle(): # xcodeproj_file.py sets the same Xcode subfolder value for this as for # FRAMEWORKS_FOLDER_PATH so Xcode builds will actually use FFP's value. env["BUILT_FRAMEWORKS_DIR"] = os.path.join( built_products_dir + os.sep + xcode_settings.GetBundleFrameworksFolderPath() ) env["CONTENTS_FOLDER_PATH"] = xcode_settings.GetBundleContentsFolderPath() env["EXECUTABLE_FOLDER_PATH"] = xcode_settings.GetBundleExecutableFolderPath() env[ "UNLOCALIZED_RESOURCES_FOLDER_PATH" ] = xcode_settings.GetBundleResourceFolder() env["JAVA_FOLDER_PATH"] = xcode_settings.GetBundleJavaFolderPath() env["FRAMEWORKS_FOLDER_PATH"] = xcode_settings.GetBundleFrameworksFolderPath() env[ "SHARED_FRAMEWORKS_FOLDER_PATH" ] = xcode_settings.GetBundleSharedFrameworksFolderPath() env[ "SHARED_SUPPORT_FOLDER_PATH" ] = xcode_settings.GetBundleSharedSupportFolderPath() env["PLUGINS_FOLDER_PATH"] = xcode_settings.GetBundlePlugInsFolderPath() env["XPCSERVICES_FOLDER_PATH"] = xcode_settings.GetBundleXPCServicesFolderPath() env["INFOPLIST_PATH"] = xcode_settings.GetBundlePlistPath() env["WRAPPER_NAME"] = xcode_settings.GetWrapperName() install_name = xcode_settings.GetInstallName() if install_name: env["LD_DYLIB_INSTALL_NAME"] = install_name install_name_base = xcode_settings.GetInstallNameBase() if install_name_base: env["DYLIB_INSTALL_NAME_BASE"] = install_name_base xcode_version, _ = XcodeVersion() if xcode_version >= "0500" and not env.get("SDKROOT"): sdk_root = xcode_settings._SdkRoot(configuration) if not sdk_root: sdk_root = xcode_settings._XcodeSdkPath("") if sdk_root is None: sdk_root = "" env["SDKROOT"] = sdk_root if not additional_settings: additional_settings = {} else: # Flatten lists to strings. for k in additional_settings: if not isinstance(additional_settings[k], str): additional_settings[k] = " ".join(additional_settings[k]) additional_settings.update(env) for k in additional_settings: additional_settings[k] = _NormalizeEnvVarReferences(additional_settings[k]) return additional_settings def _NormalizeEnvVarReferences(str): """Takes a string containing variable references in the form ${FOO}, $(FOO), or $FOO, and returns a string with all variable references in the form ${FOO}. """ # $FOO -> ${FOO} str = re.sub(r"\$([a-zA-Z_][a-zA-Z0-9_]*)", r"${\1}", str) # $(FOO) -> ${FOO} matches = re.findall(r"(\$\(([a-zA-Z0-9\-_]+)\))", str) for match in matches: to_replace, variable = match assert "$(" not in match, "$($(FOO)) variables not supported: " + match str = str.replace(to_replace, "${" + variable + "}") return str def ExpandEnvVars(string, expansions): """Expands ${VARIABLES}, $(VARIABLES), and $VARIABLES in string per the expansions list. If the variable expands to something that references another variable, this variable is expanded as well if it's in env -- until no variables present in env are left.""" for k, v in reversed(expansions): string = string.replace("${" + k + "}", v) string = string.replace("$(" + k + ")", v) string = string.replace("$" + k, v) return string def _TopologicallySortedEnvVarKeys(env): """Takes a dict |env| whose values are strings that can refer to other keys, for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of env such that key2 is after key1 in L if env[key2] refers to env[key1]. Throws an Exception in case of dependency cycles. """ # Since environment variables can refer to other variables, the evaluation # order is important. Below is the logic to compute the dependency graph # and sort it. regex = re.compile(r"\$\{([a-zA-Z0-9\-_]+)\}") def GetEdges(node): # Use a definition of edges such that user_of_variable -> used_varible. # This happens to be easier in this case, since a variable's # definition contains all variables it references in a single string. # We can then reverse the result of the topological sort at the end. # Since: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) matches = {v for v in regex.findall(env[node]) if v in env} for dependee in matches: assert "${" not in dependee, "Nested variables not supported: " + dependee return matches try: # Topologically sort, and then reverse, because we used an edge definition # that's inverted from the expected result of this function (see comment # above). order = gyp.common.TopologicallySorted(env.keys(), GetEdges) order.reverse() return order except gyp.common.CycleError as e: raise GypError( "Xcode environment variables are cyclically dependent: " + str(e.nodes) ) def GetSortedXcodeEnv( xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None ): env = _GetXcodeEnv( xcode_settings, built_products_dir, srcroot, configuration, additional_settings ) return [(key, env[key]) for key in _TopologicallySortedEnvVarKeys(env)] def GetSpecPostbuildCommands(spec, quiet=False): """Returns the list of postbuilds explicitly defined on |spec|, in a form executable by a shell.""" postbuilds = [] for postbuild in spec.get("postbuilds", []): if not quiet: postbuilds.append( "echo POSTBUILD\\(%s\\) %s" % (spec["target_name"], postbuild["postbuild_name"]) ) postbuilds.append(gyp.common.EncodePOSIXShellList(postbuild["action"])) return postbuilds def _HasIOSTarget(targets): """Returns true if any target contains the iOS specific key IPHONEOS_DEPLOYMENT_TARGET.""" for target_dict in targets.values(): for config in target_dict["configurations"].values(): if config.get("xcode_settings", {}).get("IPHONEOS_DEPLOYMENT_TARGET"): return True return False def _AddIOSDeviceConfigurations(targets): """Clone all targets and append -iphoneos to the name. Configure these targets to build for iOS devices and use correct architectures for those builds.""" for target_dict in targets.values(): toolset = target_dict["toolset"] configs = target_dict["configurations"] for config_name, simulator_config_dict in dict(configs).items(): iphoneos_config_dict = copy.deepcopy(simulator_config_dict) configs[config_name + "-iphoneos"] = iphoneos_config_dict configs[config_name + "-iphonesimulator"] = simulator_config_dict if toolset == "target": simulator_config_dict["xcode_settings"]["SDKROOT"] = "iphonesimulator" iphoneos_config_dict["xcode_settings"]["SDKROOT"] = "iphoneos" return targets def CloneConfigurationForDeviceAndEmulator(target_dicts): """If |target_dicts| contains any iOS targets, automatically create -iphoneos targets for iOS device builds.""" if _HasIOSTarget(target_dicts): return _AddIOSDeviceConfigurations(target_dicts) return target_dicts #!/usr/bin/env python3 """Unit tests for the xcode_emulation.py file.""" from gyp.xcode_emulation import XcodeSettings import sys import unittest class TestXcodeSettings(unittest.TestCase): def setUp(self): if sys.platform != "darwin": self.skipTest("This test only runs on macOS") def test_GetCflags(self): target = { "type": "static_library", "configurations": { "Release": {}, }, } configuration_name = "Release" xcode_settings = XcodeSettings(target) cflags = xcode_settings.GetCflags(configuration_name, "arm64") # Do not quote `-arch arm64` with spaces in one string. self.assertEqual( cflags, ["-fasm-blocks", "-mpascal-strings", "-Os", "-gdwarf-2", "-arch", "arm64"], ) def GypToBuildPath(self, path): return path def test_GetLdflags(self): target = { "type": "static_library", "configurations": { "Release": {}, }, } configuration_name = "Release" xcode_settings = XcodeSettings(target) ldflags = xcode_settings.GetLdflags( configuration_name, "PRODUCT_DIR", self.GypToBuildPath, "arm64" ) # Do not quote `-arch arm64` with spaces in one string. self.assertEqual(ldflags, ["-arch", "arm64", "-LPRODUCT_DIR"]) if __name__ == "__main__": unittest.main() # Copyright (c) 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Xcode-ninja wrapper project file generator. This updates the data structures passed to the Xcode gyp generator to build with ninja instead. The Xcode project itself is transformed into a list of executable targets, each with a build step to build with ninja, and a target with every source and resource file. This appears to sidestep some of the major performance headaches experienced using complex projects and large number of targets within Xcode. """ import errno import gyp.generator.ninja import os import re import xml.sax.saxutils def _WriteWorkspace(main_gyp, sources_gyp, params): """ Create a workspace to wrap main and sources gyp paths. """ (build_file_root, build_file_ext) = os.path.splitext(main_gyp) workspace_path = build_file_root + ".xcworkspace" options = params["options"] if options.generator_output: workspace_path = os.path.join(options.generator_output, workspace_path) try: os.makedirs(workspace_path) except OSError as e: if e.errno != errno.EEXIST: raise output_string = ( '\n' + '\n' ) for gyp_name in [main_gyp, sources_gyp]: name = os.path.splitext(os.path.basename(gyp_name))[0] + ".xcodeproj" name = xml.sax.saxutils.quoteattr("group:" + name) output_string += " \n" % name output_string += "\n" workspace_file = os.path.join(workspace_path, "contents.xcworkspacedata") try: with open(workspace_file) as input_file: input_string = input_file.read() if input_string == output_string: return except OSError: # Ignore errors if the file doesn't exist. pass with open(workspace_file, "w") as output_file: output_file.write(output_string) def _TargetFromSpec(old_spec, params): """ Create fake target for xcode-ninja wrapper. """ # Determine ninja top level build dir (e.g. /path/to/out). ninja_toplevel = None jobs = 0 if params: options = params["options"] ninja_toplevel = os.path.join( options.toplevel_dir, gyp.generator.ninja.ComputeOutputDir(params) ) jobs = params.get("generator_flags", {}).get("xcode_ninja_jobs", 0) target_name = old_spec.get("target_name") product_name = old_spec.get("product_name", target_name) product_extension = old_spec.get("product_extension") ninja_target = {} ninja_target["target_name"] = target_name ninja_target["product_name"] = product_name if product_extension: ninja_target["product_extension"] = product_extension ninja_target["toolset"] = old_spec.get("toolset") ninja_target["default_configuration"] = old_spec.get("default_configuration") ninja_target["configurations"] = {} # Tell Xcode to look in |ninja_toplevel| for build products. new_xcode_settings = {} if ninja_toplevel: new_xcode_settings["CONFIGURATION_BUILD_DIR"] = ( "%s/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)" % ninja_toplevel ) if "configurations" in old_spec: for config in old_spec["configurations"]: old_xcode_settings = old_spec["configurations"][config].get( "xcode_settings", {} ) if "IPHONEOS_DEPLOYMENT_TARGET" in old_xcode_settings: new_xcode_settings["CODE_SIGNING_REQUIRED"] = "NO" new_xcode_settings["IPHONEOS_DEPLOYMENT_TARGET"] = old_xcode_settings[ "IPHONEOS_DEPLOYMENT_TARGET" ] for key in ["BUNDLE_LOADER", "TEST_HOST"]: if key in old_xcode_settings: new_xcode_settings[key] = old_xcode_settings[key] ninja_target["configurations"][config] = {} ninja_target["configurations"][config][ "xcode_settings" ] = new_xcode_settings ninja_target["mac_bundle"] = old_spec.get("mac_bundle", 0) ninja_target["mac_xctest_bundle"] = old_spec.get("mac_xctest_bundle", 0) ninja_target["ios_app_extension"] = old_spec.get("ios_app_extension", 0) ninja_target["ios_watchkit_extension"] = old_spec.get("ios_watchkit_extension", 0) ninja_target["ios_watchkit_app"] = old_spec.get("ios_watchkit_app", 0) ninja_target["type"] = old_spec["type"] if ninja_toplevel: ninja_target["actions"] = [ { "action_name": "Compile and copy %s via ninja" % target_name, "inputs": [], "outputs": [], "action": [ "env", "PATH=%s" % os.environ["PATH"], "ninja", "-C", new_xcode_settings["CONFIGURATION_BUILD_DIR"], target_name, ], "message": "Compile and copy %s via ninja" % target_name, }, ] if jobs > 0: ninja_target["actions"][0]["action"].extend(("-j", jobs)) return ninja_target def IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): """Limit targets for Xcode wrapper. Xcode sometimes performs poorly with too many targets, so only include proper executable targets, with filters to customize. Arguments: target_extras: Regular expression to always add, matching any target. executable_target_pattern: Regular expression limiting executable targets. spec: Specifications for target. """ target_name = spec.get("target_name") # Always include targets matching target_extras. if target_extras is not None and re.search(target_extras, target_name): return True # Otherwise just show executable targets and xc_tests. if int(spec.get("mac_xctest_bundle", 0)) != 0 or ( spec.get("type", "") == "executable" and spec.get("product_extension", "") != "bundle" ): # If there is a filter and the target does not match, exclude the target. if executable_target_pattern is not None: if not re.search(executable_target_pattern, target_name): return False return True return False def CreateWrapper(target_list, target_dicts, data, params): """Initialize targets for the ninja wrapper. This sets up the necessary variables in the targets to generate Xcode projects that use ninja as an external builder. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. data: Dict of flattened build files keyed on gyp path. params: Dict of global options for gyp. """ orig_gyp = params["build_files"][0] for gyp_name, gyp_dict in data.items(): if gyp_name == orig_gyp: depth = gyp_dict["_DEPTH"] # Check for custom main gyp name, otherwise use the default CHROMIUM_GYP_FILE # and prepend .ninja before the .gyp extension. generator_flags = params.get("generator_flags", {}) main_gyp = generator_flags.get("xcode_ninja_main_gyp", None) if main_gyp is None: (build_file_root, build_file_ext) = os.path.splitext(orig_gyp) main_gyp = build_file_root + ".ninja" + build_file_ext # Create new |target_list|, |target_dicts| and |data| data structures. new_target_list = [] new_target_dicts = {} new_data = {} # Set base keys needed for |data|. new_data[main_gyp] = {} new_data[main_gyp]["included_files"] = [] new_data[main_gyp]["targets"] = [] new_data[main_gyp]["xcode_settings"] = data[orig_gyp].get("xcode_settings", {}) # Normally the xcode-ninja generator includes only valid executable targets. # If |xcode_ninja_executable_target_pattern| is set, that list is reduced to # executable targets that match the pattern. (Default all) executable_target_pattern = generator_flags.get( "xcode_ninja_executable_target_pattern", None ) # For including other non-executable targets, add the matching target name # to the |xcode_ninja_target_pattern| regular expression. (Default none) target_extras = generator_flags.get("xcode_ninja_target_pattern", None) for old_qualified_target in target_list: spec = target_dicts[old_qualified_target] if IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): # Add to new_target_list. target_name = spec.get("target_name") new_target_name = f"{main_gyp}:{target_name}#target" new_target_list.append(new_target_name) # Add to new_target_dicts. new_target_dicts[new_target_name] = _TargetFromSpec(spec, params) # Add to new_data. for old_target in data[old_qualified_target.split(":")[0]]["targets"]: if old_target["target_name"] == target_name: new_data_target = {} new_data_target["target_name"] = old_target["target_name"] new_data_target["toolset"] = old_target["toolset"] new_data[main_gyp]["targets"].append(new_data_target) # Create sources target. sources_target_name = "sources_for_indexing" sources_target = _TargetFromSpec( { "target_name": sources_target_name, "toolset": "target", "default_configuration": "Default", "mac_bundle": "0", "type": "executable", }, None, ) # Tell Xcode to look everywhere for headers. sources_target["configurations"] = {"Default": {"include_dirs": [depth]}} # Put excluded files into the sources target so they can be opened in Xcode. skip_excluded_files = not generator_flags.get( "xcode_ninja_list_excluded_files", True ) sources = [] for target, target_dict in target_dicts.items(): base = os.path.dirname(target) files = target_dict.get("sources", []) + target_dict.get( "mac_bundle_resources", [] ) if not skip_excluded_files: files.extend( target_dict.get("sources_excluded", []) + target_dict.get("mac_bundle_resources_excluded", []) ) for action in target_dict.get("actions", []): files.extend(action.get("inputs", [])) if not skip_excluded_files: files.extend(action.get("inputs_excluded", [])) # Remove files starting with $. These are mostly intermediate files for the # build system. files = [file for file in files if not file.startswith("$")] # Make sources relative to root build file. relative_path = os.path.dirname(main_gyp) sources += [ os.path.relpath(os.path.join(base, file), relative_path) for file in files ] sources_target["sources"] = sorted(set(sources)) # Put sources_to_index in it's own gyp. sources_gyp = os.path.join(os.path.dirname(main_gyp), sources_target_name + ".gyp") fully_qualified_target_name = f"{sources_gyp}:{sources_target_name}#target" # Add to new_target_list, new_target_dicts and new_data. new_target_list.append(fully_qualified_target_name) new_target_dicts[fully_qualified_target_name] = sources_target new_data_target = {} new_data_target["target_name"] = sources_target["target_name"] new_data_target["_DEPTH"] = depth new_data_target["toolset"] = "target" new_data[sources_gyp] = {} new_data[sources_gyp]["targets"] = [] new_data[sources_gyp]["included_files"] = [] new_data[sources_gyp]["xcode_settings"] = data[orig_gyp].get("xcode_settings", {}) new_data[sources_gyp]["targets"].append(new_data_target) # Write workspace to file. _WriteWorkspace(main_gyp, sources_gyp, params) return (new_target_list, new_target_dicts, new_data) # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Xcode project file generator. This module is both an Xcode project file generator and a documentation of the Xcode project file format. Knowledge of the project file format was gained based on extensive experience with Xcode, and by making changes to projects in Xcode.app and observing the resultant changes in the associated project files. XCODE PROJECT FILES The generator targets the file format as written by Xcode 3.2 (specifically, 3.2.6), but past experience has taught that the format has not changed significantly in the past several years, and future versions of Xcode are able to read older project files. Xcode project files are "bundled": the project "file" from an end-user's perspective is actually a directory with an ".xcodeproj" extension. The project file from this module's perspective is actually a file inside this directory, always named "project.pbxproj". This file contains a complete description of the project and is all that is needed to use the xcodeproj. Other files contained in the xcodeproj directory are simply used to store per-user settings, such as the state of various UI elements in the Xcode application. The project.pbxproj file is a property list, stored in a format almost identical to the NeXTstep property list format. The file is able to carry Unicode data, and is encoded in UTF-8. The root element in the property list is a dictionary that contains several properties of minimal interest, and two properties of immense interest. The most important property is a dictionary named "objects". The entire structure of the project is represented by the children of this property. The objects dictionary is keyed by unique 96-bit values represented by 24 uppercase hexadecimal characters. Each value in the objects dictionary is itself a dictionary, describing an individual object. Each object in the dictionary is a member of a class, which is identified by the "isa" property of each object. A variety of classes are represented in a project file. Objects can refer to other objects by ID, using the 24-character hexadecimal object key. A project's objects form a tree, with a root object of class PBXProject at the root. As an example, the PBXProject object serves as parent to an XCConfigurationList object defining the build configurations used in the project, a PBXGroup object serving as a container for all files referenced in the project, and a list of target objects, each of which defines a target in the project. There are several different types of target object, such as PBXNativeTarget and PBXAggregateTarget. In this module, this relationship is expressed by having each target type derive from an abstract base named XCTarget. The project.pbxproj file's root dictionary also contains a property, sibling to the "objects" dictionary, named "rootObject". The value of rootObject is a 24-character object key referring to the root PBXProject object in the objects dictionary. In Xcode, every file used as input to a target or produced as a final product of a target must appear somewhere in the hierarchy rooted at the PBXGroup object referenced by the PBXProject's mainGroup property. A PBXGroup is generally represented as a folder in the Xcode application. PBXGroups can contain other PBXGroups as well as PBXFileReferences, which are pointers to actual files. Each XCTarget contains a list of build phases, represented in this module by the abstract base XCBuildPhase. Examples of concrete XCBuildPhase derivations are PBXSourcesBuildPhase and PBXFrameworksBuildPhase, which correspond to the "Compile Sources" and "Link Binary With Libraries" phases displayed in the Xcode application. Files used as input to these phases (for example, source files in the former case and libraries and frameworks in the latter) are represented by PBXBuildFile objects, referenced by elements of "files" lists in XCTarget objects. Each PBXBuildFile object refers to a PBXBuildFile object as a "weak" reference: it does not "own" the PBXBuildFile, which is owned by the root object's mainGroup or a descendant group. In most cases, the layer of indirection between an XCBuildPhase and a PBXFileReference via a PBXBuildFile appears extraneous, but there's actually one reason for this: file-specific compiler flags are added to the PBXBuildFile object so as to allow a single file to be a member of multiple targets while having distinct compiler flags for each. These flags can be modified in the Xcode applciation in the "Build" tab of a File Info window. When a project is open in the Xcode application, Xcode will rewrite it. As such, this module is careful to adhere to the formatting used by Xcode, to avoid insignificant changes appearing in the file when it is used in the Xcode application. This will keep version control repositories happy, and makes it possible to compare a project file used in Xcode to one generated by this module to determine if any significant changes were made in the application. Xcode has its own way of assigning 24-character identifiers to each object, which is not duplicated here. Because the identifier only is only generated once, when an object is created, and is then left unchanged, there is no need to attempt to duplicate Xcode's behavior in this area. The generator is free to select any identifier, even at random, to refer to the objects it creates, and Xcode will retain those identifiers and use them when subsequently rewriting the project file. However, the generator would choose new random identifiers each time the project files are generated, leading to difficulties comparing "used" project files to "pristine" ones produced by this module, and causing the appearance of changes as every object identifier is changed when updated projects are checked in to a version control repository. To mitigate this problem, this module chooses identifiers in a more deterministic way, by hashing a description of each object as well as its parent and ancestor objects. This strategy should result in minimal "shift" in IDs as successive generations of project files are produced. THIS MODULE This module introduces several classes, all derived from the XCObject class. Nearly all of the "brains" are built into the XCObject class, which understands how to create and modify objects, maintain the proper tree structure, compute identifiers, and print objects. For the most part, classes derived from XCObject need only provide a _schema class object, a dictionary that expresses what properties objects of the class may contain. Given this structure, it's possible to build a minimal project file by creating objects of the appropriate types and making the proper connections: config_list = XCConfigurationList() group = PBXGroup() project = PBXProject({'buildConfigurationList': config_list, 'mainGroup': group}) With the project object set up, it can be added to an XCProjectFile object. XCProjectFile is a pseudo-class in the sense that it is a concrete XCObject subclass that does not actually correspond to a class type found in a project file. Rather, it is used to represent the project file's root dictionary. Printing an XCProjectFile will print the entire project file, including the full "objects" dictionary. project_file = XCProjectFile({'rootObject': project}) project_file.ComputeIDs() project_file.Print() Xcode project files are always encoded in UTF-8. This module will accept strings of either the str class or the unicode class. Strings of class str are assumed to already be encoded in UTF-8. Obviously, if you're just using ASCII, you won't encounter difficulties because ASCII is a UTF-8 subset. Strings of class unicode are handled properly and encoded in UTF-8 when a project file is output. """ import gyp.common from functools import cmp_to_key import hashlib from operator import attrgetter import posixpath import re import struct import sys def cmp(x, y): return (x > y) - (x < y) # See XCObject._EncodeString. This pattern is used to determine when a string # can be printed unquoted. Strings that match this pattern may be printed # unquoted. Strings that do not match must be quoted and may be further # transformed to be properly encoded. Note that this expression matches the # characters listed with "+", for 1 or more occurrences: if a string is empty, # it must not match this pattern, because it needs to be encoded as "". _unquoted = re.compile("^[A-Za-z0-9$./_]+$") # Strings that match this pattern are quoted regardless of what _unquoted says. # Oddly, Xcode will quote any string with a run of three or more underscores. _quoted = re.compile("___") # This pattern should match any character that needs to be escaped by # XCObject._EncodeString. See that function. _escaped = re.compile('[\\\\"]|[\x00-\x1f]') # Used by SourceTreeAndPathFromPath _path_leading_variable = re.compile(r"^\$\((.*?)\)(/(.*))?$") def SourceTreeAndPathFromPath(input_path): """Given input_path, returns a tuple with sourceTree and path values. Examples: input_path (source_tree, output_path) '$(VAR)/path' ('VAR', 'path') '$(VAR)' ('VAR', None) 'path' (None, 'path') """ source_group_match = _path_leading_variable.match(input_path) if source_group_match: source_tree = source_group_match.group(1) output_path = source_group_match.group(3) # This may be None. else: source_tree = None output_path = input_path return (source_tree, output_path) def ConvertVariablesToShellSyntax(input_string): return re.sub(r"\$\((.*?)\)", "${\\1}", input_string) class XCObject: """The abstract base of all class types used in Xcode project files. Class variables: _schema: A dictionary defining the properties of this class. The keys to _schema are string property keys as used in project files. Values are a list of four or five elements: [ is_list, property_type, is_strong, is_required, default ] is_list: True if the property described is a list, as opposed to a single element. property_type: The type to use as the value of the property, or if is_list is True, the type to use for each element of the value's list. property_type must be an XCObject subclass, or one of the built-in types str, int, or dict. is_strong: If property_type is an XCObject subclass, is_strong is True to assert that this class "owns," or serves as parent, to the property value (or, if is_list is True, values). is_strong must be False if property_type is not an XCObject subclass. is_required: True if the property is required for the class. Note that is_required being True does not preclude an empty string ("", in the case of property_type str) or list ([], in the case of is_list True) from being set for the property. default: Optional. If is_required is True, default may be set to provide a default value for objects that do not supply their own value. If is_required is True and default is not provided, users of the class must supply their own value for the property. Note that although the values of the array are expressed in boolean terms, subclasses provide values as integers to conserve horizontal space. _should_print_single_line: False in XCObject. Subclasses whose objects should be written to the project file in the alternate single-line format, such as PBXFileReference and PBXBuildFile, should set this to True. _encode_transforms: Used by _EncodeString to encode unprintable characters. The index into this list is the ordinal of the character to transform; each value is a string used to represent the character in the output. XCObject provides an _encode_transforms list suitable for most XCObject subclasses. _alternate_encode_transforms: Provided for subclasses that wish to use the alternate encoding rules. Xcode seems to use these rules when printing objects in single-line format. Subclasses that desire this behavior should set _encode_transforms to _alternate_encode_transforms. _hashables: A list of XCObject subclasses that can be hashed by ComputeIDs to construct this object's ID. Most classes that need custom hashing behavior should do it by overriding Hashables, but in some cases an object's parent may wish to push a hashable value into its child, and it can do so by appending to _hashables. Attributes: id: The object's identifier, a 24-character uppercase hexadecimal string. Usually, objects being created should not set id until the entire project file structure is built. At that point, UpdateIDs() should be called on the root object to assign deterministic values for id to each object in the tree. parent: The object's parent. This is set by a parent XCObject when a child object is added to it. _properties: The object's property dictionary. An object's properties are described by its class' _schema variable. """ _schema = {} _should_print_single_line = False # See _EncodeString. _encode_transforms = [] i = 0 while i < ord(" "): _encode_transforms.append("\\U%04x" % i) i = i + 1 _encode_transforms[7] = "\\a" _encode_transforms[8] = "\\b" _encode_transforms[9] = "\\t" _encode_transforms[10] = "\\n" _encode_transforms[11] = "\\v" _encode_transforms[12] = "\\f" _encode_transforms[13] = "\\n" _alternate_encode_transforms = list(_encode_transforms) _alternate_encode_transforms[9] = chr(9) _alternate_encode_transforms[10] = chr(10) _alternate_encode_transforms[11] = chr(11) def __init__(self, properties=None, id=None, parent=None): self.id = id self.parent = parent self._properties = {} self._hashables = [] self._SetDefaultsFromSchema() self.UpdateProperties(properties) def __repr__(self): try: name = self.Name() except NotImplementedError: return f"<{self.__class__.__name__} at 0x{id(self):x}>" return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>" def Copy(self): """Make a copy of this object. The new object will have its own copy of lists and dicts. Any XCObject objects owned by this object (marked "strong") will be copied in the new object, even those found in lists. If this object has any weak references to other XCObjects, the same references are added to the new object without making a copy. """ that = self.__class__(id=self.id, parent=self.parent) for key, value in self._properties.items(): is_strong = self._schema[key][2] if isinstance(value, XCObject): if is_strong: new_value = value.Copy() new_value.parent = that that._properties[key] = new_value else: that._properties[key] = value elif isinstance(value, (str, int)): that._properties[key] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, so it's safe to # call Copy. that._properties[key] = [] for item in value: new_item = item.Copy() new_item.parent = that that._properties[key].append(new_item) else: that._properties[key] = value[:] elif isinstance(value, dict): # dicts are never strong. if is_strong: raise TypeError( "Strong dict for key " + key + " in " + self.__class__.__name__ ) else: that._properties[key] = value.copy() else: raise TypeError( "Unexpected type " + value.__class__.__name__ + " for key " + key + " in " + self.__class__.__name__ ) return that def Name(self): """Return the name corresponding to an object. Not all objects necessarily need to be nameable, and not all that do have a "name" property. Override as needed. """ # If the schema indicates that "name" is required, try to access the # property even if it doesn't exist. This will result in a KeyError # being raised for the property that should be present, which seems more # appropriate than NotImplementedError in this case. if "name" in self._properties or ( "name" in self._schema and self._schema["name"][3] ): return self._properties["name"] raise NotImplementedError(self.__class__.__name__ + " must implement Name") def Comment(self): """Return a comment string for the object. Most objects just use their name as the comment, but PBXProject uses different values. The returned comment is not escaped and does not have any comment marker strings applied to it. """ return self.Name() def Hashables(self): hashables = [self.__class__.__name__] name = self.Name() if name is not None: hashables.append(name) hashables.extend(self._hashables) return hashables def HashablesForChild(self): return None def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None): """Set "id" properties deterministically. An object's "id" property is set based on a hash of its class type and name, as well as the class type and name of all ancestor objects. As such, it is only advisable to call ComputeIDs once an entire project file tree is built. If recursive is True, recurse into all descendant objects and update their hashes. If overwrite is True, any existing value set in the "id" property will be replaced. """ def _HashUpdate(hash, data): """Update hash with data's length and contents. If the hash were updated only with the value of data, it would be possible for clowns to induce collisions by manipulating the names of their objects. By adding the length, it's exceedingly less likely that ID collisions will be encountered, intentionally or not. """ hash.update(struct.pack(">i", len(data))) if isinstance(data, str): data = data.encode("utf-8") hash.update(data) if seed_hash is None: seed_hash = hashlib.sha1() hash = seed_hash.copy() hashables = self.Hashables() assert len(hashables) > 0 for hashable in hashables: _HashUpdate(hash, hashable) if recursive: hashables_for_child = self.HashablesForChild() if hashables_for_child is None: child_hash = hash else: assert len(hashables_for_child) > 0 child_hash = seed_hash.copy() for hashable in hashables_for_child: _HashUpdate(child_hash, hashable) for child in self.Children(): child.ComputeIDs(recursive, overwrite, child_hash) if overwrite or self.id is None: # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is # is 160 bits. Instead of throwing out 64 bits of the digest, xor them # into the portion that gets used. assert hash.digest_size % 4 == 0 digest_int_count = hash.digest_size // 4 digest_ints = struct.unpack(">" + "I" * digest_int_count, hash.digest()) id_ints = [0, 0, 0] for index in range(0, digest_int_count): id_ints[index % 3] ^= digest_ints[index] self.id = "%08X%08X%08X" % tuple(id_ints) def EnsureNoIDCollisions(self): """Verifies that no two objects have the same ID. Checks all descendants. """ ids = {} descendants = self.Descendants() for descendant in descendants: if descendant.id in ids: other = ids[descendant.id] raise KeyError( 'Duplicate ID %s, objects "%s" and "%s" in "%s"' % ( descendant.id, str(descendant._properties), str(other._properties), self._properties["rootObject"].Name(), ) ) ids[descendant.id] = descendant def Children(self): """Returns a list of all of this object's owned (strong) children.""" children = [] for property, attributes in self._schema.items(): (is_list, property_type, is_strong) = attributes[0:3] if is_strong and property in self._properties: if not is_list: children.append(self._properties[property]) else: children.extend(self._properties[property]) return children def Descendants(self): """Returns a list of all of this object's descendants, including this object. """ children = self.Children() descendants = [self] for child in children: descendants.extend(child.Descendants()) return descendants def PBXProjectAncestor(self): # The base case for recursion is defined at PBXProject.PBXProjectAncestor. if self.parent: return self.parent.PBXProjectAncestor() return None def _EncodeComment(self, comment): """Encodes a comment to be placed in the project file output, mimicking Xcode behavior. """ # This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If # the string already contains a "*/", it is turned into "(*)/". This keeps # the file writer from outputting something that would be treated as the # end of a comment in the middle of something intended to be entirely a # comment. return "/* " + comment.replace("*/", "(*)/") + " */" def _EncodeTransform(self, match): # This function works closely with _EncodeString. It will only be called # by re.sub with match.group(0) containing a character matched by the # the _escaped expression. char = match.group(0) # Backslashes (\) and quotation marks (") are always replaced with a # backslash-escaped version of the same. Everything else gets its # replacement from the class' _encode_transforms array. if char == "\\": return "\\\\" if char == '"': return '\\"' return self._encode_transforms[ord(char)] def _EncodeString(self, value): """Encodes a string to be placed in the project file output, mimicking Xcode behavior. """ # Use quotation marks when any character outside of the range A-Z, a-z, 0-9, # $ (dollar sign), . (period), and _ (underscore) is present. Also use # quotation marks to represent empty strings. # # Escape " (double-quote) and \ (backslash) by preceding them with a # backslash. # # Some characters below the printable ASCII range are encoded specially: # 7 ^G BEL is encoded as "\a" # 8 ^H BS is encoded as "\b" # 11 ^K VT is encoded as "\v" # 12 ^L NP is encoded as "\f" # 127 ^? DEL is passed through as-is without escaping # - In PBXFileReference and PBXBuildFile objects: # 9 ^I HT is passed through as-is without escaping # 10 ^J NL is passed through as-is without escaping # 13 ^M CR is passed through as-is without escaping # - In other objects: # 9 ^I HT is encoded as "\t" # 10 ^J NL is encoded as "\n" # 13 ^M CR is encoded as "\n" rendering it indistinguishable from # 10 ^J NL # All other characters within the ASCII control character range (0 through # 31 inclusive) are encoded as "\U001f" referring to the Unicode code point # in hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e". # Characters above the ASCII range are passed through to the output encoded # as UTF-8 without any escaping. These mappings are contained in the # class' _encode_transforms list. if _unquoted.search(value) and not _quoted.search(value): return value return '"' + _escaped.sub(self._EncodeTransform, value) + '"' def _XCPrint(self, file, tabs, line): file.write("\t" * tabs + line) def _XCPrintableValue(self, tabs, value, flatten_list=False): """Returns a representation of value that may be printed in a project file, mimicking Xcode's behavior. _XCPrintableValue can handle str and int values, XCObjects (which are made printable by returning their id property), and list and dict objects composed of any of the above types. When printing a list or dict, and _should_print_single_line is False, the tabs parameter is used to determine how much to indent the lines corresponding to the items in the list or dict. If flatten_list is True, single-element lists will be transformed into strings. """ printable = "" comment = None if self._should_print_single_line: sep = " " element_tabs = "" end_tabs = "" else: sep = "\n" element_tabs = "\t" * (tabs + 1) end_tabs = "\t" * tabs if isinstance(value, XCObject): printable += value.id comment = value.Comment() elif isinstance(value, str): printable += self._EncodeString(value) elif isinstance(value, str): printable += self._EncodeString(value.encode("utf-8")) elif isinstance(value, int): printable += str(value) elif isinstance(value, list): if flatten_list and len(value) <= 1: if len(value) == 0: printable += self._EncodeString("") else: printable += self._EncodeString(value[0]) else: printable = "(" + sep for item in value: printable += ( element_tabs + self._XCPrintableValue(tabs + 1, item, flatten_list) + "," + sep ) printable += end_tabs + ")" elif isinstance(value, dict): printable = "{" + sep for item_key, item_value in sorted(value.items()): printable += ( element_tabs + self._XCPrintableValue(tabs + 1, item_key, flatten_list) + " = " + self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ";" + sep ) printable += end_tabs + "}" else: raise TypeError("Can't make " + value.__class__.__name__ + " printable") if comment: printable += " " + self._EncodeComment(comment) return printable def _XCKVPrint(self, file, tabs, key, value): """Prints a key and value, members of an XCObject's _properties dictionary, to file. tabs is an int identifying the indentation level. If the class' _should_print_single_line variable is True, tabs is ignored and the key-value pair will be followed by a space insead of a newline. """ if self._should_print_single_line: printable = "" after_kv = " " else: printable = "\t" * tabs after_kv = "\n" # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy # objects without comments. Sometimes it prints them with comments, but # the majority of the time, it doesn't. To avoid unnecessary changes to # the project file after Xcode opens it, don't write comments for # remoteGlobalIDString. This is a sucky hack and it would certainly be # cleaner to extend the schema to indicate whether or not a comment should # be printed, but since this is the only case where the problem occurs and # Xcode itself can't seem to make up its mind, the hack will suffice. # # Also see PBXContainerItemProxy._schema['remoteGlobalIDString']. if key == "remoteGlobalIDString" and isinstance(self, PBXContainerItemProxy): value_to_print = value.id else: value_to_print = value # PBXBuildFile's settings property is represented in the output as a dict, # but a hack here has it represented as a string. Arrange to strip off the # quotes so that it shows up in the output as expected. if key == "settings" and isinstance(self, PBXBuildFile): strip_value_quotes = True else: strip_value_quotes = False # In another one-off, let's set flatten_list on buildSettings properties # of XCBuildConfiguration objects, because that's how Xcode treats them. if key == "buildSettings" and isinstance(self, XCBuildConfiguration): flatten_list = True else: flatten_list = False try: printable_key = self._XCPrintableValue(tabs, key, flatten_list) printable_value = self._XCPrintableValue(tabs, value_to_print, flatten_list) if ( strip_value_quotes and len(printable_value) > 1 and printable_value[0] == '"' and printable_value[-1] == '"' ): printable_value = printable_value[1:-1] printable += printable_key + " = " + printable_value + ";" + after_kv except TypeError as e: gyp.common.ExceptionAppend(e, 'while printing key "%s"' % key) raise self._XCPrint(file, 0, printable) def Print(self, file=sys.stdout): """Prints a reprentation of this object to file, adhering to Xcode output formatting. """ self.VerifyHasRequiredProperties() if self._should_print_single_line: # When printing an object in a single line, Xcode doesn't put any space # between the beginning of a dictionary (or presumably a list) and the # first contained item, so you wind up with snippets like # ...CDEF = {isa = PBXFileReference; fileRef = 0123... # If it were me, I would have put a space in there after the opening # curly, but I guess this is just another one of those inconsistencies # between how Xcode prints PBXFileReference and PBXBuildFile objects as # compared to other objects. Mimic Xcode's behavior here by using an # empty string for sep. sep = "" end_tabs = 0 else: sep = "\n" end_tabs = 2 # Start the object. For example, '\t\tPBXProject = {\n'. self._XCPrint(file, 2, self._XCPrintableValue(2, self) + " = {" + sep) # "isa" isn't in the _properties dictionary, it's an intrinsic property # of the class which the object belongs to. Xcode always outputs "isa" # as the first element of an object dictionary. self._XCKVPrint(file, 3, "isa", self.__class__.__name__) # The remaining elements of an object dictionary are sorted alphabetically. for property, value in sorted(self._properties.items()): self._XCKVPrint(file, 3, property, value) # End the object. self._XCPrint(file, end_tabs, "};\n") def UpdateProperties(self, properties, do_copy=False): """Merge the supplied properties into the _properties dictionary. The input properties must adhere to the class schema or a KeyError or TypeError exception will be raised. If adding an object of an XCObject subclass and the schema indicates a strong relationship, the object's parent will be set to this object. If do_copy is True, then lists, dicts, strong-owned XCObjects, and strong-owned XCObjects in lists will be copied instead of having their references added. """ if properties is None: return for property, value in properties.items(): # Make sure the property is in the schema. if property not in self._schema: raise KeyError(property + " not in " + self.__class__.__name__) # Make sure the property conforms to the schema. (is_list, property_type, is_strong) = self._schema[property][0:3] if is_list: if value.__class__ != list: raise TypeError( property + " of " + self.__class__.__name__ + " must be list, not " + value.__class__.__name__ ) for item in value: if not isinstance(item, property_type) and not ( isinstance(item, str) and property_type == str ): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. raise TypeError( "item of " + property + " of " + self.__class__.__name__ + " must be " + property_type.__name__ + ", not " + item.__class__.__name__ ) elif not isinstance(value, property_type) and not ( isinstance(value, str) and property_type == str ): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. raise TypeError( property + " of " + self.__class__.__name__ + " must be " + property_type.__name__ + ", not " + value.__class__.__name__ ) # Checks passed, perform the assignment. if do_copy: if isinstance(value, XCObject): if is_strong: self._properties[property] = value.Copy() else: self._properties[property] = value elif isinstance(value, (str, int)): self._properties[property] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, # so it's safe to call Copy. self._properties[property] = [] for item in value: self._properties[property].append(item.Copy()) else: self._properties[property] = value[:] elif isinstance(value, dict): self._properties[property] = value.copy() else: raise TypeError( "Don't know how to copy a " + value.__class__.__name__ + " object for " + property + " in " + self.__class__.__name__ ) else: self._properties[property] = value # Set up the child's back-reference to this object. Don't use |value| # any more because it may not be right if do_copy is true. if is_strong: if not is_list: self._properties[property].parent = self else: for item in self._properties[property]: item.parent = self def HasProperty(self, key): return key in self._properties def GetProperty(self, key): return self._properties[key] def SetProperty(self, key, value): self.UpdateProperties({key: value}) def DelProperty(self, key): if key in self._properties: del self._properties[key] def AppendProperty(self, key, value): # TODO(mark): Support ExtendProperty too (and make this call that)? # Schema validation. if key not in self._schema: raise KeyError(key + " not in " + self.__class__.__name__) (is_list, property_type, is_strong) = self._schema[key][0:3] if not is_list: raise TypeError(key + " of " + self.__class__.__name__ + " must be list") if not isinstance(value, property_type): raise TypeError( "item of " + key + " of " + self.__class__.__name__ + " must be " + property_type.__name__ + ", not " + value.__class__.__name__ ) # If the property doesn't exist yet, create a new empty list to receive the # item. self._properties[key] = self._properties.get(key, []) # Set up the ownership link. if is_strong: value.parent = self # Store the item. self._properties[key].append(value) def VerifyHasRequiredProperties(self): """Ensure that all properties identified as required by the schema are set. """ # TODO(mark): A stronger verification mechanism is needed. Some # subclasses need to perform validation beyond what the schema can enforce. for property, attributes in self._schema.items(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and property not in self._properties: raise KeyError(self.__class__.__name__ + " requires " + property) def _SetDefaultsFromSchema(self): """Assign object default values according to the schema. This will not overwrite properties that have already been set.""" defaults = {} for property, attributes in self._schema.items(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if ( is_required and len(attributes) >= 5 and property not in self._properties ): default = attributes[4] defaults[property] = default if len(defaults) > 0: # Use do_copy=True so that each new object gets its own copy of strong # objects, lists, and dicts. self.UpdateProperties(defaults, do_copy=True) class XCHierarchicalElement(XCObject): """Abstract base for PBXGroup and PBXFileReference. Not represented in a project file.""" # TODO(mark): Do name and path belong here? Probably so. # If path is set and name is not, name may have a default value. Name will # be set to the basename of path, if the basename of path is different from # the full value of path. If path is already just a leaf name, name will # not be set. _schema = XCObject._schema.copy() _schema.update( { "comments": [0, str, 0, 0], "fileEncoding": [0, str, 0, 0], "includeInIndex": [0, int, 0, 0], "indentWidth": [0, int, 0, 0], "lineEnding": [0, int, 0, 0], "sourceTree": [0, str, 0, 1, ""], "tabWidth": [0, int, 0, 0], "usesTabs": [0, int, 0, 0], "wrapsLines": [0, int, 0, 0], } ) def __init__(self, properties=None, id=None, parent=None): # super XCObject.__init__(self, properties, id, parent) if "path" in self._properties and "name" not in self._properties: path = self._properties["path"] name = posixpath.basename(path) if name not in ("", path): self.SetProperty("name", name) if "path" in self._properties and ( "sourceTree" not in self._properties or self._properties["sourceTree"] == "" ): # If the pathname begins with an Xcode variable like "$(SDKROOT)/", take # the variable out and make the path be relative to that variable by # assigning the variable name as the sourceTree. (source_tree, path) = SourceTreeAndPathFromPath(self._properties["path"]) if source_tree is not None: self._properties["sourceTree"] = source_tree if path is not None: self._properties["path"] = path if ( source_tree is not None and path is None and "name" not in self._properties ): # The path was of the form "$(SDKROOT)" with no path following it. # This object is now relative to that variable, so it has no path # attribute of its own. It does, however, keep a name. del self._properties["path"] self._properties["name"] = source_tree def Name(self): if "name" in self._properties: return self._properties["name"] elif "path" in self._properties: return self._properties["path"] else: # This happens in the case of the root PBXGroup. return None def Hashables(self): """Custom hashables for XCHierarchicalElements. XCHierarchicalElements are special. Generally, their hashes shouldn't change if the paths don't change. The normal XCObject implementation of Hashables adds a hashable for each object, which means that if the hierarchical structure changes (possibly due to changes caused when TakeOverOnlyChild runs and encounters slight changes in the hierarchy), the hashes will change. For example, if a project file initially contains a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent a/b. If someone later adds a/f2 to the project file, a/b can no longer be collapsed, and f1 winds up with parent b and grandparent a. That would be sufficient to change f1's hash. To counteract this problem, hashables for all XCHierarchicalElements except for the main group (which has neither a name nor a path) are taken to be just the set of path components. Because hashables are inherited from parents, this provides assurance that a/b/f1 has the same set of hashables whether its parent is b or a/b. The main group is a special case. As it is permitted to have no name or path, it is permitted to use the standard XCObject hash mechanism. This is not considered a problem because there can be only one main group. """ if self == self.PBXProjectAncestor()._properties["mainGroup"]: # super return XCObject.Hashables(self) hashables = [] # Put the name in first, ensuring that if TakeOverOnlyChild collapses # children into a top-level group like "Source", the name always goes # into the list of hashables without interfering with path components. if "name" in self._properties: # Make it less likely for people to manipulate hashes by following the # pattern of always pushing an object type value onto the list first. hashables.append(self.__class__.__name__ + ".name") hashables.append(self._properties["name"]) # NOTE: This still has the problem that if an absolute path is encountered, # including paths with a sourceTree, they'll still inherit their parents' # hashables, even though the paths aren't relative to their parents. This # is not expected to be much of a problem in practice. path = self.PathFromSourceTreeAndPath() if path is not None: components = path.split(posixpath.sep) for component in components: hashables.append(self.__class__.__name__ + ".path") hashables.append(component) hashables.extend(self._hashables) return hashables def Compare(self, other): # Allow comparison of these types. PBXGroup has the highest sort rank; # PBXVariantGroup is treated as equal to PBXFileReference. valid_class_types = { PBXFileReference: "file", PBXGroup: "group", PBXVariantGroup: "file", } self_type = valid_class_types[self.__class__] other_type = valid_class_types[other.__class__] if self_type == other_type: # If the two objects are of the same sort rank, compare their names. return cmp(self.Name(), other.Name()) # Otherwise, sort groups before everything else. if self_type == "group": return -1 return 1 def CompareRootGroup(self, other): # This function should be used only to compare direct children of the # containing PBXProject's mainGroup. These groups should appear in the # listed order. # TODO(mark): "Build" is used by gyp.generator.xcode, perhaps the # generator should have a way of influencing this list rather than having # to hardcode for the generator here. order = [ "Source", "Intermediates", "Projects", "Frameworks", "Products", "Build", ] # If the groups aren't in the listed order, do a name comparison. # Otherwise, groups in the listed order should come before those that # aren't. self_name = self.Name() other_name = other.Name() self_in = isinstance(self, PBXGroup) and self_name in order other_in = isinstance(self, PBXGroup) and other_name in order if not self_in and not other_in: return self.Compare(other) if self_name in order and other_name not in order: return -1 if other_name in order and self_name not in order: return 1 # If both groups are in the listed order, go by the defined order. self_index = order.index(self_name) other_index = order.index(other_name) if self_index < other_index: return -1 if self_index > other_index: return 1 return 0 def PathFromSourceTreeAndPath(self): # Turn the object's sourceTree and path properties into a single flat # string of a form comparable to the path parameter. If there's a # sourceTree property other than "", wrap it in $(...) for the # comparison. components = [] if self._properties["sourceTree"] != "": components.append("$(" + self._properties["sourceTree"] + ")") if "path" in self._properties: components.append(self._properties["path"]) if len(components) > 0: return posixpath.join(*components) return None def FullPath(self): # Returns a full path to self relative to the project file, or relative # to some other source tree. Start with self, and walk up the chain of # parents prepending their paths, if any, until no more parents are # available (project-relative path) or until a path relative to some # source tree is found. xche = self path = None while isinstance(xche, XCHierarchicalElement) and ( path is None or (not path.startswith("/") and not path.startswith("$")) ): this_path = xche.PathFromSourceTreeAndPath() if this_path is not None and path is not None: path = posixpath.join(this_path, path) elif this_path is not None: path = this_path xche = xche.parent return path class PBXGroup(XCHierarchicalElement): """ Attributes: _children_by_path: Maps pathnames of children of this PBXGroup to the actual child XCHierarchicalElement objects. _variant_children_by_name_and_path: Maps (name, path) tuples of PBXVariantGroup children to the actual child PBXVariantGroup objects. """ _schema = XCHierarchicalElement._schema.copy() _schema.update( { "children": [1, XCHierarchicalElement, 1, 1, []], "name": [0, str, 0, 0], "path": [0, str, 0, 0], } ) def __init__(self, properties=None, id=None, parent=None): # super XCHierarchicalElement.__init__(self, properties, id, parent) self._children_by_path = {} self._variant_children_by_name_and_path = {} for child in self._properties.get("children", []): self._AddChildToDicts(child) def Hashables(self): # super hashables = XCHierarchicalElement.Hashables(self) # It is not sufficient to just rely on name and parent to build a unique # hashable : a node could have two child PBXGroup sharing a common name. # To add entropy the hashable is enhanced with the names of all its # children. for child in self._properties.get("children", []): child_name = child.Name() if child_name is not None: hashables.append(child_name) return hashables def HashablesForChild(self): # To avoid a circular reference the hashables used to compute a child id do # not include the child names. return XCHierarchicalElement.Hashables(self) def _AddChildToDicts(self, child): # Sets up this PBXGroup object's dicts to reference the child properly. child_path = child.PathFromSourceTreeAndPath() if child_path: if child_path in self._children_by_path: raise ValueError("Found multiple children with path " + child_path) self._children_by_path[child_path] = child if isinstance(child, PBXVariantGroup): child_name = child._properties.get("name", None) key = (child_name, child_path) if key in self._variant_children_by_name_and_path: raise ValueError( "Found multiple PBXVariantGroup children with " + "name " + str(child_name) + " and path " + str(child_path) ) self._variant_children_by_name_and_path[key] = child def AppendChild(self, child): # Callers should use this instead of calling # AppendProperty('children', child) directly because this function # maintains the group's dicts. self.AppendProperty("children", child) self._AddChildToDicts(child) def GetChildByName(self, name): # This is not currently optimized with a dict as GetChildByPath is because # it has few callers. Most callers probably want GetChildByPath. This # function is only useful to get children that have names but no paths, # which is rare. The children of the main group ("Source", "Products", # etc.) is pretty much the only case where this likely to come up. # # TODO(mark): Maybe this should raise an error if more than one child is # present with the same name. if "children" not in self._properties: return None for child in self._properties["children"]: if child.Name() == name: return child return None def GetChildByPath(self, path): if not path: return None if path in self._children_by_path: return self._children_by_path[path] return None def GetChildByRemoteObject(self, remote_object): # This method is a little bit esoteric. Given a remote_object, which # should be a PBXFileReference in another project file, this method will # return this group's PBXReferenceProxy object serving as a local proxy # for the remote PBXFileReference. # # This function might benefit from a dict optimization as GetChildByPath # for some workloads, but profiling shows that it's not currently a # problem. if "children" not in self._properties: return None for child in self._properties["children"]: if not isinstance(child, PBXReferenceProxy): continue container_proxy = child._properties["remoteRef"] if container_proxy._properties["remoteGlobalIDString"] == remote_object: return child return None def AddOrGetFileByPath(self, path, hierarchical): """Returns an existing or new file reference corresponding to path. If hierarchical is True, this method will create or use the necessary hierarchical group structure corresponding to path. Otherwise, it will look in and create an item in the current group only. If an existing matching reference is found, it is returned, otherwise, a new one will be created, added to the correct group, and returned. If path identifies a directory by virtue of carrying a trailing slash, this method returns a PBXFileReference of "folder" type. If path identifies a variant, by virtue of it identifying a file inside a directory with an ".lproj" extension, this method returns a PBXVariantGroup containing the variant named by path, and possibly other variants. For all other paths, a "normal" PBXFileReference will be returned. """ # Adding or getting a directory? Directories end with a trailing slash. is_dir = False if path.endswith("/"): is_dir = True path = posixpath.normpath(path) if is_dir: path = path + "/" # Adding or getting a variant? Variants are files inside directories # with an ".lproj" extension. Xcode uses variants for localization. For # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named # MainMenu.nib inside path/to, and give it a variant named Language. In # this example, grandparent would be set to path/to and parent_root would # be set to Language. variant_name = None parent = posixpath.dirname(path) grandparent = posixpath.dirname(parent) parent_basename = posixpath.basename(parent) (parent_root, parent_ext) = posixpath.splitext(parent_basename) if parent_ext == ".lproj": variant_name = parent_root if grandparent == "": grandparent = None # Putting a directory inside a variant group is not currently supported. assert not is_dir or variant_name is None path_split = path.split(posixpath.sep) if ( len(path_split) == 1 or ((is_dir or variant_name is not None) and len(path_split) == 2) or not hierarchical ): # The PBXFileReference or PBXVariantGroup will be added to or gotten from # this PBXGroup, no recursion necessary. if variant_name is None: # Add or get a PBXFileReference. file_ref = self.GetChildByPath(path) if file_ref is not None: assert file_ref.__class__ == PBXFileReference else: file_ref = PBXFileReference({"path": path}) self.AppendChild(file_ref) else: # Add or get a PBXVariantGroup. The variant group name is the same # as the basename (MainMenu.nib in the example above). grandparent # specifies the path to the variant group itself, and path_split[-2:] # is the path of the specific variant relative to its group. variant_group_name = posixpath.basename(path) variant_group_ref = self.AddOrGetVariantGroupByNameAndPath( variant_group_name, grandparent ) variant_path = posixpath.sep.join(path_split[-2:]) variant_ref = variant_group_ref.GetChildByPath(variant_path) if variant_ref is not None: assert variant_ref.__class__ == PBXFileReference else: variant_ref = PBXFileReference( {"name": variant_name, "path": variant_path} ) variant_group_ref.AppendChild(variant_ref) # The caller is interested in the variant group, not the specific # variant file. file_ref = variant_group_ref return file_ref else: # Hierarchical recursion. Add or get a PBXGroup corresponding to the # outermost path component, and then recurse into it, chopping off that # path component. next_dir = path_split[0] group_ref = self.GetChildByPath(next_dir) if group_ref is not None: assert group_ref.__class__ == PBXGroup else: group_ref = PBXGroup({"path": next_dir}) self.AppendChild(group_ref) return group_ref.AddOrGetFileByPath( posixpath.sep.join(path_split[1:]), hierarchical ) def AddOrGetVariantGroupByNameAndPath(self, name, path): """Returns an existing or new PBXVariantGroup for name and path. If a PBXVariantGroup identified by the name and path arguments is already present as a child of this object, it is returned. Otherwise, a new PBXVariantGroup with the correct properties is created, added as a child, and returned. This method will generally be called by AddOrGetFileByPath, which knows when to create a variant group based on the structure of the pathnames passed to it. """ key = (name, path) if key in self._variant_children_by_name_and_path: variant_group_ref = self._variant_children_by_name_and_path[key] assert variant_group_ref.__class__ == PBXVariantGroup return variant_group_ref variant_group_properties = {"name": name} if path is not None: variant_group_properties["path"] = path variant_group_ref = PBXVariantGroup(variant_group_properties) self.AppendChild(variant_group_ref) return variant_group_ref def TakeOverOnlyChild(self, recurse=False): """If this PBXGroup has only one child and it's also a PBXGroup, take it over by making all of its children this object's children. This function will continue to take over only children when those children are groups. If there are three PBXGroups representing a, b, and c, with c inside b and b inside a, and a and b have no other children, this will result in a taking over both b and c, forming a PBXGroup for a/b/c. If recurse is True, this function will recurse into children and ask them to collapse themselves by taking over only children as well. Assuming an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f (d1, d2, and f are files, the rest are groups), recursion will result in a group for a/b/c containing a group for d3/e. """ # At this stage, check that child class types are PBXGroup exactly, # instead of using isinstance. The only subclass of PBXGroup, # PBXVariantGroup, should not participate in reparenting in the same way: # reparenting by merging different object types would be wrong. while ( len(self._properties["children"]) == 1 and self._properties["children"][0].__class__ == PBXGroup ): # Loop to take over the innermost only-child group possible. child = self._properties["children"][0] # Assume the child's properties, including its children. Save a copy # of this object's old properties, because they'll still be needed. # This object retains its existing id and parent attributes. old_properties = self._properties self._properties = child._properties self._children_by_path = child._children_by_path if ( "sourceTree" not in self._properties or self._properties["sourceTree"] == "" ): # The child was relative to its parent. Fix up the path. Note that # children with a sourceTree other than "" are not relative to # their parents, so no path fix-up is needed in that case. if "path" in old_properties: if "path" in self._properties: # Both the original parent and child have paths set. self._properties["path"] = posixpath.join( old_properties["path"], self._properties["path"] ) else: # Only the original parent has a path, use it. self._properties["path"] = old_properties["path"] if "sourceTree" in old_properties: # The original parent had a sourceTree set, use it. self._properties["sourceTree"] = old_properties["sourceTree"] # If the original parent had a name set, keep using it. If the original # parent didn't have a name but the child did, let the child's name # live on. If the name attribute seems unnecessary now, get rid of it. if "name" in old_properties and old_properties["name"] not in ( None, self.Name(), ): self._properties["name"] = old_properties["name"] if ( "name" in self._properties and "path" in self._properties and self._properties["name"] == self._properties["path"] ): del self._properties["name"] # Notify all children of their new parent. for child in self._properties["children"]: child.parent = self # If asked to recurse, recurse. if recurse: for child in self._properties["children"]: if child.__class__ == PBXGroup: child.TakeOverOnlyChild(recurse) def SortGroup(self): self._properties["children"] = sorted( self._properties["children"], key=cmp_to_key(lambda x, y: x.Compare(y)) ) # Recurse. for child in self._properties["children"]: if isinstance(child, PBXGroup): child.SortGroup() class XCFileLikeElement(XCHierarchicalElement): # Abstract base for objects that can be used as the fileRef property of # PBXBuildFile. def PathHashables(self): # A PBXBuildFile that refers to this object will call this method to # obtain additional hashables specific to this XCFileLikeElement. Don't # just use this object's hashables, they're not specific and unique enough # on their own (without access to the parent hashables.) Instead, provide # hashables that identify this object by path by getting its hashables as # well as the hashables of ancestor XCHierarchicalElement objects. hashables = [] xche = self while isinstance(xche, XCHierarchicalElement): xche_hashables = xche.Hashables() for index, xche_hashable in enumerate(xche_hashables): hashables.insert(index, xche_hashable) xche = xche.parent return hashables class XCContainerPortal(XCObject): # Abstract base for objects that can be used as the containerPortal property # of PBXContainerItemProxy. pass class XCRemoteObject(XCObject): # Abstract base for objects that can be used as the remoteGlobalIDString # property of PBXContainerItemProxy. pass class PBXFileReference(XCFileLikeElement, XCContainerPortal, XCRemoteObject): _schema = XCFileLikeElement._schema.copy() _schema.update( { "explicitFileType": [0, str, 0, 0], "lastKnownFileType": [0, str, 0, 0], "name": [0, str, 0, 0], "path": [0, str, 0, 1], } ) # Weird output rules for PBXFileReference. _should_print_single_line = True # super _encode_transforms = XCFileLikeElement._alternate_encode_transforms def __init__(self, properties=None, id=None, parent=None): # super XCFileLikeElement.__init__(self, properties, id, parent) if "path" in self._properties and self._properties["path"].endswith("/"): self._properties["path"] = self._properties["path"][:-1] is_dir = True else: is_dir = False if ( "path" in self._properties and "lastKnownFileType" not in self._properties and "explicitFileType" not in self._properties ): # TODO(mark): This is the replacement for a replacement for a quick hack. # It is no longer incredibly sucky, but this list needs to be extended. extension_map = { "a": "archive.ar", "app": "wrapper.application", "bdic": "file", "bundle": "wrapper.cfbundle", "c": "sourcecode.c.c", "cc": "sourcecode.cpp.cpp", "cpp": "sourcecode.cpp.cpp", "css": "text.css", "cxx": "sourcecode.cpp.cpp", "dart": "sourcecode", "dylib": "compiled.mach-o.dylib", "framework": "wrapper.framework", "gyp": "sourcecode", "gypi": "sourcecode", "h": "sourcecode.c.h", "hxx": "sourcecode.cpp.h", "icns": "image.icns", "java": "sourcecode.java", "js": "sourcecode.javascript", "kext": "wrapper.kext", "m": "sourcecode.c.objc", "mm": "sourcecode.cpp.objcpp", "nib": "wrapper.nib", "o": "compiled.mach-o.objfile", "pdf": "image.pdf", "pl": "text.script.perl", "plist": "text.plist.xml", "pm": "text.script.perl", "png": "image.png", "py": "text.script.python", "r": "sourcecode.rez", "rez": "sourcecode.rez", "s": "sourcecode.asm", "storyboard": "file.storyboard", "strings": "text.plist.strings", "swift": "sourcecode.swift", "ttf": "file", "xcassets": "folder.assetcatalog", "xcconfig": "text.xcconfig", "xcdatamodel": "wrapper.xcdatamodel", "xcdatamodeld": "wrapper.xcdatamodeld", "xib": "file.xib", "y": "sourcecode.yacc", } prop_map = { "dart": "explicitFileType", "gyp": "explicitFileType", "gypi": "explicitFileType", } if is_dir: file_type = "folder" prop_name = "lastKnownFileType" else: basename = posixpath.basename(self._properties["path"]) (root, ext) = posixpath.splitext(basename) # Check the map using a lowercase extension. # TODO(mark): Maybe it should try with the original case first and fall # back to lowercase, in case there are any instances where case # matters. There currently aren't. if ext != "": ext = ext[1:].lower() # TODO(mark): "text" is the default value, but "file" is appropriate # for unrecognized files not containing text. Xcode seems to choose # based on content. file_type = extension_map.get(ext, "text") prop_name = prop_map.get(ext, "lastKnownFileType") self._properties[prop_name] = file_type class PBXVariantGroup(PBXGroup, XCFileLikeElement): """PBXVariantGroup is used by Xcode to represent localizations.""" # No additions to the schema relative to PBXGroup. pass # PBXReferenceProxy is also an XCFileLikeElement subclass. It is defined below # because it uses PBXContainerItemProxy, defined below. class XCBuildConfiguration(XCObject): _schema = XCObject._schema.copy() _schema.update( { "baseConfigurationReference": [0, PBXFileReference, 0, 0], "buildSettings": [0, dict, 0, 1, {}], "name": [0, str, 0, 1], } ) def HasBuildSetting(self, key): return key in self._properties["buildSettings"] def GetBuildSetting(self, key): return self._properties["buildSettings"][key] def SetBuildSetting(self, key, value): # TODO(mark): If a list, copy? self._properties["buildSettings"][key] = value def AppendBuildSetting(self, key, value): if key not in self._properties["buildSettings"]: self._properties["buildSettings"][key] = [] self._properties["buildSettings"][key].append(value) def DelBuildSetting(self, key): if key in self._properties["buildSettings"]: del self._properties["buildSettings"][key] def SetBaseConfiguration(self, value): self._properties["baseConfigurationReference"] = value class XCConfigurationList(XCObject): # _configs is the default list of configurations. _configs = [ XCBuildConfiguration({"name": "Debug"}), XCBuildConfiguration({"name": "Release"}), ] _schema = XCObject._schema.copy() _schema.update( { "buildConfigurations": [1, XCBuildConfiguration, 1, 1, _configs], "defaultConfigurationIsVisible": [0, int, 0, 1, 1], "defaultConfigurationName": [0, str, 0, 1, "Release"], } ) def Name(self): return ( "Build configuration list for " + self.parent.__class__.__name__ + ' "' + self.parent.Name() + '"' ) def ConfigurationNamed(self, name): """Convenience accessor to obtain an XCBuildConfiguration by name.""" for configuration in self._properties["buildConfigurations"]: if configuration._properties["name"] == name: return configuration raise KeyError(name) def DefaultConfiguration(self): """Convenience accessor to obtain the default XCBuildConfiguration.""" return self.ConfigurationNamed(self._properties["defaultConfigurationName"]) def HasBuildSetting(self, key): """Determines the state of a build setting in all XCBuildConfiguration child objects. If all child objects have key in their build settings, and the value is the same in all child objects, returns 1. If no child objects have the key in their build settings, returns 0. If some, but not all, child objects have the key in their build settings, or if any children have different values for the key, returns -1. """ has = None value = None for configuration in self._properties["buildConfigurations"]: configuration_has = configuration.HasBuildSetting(key) if has is None: has = configuration_has elif has != configuration_has: return -1 if configuration_has: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value elif value != configuration_value: return -1 if not has: return 0 return 1 def GetBuildSetting(self, key): """Gets the build setting for key. All child XCConfiguration objects must have the same value set for the setting, or a ValueError will be raised. """ # TODO(mark): This is wrong for build settings that are lists. The list # contents should be compared (and a list copy returned?) value = None for configuration in self._properties["buildConfigurations"]: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value else: if value != configuration_value: raise ValueError("Variant values for " + key) return value def SetBuildSetting(self, key, value): """Sets the build setting for key to value in all child XCBuildConfiguration objects. """ for configuration in self._properties["buildConfigurations"]: configuration.SetBuildSetting(key, value) def AppendBuildSetting(self, key, value): """Appends value to the build setting for key, which is treated as a list, in all child XCBuildConfiguration objects. """ for configuration in self._properties["buildConfigurations"]: configuration.AppendBuildSetting(key, value) def DelBuildSetting(self, key): """Deletes the build setting key from all child XCBuildConfiguration objects. """ for configuration in self._properties["buildConfigurations"]: configuration.DelBuildSetting(key) def SetBaseConfiguration(self, value): """Sets the build configuration in all child XCBuildConfiguration objects. """ for configuration in self._properties["buildConfigurations"]: configuration.SetBaseConfiguration(value) class PBXBuildFile(XCObject): _schema = XCObject._schema.copy() _schema.update( { "fileRef": [0, XCFileLikeElement, 0, 1], "settings": [0, str, 0, 0], # hack, it's a dict } ) # Weird output rules for PBXBuildFile. _should_print_single_line = True _encode_transforms = XCObject._alternate_encode_transforms def Name(self): # Example: "main.cc in Sources" return self._properties["fileRef"].Name() + " in " + self.parent.Name() def Hashables(self): # super hashables = XCObject.Hashables(self) # It is not sufficient to just rely on Name() to get the # XCFileLikeElement's name, because that is not a complete pathname. # PathHashables returns hashables unique enough that no two # PBXBuildFiles should wind up with the same set of hashables, unless # someone adds the same file multiple times to the same target. That # would be considered invalid anyway. hashables.extend(self._properties["fileRef"].PathHashables()) return hashables class XCBuildPhase(XCObject): """Abstract base for build phase classes. Not represented in a project file. Attributes: _files_by_path: A dict mapping each path of a child in the files list by path (keys) to the corresponding PBXBuildFile children (values). _files_by_xcfilelikeelement: A dict mapping each XCFileLikeElement (keys) to the corresponding PBXBuildFile children (values). """ # TODO(mark): Some build phase types, like PBXShellScriptBuildPhase, don't # actually have a "files" list. XCBuildPhase should not have "files" but # another abstract subclass of it should provide this, and concrete build # phase types that do have "files" lists should be derived from that new # abstract subclass. XCBuildPhase should only provide buildActionMask and # runOnlyForDeploymentPostprocessing, and not files or the various # file-related methods and attributes. _schema = XCObject._schema.copy() _schema.update( { "buildActionMask": [0, int, 0, 1, 0x7FFFFFFF], "files": [1, PBXBuildFile, 1, 1, []], "runOnlyForDeploymentPostprocessing": [0, int, 0, 1, 0], } ) def __init__(self, properties=None, id=None, parent=None): # super XCObject.__init__(self, properties, id, parent) self._files_by_path = {} self._files_by_xcfilelikeelement = {} for pbxbuildfile in self._properties.get("files", []): self._AddBuildFileToDicts(pbxbuildfile) def FileGroup(self, path): # Subclasses must override this by returning a two-element tuple. The # first item in the tuple should be the PBXGroup to which "path" should be # added, either as a child or deeper descendant. The second item should # be a boolean indicating whether files should be added into hierarchical # groups or one single flat group. raise NotImplementedError(self.__class__.__name__ + " must implement FileGroup") def _AddPathToDict(self, pbxbuildfile, path): """Adds path to the dict tracking paths belonging to this build phase. If the path is already a member of this build phase, raises an exception. """ if path in self._files_by_path: raise ValueError("Found multiple build files with path " + path) self._files_by_path[path] = pbxbuildfile def _AddBuildFileToDicts(self, pbxbuildfile, path=None): """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts. If path is specified, then it is the path that is being added to the phase, and pbxbuildfile must contain either a PBXFileReference directly referencing that path, or it must contain a PBXVariantGroup that itself contains a PBXFileReference referencing the path. If path is not specified, either the PBXFileReference's path or the paths of all children of the PBXVariantGroup are taken as being added to the phase. If the path is already present in the phase, raises an exception. If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile are already present in the phase, referenced by a different PBXBuildFile object, raises an exception. This does not raise an exception when a PBXFileReference or PBXVariantGroup reappear and are referenced by the same PBXBuildFile that has already introduced them, because in the case of PBXVariantGroup objects, they may correspond to multiple paths that are not all added simultaneously. When this situation occurs, the path needs to be added to _files_by_path, but nothing needs to change in _files_by_xcfilelikeelement, and the caller should have avoided adding the PBXBuildFile if it is already present in the list of children. """ xcfilelikeelement = pbxbuildfile._properties["fileRef"] paths = [] if path is not None: # It's best when the caller provides the path. if isinstance(xcfilelikeelement, PBXVariantGroup): paths.append(path) else: # If the caller didn't provide a path, there can be either multiple # paths (PBXVariantGroup) or one. if isinstance(xcfilelikeelement, PBXVariantGroup): for variant in xcfilelikeelement._properties["children"]: paths.append(variant.FullPath()) else: paths.append(xcfilelikeelement.FullPath()) # Add the paths first, because if something's going to raise, the # messages provided by _AddPathToDict are more useful owing to its # having access to a real pathname and not just an object's Name(). for a_path in paths: self._AddPathToDict(pbxbuildfile, a_path) # If another PBXBuildFile references this XCFileLikeElement, there's a # problem. if ( xcfilelikeelement in self._files_by_xcfilelikeelement and self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile ): raise ValueError( "Found multiple build files for " + xcfilelikeelement.Name() ) self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile def AppendBuildFile(self, pbxbuildfile, path=None): # Callers should use this instead of calling # AppendProperty('files', pbxbuildfile) directly because this function # maintains the object's dicts. Better yet, callers can just call AddFile # with a pathname and not worry about building their own PBXBuildFile # objects. self.AppendProperty("files", pbxbuildfile) self._AddBuildFileToDicts(pbxbuildfile, path) def AddFile(self, path, settings=None): (file_group, hierarchical) = self.FileGroup(path) file_ref = file_group.AddOrGetFileByPath(path, hierarchical) if file_ref in self._files_by_xcfilelikeelement and isinstance( file_ref, PBXVariantGroup ): # There's already a PBXBuildFile in this phase corresponding to the # PBXVariantGroup. path just provides a new variant that belongs to # the group. Add the path to the dict. pbxbuildfile = self._files_by_xcfilelikeelement[file_ref] self._AddBuildFileToDicts(pbxbuildfile, path) else: # Add a new PBXBuildFile to get file_ref into the phase. if settings is None: pbxbuildfile = PBXBuildFile({"fileRef": file_ref}) else: pbxbuildfile = PBXBuildFile({"fileRef": file_ref, "settings": settings}) self.AppendBuildFile(pbxbuildfile, path) class PBXHeadersBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return "Headers" def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXResourcesBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return "Resources" def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXSourcesBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return "Sources" def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXFrameworksBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return "Frameworks" def FileGroup(self, path): (root, ext) = posixpath.splitext(path) if ext != "": ext = ext[1:].lower() if ext == "o": # .o files are added to Xcode Frameworks phases, but conceptually aren't # frameworks, they're more like sources or intermediates. Redirect them # to show up in one of those other groups. return self.PBXProjectAncestor().RootGroupForPath(path) else: return (self.PBXProjectAncestor().FrameworksGroup(), False) class PBXShellScriptBuildPhase(XCBuildPhase): _schema = XCBuildPhase._schema.copy() _schema.update( { "inputPaths": [1, str, 0, 1, []], "name": [0, str, 0, 0], "outputPaths": [1, str, 0, 1, []], "shellPath": [0, str, 0, 1, "/bin/sh"], "shellScript": [0, str, 0, 1], "showEnvVarsInLog": [0, int, 0, 0], } ) def Name(self): if "name" in self._properties: return self._properties["name"] return "ShellScript" class PBXCopyFilesBuildPhase(XCBuildPhase): _schema = XCBuildPhase._schema.copy() _schema.update( { "dstPath": [0, str, 0, 1], "dstSubfolderSpec": [0, int, 0, 1], "name": [0, str, 0, 0], } ) # path_tree_re matches "$(DIR)/path", "$(DIR)/$(DIR2)/path" or just "$(DIR)". # Match group 1 is "DIR", group 3 is "path" or "$(DIR2") or "$(DIR2)/path" # or None. If group 3 is "path", group 4 will be None otherwise group 4 is # "DIR2" and group 6 is "path". path_tree_re = re.compile(r"^\$\((.*?)\)(/(\$\((.*?)\)(/(.*)|)|(.*)|)|)$") # path_tree_{first,second}_to_subfolder map names of Xcode variables to the # associated dstSubfolderSpec property value used in a PBXCopyFilesBuildPhase # object. path_tree_first_to_subfolder = { # Types that can be chosen via the Xcode UI. "BUILT_PRODUCTS_DIR": 16, # Products Directory "BUILT_FRAMEWORKS_DIR": 10, # Not an official Xcode macro. # Existed before support for the # names below was added. Maps to # "Frameworks". } path_tree_second_to_subfolder = { "WRAPPER_NAME": 1, # Wrapper # Although Xcode's friendly name is "Executables", the destination # is demonstrably the value of the build setting # EXECUTABLE_FOLDER_PATH not EXECUTABLES_FOLDER_PATH. "EXECUTABLE_FOLDER_PATH": 6, # Executables. "UNLOCALIZED_RESOURCES_FOLDER_PATH": 7, # Resources "JAVA_FOLDER_PATH": 15, # Java Resources "FRAMEWORKS_FOLDER_PATH": 10, # Frameworks "SHARED_FRAMEWORKS_FOLDER_PATH": 11, # Shared Frameworks "SHARED_SUPPORT_FOLDER_PATH": 12, # Shared Support "PLUGINS_FOLDER_PATH": 13, # PlugIns # For XPC Services, Xcode sets both dstPath and dstSubfolderSpec. # Note that it re-uses the BUILT_PRODUCTS_DIR value for # dstSubfolderSpec. dstPath is set below. "XPCSERVICES_FOLDER_PATH": 16, # XPC Services. } def Name(self): if "name" in self._properties: return self._properties["name"] return "CopyFiles" def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) def SetDestination(self, path): """Set the dstSubfolderSpec and dstPath properties from path. path may be specified in the same notation used for XCHierarchicalElements, specifically, "$(DIR)/path". """ path_tree_match = self.path_tree_re.search(path) if path_tree_match: path_tree = path_tree_match.group(1) if path_tree in self.path_tree_first_to_subfolder: subfolder = self.path_tree_first_to_subfolder[path_tree] relative_path = path_tree_match.group(3) if relative_path is None: relative_path = "" if subfolder == 16 and path_tree_match.group(4) is not None: # BUILT_PRODUCTS_DIR (16) is the first element in a path whose # second element is possibly one of the variable names in # path_tree_second_to_subfolder. Xcode sets the values of all these # variables to relative paths so .gyp files must prefix them with # BUILT_PRODUCTS_DIR, e.g. # $(BUILT_PRODUCTS_DIR)/$(PLUGINS_FOLDER_PATH). Then # xcode_emulation.py can export these variables with the same values # as Xcode yet make & ninja files can determine the absolute path # to the target. Xcode uses the dstSubfolderSpec value set here # to determine the full path. # # An alternative of xcode_emulation.py setting the values to # absolute paths when exporting these variables has been # ruled out because then the values would be different # depending on the build tool. # # Another alternative is to invent new names for the variables used # to match to the subfolder indices in the second table. .gyp files # then will not need to prepend $(BUILT_PRODUCTS_DIR) because # xcode_emulation.py can set the values of those variables to # the absolute paths when exporting. This is possibly the thinking # behind BUILT_FRAMEWORKS_DIR which is used in exactly this manner. # # Requiring prepending BUILT_PRODUCTS_DIR has been chosen because # this same way could be used to specify destinations in .gyp files # that pre-date this addition to GYP. However they would only work # with the Xcode generator. # The previous version of xcode_emulation.py # does not export these variables. Such files will get the benefit # of the Xcode UI showing the proper destination name simply by # regenerating the projects with this version of GYP. path_tree = path_tree_match.group(4) relative_path = path_tree_match.group(6) separator = "/" if path_tree in self.path_tree_second_to_subfolder: subfolder = self.path_tree_second_to_subfolder[path_tree] if relative_path is None: relative_path = "" separator = "" if path_tree == "XPCSERVICES_FOLDER_PATH": relative_path = ( "$(CONTENTS_FOLDER_PATH)/XPCServices" + separator + relative_path ) else: # subfolder = 16 from above # The second element of the path is an unrecognized variable. # Include it and any remaining elements in relative_path. relative_path = path_tree_match.group(3) else: # The path starts with an unrecognized Xcode variable # name like $(SRCROOT). Xcode will still handle this # as an "absolute path" that starts with the variable. subfolder = 0 relative_path = path elif path.startswith("/"): # Special case. Absolute paths are in dstSubfolderSpec 0. subfolder = 0 relative_path = path[1:] else: raise ValueError( f"Can't use path {path} in a {self.__class__.__name__}" ) self._properties["dstPath"] = relative_path self._properties["dstSubfolderSpec"] = subfolder class PBXBuildRule(XCObject): _schema = XCObject._schema.copy() _schema.update( { "compilerSpec": [0, str, 0, 1], "filePatterns": [0, str, 0, 0], "fileType": [0, str, 0, 1], "isEditable": [0, int, 0, 1, 1], "outputFiles": [1, str, 0, 1, []], "script": [0, str, 0, 0], } ) def Name(self): # Not very inspired, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.append(self._properties["fileType"]) if "filePatterns" in self._properties: hashables.append(self._properties["filePatterns"]) return hashables class PBXContainerItemProxy(XCObject): # When referencing an item in this project file, containerPortal is the # PBXProject root object of this project file. When referencing an item in # another project file, containerPortal is a PBXFileReference identifying # the other project file. # # When serving as a proxy to an XCTarget (in this project file or another), # proxyType is 1. When serving as a proxy to a PBXFileReference (in another # project file), proxyType is 2. Type 2 is used for references to the # producs of the other project file's targets. # # Xcode is weird about remoteGlobalIDString. Usually, it's printed without # a comment, indicating that it's tracked internally simply as a string, but # sometimes it's printed with a comment (usually when the object is initially # created), indicating that it's tracked as a project file object at least # sometimes. This module always tracks it as an object, but contains a hack # to prevent it from printing the comment in the project file output. See # _XCKVPrint. _schema = XCObject._schema.copy() _schema.update( { "containerPortal": [0, XCContainerPortal, 0, 1], "proxyType": [0, int, 0, 1], "remoteGlobalIDString": [0, XCRemoteObject, 0, 1], "remoteInfo": [0, str, 0, 1], } ) def __repr__(self): props = self._properties name = "{}.gyp:{}".format(props["containerPortal"].Name(), props["remoteInfo"]) return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>" def Name(self): # Admittedly not the best name, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.extend(self._properties["containerPortal"].Hashables()) hashables.extend(self._properties["remoteGlobalIDString"].Hashables()) return hashables class PBXTargetDependency(XCObject): # The "target" property accepts an XCTarget object, and obviously not # NoneType. But XCTarget is defined below, so it can't be put into the # schema yet. The definition of PBXTargetDependency can't be moved below # XCTarget because XCTarget's own schema references PBXTargetDependency. # Python doesn't deal well with this circular relationship, and doesn't have # a real way to do forward declarations. To work around, the type of # the "target" property is reset below, after XCTarget is defined. # # At least one of "name" and "target" is required. _schema = XCObject._schema.copy() _schema.update( { "name": [0, str, 0, 0], "target": [0, None.__class__, 0, 0], "targetProxy": [0, PBXContainerItemProxy, 1, 1], } ) def __repr__(self): name = self._properties.get("name") or self._properties["target"].Name() return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>" def Name(self): # Admittedly not the best name, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.extend(self._properties["targetProxy"].Hashables()) return hashables class PBXReferenceProxy(XCFileLikeElement): _schema = XCFileLikeElement._schema.copy() _schema.update( { "fileType": [0, str, 0, 1], "path": [0, str, 0, 1], "remoteRef": [0, PBXContainerItemProxy, 1, 1], } ) class XCTarget(XCRemoteObject): # An XCTarget is really just an XCObject, the XCRemoteObject thing is just # to allow PBXProject to be used in the remoteGlobalIDString property of # PBXContainerItemProxy. # # Setting a "name" property at instantiation may also affect "productName", # which may in turn affect the "PRODUCT_NAME" build setting in children of # "buildConfigurationList". See __init__ below. _schema = XCRemoteObject._schema.copy() _schema.update( { "buildConfigurationList": [ 0, XCConfigurationList, 1, 1, XCConfigurationList(), ], "buildPhases": [1, XCBuildPhase, 1, 1, []], "dependencies": [1, PBXTargetDependency, 1, 1, []], "name": [0, str, 0, 1], "productName": [0, str, 0, 1], } ) def __init__( self, properties=None, id=None, parent=None, force_outdir=None, force_prefix=None, force_extension=None, ): # super XCRemoteObject.__init__(self, properties, id, parent) # Set up additional defaults not expressed in the schema. If a "name" # property was supplied, set "productName" if it is not present. Also set # the "PRODUCT_NAME" build setting in each configuration, but only if # the setting is not present in any build configuration. if "name" in self._properties and "productName" not in self._properties: self.SetProperty("productName", self._properties["name"]) if "productName" in self._properties: if "buildConfigurationList" in self._properties: configs = self._properties["buildConfigurationList"] if configs.HasBuildSetting("PRODUCT_NAME") == 0: configs.SetBuildSetting( "PRODUCT_NAME", self._properties["productName"] ) def AddDependency(self, other): pbxproject = self.PBXProjectAncestor() other_pbxproject = other.PBXProjectAncestor() if pbxproject == other_pbxproject: # Add a dependency to another target in the same project file. container = PBXContainerItemProxy( { "containerPortal": pbxproject, "proxyType": 1, "remoteGlobalIDString": other, "remoteInfo": other.Name(), } ) dependency = PBXTargetDependency( {"target": other, "targetProxy": container} ) self.AppendProperty("dependencies", dependency) else: # Add a dependency to a target in a different project file. other_project_ref = pbxproject.AddOrGetProjectReference(other_pbxproject)[1] container = PBXContainerItemProxy( { "containerPortal": other_project_ref, "proxyType": 1, "remoteGlobalIDString": other, "remoteInfo": other.Name(), } ) dependency = PBXTargetDependency( {"name": other.Name(), "targetProxy": container} ) self.AppendProperty("dependencies", dependency) # Proxy all of these through to the build configuration list. def ConfigurationNamed(self, name): return self._properties["buildConfigurationList"].ConfigurationNamed(name) def DefaultConfiguration(self): return self._properties["buildConfigurationList"].DefaultConfiguration() def HasBuildSetting(self, key): return self._properties["buildConfigurationList"].HasBuildSetting(key) def GetBuildSetting(self, key): return self._properties["buildConfigurationList"].GetBuildSetting(key) def SetBuildSetting(self, key, value): return self._properties["buildConfigurationList"].SetBuildSetting(key, value) def AppendBuildSetting(self, key, value): return self._properties["buildConfigurationList"].AppendBuildSetting(key, value) def DelBuildSetting(self, key): return self._properties["buildConfigurationList"].DelBuildSetting(key) # Redefine the type of the "target" property. See PBXTargetDependency._schema # above. PBXTargetDependency._schema["target"][1] = XCTarget class PBXNativeTarget(XCTarget): # buildPhases is overridden in the schema to be able to set defaults. # # NOTE: Contrary to most objects, it is advisable to set parent when # constructing PBXNativeTarget. A parent of an XCTarget must be a PBXProject # object. A parent reference is required for a PBXNativeTarget during # construction to be able to set up the target defaults for productReference, # because a PBXBuildFile object must be created for the target and it must # be added to the PBXProject's mainGroup hierarchy. _schema = XCTarget._schema.copy() _schema.update( { "buildPhases": [ 1, XCBuildPhase, 1, 1, [PBXSourcesBuildPhase(), PBXFrameworksBuildPhase()], ], "buildRules": [1, PBXBuildRule, 1, 1, []], "productReference": [0, PBXFileReference, 0, 1], "productType": [0, str, 0, 1], } ) # Mapping from Xcode product-types to settings. The settings are: # filetype : used for explicitFileType in the project file # prefix : the prefix for the file name # suffix : the suffix for the file name _product_filetypes = { "com.apple.product-type.application": ["wrapper.application", "", ".app"], "com.apple.product-type.application.watchapp": [ "wrapper.application", "", ".app", ], "com.apple.product-type.watchkit-extension": [ "wrapper.app-extension", "", ".appex", ], "com.apple.product-type.app-extension": ["wrapper.app-extension", "", ".appex"], "com.apple.product-type.bundle": ["wrapper.cfbundle", "", ".bundle"], "com.apple.product-type.framework": ["wrapper.framework", "", ".framework"], "com.apple.product-type.library.dynamic": [ "compiled.mach-o.dylib", "lib", ".dylib", ], "com.apple.product-type.library.static": ["archive.ar", "lib", ".a"], "com.apple.product-type.tool": ["compiled.mach-o.executable", "", ""], "com.apple.product-type.bundle.unit-test": ["wrapper.cfbundle", "", ".xctest"], "com.apple.product-type.bundle.ui-testing": ["wrapper.cfbundle", "", ".xctest"], "com.googlecode.gyp.xcode.bundle": ["compiled.mach-o.dylib", "", ".so"], "com.apple.product-type.kernel-extension": ["wrapper.kext", "", ".kext"], } def __init__( self, properties=None, id=None, parent=None, force_outdir=None, force_prefix=None, force_extension=None, ): # super XCTarget.__init__(self, properties, id, parent) if ( "productName" in self._properties and "productType" in self._properties and "productReference" not in self._properties and self._properties["productType"] in self._product_filetypes ): products_group = None pbxproject = self.PBXProjectAncestor() if pbxproject is not None: products_group = pbxproject.ProductsGroup() if products_group is not None: (filetype, prefix, suffix) = self._product_filetypes[ self._properties["productType"] ] # Xcode does not have a distinct type for loadable modules that are # pure BSD targets (not in a bundle wrapper). GYP allows such modules # to be specified by setting a target type to loadable_module without # having mac_bundle set. These are mapped to the pseudo-product type # com.googlecode.gyp.xcode.bundle. # # By picking up this special type and converting it to a dynamic # library (com.apple.product-type.library.dynamic) with fix-ups, # single-file loadable modules can be produced. # # MACH_O_TYPE is changed to mh_bundle to produce the proper file type # (as opposed to mh_dylib). In order for linking to succeed, # DYLIB_CURRENT_VERSION and DYLIB_COMPATIBILITY_VERSION must be # cleared. They are meaningless for type mh_bundle. # # Finally, the .so extension is forcibly applied over the default # (.dylib), unless another forced extension is already selected. # .dylib is plainly wrong, and .bundle is used by loadable_modules in # bundle wrappers (com.apple.product-type.bundle). .so seems an odd # choice because it's used as the extension on many other systems that # don't distinguish between linkable shared libraries and non-linkable # loadable modules, but there's precedent: Python loadable modules on # Mac OS X use an .so extension. if self._properties["productType"] == "com.googlecode.gyp.xcode.bundle": self._properties[ "productType" ] = "com.apple.product-type.library.dynamic" self.SetBuildSetting("MACH_O_TYPE", "mh_bundle") self.SetBuildSetting("DYLIB_CURRENT_VERSION", "") self.SetBuildSetting("DYLIB_COMPATIBILITY_VERSION", "") if force_extension is None: force_extension = suffix[1:] if ( self._properties["productType"] in { "com.apple.product-type-bundle.unit.test", "com.apple.product-type-bundle.ui-testing" } ) and force_extension is None: force_extension = suffix[1:] if force_extension is not None: # If it's a wrapper (bundle), set WRAPPER_EXTENSION. # Extension override. suffix = "." + force_extension if filetype.startswith("wrapper."): self.SetBuildSetting("WRAPPER_EXTENSION", force_extension) else: self.SetBuildSetting("EXECUTABLE_EXTENSION", force_extension) if filetype.startswith("compiled.mach-o.executable"): product_name = self._properties["productName"] product_name += suffix suffix = "" self.SetProperty("productName", product_name) self.SetBuildSetting("PRODUCT_NAME", product_name) # Xcode handles most prefixes based on the target type, however there # are exceptions. If a "BSD Dynamic Library" target is added in the # Xcode UI, Xcode sets EXECUTABLE_PREFIX. This check duplicates that # behavior. if force_prefix is not None: prefix = force_prefix if filetype.startswith("wrapper."): self.SetBuildSetting("WRAPPER_PREFIX", prefix) else: self.SetBuildSetting("EXECUTABLE_PREFIX", prefix) if force_outdir is not None: self.SetBuildSetting("TARGET_BUILD_DIR", force_outdir) # TODO(tvl): Remove the below hack. # http://code.google.com/p/gyp/issues/detail?id=122 # Some targets include the prefix in the target_name. These targets # really should just add a product_name setting that doesn't include # the prefix. For example: # target_name = 'libevent', product_name = 'event' # This check cleans up for them. product_name = self._properties["productName"] prefix_len = len(prefix) if prefix_len and (product_name[:prefix_len] == prefix): product_name = product_name[prefix_len:] self.SetProperty("productName", product_name) self.SetBuildSetting("PRODUCT_NAME", product_name) ref_props = { "explicitFileType": filetype, "includeInIndex": 0, "path": prefix + product_name + suffix, "sourceTree": "BUILT_PRODUCTS_DIR", } file_ref = PBXFileReference(ref_props) products_group.AppendChild(file_ref) self.SetProperty("productReference", file_ref) def GetBuildPhaseByType(self, type): if "buildPhases" not in self._properties: return None the_phase = None for phase in self._properties["buildPhases"]: if isinstance(phase, type): # Some phases may be present in multiples in a well-formed project file, # but phases like PBXSourcesBuildPhase may only be present singly, and # this function is intended as an aid to GetBuildPhaseByType. Loop # over the entire list of phases and assert if more than one of the # desired type is found. assert the_phase is None the_phase = phase return the_phase def HeadersPhase(self): headers_phase = self.GetBuildPhaseByType(PBXHeadersBuildPhase) if headers_phase is None: headers_phase = PBXHeadersBuildPhase() # The headers phase should come before the resources, sources, and # frameworks phases, if any. insert_at = len(self._properties["buildPhases"]) for index, phase in enumerate(self._properties["buildPhases"]): if isinstance( phase, ( PBXResourcesBuildPhase, PBXSourcesBuildPhase, PBXFrameworksBuildPhase, ), ): insert_at = index break self._properties["buildPhases"].insert(insert_at, headers_phase) headers_phase.parent = self return headers_phase def ResourcesPhase(self): resources_phase = self.GetBuildPhaseByType(PBXResourcesBuildPhase) if resources_phase is None: resources_phase = PBXResourcesBuildPhase() # The resources phase should come before the sources and frameworks # phases, if any. insert_at = len(self._properties["buildPhases"]) for index, phase in enumerate(self._properties["buildPhases"]): if isinstance(phase, (PBXSourcesBuildPhase, PBXFrameworksBuildPhase)): insert_at = index break self._properties["buildPhases"].insert(insert_at, resources_phase) resources_phase.parent = self return resources_phase def SourcesPhase(self): sources_phase = self.GetBuildPhaseByType(PBXSourcesBuildPhase) if sources_phase is None: sources_phase = PBXSourcesBuildPhase() self.AppendProperty("buildPhases", sources_phase) return sources_phase def FrameworksPhase(self): frameworks_phase = self.GetBuildPhaseByType(PBXFrameworksBuildPhase) if frameworks_phase is None: frameworks_phase = PBXFrameworksBuildPhase() self.AppendProperty("buildPhases", frameworks_phase) return frameworks_phase def AddDependency(self, other): # super XCTarget.AddDependency(self, other) static_library_type = "com.apple.product-type.library.static" shared_library_type = "com.apple.product-type.library.dynamic" framework_type = "com.apple.product-type.framework" if ( isinstance(other, PBXNativeTarget) and "productType" in self._properties and self._properties["productType"] != static_library_type and "productType" in other._properties and ( other._properties["productType"] == static_library_type or ( ( other._properties["productType"] in { shared_library_type, framework_type } ) and ( (not other.HasBuildSetting("MACH_O_TYPE")) or other.GetBuildSetting("MACH_O_TYPE") != "mh_bundle" ) ) ) ): file_ref = other.GetProperty("productReference") pbxproject = self.PBXProjectAncestor() other_pbxproject = other.PBXProjectAncestor() if pbxproject != other_pbxproject: other_project_product_group = pbxproject.AddOrGetProjectReference( other_pbxproject )[0] file_ref = other_project_product_group.GetChildByRemoteObject(file_ref) self.FrameworksPhase().AppendProperty( "files", PBXBuildFile({"fileRef": file_ref}) ) class PBXAggregateTarget(XCTarget): pass class PBXProject(XCContainerPortal): # A PBXProject is really just an XCObject, the XCContainerPortal thing is # just to allow PBXProject to be used in the containerPortal property of # PBXContainerItemProxy. """ Attributes: path: "sample.xcodeproj". TODO(mark) Document me! _other_pbxprojects: A dictionary, keyed by other PBXProject objects. Each value is a reference to the dict in the projectReferences list associated with the keyed PBXProject. """ _schema = XCContainerPortal._schema.copy() _schema.update( { "attributes": [0, dict, 0, 0], "buildConfigurationList": [ 0, XCConfigurationList, 1, 1, XCConfigurationList(), ], "compatibilityVersion": [0, str, 0, 1, "Xcode 3.2"], "hasScannedForEncodings": [0, int, 0, 1, 1], "mainGroup": [0, PBXGroup, 1, 1, PBXGroup()], "projectDirPath": [0, str, 0, 1, ""], "projectReferences": [1, dict, 0, 0], "projectRoot": [0, str, 0, 1, ""], "targets": [1, XCTarget, 1, 1, []], } ) def __init__(self, properties=None, id=None, parent=None, path=None): self.path = path self._other_pbxprojects = {} # super XCContainerPortal.__init__(self, properties, id, parent) def Name(self): name = self.path if name[-10:] == ".xcodeproj": name = name[:-10] return posixpath.basename(name) def Path(self): return self.path def Comment(self): return "Project object" def Children(self): # super children = XCContainerPortal.Children(self) # Add children that the schema doesn't know about. Maybe there's a more # elegant way around this, but this is the only case where we need to own # objects in a dictionary (that is itself in a list), and three lines for # a one-off isn't that big a deal. if "projectReferences" in self._properties: for reference in self._properties["projectReferences"]: children.append(reference["ProductGroup"]) return children def PBXProjectAncestor(self): return self def _GroupByName(self, name): if "mainGroup" not in self._properties: self.SetProperty("mainGroup", PBXGroup()) main_group = self._properties["mainGroup"] group = main_group.GetChildByName(name) if group is None: group = PBXGroup({"name": name}) main_group.AppendChild(group) return group # SourceGroup and ProductsGroup are created by default in Xcode's own # templates. def SourceGroup(self): return self._GroupByName("Source") def ProductsGroup(self): return self._GroupByName("Products") # IntermediatesGroup is used to collect source-like files that are generated # by rules or script phases and are placed in intermediate directories such # as DerivedSources. def IntermediatesGroup(self): return self._GroupByName("Intermediates") # FrameworksGroup and ProjectsGroup are top-level groups used to collect # frameworks and projects. def FrameworksGroup(self): return self._GroupByName("Frameworks") def ProjectsGroup(self): return self._GroupByName("Projects") def RootGroupForPath(self, path): """Returns a PBXGroup child of this object to which path should be added. This method is intended to choose between SourceGroup and IntermediatesGroup on the basis of whether path is present in a source directory or an intermediates directory. For the purposes of this determination, any path located within a derived file directory such as PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates directory. The returned value is a two-element tuple. The first element is the PBXGroup, and the second element specifies whether that group should be organized hierarchically (True) or as a single flat list (False). """ # TODO(mark): make this a class variable and bind to self on call? # Also, this list is nowhere near exhaustive. # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by # gyp.generator.xcode. There should probably be some way for that module # to push the names in, rather than having to hard-code them here. source_tree_groups = { "DERIVED_FILE_DIR": (self.IntermediatesGroup, True), "INTERMEDIATE_DIR": (self.IntermediatesGroup, True), "PROJECT_DERIVED_FILE_DIR": (self.IntermediatesGroup, True), "SHARED_INTERMEDIATE_DIR": (self.IntermediatesGroup, True), } (source_tree, path) = SourceTreeAndPathFromPath(path) if source_tree is not None and source_tree in source_tree_groups: (group_func, hierarchical) = source_tree_groups[source_tree] group = group_func() return (group, hierarchical) # TODO(mark): make additional choices based on file extension. return (self.SourceGroup(), True) def AddOrGetFileInRootGroup(self, path): """Returns a PBXFileReference corresponding to path in the correct group according to RootGroupForPath's heuristics. If an existing PBXFileReference for path exists, it will be returned. Otherwise, one will be created and returned. """ (group, hierarchical) = self.RootGroupForPath(path) return group.AddOrGetFileByPath(path, hierarchical) def RootGroupsTakeOverOnlyChildren(self, recurse=False): """Calls TakeOverOnlyChild for all groups in the main group.""" for group in self._properties["mainGroup"]._properties["children"]: if isinstance(group, PBXGroup): group.TakeOverOnlyChild(recurse) def SortGroups(self): # Sort the children of the mainGroup (like "Source" and "Products") # according to their defined order. self._properties["mainGroup"]._properties["children"] = sorted( self._properties["mainGroup"]._properties["children"], key=cmp_to_key(lambda x, y: x.CompareRootGroup(y)), ) # Sort everything else by putting group before files, and going # alphabetically by name within sections of groups and files. SortGroup # is recursive. for group in self._properties["mainGroup"]._properties["children"]: if not isinstance(group, PBXGroup): continue if group.Name() == "Products": # The Products group is a special case. Instead of sorting # alphabetically, sort things in the order of the targets that # produce the products. To do this, just build up a new list of # products based on the targets. products = [] for target in self._properties["targets"]: if not isinstance(target, PBXNativeTarget): continue product = target._properties["productReference"] # Make sure that the product is already in the products group. assert product in group._properties["children"] products.append(product) # Make sure that this process doesn't miss anything that was already # in the products group. assert len(products) == len(group._properties["children"]) group._properties["children"] = products else: group.SortGroup() def AddOrGetProjectReference(self, other_pbxproject): """Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary. """ if "projectReferences" not in self._properties: self._properties["projectReferences"] = [] product_group = None project_ref = None if other_pbxproject not in self._other_pbxprojects: # This project file isn't yet linked to the other one. Establish the # link. product_group = PBXGroup({"name": "Products"}) # ProductGroup is strong. product_group.parent = self # There's nothing unique about this PBXGroup, and if left alone, it will # wind up with the same set of hashables as all other PBXGroup objects # owned by the projectReferences list. Add the hashables of the # remote PBXProject that it's related to. product_group._hashables.extend(other_pbxproject.Hashables()) # The other project reports its path as relative to the same directory # that this project's path is relative to. The other project's path # is not necessarily already relative to this project. Figure out the # pathname that this project needs to use to refer to the other one. this_path = posixpath.dirname(self.Path()) projectDirPath = self.GetProperty("projectDirPath") if projectDirPath: if posixpath.isabs(projectDirPath[0]): this_path = projectDirPath else: this_path = posixpath.join(this_path, projectDirPath) other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path) # ProjectRef is weak (it's owned by the mainGroup hierarchy). project_ref = PBXFileReference( { "lastKnownFileType": "wrapper.pb-project", "path": other_path, "sourceTree": "SOURCE_ROOT", } ) self.ProjectsGroup().AppendChild(project_ref) ref_dict = {"ProductGroup": product_group, "ProjectRef": project_ref} self._other_pbxprojects[other_pbxproject] = ref_dict self.AppendProperty("projectReferences", ref_dict) # Xcode seems to sort this list case-insensitively self._properties["projectReferences"] = sorted( self._properties["projectReferences"], key=lambda x: x["ProjectRef"].Name().lower() ) else: # The link already exists. Pull out the relevnt data. project_ref_dict = self._other_pbxprojects[other_pbxproject] product_group = project_ref_dict["ProductGroup"] project_ref = project_ref_dict["ProjectRef"] self._SetUpProductReferences(other_pbxproject, product_group, project_ref) inherit_unique_symroot = self._AllSymrootsUnique(other_pbxproject, False) targets = other_pbxproject.GetProperty("targets") if all(self._AllSymrootsUnique(t, inherit_unique_symroot) for t in targets): dir_path = project_ref._properties["path"] product_group._hashables.extend(dir_path) return [product_group, project_ref] def _AllSymrootsUnique(self, target, inherit_unique_symroot): # Returns True if all configurations have a unique 'SYMROOT' attribute. # The value of inherit_unique_symroot decides, if a configuration is assumed # to inherit a unique 'SYMROOT' attribute from its parent, if it doesn't # define an explicit value for 'SYMROOT'. symroots = self._DefinedSymroots(target) for s in self._DefinedSymroots(target): if ( s is not None and not self._IsUniqueSymrootForTarget(s) or s is None and not inherit_unique_symroot ): return False return True if symroots else inherit_unique_symroot def _DefinedSymroots(self, target): # Returns all values for the 'SYMROOT' attribute defined in all # configurations for this target. If any configuration doesn't define the # 'SYMROOT' attribute, None is added to the returned set. If all # configurations don't define the 'SYMROOT' attribute, an empty set is # returned. config_list = target.GetProperty("buildConfigurationList") symroots = set() for config in config_list.GetProperty("buildConfigurations"): setting = config.GetProperty("buildSettings") if "SYMROOT" in setting: symroots.add(setting["SYMROOT"]) else: symroots.add(None) if len(symroots) == 1 and None in symroots: return set() return symroots def _IsUniqueSymrootForTarget(self, symroot): # This method returns True if all configurations in target contain a # 'SYMROOT' attribute that is unique for the given target. A value is # unique, if the Xcode macro '$SRCROOT' appears in it in any form. uniquifier = ["$SRCROOT", "$(SRCROOT)"] if any(x in symroot for x in uniquifier): return True return False def _SetUpProductReferences(self, other_pbxproject, product_group, project_ref): # TODO(mark): This only adds references to products in other_pbxproject # when they don't exist in this pbxproject. Perhaps it should also # remove references from this pbxproject that are no longer present in # other_pbxproject. Perhaps it should update various properties if they # change. for target in other_pbxproject._properties["targets"]: if not isinstance(target, PBXNativeTarget): continue other_fileref = target._properties["productReference"] if product_group.GetChildByRemoteObject(other_fileref) is None: # Xcode sets remoteInfo to the name of the target and not the name # of its product, despite this proxy being a reference to the product. container_item = PBXContainerItemProxy( { "containerPortal": project_ref, "proxyType": 2, "remoteGlobalIDString": other_fileref, "remoteInfo": target.Name(), } ) # TODO(mark): Does sourceTree get copied straight over from the other # project? Can the other project ever have lastKnownFileType here # instead of explicitFileType? (Use it if so?) Can path ever be # unset? (I don't think so.) Can other_fileref have name set, and # does it impact the PBXReferenceProxy if so? These are the questions # that perhaps will be answered one day. reference_proxy = PBXReferenceProxy( { "fileType": other_fileref._properties["explicitFileType"], "path": other_fileref._properties["path"], "sourceTree": other_fileref._properties["sourceTree"], "remoteRef": container_item, } ) product_group.AppendChild(reference_proxy) def SortRemoteProductReferences(self): # For each remote project file, sort the associated ProductGroup in the # same order that the targets are sorted in the remote project file. This # is the sort order used by Xcode. def CompareProducts(x, y, remote_products): # x and y are PBXReferenceProxy objects. Go through their associated # PBXContainerItem to get the remote PBXFileReference, which will be # present in the remote_products list. x_remote = x._properties["remoteRef"]._properties["remoteGlobalIDString"] y_remote = y._properties["remoteRef"]._properties["remoteGlobalIDString"] x_index = remote_products.index(x_remote) y_index = remote_products.index(y_remote) # Use the order of each remote PBXFileReference in remote_products to # determine the sort order. return cmp(x_index, y_index) for other_pbxproject, ref_dict in self._other_pbxprojects.items(): # Build up a list of products in the remote project file, ordered the # same as the targets that produce them. remote_products = [] for target in other_pbxproject._properties["targets"]: if not isinstance(target, PBXNativeTarget): continue remote_products.append(target._properties["productReference"]) # Sort the PBXReferenceProxy children according to the list of remote # products. product_group = ref_dict["ProductGroup"] product_group._properties["children"] = sorted( product_group._properties["children"], key=cmp_to_key( lambda x, y, rp=remote_products: CompareProducts(x, y, rp)), ) class XCProjectFile(XCObject): _schema = XCObject._schema.copy() _schema.update( { "archiveVersion": [0, int, 0, 1, 1], "classes": [0, dict, 0, 1, {}], "objectVersion": [0, int, 0, 1, 46], "rootObject": [0, PBXProject, 1, 1], } ) def ComputeIDs(self, recursive=True, overwrite=True, hash=None): # Although XCProjectFile is implemented here as an XCObject, it's not a # proper object in the Xcode sense, and it certainly doesn't have its own # ID. Pass through an attempt to update IDs to the real root object. if recursive: self._properties["rootObject"].ComputeIDs(recursive, overwrite, hash) def Print(self, file=sys.stdout): self.VerifyHasRequiredProperties() # Add the special "objects" property, which will be caught and handled # separately during printing. This structure allows a fairly standard # loop do the normal printing. self._properties["objects"] = {} self._XCPrint(file, 0, "// !$*UTF8*$!\n") if self._should_print_single_line: self._XCPrint(file, 0, "{ ") else: self._XCPrint(file, 0, "{\n") for property, value in sorted( self._properties.items() ): if property == "objects": self._PrintObjects(file) else: self._XCKVPrint(file, 1, property, value) self._XCPrint(file, 0, "}\n") del self._properties["objects"] def _PrintObjects(self, file): if self._should_print_single_line: self._XCPrint(file, 0, "objects = {") else: self._XCPrint(file, 1, "objects = {\n") objects_by_class = {} for object in self.Descendants(): if object == self: continue class_name = object.__class__.__name__ if class_name not in objects_by_class: objects_by_class[class_name] = [] objects_by_class[class_name].append(object) for class_name in sorted(objects_by_class): self._XCPrint(file, 0, "\n") self._XCPrint(file, 0, "/* Begin " + class_name + " section */\n") for object in sorted( objects_by_class[class_name], key=attrgetter("id") ): object.Print(file) self._XCPrint(file, 0, "/* End " + class_name + " section */\n") if self._should_print_single_line: self._XCPrint(file, 0, "}; ") else: self._XCPrint(file, 1, "};\n") # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Applies a fix to CR LF TAB handling in xml.dom. Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293 Working around this: http://bugs.python.org/issue5752 TODO(bradnelson): Consider dropping this when we drop XP support. """ import xml.dom.minidom def _Replacement_write_data(writer, data, is_attrib=False): """Writes datachars to writer.""" data = data.replace("&", "&").replace("<", "<") data = data.replace('"', """).replace(">", ">") if is_attrib: data = data.replace("\r", " ").replace("\n", " ").replace("\t", " ") writer.write(data) def _Replacement_writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent + "<" + self.tagName) attrs = self._get_attributes() a_names = sorted(attrs.keys()) for a_name in a_names: writer.write(' %s="' % a_name) _Replacement_write_data(writer, attrs[a_name].value, is_attrib=True) writer.write('"') if self.childNodes: writer.write(">%s" % newl) for node in self.childNodes: node.writexml(writer, indent + addindent, addindent, newl) writer.write(f"{indent}{newl}") else: writer.write("/>%s" % newl) class XmlFix: """Object to manage temporary patching of xml.dom.minidom.""" def __init__(self): # Preserve current xml.dom.minidom functions. self.write_data = xml.dom.minidom._write_data self.writexml = xml.dom.minidom.Element.writexml # Inject replacement versions of a function and a method. xml.dom.minidom._write_data = _Replacement_write_data xml.dom.minidom.Element.writexml = _Replacement_writexml def Cleanup(self): if self.write_data: xml.dom.minidom._write_data = self.write_data xml.dom.minidom.Element.writexml = self.writexml self.write_data = None def __del__(self): self.Cleanup() This software is made available under the terms of *either* of the licenses found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made under the terms of *both* these licenses. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 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 (50%) 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. 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 Copyright (c) Donald Stufft and individual 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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. __title__ = "packaging" __summary__ = "Core utilities for Python packages" __uri__ = "https://github.com/pypa/packaging" __version__ = "23.3.dev0" __author__ = "Donald Stufft and individual contributors" __email__ = "donald@stufft.io" __license__ = "BSD-2-Clause or Apache-2.0" __copyright__ = "2014 %s" % __author__ """ ELF file parser. This provides a class ``ELFFile`` that parses an ELF executable in a similar interface to ``ZipFile``. Only the read interface is implemented. Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html """ import enum import os import struct from typing import IO, Optional, Tuple class ELFInvalid(ValueError): pass class EIClass(enum.IntEnum): C32 = 1 C64 = 2 class EIData(enum.IntEnum): Lsb = 1 Msb = 2 class EMachine(enum.IntEnum): I386 = 3 S390 = 22 Arm = 40 X8664 = 62 AArc64 = 183 class ELFFile: """ Representation of an ELF executable. """ def __init__(self, f: IO[bytes]) -> None: self._f = f try: ident = self._read("16B") except struct.error: raise ELFInvalid("unable to parse identification") magic = bytes(ident[:4]) if magic != b"\x7fELF": raise ELFInvalid(f"invalid magic: {magic!r}") self.capacity = ident[4] # Format for program header (bitness). self.encoding = ident[5] # Data structure encoding (endianness). try: # e_fmt: Format for program header. # p_fmt: Format for section header. # p_idx: Indexes to find p_type, p_offset, and p_filesz. e_fmt, self._p_fmt, self._p_idx = { (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. }[(self.capacity, self.encoding)] except KeyError: raise ELFInvalid( f"unrecognized capacity ({self.capacity}) or " f"encoding ({self.encoding})" ) try: ( _, self.machine, # Architecture type. _, _, self._e_phoff, # Offset of program header. _, self.flags, # Processor-specific flags. _, self._e_phentsize, # Size of section. self._e_phnum, # Number of sections. ) = self._read(e_fmt) except struct.error as e: raise ELFInvalid("unable to parse machine and section information") from e def _read(self, fmt: str) -> Tuple[int, ...]: return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) @property def interpreter(self) -> Optional[str]: """ The path recorded in the ``PT_INTERP`` section header. """ for index in range(self._e_phnum): self._f.seek(self._e_phoff + self._e_phentsize * index) try: data = self._read(self._p_fmt) except struct.error: continue if data[self._p_idx[0]] != 3: # Not PT_INTERP. continue self._f.seek(data[self._p_idx[1]]) return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") return None import collections import contextlib import functools import os import re import sys import warnings from typing import Dict, Generator, Iterator, NamedTuple, Optional, Sequence, Tuple from ._elffile import EIClass, EIData, ELFFile, EMachine EF_ARM_ABIMASK = 0xFF000000 EF_ARM_ABI_VER5 = 0x05000000 EF_ARM_ABI_FLOAT_HARD = 0x00000400 # `os.PathLike` not a generic type until Python 3.9, so sticking with `str` # as the type for `path` until then. @contextlib.contextmanager def _parse_elf(path: str) -> Generator[Optional[ELFFile], None, None]: try: with open(path, "rb") as f: yield ELFFile(f) except (OSError, TypeError, ValueError): yield None def _is_linux_armhf(executable: str) -> bool: # hard-float ABI can be detected from the ELF header of the running # process # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf with _parse_elf(executable) as f: return ( f is not None and f.capacity == EIClass.C32 and f.encoding == EIData.Lsb and f.machine == EMachine.Arm and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD ) def _is_linux_i686(executable: str) -> bool: with _parse_elf(executable) as f: return ( f is not None and f.capacity == EIClass.C32 and f.encoding == EIData.Lsb and f.machine == EMachine.I386 ) def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: if "armv7l" in archs: return _is_linux_armhf(executable) if "i686" in archs: return _is_linux_i686(executable) allowed_archs = {"x86_64", "aarch64", "ppc64", "ppc64le", "s390x", "loongarch64"} return any(arch in allowed_archs for arch in archs) # If glibc ever changes its major version, we need to know what the last # minor version was, so we can build the complete list of all versions. # For now, guess what the highest minor version might be, assume it will # be 50 for testing. Once this actually happens, update the dictionary # with the actual value. _LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50) class _GLibCVersion(NamedTuple): major: int minor: int def _glibc_version_string_confstr() -> Optional[str]: """ Primary implementation of glibc_version_string using os.confstr. """ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely # to be broken or missing. This strategy is used in the standard library # platform module. # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 try: # Should be a string like "glibc 2.17". version_string: str = getattr(os, "confstr")("CS_GNU_LIBC_VERSION") assert version_string is not None _, version = version_string.rsplit() except (AssertionError, AttributeError, OSError, ValueError): # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... return None return version def _glibc_version_string_ctypes() -> Optional[str]: """ Fallback implementation of glibc_version_string using ctypes. """ try: import ctypes except ImportError: return None # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure out # which libc our process is actually using. # # We must also handle the special case where the executable is not a # dynamically linked executable. This can occur when using musl libc, # for example. In this situation, dlopen() will error, leading to an # OSError. Interestingly, at least in the case of musl, there is no # errno set on the OSError. The single string argument used to construct # OSError comes from libc itself and is therefore not portable to # hard code here. In any case, failure to call dlopen() means we # can proceed, so we bail on our attempt. try: process_namespace = ctypes.CDLL(None) except OSError: return None try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: # Symbol doesn't exist -> therefore, we are not linked to # glibc. return None # Call gnu_get_libc_version, which returns a string like "2.5" gnu_get_libc_version.restype = ctypes.c_char_p version_str: str = gnu_get_libc_version() # py2 / py3 compatibility: if not isinstance(version_str, str): version_str = version_str.decode("ascii") return version_str def _glibc_version_string() -> Optional[str]: """Returns glibc version string, or None if not using glibc.""" return _glibc_version_string_confstr() or _glibc_version_string_ctypes() def _parse_glibc_version(version_str: str) -> Tuple[int, int]: """Parse glibc version. We use a regexp instead of str.split because we want to discard any random junk that might come after the minor version -- this might happen in patched/forked versions of glibc (e.g. Linaro's version of glibc uses version strings like "2.20-2014.11"). See gh-3588. """ m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str) if not m: warnings.warn( f"Expected glibc version with 2 components major.minor," f" got: {version_str}", RuntimeWarning, ) return -1, -1 return int(m.group("major")), int(m.group("minor")) @functools.lru_cache() def _get_glibc_version() -> Tuple[int, int]: version_str = _glibc_version_string() if version_str is None: return (-1, -1) return _parse_glibc_version(version_str) # From PEP 513, PEP 600 def _is_compatible(arch: str, version: _GLibCVersion) -> bool: sys_glibc = _get_glibc_version() if sys_glibc < version: return False # Check for presence of _manylinux module. try: import _manylinux # noqa except ImportError: return True if hasattr(_manylinux, "manylinux_compatible"): result = _manylinux.manylinux_compatible(version[0], version[1], arch) if result is not None: return bool(result) return True if version == _GLibCVersion(2, 5): if hasattr(_manylinux, "manylinux1_compatible"): return bool(_manylinux.manylinux1_compatible) if version == _GLibCVersion(2, 12): if hasattr(_manylinux, "manylinux2010_compatible"): return bool(_manylinux.manylinux2010_compatible) if version == _GLibCVersion(2, 17): if hasattr(_manylinux, "manylinux2014_compatible"): return bool(_manylinux.manylinux2014_compatible) return True _LEGACY_MANYLINUX_MAP = { # CentOS 7 w/ glibc 2.17 (PEP 599) (2, 17): "manylinux2014", # CentOS 6 w/ glibc 2.12 (PEP 571) (2, 12): "manylinux2010", # CentOS 5 w/ glibc 2.5 (PEP 513) (2, 5): "manylinux1", } def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate manylinux tags compatible to the current platform. :param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be manylinux-compatible. :returns: An iterator of compatible manylinux tags. """ if not _have_compatible_abi(sys.executable, archs): return # Oldest glibc to be supported regardless of architecture is (2, 17). too_old_glibc2 = _GLibCVersion(2, 16) if set(archs) & {"x86_64", "i686"}: # On x86/i686 also oldest glibc to be supported is (2, 5). too_old_glibc2 = _GLibCVersion(2, 4) current_glibc = _GLibCVersion(*_get_glibc_version()) glibc_max_list = [current_glibc] # We can assume compatibility across glibc major versions. # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 # # Build a list of maximum glibc versions so that we can # output the canonical list of all glibc from current_glibc # down to too_old_glibc2, including all intermediary versions. for glibc_major in range(current_glibc.major - 1, 1, -1): glibc_minor = _LAST_GLIBC_MINOR[glibc_major] glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) for arch in archs: for glibc_max in glibc_max_list: if glibc_max.major == too_old_glibc2.major: min_minor = too_old_glibc2.minor else: # For other glibc major versions oldest supported is (x, 0). min_minor = -1 for glibc_minor in range(glibc_max.minor, min_minor, -1): glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) tag = "manylinux_{}_{}".format(*glibc_version) if _is_compatible(arch, glibc_version): yield f"{tag}_{arch}" # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. if glibc_version in _LEGACY_MANYLINUX_MAP: legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version] if _is_compatible(arch, glibc_version): yield f"{legacy_tag}_{arch}" """PEP 656 support. This module implements logic to detect if the currently running Python is linked against musl, and what musl version is used. """ import functools import re import subprocess import sys from typing import Iterator, NamedTuple, Optional, Sequence from ._elffile import ELFFile class _MuslVersion(NamedTuple): major: int minor: int def _parse_musl_version(output: str) -> Optional[_MuslVersion]: lines = [n for n in (n.strip() for n in output.splitlines()) if n] if len(lines) < 2 or lines[0][:4] != "musl": return None m = re.match(r"Version (\d+)\.(\d+)", lines[1]) if not m: return None return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) @functools.lru_cache() def _get_musl_version(executable: str) -> Optional[_MuslVersion]: """Detect currently-running musl runtime version. This is done by checking the specified executable's dynamic linking information, and invoking the loader to parse its output for a version string. If the loader is musl, the output would be something like:: musl libc (x86_64) Version 1.2.2 Dynamic Program Loader """ try: with open(executable, "rb") as f: ld = ELFFile(f).interpreter except (OSError, TypeError, ValueError): return None if ld is None or "musl" not in ld: return None proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True) return _parse_musl_version(proc.stderr) def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate musllinux tags compatible to the current platform. :param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be musllinux-compatible. :returns: An iterator of compatible musllinux tags. """ sys_musl = _get_musl_version(sys.executable) if sys_musl is None: # Python not dynamically linked against musl. return for arch in archs: for minor in range(sys_musl.minor, -1, -1): yield f"musllinux_{sys_musl.major}_{minor}_{arch}" if __name__ == "__main__": # pragma: no cover import sysconfig plat = sysconfig.get_platform() assert plat.startswith("linux-"), "not linux" print("plat:", plat) print("musl:", _get_musl_version(sys.executable)) print("tags:", end=" ") for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])): print(t, end="\n ") """Handwritten parser of dependency specifiers. The docstring for each __parse_* function contains ENBF-inspired grammar representing the implementation. """ import ast from typing import Any, List, NamedTuple, Optional, Tuple, Union from ._tokenizer import DEFAULT_RULES, Tokenizer class Node: def __init__(self, value: str) -> None: self.value = value def __str__(self) -> str: return self.value def __repr__(self) -> str: return f"<{self.__class__.__name__}('{self}')>" def serialize(self) -> str: raise NotImplementedError class Variable(Node): def serialize(self) -> str: return str(self) class Value(Node): def serialize(self) -> str: return f'"{self}"' class Op(Node): def serialize(self) -> str: return str(self) MarkerVar = Union[Variable, Value] MarkerItem = Tuple[MarkerVar, Op, MarkerVar] # MarkerAtom = Union[MarkerItem, List["MarkerAtom"]] # MarkerList = List[Union["MarkerList", MarkerAtom, str]] # mypy does not support recursive type definition # https://github.com/python/mypy/issues/731 MarkerAtom = Any MarkerList = List[Any] class ParsedRequirement(NamedTuple): name: str url: str extras: List[str] specifier: str marker: Optional[MarkerList] # -------------------------------------------------------------------------------------- # Recursive descent parser for dependency specifier # -------------------------------------------------------------------------------------- def parse_requirement(source: str) -> ParsedRequirement: return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: """ requirement = WS? IDENTIFIER WS? extras WS? requirement_details """ tokenizer.consume("WS") name_token = tokenizer.expect( "IDENTIFIER", expected="package name at the start of dependency specifier" ) name = name_token.text tokenizer.consume("WS") extras = _parse_extras(tokenizer) tokenizer.consume("WS") url, specifier, marker = _parse_requirement_details(tokenizer) tokenizer.expect("END", expected="end of dependency specifier") return ParsedRequirement(name, url, extras, specifier, marker) def _parse_requirement_details( tokenizer: Tokenizer, ) -> Tuple[str, str, Optional[MarkerList]]: """ requirement_details = AT URL (WS requirement_marker?)? | specifier WS? (requirement_marker)? """ specifier = "" url = "" marker = None if tokenizer.check("AT"): tokenizer.read() tokenizer.consume("WS") url_start = tokenizer.position url = tokenizer.expect("URL", expected="URL after @").text if tokenizer.check("END", peek=True): return (url, specifier, marker) tokenizer.expect("WS", expected="whitespace after URL") # The input might end after whitespace. if tokenizer.check("END", peek=True): return (url, specifier, marker) marker = _parse_requirement_marker( tokenizer, span_start=url_start, after="URL and whitespace" ) else: specifier_start = tokenizer.position specifier = _parse_specifier(tokenizer) tokenizer.consume("WS") if tokenizer.check("END", peek=True): return (url, specifier, marker) marker = _parse_requirement_marker( tokenizer, span_start=specifier_start, after=( "version specifier" if specifier else "name and no valid version specifier" ), ) return (url, specifier, marker) def _parse_requirement_marker( tokenizer: Tokenizer, *, span_start: int, after: str ) -> MarkerList: """ requirement_marker = SEMICOLON marker WS? """ if not tokenizer.check("SEMICOLON"): tokenizer.raise_syntax_error( f"Expected end or semicolon (after {after})", span_start=span_start, ) tokenizer.read() marker = _parse_marker(tokenizer) tokenizer.consume("WS") return marker def _parse_extras(tokenizer: Tokenizer) -> List[str]: """ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? """ if not tokenizer.check("LEFT_BRACKET", peek=True): return [] with tokenizer.enclosing_tokens( "LEFT_BRACKET", "RIGHT_BRACKET", around="extras", ): tokenizer.consume("WS") extras = _parse_extras_list(tokenizer) tokenizer.consume("WS") return extras def _parse_extras_list(tokenizer: Tokenizer) -> List[str]: """ extras_list = identifier (wsp* ',' wsp* identifier)* """ extras: List[str] = [] if not tokenizer.check("IDENTIFIER"): return extras extras.append(tokenizer.read().text) while True: tokenizer.consume("WS") if tokenizer.check("IDENTIFIER", peek=True): tokenizer.raise_syntax_error("Expected comma between extra names") elif not tokenizer.check("COMMA"): break tokenizer.read() tokenizer.consume("WS") extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") extras.append(extra_token.text) return extras def _parse_specifier(tokenizer: Tokenizer) -> str: """ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS | WS? version_many WS? """ with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="version specifier", ): tokenizer.consume("WS") parsed_specifiers = _parse_version_many(tokenizer) tokenizer.consume("WS") return parsed_specifiers def _parse_version_many(tokenizer: Tokenizer) -> str: """ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? """ parsed_specifiers = "" while tokenizer.check("SPECIFIER"): span_start = tokenizer.position parsed_specifiers += tokenizer.read().text if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): tokenizer.raise_syntax_error( ".* suffix can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position + 1, ) if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): tokenizer.raise_syntax_error( "Local version label can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position, ) tokenizer.consume("WS") if not tokenizer.check("COMMA"): break parsed_specifiers += tokenizer.read().text tokenizer.consume("WS") return parsed_specifiers # -------------------------------------------------------------------------------------- # Recursive descent parser for marker expression # -------------------------------------------------------------------------------------- def parse_marker(source: str) -> MarkerList: return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: retval = _parse_marker(tokenizer) tokenizer.expect("END", expected="end of marker expression") return retval def _parse_marker(tokenizer: Tokenizer) -> MarkerList: """ marker = marker_atom (BOOLOP marker_atom)+ """ expression = [_parse_marker_atom(tokenizer)] while tokenizer.check("BOOLOP"): token = tokenizer.read() expr_right = _parse_marker_atom(tokenizer) expression.extend((token.text, expr_right)) return expression def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: """ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? | WS? marker_item WS? """ tokenizer.consume("WS") if tokenizer.check("LEFT_PARENTHESIS", peek=True): with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="marker expression", ): tokenizer.consume("WS") marker: MarkerAtom = _parse_marker(tokenizer) tokenizer.consume("WS") else: marker = _parse_marker_item(tokenizer) tokenizer.consume("WS") return marker def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: """ marker_item = WS? marker_var WS? marker_op WS? marker_var WS? """ tokenizer.consume("WS") marker_var_left = _parse_marker_var(tokenizer) tokenizer.consume("WS") marker_op = _parse_marker_op(tokenizer) tokenizer.consume("WS") marker_var_right = _parse_marker_var(tokenizer) tokenizer.consume("WS") return (marker_var_left, marker_op, marker_var_right) def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: """ marker_var = VARIABLE | QUOTED_STRING """ if tokenizer.check("VARIABLE"): return process_env_var(tokenizer.read().text.replace(".", "_")) elif tokenizer.check("QUOTED_STRING"): return process_python_str(tokenizer.read().text) else: tokenizer.raise_syntax_error( message="Expected a marker variable or quoted string" ) def process_env_var(env_var: str) -> Variable: if ( env_var == "platform_python_implementation" or env_var == "python_implementation" ): return Variable("platform_python_implementation") else: return Variable(env_var) def process_python_str(python_str: str) -> Value: value = ast.literal_eval(python_str) return Value(str(value)) def _parse_marker_op(tokenizer: Tokenizer) -> Op: """ marker_op = IN | NOT IN | OP """ if tokenizer.check("IN"): tokenizer.read() return Op("in") elif tokenizer.check("NOT"): tokenizer.read() tokenizer.expect("WS", expected="whitespace after 'not'") tokenizer.expect("IN", expected="'in' after 'not'") return Op("not in") elif tokenizer.check("OP"): return Op(tokenizer.read().text) else: return tokenizer.raise_syntax_error( "Expected marker operator, one of " "<=, <, !=, ==, >=, >, ~=, ===, in, not in" ) # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. class InfinityType: def __repr__(self) -> str: return "Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return False def __le__(self, other: object) -> bool: return False def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__) def __gt__(self, other: object) -> bool: return True def __ge__(self, other: object) -> bool: return True def __neg__(self: object) -> "NegativeInfinityType": return NegativeInfinity Infinity = InfinityType() class NegativeInfinityType: def __repr__(self) -> str: return "-Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return True def __le__(self, other: object) -> bool: return True def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__) def __gt__(self, other: object) -> bool: return False def __ge__(self, other: object) -> bool: return False def __neg__(self: object) -> InfinityType: return Infinity NegativeInfinity = NegativeInfinityType() import contextlib import re from dataclasses import dataclass from typing import Dict, Iterator, NoReturn, Optional, Tuple, Union from .specifiers import Specifier @dataclass class Token: name: str text: str position: int class ParserSyntaxError(Exception): """The provided source text could not be parsed correctly.""" def __init__( self, message: str, *, source: str, span: Tuple[int, int], ) -> None: self.span = span self.message = message self.source = source super().__init__() def __str__(self) -> str: marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" return "\n ".join([self.message, self.source, marker]) DEFAULT_RULES: "Dict[str, Union[str, re.Pattern[str]]]" = { "LEFT_PARENTHESIS": r"\(", "RIGHT_PARENTHESIS": r"\)", "LEFT_BRACKET": r"\[", "RIGHT_BRACKET": r"\]", "SEMICOLON": r";", "COMMA": r",", "QUOTED_STRING": re.compile( r""" ( ('[^']*') | ("[^"]*") ) """, re.VERBOSE, ), "OP": r"(===|==|~=|!=|<=|>=|<|>)", "BOOLOP": r"\b(or|and)\b", "IN": r"\bin\b", "NOT": r"\bnot\b", "VARIABLE": re.compile( r""" \b( python_version |python_full_version |os[._]name |sys[._]platform |platform_(release|system) |platform[._](version|machine|python_implementation) |python_implementation |implementation_(name|version) |extra )\b """, re.VERBOSE, ), "SPECIFIER": re.compile( Specifier._operator_regex_str + Specifier._version_regex_str, re.VERBOSE | re.IGNORECASE, ), "AT": r"\@", "URL": r"[^ \t]+", "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b", "VERSION_PREFIX_TRAIL": r"\.\*", "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*", "WS": r"[ \t]+", "END": r"$", } class Tokenizer: """Context-sensitive token parsing. Provides methods to examine the input stream to check whether the next token matches. """ def __init__( self, source: str, *, rules: "Dict[str, Union[str, re.Pattern[str]]]", ) -> None: self.source = source self.rules: Dict[str, re.Pattern[str]] = { name: re.compile(pattern) for name, pattern in rules.items() } self.next_token: Optional[Token] = None self.position = 0 def consume(self, name: str) -> None: """Move beyond provided token name, if at current position.""" if self.check(name): self.read() def check(self, name: str, *, peek: bool = False) -> bool: """Check whether the next token has the provided name. By default, if the check succeeds, the token *must* be read before another check. If `peek` is set to `True`, the token is not loaded and would need to be checked again. """ assert ( self.next_token is None ), f"Cannot check for {name!r}, already have {self.next_token!r}" assert name in self.rules, f"Unknown token name: {name!r}" expression = self.rules[name] match = expression.match(self.source, self.position) if match is None: return False if not peek: self.next_token = Token(name, match[0], self.position) return True def expect(self, name: str, *, expected: str) -> Token: """Expect a certain token name next, failing with a syntax error otherwise. The token is *not* read. """ if not self.check(name): raise self.raise_syntax_error(f"Expected {expected}") return self.read() def read(self) -> Token: """Consume the next token and return it.""" token = self.next_token assert token is not None self.position += len(token.text) self.next_token = None return token def raise_syntax_error( self, message: str, *, span_start: Optional[int] = None, span_end: Optional[int] = None, ) -> NoReturn: """Raise ParserSyntaxError at the given position.""" span = ( self.position if span_start is None else span_start, self.position if span_end is None else span_end, ) raise ParserSyntaxError( message, source=self.source, span=span, ) @contextlib.contextmanager def enclosing_tokens( self, open_token: str, close_token: str, *, around: str ) -> Iterator[None]: if self.check(open_token): open_position = self.position self.read() else: open_position = None yield if open_position is None: return if not self.check(close_token): self.raise_syntax_error( f"Expected matching {close_token} for {open_token}, after {around}", span_start=open_position, ) self.read() # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import operator import os import platform import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from ._parser import ( MarkerAtom, MarkerList, Op, Value, Variable, parse_marker as _parse_marker, ) from ._tokenizer import ParserSyntaxError from .specifiers import InvalidSpecifier, Specifier from .utils import canonicalize_name __all__ = [ "InvalidMarker", "UndefinedComparison", "UndefinedEnvironmentName", "Marker", "default_environment", ] Operator = Callable[[str, str], bool] class InvalidMarker(ValueError): """ An invalid marker was found, users should refer to PEP 508. """ class UndefinedComparison(ValueError): """ An invalid operation was attempted on a value that doesn't support it. """ class UndefinedEnvironmentName(ValueError): """ A name was attempted to be used that does not exist inside of the environment. """ def _normalize_extra_values(results: Any) -> Any: """ Normalize extra values. """ if isinstance(results[0], tuple): lhs, op, rhs = results[0] if isinstance(lhs, Variable) and lhs.value == "extra": normalized_extra = canonicalize_name(rhs.value) rhs = Value(normalized_extra) elif isinstance(rhs, Variable) and rhs.value == "extra": normalized_extra = canonicalize_name(lhs.value) lhs = Value(normalized_extra) results[0] = lhs, op, rhs return results def _format_marker( marker: Union[List[str], MarkerAtom, str], first: Optional[bool] = True ) -> str: assert isinstance(marker, (list, tuple, str)) # Sometimes we have a structure like [[...]] which is a single item list # where the single item is itself it's own list. In that case we want skip # the rest of this function so that we don't get extraneous () on the # outside. if ( isinstance(marker, list) and len(marker) == 1 and isinstance(marker[0], (list, tuple)) ): return _format_marker(marker[0]) if isinstance(marker, list): inner = (_format_marker(m, first=False) for m in marker) if first: return " ".join(inner) else: return "(" + " ".join(inner) + ")" elif isinstance(marker, tuple): return " ".join([m.serialize() for m in marker]) else: return marker _operators: Dict[str, Operator] = { "in": lambda lhs, rhs: lhs in rhs, "not in": lambda lhs, rhs: lhs not in rhs, "<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, ">": operator.gt, } def _eval_op(lhs: str, op: Op, rhs: str) -> bool: try: spec = Specifier("".join([op.serialize(), rhs])) except InvalidSpecifier: pass else: return spec.contains(lhs, prereleases=True) oper: Optional[Operator] = _operators.get(op.serialize()) if oper is None: raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") return oper(lhs, rhs) def _normalize(*values: str, key: str) -> Tuple[str, ...]: # PEP 685 – Comparison of extra names for optional distribution dependencies # https://peps.python.org/pep-0685/ # > When comparing extra names, tools MUST normalize the names being # > compared using the semantics outlined in PEP 503 for names if key == "extra": return tuple(canonicalize_name(v) for v in values) # other environment markers don't have such standards return values def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool: groups: List[List[bool]] = [[]] for marker in markers: assert isinstance(marker, (list, tuple, str)) if isinstance(marker, list): groups[-1].append(_evaluate_markers(marker, environment)) elif isinstance(marker, tuple): lhs, op, rhs = marker if isinstance(lhs, Variable): environment_key = lhs.value lhs_value = environment[environment_key] rhs_value = rhs.value else: lhs_value = lhs.value environment_key = rhs.value rhs_value = environment[environment_key] lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) groups[-1].append(_eval_op(lhs_value, op, rhs_value)) else: assert marker in ["and", "or"] if marker == "or": groups.append([]) return any(all(item) for item in groups) def format_full_version(info: "sys._version_info") -> str: version = "{0.major}.{0.minor}.{0.micro}".format(info) kind = info.releaselevel if kind != "final": version += kind[0] + str(info.serial) return version def default_environment() -> Dict[str, str]: iver = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name return { "implementation_name": implementation_name, "implementation_version": iver, "os_name": os.name, "platform_machine": platform.machine(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "platform_python_implementation": platform.python_implementation(), "python_version": ".".join(platform.python_version_tuple()[:2]), "sys_platform": sys.platform, } class Marker: def __init__(self, marker: str) -> None: # Note: We create a Marker object without calling this constructor in # packaging.requirements.Requirement. If any additional logic is # added here, make sure to mirror/adapt Requirement. try: self._markers = _normalize_extra_values(_parse_marker(marker)) # The attribute `_markers` can be described in terms of a recursive type: # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] # # For example, the following expression: # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") # # is parsed into: # [ # (, ')>, ), # 'and', # [ # (, , ), # 'or', # (, , ) # ] # ] except ParserSyntaxError as e: raise InvalidMarker(str(e)) from e def __str__(self) -> str: return _format_marker(self._markers) def __repr__(self) -> str: return f"" def __hash__(self) -> int: return hash((self.__class__.__name__, str(self))) def __eq__(self, other: Any) -> bool: if not isinstance(other, Marker): return NotImplemented return str(self) == str(other) def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool: """Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Python process. """ current_environment = default_environment() current_environment["extra"] = "" if environment is not None: current_environment.update(environment) # The API used to allow setting extra to None. We need to handle this # case for backwards compatibility. if current_environment["extra"] is None: current_environment["extra"] = "" return _evaluate_markers(self._markers, current_environment) import email.feedparser import email.header import email.message import email.parser import email.policy import sys import typing from typing import ( Any, Callable, Dict, Generic, List, Optional, Tuple, Type, Union, cast, ) from . import requirements, specifiers, utils, version as version_module T = typing.TypeVar("T") if sys.version_info[:2] >= (3, 8): # pragma: no cover from typing import Literal, TypedDict else: # pragma: no cover if typing.TYPE_CHECKING: from typing_extensions import Literal, TypedDict else: try: from typing_extensions import Literal, TypedDict except ImportError: class Literal: def __init_subclass__(*_args, **_kwargs): pass class TypedDict: def __init_subclass__(*_args, **_kwargs): pass try: ExceptionGroup except NameError: # pragma: no cover class ExceptionGroup(Exception): # noqa: N818 """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. If :external:exc:`ExceptionGroup` is already defined by Python itself, that version is used instead. """ message: str exceptions: List[Exception] def __init__(self, message: str, exceptions: List[Exception]) -> None: self.message = message self.exceptions = exceptions def __repr__(self) -> str: return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" else: # pragma: no cover ExceptionGroup = ExceptionGroup class InvalidMetadata(ValueError): """A metadata field contains invalid data.""" field: str """The name of the field that contains invalid data.""" def __init__(self, field: str, message: str) -> None: self.field = field super().__init__(message) # The RawMetadata class attempts to make as few assumptions about the underlying # serialization formats as possible. The idea is that as long as a serialization # formats offer some very basic primitives in *some* way then we can support # serializing to and from that format. class RawMetadata(TypedDict, total=False): """A dictionary of raw core metadata. Each field in core metadata maps to a key of this dictionary (when data is provided). The key is lower-case and underscores are used instead of dashes compared to the equivalent core metadata field. Any core metadata field that can be specified multiple times or can hold multiple values in a single field have a key with a plural name. See :class:`Metadata` whose attributes match the keys of this dictionary. Core metadata fields that can be specified multiple times are stored as a list or dict depending on which is appropriate for the field. Any fields which hold multiple values in a single field are stored as a list. """ # Metadata 1.0 - PEP 241 metadata_version: str name: str version: str platforms: List[str] summary: str description: str keywords: List[str] home_page: str author: str author_email: str license: str # Metadata 1.1 - PEP 314 supported_platforms: List[str] download_url: str classifiers: List[str] requires: List[str] provides: List[str] obsoletes: List[str] # Metadata 1.2 - PEP 345 maintainer: str maintainer_email: str requires_dist: List[str] provides_dist: List[str] obsoletes_dist: List[str] requires_python: str requires_external: List[str] project_urls: Dict[str, str] # Metadata 2.0 # PEP 426 attempted to completely revamp the metadata format # but got stuck without ever being able to build consensus on # it and ultimately ended up withdrawn. # # However, a number of tools had started emitting METADATA with # `2.0` Metadata-Version, so for historical reasons, this version # was skipped. # Metadata 2.1 - PEP 566 description_content_type: str provides_extra: List[str] # Metadata 2.2 - PEP 643 dynamic: List[str] # Metadata 2.3 - PEP 685 # No new fields were added in PEP 685, just some edge case were # tightened up to provide better interoptability. _STRING_FIELDS = { "author", "author_email", "description", "description_content_type", "download_url", "home_page", "license", "maintainer", "maintainer_email", "metadata_version", "name", "requires_python", "summary", "version", } _LIST_FIELDS = { "classifiers", "dynamic", "obsoletes", "obsoletes_dist", "platforms", "provides", "provides_dist", "provides_extra", "requires", "requires_dist", "requires_external", "supported_platforms", } _DICT_FIELDS = { "project_urls", } def _parse_keywords(data: str) -> List[str]: """Split a string of comma-separate keyboards into a list of keywords.""" return [k.strip() for k in data.split(",")] def _parse_project_urls(data: List[str]) -> Dict[str, str]: """Parse a list of label/URL string pairings separated by a comma.""" urls = {} for pair in data: # Our logic is slightly tricky here as we want to try and do # *something* reasonable with malformed data. # # The main thing that we have to worry about, is data that does # not have a ',' at all to split the label from the Value. There # isn't a singular right answer here, and we will fail validation # later on (if the caller is validating) so it doesn't *really* # matter, but since the missing value has to be an empty str # and our return value is dict[str, str], if we let the key # be the missing value, then they'd have multiple '' values that # overwrite each other in a accumulating dict. # # The other potentional issue is that it's possible to have the # same label multiple times in the metadata, with no solid "right" # answer with what to do in that case. As such, we'll do the only # thing we can, which is treat the field as unparseable and add it # to our list of unparsed fields. parts = [p.strip() for p in pair.split(",", 1)] parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items # TODO: The spec doesn't say anything about if the keys should be # considered case sensitive or not... logically they should # be case-preserving and case-insensitive, but doing that # would open up more cases where we might have duplicate # entries. label, url = parts if label in urls: # The label already exists in our set of urls, so this field # is unparseable, and we can just add the whole thing to our # unparseable data and stop processing it. raise KeyError("duplicate labels in project urls") urls[label] = url return urls def _get_payload(msg: email.message.Message, source: Union[bytes, str]) -> str: """Get the body of the message.""" # If our source is a str, then our caller has managed encodings for us, # and we don't need to deal with it. if isinstance(source, str): payload: str = msg.get_payload() return payload # If our source is a bytes, then we're managing the encoding and we need # to deal with it. else: bpayload: bytes = msg.get_payload(decode=True) try: return bpayload.decode("utf8", "strict") except UnicodeDecodeError: raise ValueError("payload in an invalid encoding") # The various parse_FORMAT functions here are intended to be as lenient as # possible in their parsing, while still returning a correctly typed # RawMetadata. # # To aid in this, we also generally want to do as little touching of the # data as possible, except where there are possibly some historic holdovers # that make valid data awkward to work with. # # While this is a lower level, intermediate format than our ``Metadata`` # class, some light touch ups can make a massive difference in usability. # Map METADATA fields to RawMetadata. _EMAIL_TO_RAW_MAPPING = { "author": "author", "author-email": "author_email", "classifier": "classifiers", "description": "description", "description-content-type": "description_content_type", "download-url": "download_url", "dynamic": "dynamic", "home-page": "home_page", "keywords": "keywords", "license": "license", "maintainer": "maintainer", "maintainer-email": "maintainer_email", "metadata-version": "metadata_version", "name": "name", "obsoletes": "obsoletes", "obsoletes-dist": "obsoletes_dist", "platform": "platforms", "project-url": "project_urls", "provides": "provides", "provides-dist": "provides_dist", "provides-extra": "provides_extra", "requires": "requires", "requires-dist": "requires_dist", "requires-external": "requires_external", "requires-python": "requires_python", "summary": "summary", "supported-platform": "supported_platforms", "version": "version", } _RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[str]]]: """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). This function returns a two-item tuple of dicts. The first dict is of recognized fields from the core metadata specification. Fields that can be parsed and translated into Python's built-in types are converted appropriately. All other fields are left as-is. Fields that are allowed to appear multiple times are stored as lists. The second dict contains all other fields from the metadata. This includes any unrecognized fields. It also includes any fields which are expected to be parsed into a built-in type but were not formatted appropriately. Finally, any fields that are expected to appear only once but are repeated are included in this dict. """ raw: Dict[str, Union[str, List[str], Dict[str, str]]] = {} unparsed: Dict[str, List[str]] = {} if isinstance(data, str): parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) else: parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) # We have to wrap parsed.keys() in a set, because in the case of multiple # values for a key (a list), the key will appear multiple times in the # list of keys, but we're avoiding that by using get_all(). for name in frozenset(parsed.keys()): # Header names in RFC are case insensitive, so we'll normalize to all # lower case to make comparisons easier. name = name.lower() # We use get_all() here, even for fields that aren't multiple use, # because otherwise someone could have e.g. two Name fields, and we # would just silently ignore it rather than doing something about it. headers = parsed.get_all(name) or [] # The way the email module works when parsing bytes is that it # unconditionally decodes the bytes as ascii using the surrogateescape # handler. When you pull that data back out (such as with get_all() ), # it looks to see if the str has any surrogate escapes, and if it does # it wraps it in a Header object instead of returning the string. # # As such, we'll look for those Header objects, and fix up the encoding. value = [] # Flag if we have run into any issues processing the headers, thus # signalling that the data belongs in 'unparsed'. valid_encoding = True for h in headers: # It's unclear if this can return more types than just a Header or # a str, so we'll just assert here to make sure. assert isinstance(h, (email.header.Header, str)) # If it's a header object, we need to do our little dance to get # the real data out of it. In cases where there is invalid data # we're going to end up with mojibake, but there's no obvious, good # way around that without reimplementing parts of the Header object # ourselves. # # That should be fine since, if mojibacked happens, this key is # going into the unparsed dict anyways. if isinstance(h, email.header.Header): # The Header object stores it's data as chunks, and each chunk # can be independently encoded, so we'll need to check each # of them. chunks: List[Tuple[bytes, Optional[str]]] = [] for bin, encoding in email.header.decode_header(h): try: bin.decode("utf8", "strict") except UnicodeDecodeError: # Enable mojibake. encoding = "latin1" valid_encoding = False else: encoding = "utf8" chunks.append((bin, encoding)) # Turn our chunks back into a Header object, then let that # Header object do the right thing to turn them into a # string for us. value.append(str(email.header.make_header(chunks))) # This is already a string, so just add it. else: value.append(h) # We've processed all of our values to get them into a list of str, # but we may have mojibake data, in which case this is an unparsed # field. if not valid_encoding: unparsed[name] = value continue raw_name = _EMAIL_TO_RAW_MAPPING.get(name) if raw_name is None: # This is a bit of a weird situation, we've encountered a key that # we don't know what it means, so we don't know whether it's meant # to be a list or not. # # Since we can't really tell one way or another, we'll just leave it # as a list, even though it may be a single item list, because that's # what makes the most sense for email headers. unparsed[name] = value continue # If this is one of our string fields, then we'll check to see if our # value is a list of a single item. If it is then we'll assume that # it was emitted as a single string, and unwrap the str from inside # the list. # # If it's any other kind of data, then we haven't the faintest clue # what we should parse it as, and we have to just add it to our list # of unparsed stuff. if raw_name in _STRING_FIELDS and len(value) == 1: raw[raw_name] = value[0] # If this is one of our list of string fields, then we can just assign # the value, since email *only* has strings, and our get_all() call # above ensures that this is a list. elif raw_name in _LIST_FIELDS: raw[raw_name] = value # Special Case: Keywords # The keywords field is implemented in the metadata spec as a str, # but it conceptually is a list of strings, and is serialized using # ", ".join(keywords), so we'll do some light data massaging to turn # this into what it logically is. elif raw_name == "keywords" and len(value) == 1: raw[raw_name] = _parse_keywords(value[0]) # Special Case: Project-URL # The project urls is implemented in the metadata spec as a list of # specially-formatted strings that represent a key and a value, which # is fundamentally a mapping, however the email format doesn't support # mappings in a sane way, so it was crammed into a list of strings # instead. # # We will do a little light data massaging to turn this into a map as # it logically should be. elif raw_name == "project_urls": try: raw[raw_name] = _parse_project_urls(value) except KeyError: unparsed[name] = value # Nothing that we've done has managed to parse this, so it'll just # throw it in our unparseable data and move on. else: unparsed[name] = value # We need to support getting the Description from the message payload in # addition to getting it from the the headers. This does mean, though, there # is the possibility of it being set both ways, in which case we put both # in 'unparsed' since we don't know which is right. try: payload = _get_payload(parsed, data) except ValueError: unparsed.setdefault("description", []).append( parsed.get_payload(decode=isinstance(data, bytes)) ) else: if payload: # Check to see if we've already got a description, if so then both # it, and this body move to unparseable. if "description" in raw: description_header = cast(str, raw.pop("description")) unparsed.setdefault("description", []).extend( [description_header, payload] ) elif "description" in unparsed: unparsed["description"].append(payload) else: raw["description"] = payload # We need to cast our `raw` to a metadata, because a TypedDict only support # literal key names, but we're computing our key names on purpose, but the # way this function is implemented, our `TypedDict` can only have valid key # names. return cast(RawMetadata, raw), unparsed _NOT_FOUND = object() # Keep the two values in sync. _VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"] _MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"] _REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) class _Validator(Generic[T]): """Validate a metadata field. All _process_*() methods correspond to a core metadata field. The method is called with the field's raw value. If the raw value is valid it is returned in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause as appropriate). """ name: str raw_name: str added: _MetadataVersion def __init__( self, *, added: _MetadataVersion = "1.0", ) -> None: self.added = added def __set_name__(self, _owner: "Metadata", name: str) -> None: self.name = name self.raw_name = _RAW_TO_EMAIL_MAPPING[name] def __get__(self, instance: "Metadata", _owner: Type["Metadata"]) -> T: # With Python 3.8, the caching can be replaced with functools.cached_property(). # No need to check the cache as attribute lookup will resolve into the # instance's __dict__ before __get__ is called. cache = instance.__dict__ value = instance._raw.get(self.name) # To make the _process_* methods easier, we'll check if the value is None # and if this field is NOT a required attribute, and if both of those # things are true, we'll skip the the converter. This will mean that the # converters never have to deal with the None union. if self.name in _REQUIRED_ATTRS or value is not None: try: converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") except AttributeError: pass else: value = converter(value) cache[self.name] = value try: del instance._raw[self.name] # type: ignore[misc] except KeyError: pass return cast(T, value) def _invalid_metadata( self, msg: str, cause: Optional[Exception] = None ) -> InvalidMetadata: exc = InvalidMetadata( self.raw_name, msg.format_map({"field": repr(self.raw_name)}) ) exc.__cause__ = cause return exc def _process_metadata_version(self, value: str) -> _MetadataVersion: # Implicitly makes Metadata-Version required. if value not in _VALID_METADATA_VERSIONS: raise self._invalid_metadata(f"{value!r} is not a valid metadata version") return cast(_MetadataVersion, value) def _process_name(self, value: str) -> str: if not value: raise self._invalid_metadata("{field} is a required field") # Validate the name as a side-effect. try: utils.canonicalize_name(value, validate=True) except utils.InvalidName as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) else: return value def _process_version(self, value: str) -> version_module.Version: if not value: raise self._invalid_metadata("{field} is a required field") try: return version_module.parse(value) except version_module.InvalidVersion as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) def _process_summary(self, value: str) -> str: """Check the field contains no newlines.""" if "\n" in value: raise self._invalid_metadata("{field} must be a single line") return value def _process_description_content_type(self, value: str) -> str: content_types = {"text/plain", "text/x-rst", "text/markdown"} message = email.message.EmailMessage() message["content-type"] = value content_type, parameters = ( # Defaults to `text/plain` if parsing failed. message.get_content_type().lower(), message["content-type"].params, ) # Check if content-type is valid or defaulted to `text/plain` and thus was # not parseable. if content_type not in content_types or content_type not in value.lower(): raise self._invalid_metadata( f"{{field}} must be one of {list(content_types)}, not {value!r}" ) charset = parameters.get("charset", "UTF-8") if charset != "UTF-8": raise self._invalid_metadata( f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" ) markdown_variants = {"GFM", "CommonMark"} variant = parameters.get("variant", "GFM") # Use an acceptable default. if content_type == "text/markdown" and variant not in markdown_variants: raise self._invalid_metadata( f"valid Markdown variants for {{field}} are {list(markdown_variants)}, " f"not {variant!r}", ) return value def _process_dynamic(self, value: List[str]) -> List[str]: for dynamic_field in map(str.lower, value): if dynamic_field in {"name", "version", "metadata-version"}: raise self._invalid_metadata( f"{value!r} is not allowed as a dynamic field" ) elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: raise self._invalid_metadata(f"{value!r} is not a valid dynamic field") return list(map(str.lower, value)) def _process_provides_extra( self, value: List[str], ) -> List[utils.NormalizedName]: normalized_names = [] try: for name in value: normalized_names.append(utils.canonicalize_name(name, validate=True)) except utils.InvalidName as exc: raise self._invalid_metadata( f"{name!r} is invalid for {{field}}", cause=exc ) else: return normalized_names def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: try: return specifiers.SpecifierSet(value) except specifiers.InvalidSpecifier as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) def _process_requires_dist( self, value: List[str], ) -> List[requirements.Requirement]: reqs = [] try: for req in value: reqs.append(requirements.Requirement(req)) except requirements.InvalidRequirement as exc: raise self._invalid_metadata(f"{req!r} is invalid for {{field}}", cause=exc) else: return reqs class Metadata: """Representation of distribution metadata. Compared to :class:`RawMetadata`, this class provides objects representing metadata fields instead of only using built-in types. Any invalid metadata will cause :exc:`InvalidMetadata` to be raised (with a :py:attr:`~BaseException.__cause__` attribute as appropriate). """ _raw: RawMetadata @classmethod def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> "Metadata": """Create an instance from :class:`RawMetadata`. If *validate* is true, all metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ ins = cls() ins._raw = data.copy() # Mutations occur due to caching enriched values. if validate: exceptions: List[Exception] = [] try: metadata_version = ins.metadata_version metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) except InvalidMetadata as metadata_version_exc: exceptions.append(metadata_version_exc) metadata_version = None # Make sure to check for the fields that are present, the required # fields (so their absence can be reported). fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS # Remove fields that have already been checked. fields_to_check -= {"metadata_version"} for key in fields_to_check: try: if metadata_version: # Can't use getattr() as that triggers descriptor protocol which # will fail due to no value for the instance argument. try: field_metadata_version = cls.__dict__[key].added except KeyError: exc = InvalidMetadata(key, f"unrecognized field: {key!r}") exceptions.append(exc) continue field_age = _VALID_METADATA_VERSIONS.index( field_metadata_version ) if field_age > metadata_age: field = _RAW_TO_EMAIL_MAPPING[key] exc = InvalidMetadata( field, "{field} introduced in metadata version " "{field_metadata_version}, not {metadata_version}", ) exceptions.append(exc) continue getattr(ins, key) except InvalidMetadata as exc: exceptions.append(exc) if exceptions: raise ExceptionGroup("invalid metadata", exceptions) return ins @classmethod def from_email( cls, data: Union[bytes, str], *, validate: bool = True ) -> "Metadata": """Parse metadata from email headers. If *validate* is true, the metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ raw, unparsed = parse_email(data) if validate: exceptions: list[Exception] = [] for unparsed_key in unparsed: if unparsed_key in _EMAIL_TO_RAW_MAPPING: message = f"{unparsed_key!r} has invalid data" else: message = f"unrecognized field: {unparsed_key!r}" exceptions.append(InvalidMetadata(unparsed_key, message)) if exceptions: raise ExceptionGroup("unparsed", exceptions) try: return cls.from_raw(raw, validate=validate) except ExceptionGroup as exc_group: raise ExceptionGroup( "invalid or unparsed metadata", exc_group.exceptions ) from None metadata_version: _Validator[_MetadataVersion] = _Validator() """:external:ref:`core-metadata-metadata-version` (required; validated to be a valid metadata version)""" name: _Validator[str] = _Validator() """:external:ref:`core-metadata-name` (required; validated using :func:`~packaging.utils.canonicalize_name` and its *validate* parameter)""" version: _Validator[version_module.Version] = _Validator() """:external:ref:`core-metadata-version` (required)""" dynamic: _Validator[Optional[List[str]]] = _Validator( added="2.2", ) """:external:ref:`core-metadata-dynamic` (validated against core metadata field names and lowercased)""" platforms: _Validator[Optional[List[str]]] = _Validator() """:external:ref:`core-metadata-platform`""" supported_platforms: _Validator[Optional[List[str]]] = _Validator(added="1.1") """:external:ref:`core-metadata-supported-platform`""" summary: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" description: _Validator[Optional[str]] = _Validator() # TODO 2.1: can be in body """:external:ref:`core-metadata-description`""" description_content_type: _Validator[Optional[str]] = _Validator(added="2.1") """:external:ref:`core-metadata-description-content-type` (validated)""" keywords: _Validator[Optional[List[str]]] = _Validator() """:external:ref:`core-metadata-keywords`""" home_page: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-home-page`""" download_url: _Validator[Optional[str]] = _Validator(added="1.1") """:external:ref:`core-metadata-download-url`""" author: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-author`""" author_email: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-author-email`""" maintainer: _Validator[Optional[str]] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer`""" maintainer_email: _Validator[Optional[str]] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer-email`""" license: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-license`""" classifiers: _Validator[Optional[List[str]]] = _Validator(added="1.1") """:external:ref:`core-metadata-classifier`""" requires_dist: _Validator[Optional[List[requirements.Requirement]]] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-dist`""" requires_python: _Validator[Optional[specifiers.SpecifierSet]] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-python`""" # Because `Requires-External` allows for non-PEP 440 version specifiers, we # don't do any processing on the values. requires_external: _Validator[Optional[List[str]]] = _Validator(added="1.2") """:external:ref:`core-metadata-requires-external`""" project_urls: _Validator[Optional[Dict[str, str]]] = _Validator(added="1.2") """:external:ref:`core-metadata-project-url`""" # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation # regardless of metadata version. provides_extra: _Validator[Optional[List[utils.NormalizedName]]] = _Validator( added="2.1", ) """:external:ref:`core-metadata-provides-extra`""" provides_dist: _Validator[Optional[List[str]]] = _Validator(added="1.2") """:external:ref:`core-metadata-provides-dist`""" obsoletes_dist: _Validator[Optional[List[str]]] = _Validator(added="1.2") """:external:ref:`core-metadata-obsoletes-dist`""" requires: _Validator[Optional[List[str]]] = _Validator(added="1.1") """``Requires`` (deprecated)""" provides: _Validator[Optional[List[str]]] = _Validator(added="1.1") """``Provides`` (deprecated)""" obsoletes: _Validator[Optional[List[str]]] = _Validator(added="1.1") """``Obsoletes`` (deprecated)""" # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from typing import Any, Iterator, Optional, Set from ._parser import parse_requirement as _parse_requirement from ._tokenizer import ParserSyntaxError from .markers import Marker, _normalize_extra_values from .specifiers import SpecifierSet from .utils import canonicalize_name class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """ class Requirement: """Parse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. """ # TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name? def __init__(self, requirement_string: str) -> None: try: parsed = _parse_requirement(requirement_string) except ParserSyntaxError as e: raise InvalidRequirement(str(e)) from e self.name: str = parsed.name self.url: Optional[str] = parsed.url or None self.extras: Set[str] = set(parsed.extras if parsed.extras else []) self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) self.marker: Optional[Marker] = None if parsed.marker is not None: self.marker = Marker.__new__(Marker) self.marker._markers = _normalize_extra_values(parsed.marker) def _iter_parts(self, name: str) -> Iterator[str]: yield name if self.extras: formatted_extras = ",".join(sorted(self.extras)) yield f"[{formatted_extras}]" if self.specifier: yield str(self.specifier) if self.url: yield f"@ {self.url}" if self.marker: yield " " if self.marker: yield f"; {self.marker}" def __str__(self) -> str: return "".join(self._iter_parts(self.name)) def __repr__(self) -> str: return f"" def __hash__(self) -> int: return hash( ( self.__class__.__name__, *self._iter_parts(canonicalize_name(self.name)), ) ) def __eq__(self, other: Any) -> bool: if not isinstance(other, Requirement): return NotImplemented return ( canonicalize_name(self.name) == canonicalize_name(other.name) and self.extras == other.extras and self.specifier == other.specifier and self.url == other.url and self.marker == other.marker ) # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. """ .. testsetup:: from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier from packaging.version import Version """ import abc import itertools import re from typing import ( Callable, Iterable, Iterator, List, Optional, Set, Tuple, TypeVar, Union, ) from .utils import canonicalize_version from .version import Version UnparsedVersion = Union[Version, str] UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) CallableOperator = Callable[[Version, str], bool] def _coerce_version(version: UnparsedVersion) -> Version: if not isinstance(version, Version): version = Version(version) return version class InvalidSpecifier(ValueError): """ Raised when attempting to create a :class:`Specifier` with a specifier string that is invalid. >>> Specifier("lolwat") Traceback (most recent call last): ... packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' """ class BaseSpecifier(metaclass=abc.ABCMeta): @abc.abstractmethod def __str__(self) -> str: """ Returns the str representation of this Specifier-like object. This should be representative of the Specifier itself. """ @abc.abstractmethod def __hash__(self) -> int: """ Returns a hash value for this Specifier-like object. """ @abc.abstractmethod def __eq__(self, other: object) -> bool: """ Returns a boolean representing whether or not the two Specifier-like objects are equal. :param other: The other object to check against. """ @property @abc.abstractmethod def prereleases(self) -> Optional[bool]: """Whether or not pre-releases as a whole are allowed. This can be set to either ``True`` or ``False`` to explicitly enable or disable prereleases or it can be set to ``None`` (the default) to use default semantics. """ @prereleases.setter def prereleases(self, value: bool) -> None: """Setter for :attr:`prereleases`. :param value: The value to set. """ @abc.abstractmethod def contains(self, item: str, prereleases: Optional[bool] = None) -> bool: """ Determines if the given item is contained within this specifier. """ @abc.abstractmethod def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None ) -> Iterator[UnparsedVersionVar]: """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """ class Specifier(BaseSpecifier): """This class abstracts handling of version specifiers. .. tip:: It is generally not required to instantiate this manually. You should instead prefer to work with :class:`SpecifierSet` instead, which can parse comma-separated version specifiers (which is what package metadata contains). """ _operator_regex_str = r""" (?P(~=|==|!=|<=|>=|<|>|===)) """ _version_regex_str = r""" (?P (?: # The identity operators allow for an escape hatch that will # do an exact string match of the version you wish to install. # This will not be parsed by PEP 440 and we cannot determine # any semantic meaning from it. This operator is discouraged # but included entirely as an escape hatch. (?<====) # Only match for the identity operator \s* [^\s;)]* # The arbitrary version can be just about anything, # we match everything except for whitespace, a # semi-colon for marker support, and a closing paren # since versions can be enclosed in them. ) | (?: # The (non)equality operators allow for wild card and local # versions to be specified so we have to define these two # operators separately to enable that. (?<===|!=) # Only match for equals and not equals \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release # You cannot use a wild card and a pre-release, post-release, a dev or # local version together so group them with a | and make them optional. (?: \.\* # Wild card syntax of .* | (?: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local )? ) | (?: # The compatible operator requires at least two digits in the # release segment. (?<=~=) # Only match for the compatible operator \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) (?: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) | (?: # All other operators only allow a sub set of what the # (non)equality operators do. Specifically they do not allow # local versions to be specified nor do they allow the prefix # matching wild cards. (?=": "greater_than_equal", "<": "less_than", ">": "greater_than", "===": "arbitrary", } def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None: """Initialize a Specifier instance. :param spec: The string representation of a specifier which will be parsed and normalized before use. :param prereleases: This tells the specifier if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers. :raises InvalidSpecifier: If the given specifier is invalid (i.e. bad syntax). """ match = self._regex.search(spec) if not match: raise InvalidSpecifier(f"Invalid specifier: '{spec}'") self._spec: Tuple[str, str] = ( match.group("operator").strip(), match.group("version").strip(), ) # Store whether or not this Specifier should accept prereleases self._prereleases = prereleases # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515 @property # type: ignore[override] def prereleases(self) -> bool: # If there is an explicit prereleases set for this, then we'll just # blindly use that. if self._prereleases is not None: return self._prereleases # Look at all of our specifiers and determine if they are inclusive # operators, and if they are if they are including an explicit # prerelease. operator, version = self._spec if operator in ["==", ">=", "<=", "~=", "==="]: # The == specifier can include a trailing .*, if it does we # want to remove before parsing. if operator == "==" and version.endswith(".*"): version = version[:-2] # Parse the version, and if it is a pre-release than this # specifier allows pre-releases. if Version(version).is_prerelease: return True return False @prereleases.setter def prereleases(self, value: bool) -> None: self._prereleases = value @property def operator(self) -> str: """The operator of this specifier. >>> Specifier("==1.2.3").operator '==' """ return self._spec[0] @property def version(self) -> str: """The version of this specifier. >>> Specifier("==1.2.3").version '1.2.3' """ return self._spec[1] def __repr__(self) -> str: """A representation of the Specifier that shows all internal state. >>> Specifier('>=1.0.0') =1.0.0')> >>> Specifier('>=1.0.0', prereleases=False) =1.0.0', prereleases=False)> >>> Specifier('>=1.0.0', prereleases=True) =1.0.0', prereleases=True)> """ pre = ( f", prereleases={self.prereleases!r}" if self._prereleases is not None else "" ) return f"<{self.__class__.__name__}({str(self)!r}{pre})>" def __str__(self) -> str: """A string representation of the Specifier that can be round-tripped. >>> str(Specifier('>=1.0.0')) '>=1.0.0' >>> str(Specifier('>=1.0.0', prereleases=False)) '>=1.0.0' """ return "{}{}".format(*self._spec) @property def _canonical_spec(self) -> Tuple[str, str]: canonical_version = canonicalize_version( self._spec[1], strip_trailing_zero=(self._spec[0] != "~="), ) return self._spec[0], canonical_version def __hash__(self) -> int: return hash(self._canonical_spec) def __eq__(self, other: object) -> bool: """Whether or not the two Specifier-like objects are equal. :param other: The other object to check against. The value of :attr:`prereleases` is ignored. >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") True >>> (Specifier("==1.2.3", prereleases=False) == ... Specifier("==1.2.3", prereleases=True)) True >>> Specifier("==1.2.3") == "==1.2.3" True >>> Specifier("==1.2.3") == Specifier("==1.2.4") False >>> Specifier("==1.2.3") == Specifier("~=1.2.3") False """ if isinstance(other, str): try: other = self.__class__(str(other)) except InvalidSpecifier: return NotImplemented elif not isinstance(other, self.__class__): return NotImplemented return self._canonical_spec == other._canonical_spec def _get_operator(self, op: str) -> CallableOperator: operator_callable: CallableOperator = getattr( self, f"_compare_{self._operators[op]}" ) return operator_callable def _compare_compatible(self, prospective: Version, spec: str) -> bool: # Compatible releases have an equivalent combination of >= and ==. That # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to # implement this in terms of the other specifiers instead of # implementing it ourselves. The only thing we need to do is construct # the other specifiers. # We want everything but the last item in the version, but we want to # ignore suffix segments. prefix = _version_join( list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] ) # Add the prefix notation to the end of our string prefix += ".*" return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( prospective, prefix ) def _compare_equal(self, prospective: Version, spec: str) -> bool: # We need special logic to handle prefix matching if spec.endswith(".*"): # In the case of prefix matching we want to ignore local segment. normalized_prospective = canonicalize_version( prospective.public, strip_trailing_zero=False ) # Get the normalized version string ignoring the trailing .* normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) # Split the spec out by bangs and dots, and pretend that there is # an implicit dot in between a release segment and a pre-release segment. split_spec = _version_split(normalized_spec) # Split the prospective version out by bangs and dots, and pretend # that there is an implicit dot in between a release segment and # a pre-release segment. split_prospective = _version_split(normalized_prospective) # 0-pad the prospective version before shortening it to get the correct # shortened version. padded_prospective, _ = _pad_version(split_prospective, split_spec) # Shorten the prospective version to be the same length as the spec # so that we can determine if the specifier is a prefix of the # prospective version or not. shortened_prospective = padded_prospective[: len(split_spec)] return shortened_prospective == split_spec else: # Convert our spec string into a Version spec_version = Version(spec) # If the specifier does not have a local segment, then we want to # act as if the prospective version also does not have a local # segment. if not spec_version.local: prospective = Version(prospective.public) return prospective == spec_version def _compare_not_equal(self, prospective: Version, spec: str) -> bool: return not self._compare_equal(prospective, spec) def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: # NB: Local version identifiers are NOT permitted in the version # specifier, so local version labels can be universally removed from # the prospective version. return Version(prospective.public) <= Version(spec) def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: # NB: Local version identifiers are NOT permitted in the version # specifier, so local version labels can be universally removed from # the prospective version. return Version(prospective.public) >= Version(spec) def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: # Convert our spec to a Version instance, since we'll want to work with # it as a version. spec = Version(spec_str) # Check to see if the prospective version is less than the spec # version. If it's not we can short circuit and just return False now # instead of doing extra unneeded work. if not prospective < spec: return False # This special case is here so that, unless the specifier itself # includes is a pre-release version, that we do not accept pre-release # versions for the version mentioned in the specifier (e.g. <3.1 should # not match 3.1.dev0, but should match 3.0.dev0). if not spec.is_prerelease and prospective.is_prerelease: if Version(prospective.base_version) == Version(spec.base_version): return False # If we've gotten to here, it means that prospective version is both # less than the spec version *and* it's not a pre-release of the same # version in the spec. return True def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: # Convert our spec to a Version instance, since we'll want to work with # it as a version. spec = Version(spec_str) # Check to see if the prospective version is greater than the spec # version. If it's not we can short circuit and just return False now # instead of doing extra unneeded work. if not prospective > spec: return False # This special case is here so that, unless the specifier itself # includes is a post-release version, that we do not accept # post-release versions for the version mentioned in the specifier # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). if not spec.is_postrelease and prospective.is_postrelease: if Version(prospective.base_version) == Version(spec.base_version): return False # Ensure that we do not allow a local version of the version mentioned # in the specifier, which is technically greater than, to match. if prospective.local is not None: if Version(prospective.base_version) == Version(spec.base_version): return False # If we've gotten to here, it means that prospective version is both # greater than the spec version *and* it's not a pre-release of the # same version in the spec. return True def _compare_arbitrary(self, prospective: Version, spec: str) -> bool: return str(prospective).lower() == str(spec).lower() def __contains__(self, item: Union[str, Version]) -> bool: """Return whether or not the item is contained in this specifier. :param item: The item to check for. This is used for the ``in`` operator and behaves the same as :meth:`contains` with no ``prereleases`` argument passed. >>> "1.2.3" in Specifier(">=1.2.3") True >>> Version("1.2.3") in Specifier(">=1.2.3") True >>> "1.0.0" in Specifier(">=1.2.3") False >>> "1.3.0a1" in Specifier(">=1.2.3") False >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) True """ return self.contains(item) def contains( self, item: UnparsedVersion, prereleases: Optional[bool] = None ) -> bool: """Return whether or not the item is contained in this specifier. :param item: The item to check for, which can be a version string or a :class:`Version` instance. :param prereleases: Whether or not to match prereleases with this Specifier. If set to ``None`` (the default), it uses :attr:`prereleases` to determine whether or not prereleases are allowed. >>> Specifier(">=1.2.3").contains("1.2.3") True >>> Specifier(">=1.2.3").contains(Version("1.2.3")) True >>> Specifier(">=1.2.3").contains("1.0.0") False >>> Specifier(">=1.2.3").contains("1.3.0a1") False >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1") True >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True) True """ # Determine if prereleases are to be allowed or not. if prereleases is None: prereleases = self.prereleases # Normalize item to a Version, this allows us to have a shortcut for # "2.0" in Specifier(">=2") normalized_item = _coerce_version(item) # Determine if we should be supporting prereleases in this specifier # or not, if we do not support prereleases than we can short circuit # logic if this version is a prereleases. if normalized_item.is_prerelease and not prereleases: return False # Actually do the comparison to determine if this item is contained # within this Specifier or not. operator_callable: CallableOperator = self._get_operator(self.operator) return operator_callable(normalized_item, self.version) def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None ) -> Iterator[UnparsedVersionVar]: """Filter items in the given iterable, that match the specifier. :param iterable: An iterable that can contain version strings and :class:`Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will be intelligently decide whether to allow prereleases or not (based on the :attr:`prereleases` attribute, and whether the only versions matching are prereleases). This method is smarter than just ``filter(Specifier().contains, [...])`` because it implements the rule from :pep:`440` that a prerelease item SHOULD be accepted if no other versions match the given specifier. >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) ['1.2.3', '1.3', ] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] """ yielded = False found_prereleases = [] kw = {"prereleases": prereleases if prereleases is not None else True} # Attempt to iterate over all the values in the iterable and if any of # them match, yield them. for version in iterable: parsed_version = _coerce_version(version) if self.contains(parsed_version, **kw): # If our version is a prerelease, and we were not set to allow # prereleases, then we'll store it for later in case nothing # else matches this specifier. if parsed_version.is_prerelease and not ( prereleases or self.prereleases ): found_prereleases.append(version) # Either this is not a prerelease, or we should have been # accepting prereleases from the beginning. else: yielded = True yield version # Now that we've iterated over everything, determine if we've yielded # any values, and if we have not and we have any prereleases stored up # then we will go ahead and yield the prereleases. if not yielded and found_prereleases: for version in found_prereleases: yield version _prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") def _version_split(version: str) -> List[str]: """Split version into components. The split components are intended for version comparison. The logic does not attempt to retain the original version string, so joining the components back with :func:`_version_join` may not produce the original version string. """ result: List[str] = [] epoch, _, rest = version.rpartition("!") result.append(epoch or "0") for item in rest.split("."): match = _prefix_regex.search(item) if match: result.extend(match.groups()) else: result.append(item) return result def _version_join(components: List[str]) -> str: """Join split version components into a version string. This function assumes the input came from :func:`_version_split`, where the first component must be the epoch (either empty or numeric), and all other components numeric. """ epoch, *rest = components return f"{epoch}!{'.'.join(rest)}" def _is_not_suffix(segment: str) -> bool: return not any( segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") ) def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]: left_split, right_split = [], [] # Get the release segment of our versions left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) # Get the rest of our versions left_split.append(left[len(left_split[0]) :]) right_split.append(right[len(right_split[0]) :]) # Insert our padding left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split))) class SpecifierSet(BaseSpecifier): """This class abstracts handling of a set of version specifiers. It can be passed a single specifier (``>=3.0``), a comma-separated list of specifiers (``>=3.0,!=3.1``), or no specifier at all. """ def __init__( self, specifiers: str = "", prereleases: Optional[bool] = None ) -> None: """Initialize a SpecifierSet instance. :param specifiers: The string representation of a specifier or a comma-separated list of specifiers which will be parsed and normalized before use. :param prereleases: This tells the SpecifierSet if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers. :raises InvalidSpecifier: If the given ``specifiers`` are not parseable than this exception will be raised. """ # Split on `,` to break each individual specifier into it's own item, and # strip each item to remove leading/trailing whitespace. split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] # Parsed each individual specifier, attempting first to make it a # Specifier. parsed: Set[Specifier] = set() for specifier in split_specifiers: parsed.add(Specifier(specifier)) # Turn our parsed specifiers into a frozen set and save them for later. self._specs = frozenset(parsed) # Store our prereleases value so we can use it later to determine if # we accept prereleases or not. self._prereleases = prereleases @property def prereleases(self) -> Optional[bool]: # If we have been given an explicit prerelease modifier, then we'll # pass that through here. if self._prereleases is not None: return self._prereleases # If we don't have any specifiers, and we don't have a forced value, # then we'll just return None since we don't know if this should have # pre-releases or not. if not self._specs: return None # Otherwise we'll see if any of the given specifiers accept # prereleases, if any of them do we'll return True, otherwise False. return any(s.prereleases for s in self._specs) @prereleases.setter def prereleases(self, value: bool) -> None: self._prereleases = value def __repr__(self) -> str: """A representation of the specifier set that shows all internal state. Note that the ordering of the individual specifiers within the set may not match the input string. >>> SpecifierSet('>=1.0.0,!=2.0.0') =1.0.0')> >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) =1.0.0', prereleases=False)> >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) =1.0.0', prereleases=True)> """ pre = ( f", prereleases={self.prereleases!r}" if self._prereleases is not None else "" ) return f"" def __str__(self) -> str: """A string representation of the specifier set that can be round-tripped. Note that the ordering of the individual specifiers within the set may not match the input string. >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) '!=1.0.1,>=1.0.0' >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) '!=1.0.1,>=1.0.0' """ return ",".join(sorted(str(s) for s in self._specs)) def __hash__(self) -> int: return hash(self._specs) def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet": """Return a SpecifierSet which is a combination of the two sets. :param other: The other object to combine with. >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' =1.0.0')> >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') =1.0.0')> """ if isinstance(other, str): other = SpecifierSet(other) elif not isinstance(other, SpecifierSet): return NotImplemented specifier = SpecifierSet() specifier._specs = frozenset(self._specs | other._specs) if self._prereleases is None and other._prereleases is not None: specifier._prereleases = other._prereleases elif self._prereleases is not None and other._prereleases is None: specifier._prereleases = self._prereleases elif self._prereleases == other._prereleases: specifier._prereleases = self._prereleases else: raise ValueError( "Cannot combine SpecifierSets with True and False prerelease " "overrides." ) return specifier def __eq__(self, other: object) -> bool: """Whether or not the two SpecifierSet-like objects are equal. :param other: The other object to check against. The value of :attr:`prereleases` is ignored. >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") True >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) True >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" True >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") False >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") False """ if isinstance(other, (str, Specifier)): other = SpecifierSet(str(other)) elif not isinstance(other, SpecifierSet): return NotImplemented return self._specs == other._specs def __len__(self) -> int: """Returns the number of specifiers in this specifier set.""" return len(self._specs) def __iter__(self) -> Iterator[Specifier]: """ Returns an iterator over all the underlying :class:`Specifier` instances in this specifier set. >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) [, =1.0.0')>] """ return iter(self._specs) def __contains__(self, item: UnparsedVersion) -> bool: """Return whether or not the item is contained in this specifier. :param item: The item to check for. This is used for the ``in`` operator and behaves the same as :meth:`contains` with no ``prereleases`` argument passed. >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") True >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") True >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") False >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") False >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) True """ return self.contains(item) def contains( self, item: UnparsedVersion, prereleases: Optional[bool] = None, installed: Optional[bool] = None, ) -> bool: """Return whether or not the item is contained in this SpecifierSet. :param item: The item to check for, which can be a version string or a :class:`Version` instance. :param prereleases: Whether or not to match prereleases with this SpecifierSet. If set to ``None`` (the default), it uses :attr:`prereleases` to determine whether or not prereleases are allowed. >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") False >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") False >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1") True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) True """ # Ensure that our item is a Version instance. if not isinstance(item, Version): item = Version(item) # Determine if we're forcing a prerelease or not, if we're not forcing # one for this particular filter call, then we'll use whatever the # SpecifierSet thinks for whether or not we should support prereleases. if prereleases is None: prereleases = self.prereleases # We can determine if we're going to allow pre-releases by looking to # see if any of the underlying items supports them. If none of them do # and this item is a pre-release then we do not allow it and we can # short circuit that here. # Note: This means that 1.0.dev1 would not be contained in something # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 if not prereleases and item.is_prerelease: return False if installed and item.is_prerelease: item = Version(item.base_version) # We simply dispatch to the underlying specs here to make sure that the # given version is contained within all of them. # Note: This use of all() here means that an empty set of specifiers # will always return True, this is an explicit design decision. return all(s.contains(item, prereleases=prereleases) for s in self._specs) def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None ) -> Iterator[UnparsedVersionVar]: """Filter items in the given iterable, that match the specifiers in this set. :param iterable: An iterable that can contain version strings and :class:`Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will be intelligently decide whether to allow prereleases or not (based on the :attr:`prereleases` attribute, and whether the only versions matching are prereleases). This method is smarter than just ``filter(SpecifierSet(...).contains, [...])`` because it implements the rule from :pep:`440` that a prerelease item SHOULD be accepted if no other versions match the given specifier. >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) ['1.3', ] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) [] >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] An "empty" SpecifierSet will filter items based on the presence of prerelease versions in the set. >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet("").filter(["1.5a1"])) ['1.5a1'] >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] """ # Determine if we're forcing a prerelease or not, if we're not forcing # one for this particular filter call, then we'll use whatever the # SpecifierSet thinks for whether or not we should support prereleases. if prereleases is None: prereleases = self.prereleases # If we have any specifiers, then we want to wrap our iterable in the # filter method for each one, this will act as a logical AND amongst # each specifier. if self._specs: for spec in self._specs: iterable = spec.filter(iterable, prereleases=bool(prereleases)) return iter(iterable) # If we do not have any specifiers, then we need to have a rough filter # which will filter out any pre-releases, unless there are no final # releases. else: filtered: List[UnparsedVersionVar] = [] found_prereleases: List[UnparsedVersionVar] = [] for item in iterable: parsed_version = _coerce_version(item) # Store any item which is a pre-release for later unless we've # already found a final version or we are accepting prereleases if parsed_version.is_prerelease and not prereleases: if not filtered: found_prereleases.append(item) else: filtered.append(item) # If we've found no items except for pre-releases, then we'll go # ahead and use the pre-releases if not filtered and found_prereleases and prereleases is None: return iter(found_prereleases) return iter(filtered) # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import logging import platform import struct import subprocess import sys import sysconfig from importlib.machinery import EXTENSION_SUFFIXES from typing import ( Dict, FrozenSet, Iterable, Iterator, List, Optional, Sequence, Tuple, Union, cast, ) from . import _manylinux, _musllinux logger = logging.getLogger(__name__) PythonVersion = Sequence[int] MacVersion = Tuple[int, int] INTERPRETER_SHORT_NAMES: Dict[str, str] = { "python": "py", # Generic. "cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy", } _32_BIT_INTERPRETER = struct.calcsize("P") == 4 class Tag: """ A representation of the tag triple for a wheel. Instances are considered immutable and thus are hashable. Equality checking is also supported. """ __slots__ = ["_interpreter", "_abi", "_platform", "_hash"] def __init__(self, interpreter: str, abi: str, platform: str) -> None: self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() # The __hash__ of every single element in a Set[Tag] will be evaluated each time # that a set calls its `.disjoint()` method, which may be called hundreds of # times when scanning a page of links for packages with tags matching that # Set[Tag]. Pre-computing the value here produces significant speedups for # downstream consumers. self._hash = hash((self._interpreter, self._abi, self._platform)) @property def interpreter(self) -> str: return self._interpreter @property def abi(self) -> str: return self._abi @property def platform(self) -> str: return self._platform def __eq__(self, other: object) -> bool: if not isinstance(other, Tag): return NotImplemented return ( (self._hash == other._hash) # Short-circuit ASAP for perf reasons. and (self._platform == other._platform) and (self._abi == other._abi) and (self._interpreter == other._interpreter) ) def __hash__(self) -> int: return self._hash def __str__(self) -> str: return f"{self._interpreter}-{self._abi}-{self._platform}" def __repr__(self) -> str: return f"<{self} @ {id(self)}>" def parse_tag(tag: str) -> FrozenSet[Tag]: """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. Returning a set is required due to the possibility that the tag is a compressed tag set. """ tags = set() interpreters, abis, platforms = tag.split("-") for interpreter in interpreters.split("."): for abi in abis.split("."): for platform_ in platforms.split("."): tags.add(Tag(interpreter, abi, platform_)) return frozenset(tags) def _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]: value: Union[int, str, None] = sysconfig.get_config_var(name) if value is None and warn: logger.debug( "Config variable '%s' is unset, Python ABI tag may be incorrect", name ) return value def _normalize_string(string: str) -> str: return string.replace(".", "_").replace("-", "_").replace(" ", "_") def _abi3_applies(python_version: PythonVersion) -> bool: """ Determine if the Python version supports abi3. PEP 384 was first implemented in Python 3.2. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]: py_version = tuple(py_version) # To allow for version comparison. abis = [] version = _version_nodot(py_version[:2]) debug = pymalloc = ucs4 = "" with_debug = _get_config_var("Py_DEBUG", warn) has_refcount = hasattr(sys, "gettotalrefcount") # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled # extension modules is the best option. # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 has_ext = "_d.pyd" in EXTENSION_SUFFIXES if with_debug or (with_debug is None and (has_refcount or has_ext)): debug = "d" if py_version < (3, 8): with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) if with_pymalloc or with_pymalloc is None: pymalloc = "m" if py_version < (3, 3): unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) if unicode_size == 4 or ( unicode_size is None and sys.maxunicode == 0x10FFFF ): ucs4 = "u" elif debug: # Debug builds can also load "normal" extension modules. # We can also assume no UCS-4 or pymalloc requirement. abis.append(f"cp{version}") abis.insert( 0, "cp{version}{debug}{pymalloc}{ucs4}".format( version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4 ), ) return abis def cpython_tags( python_version: Optional[PythonVersion] = None, abis: Optional[Iterable[str]] = None, platforms: Optional[Iterable[str]] = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for a CPython interpreter. The tags consist of: - cp-- - cp-abi3- - cp-none- - cp-abi3- # Older Python versions down to 3.2. If python_version only specifies a major version then user-provided ABIs and the 'none' ABItag will be used. If 'abi3' or 'none' are specified in 'abis' then they will be yielded at their normal position and not at the beginning. """ if not python_version: python_version = sys.version_info[:2] interpreter = f"cp{_version_nodot(python_version[:2])}" if abis is None: if len(python_version) > 1: abis = _cpython_abis(python_version, warn) else: abis = [] abis = list(abis) # 'abi3' and 'none' are explicitly handled later. for explicit_abi in ("abi3", "none"): try: abis.remove(explicit_abi) except ValueError: pass platforms = list(platforms or platform_tags()) for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_) if _abi3_applies(python_version): yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) if _abi3_applies(python_version): for minor_version in range(python_version[1] - 1, 1, -1): for platform_ in platforms: interpreter = "cp{version}".format( version=_version_nodot((python_version[0], minor_version)) ) yield Tag(interpreter, "abi3", platform_) def _generic_abi() -> List[str]: """ Return the ABI tag based on EXT_SUFFIX. """ # The following are examples of `EXT_SUFFIX`. # We want to keep the parts which are related to the ABI and remove the # parts which are related to the platform: # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 # - mac: '.cpython-310-darwin.so' => cp310 # - win: '.cp310-win_amd64.pyd' => cp310 # - win: '.pyd' => cp37 (uses _cpython_abis()) # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' # => graalpy_38_native ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") parts = ext_suffix.split(".") if len(parts) < 3: # CPython3.7 and earlier uses ".pyd" on Windows. return _cpython_abis(sys.version_info[:2]) soabi = parts[1] if soabi.startswith("cpython"): # non-windows abi = "cp" + soabi.split("-")[1] elif soabi.startswith("cp"): # windows abi = soabi.split("-")[0] elif soabi.startswith("pypy"): abi = "-".join(soabi.split("-")[:2]) elif soabi.startswith("graalpy"): abi = "-".join(soabi.split("-")[:3]) elif soabi: # pyston, ironpython, others? abi = soabi else: return [] return [_normalize_string(abi)] def generic_tags( interpreter: Optional[str] = None, abis: Optional[Iterable[str]] = None, platforms: Optional[Iterable[str]] = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for a generic interpreter. The tags consist of: - -- The "none" ABI will be added if it was not explicitly provided. """ if not interpreter: interp_name = interpreter_name() interp_version = interpreter_version(warn=warn) interpreter = "".join([interp_name, interp_version]) if abis is None: abis = _generic_abi() else: abis = list(abis) platforms = list(platforms or platform_tags()) if "none" not in abis: abis.append("none") for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_) def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: """ Yields Python versions in descending order. After the latest version, the major-only version will be yielded, and then all previous versions of that major version. """ if len(py_version) > 1: yield f"py{_version_nodot(py_version[:2])}" yield f"py{py_version[0]}" if len(py_version) > 1: for minor in range(py_version[1] - 1, -1, -1): yield f"py{_version_nodot((py_version[0], minor))}" def compatible_tags( python_version: Optional[PythonVersion] = None, interpreter: Optional[str] = None, platforms: Optional[Iterable[str]] = None, ) -> Iterator[Tag]: """ Yields the sequence of tags that are compatible with a specific version of Python. The tags consist of: - py*-none- - -none-any # ... if `interpreter` is provided. - py*-none-any """ if not python_version: python_version = sys.version_info[:2] platforms = list(platforms or platform_tags()) for version in _py_interpreter_range(python_version): for platform_ in platforms: yield Tag(version, "none", platform_) if interpreter: yield Tag(interpreter, "none", "any") for version in _py_interpreter_range(python_version): yield Tag(version, "none", "any") def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: if not is_32bit: return arch if arch.startswith("ppc"): return "ppc" return "i386" def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]: formats = [cpu_arch] if cpu_arch == "x86_64": if version < (10, 4): return [] formats.extend(["intel", "fat64", "fat32"]) elif cpu_arch == "i386": if version < (10, 4): return [] formats.extend(["intel", "fat32", "fat"]) elif cpu_arch == "ppc64": # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? if version > (10, 5) or version < (10, 4): return [] formats.append("fat64") elif cpu_arch == "ppc": if version > (10, 6): return [] formats.extend(["fat32", "fat"]) if cpu_arch in {"arm64", "x86_64"}: formats.append("universal2") if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: formats.append("universal") return formats def mac_platforms( version: Optional[MacVersion] = None, arch: Optional[str] = None ) -> Iterator[str]: """ Yields the platform tags for a macOS system. The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU architecture to generate platform tags for. Both parameters default to the appropriate value for the current system. """ version_str, _, cpu_arch = platform.mac_ver() if version is None: version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2]))) if version == (10, 16): # When built against an older macOS SDK, Python will report macOS 10.16 # instead of the real version. version_str = subprocess.run( [ sys.executable, "-sS", "-c", "import platform; print(platform.mac_ver()[0])", ], check=True, env={"SYSTEM_VERSION_COMPAT": "0"}, stdout=subprocess.PIPE, text=True, ).stdout version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2]))) else: version = version if arch is None: arch = _mac_arch(cpu_arch) else: arch = arch if (10, 0) <= version and version < (11, 0): # Prior to Mac OS 11, each yearly release of Mac OS bumped the # "minor" version number. The major version was always 10. for minor_version in range(version[1], -1, -1): compat_version = 10, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=10, minor=minor_version, binary_format=binary_format ) if version >= (11, 0): # Starting with Mac OS 11, each yearly release bumps the major version # number. The minor versions are now the midyear updates. for major_version in range(version[0], 10, -1): compat_version = major_version, 0 binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=major_version, minor=0, binary_format=binary_format ) if version >= (11, 0): # Mac OS 11 on x86_64 is compatible with binaries from previous releases. # Arm64 support was introduced in 11.0, so no Arm binaries from previous # releases exist. # # However, the "universal2" binary format can have a # macOS version earlier than 11.0 when the x86_64 part of the binary supports # that version of macOS. if arch == "x86_64": for minor_version in range(16, 3, -1): compat_version = 10, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=compat_version[0], minor=compat_version[1], binary_format=binary_format, ) else: for minor_version in range(16, 3, -1): compat_version = 10, minor_version binary_format = "universal2" yield "macosx_{major}_{minor}_{binary_format}".format( major=compat_version[0], minor=compat_version[1], binary_format=binary_format, ) def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: linux = _normalize_string(sysconfig.get_platform()) if not linux.startswith("linux_"): # we should never be here, just yield the sysconfig one and return yield linux return if is_32bit: if linux == "linux_x86_64": linux = "linux_i686" elif linux == "linux_aarch64": linux = "linux_armv8l" _, arch = linux.split("_", 1) archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) yield from _manylinux.platform_tags(archs) yield from _musllinux.platform_tags(archs) for arch in archs: yield f"linux_{arch}" def _generic_platforms() -> Iterator[str]: yield _normalize_string(sysconfig.get_platform()) def platform_tags() -> Iterator[str]: """ Provides the platform tags for this installation. """ if platform.system() == "Darwin": return mac_platforms() elif platform.system() == "Linux": return _linux_platforms() else: return _generic_platforms() def interpreter_name() -> str: """ Returns the name of the running interpreter. Some implementations have a reserved, two-letter abbreviation which will be returned when appropriate. """ name = sys.implementation.name return INTERPRETER_SHORT_NAMES.get(name) or name def interpreter_version(*, warn: bool = False) -> str: """ Returns the version of the running interpreter. """ version = _get_config_var("py_version_nodot", warn=warn) if version: version = str(version) else: version = _version_nodot(sys.version_info[:2]) return version def _version_nodot(version: PythonVersion) -> str: return "".join(map(str, version)) def sys_tags(*, warn: bool = False) -> Iterator[Tag]: """ Returns the sequence of tag triples for the running interpreter. The order of the sequence corresponds to priority order for the interpreter, from most to least important. """ interp_name = interpreter_name() if interp_name == "cp": yield from cpython_tags(warn=warn) else: yield from generic_tags() if interp_name == "pp": interp = "pp3" elif interp_name == "cp": interp = "cp" + interpreter_version(warn=warn) else: interp = None yield from compatible_tags(interpreter=interp) # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import re from typing import FrozenSet, NewType, Tuple, Union, cast from .tags import Tag, parse_tag from .version import InvalidVersion, Version BuildTag = Union[Tuple[()], Tuple[int, str]] NormalizedName = NewType("NormalizedName", str) class InvalidName(ValueError): """ An invalid distribution name; users should refer to the packaging user guide. """ class InvalidWheelFilename(ValueError): """ An invalid wheel filename was found, users should refer to PEP 427. """ class InvalidSdistFilename(ValueError): """ An invalid sdist filename was found, users should refer to the packaging user guide. """ # Core metadata spec for `Name` _validate_regex = re.compile( r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE ) _canonicalize_regex = re.compile(r"[-_.]+") _normalized_regex = re.compile(r"^([a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9])$") # PEP 427: The build number must start with a digit. _build_tag_regex = re.compile(r"(\d+)(.*)") def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: if validate and not _validate_regex.match(name): raise InvalidName(f"name is invalid: {name!r}") # This is taken from PEP 503. value = _canonicalize_regex.sub("-", name).lower() return cast(NormalizedName, value) def is_normalized_name(name: str) -> bool: return _normalized_regex.match(name) is not None def canonicalize_version( version: Union[Version, str], *, strip_trailing_zero: bool = True ) -> str: """ This is very similar to Version.__str__, but has one subtle difference with the way it handles the release segment. """ if isinstance(version, str): try: parsed = Version(version) except InvalidVersion: # Legacy versions cannot be normalized return version else: parsed = version parts = [] # Epoch if parsed.epoch != 0: parts.append(f"{parsed.epoch}!") # Release segment release_segment = ".".join(str(x) for x in parsed.release) if strip_trailing_zero: # NB: This strips trailing '.0's to normalize release_segment = re.sub(r"(\.0)+$", "", release_segment) parts.append(release_segment) # Pre-release if parsed.pre is not None: parts.append("".join(str(x) for x in parsed.pre)) # Post-release if parsed.post is not None: parts.append(f".post{parsed.post}") # Development release if parsed.dev is not None: parts.append(f".dev{parsed.dev}") # Local version segment if parsed.local is not None: parts.append(f"+{parsed.local}") return "".join(parts) def parse_wheel_filename( filename: str, ) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]: if not filename.endswith(".whl"): raise InvalidWheelFilename( f"Invalid wheel filename (extension must be '.whl'): {filename}" ) filename = filename[:-4] dashes = filename.count("-") if dashes not in (4, 5): raise InvalidWheelFilename( f"Invalid wheel filename (wrong number of parts): {filename}" ) parts = filename.split("-", dashes - 2) name_part = parts[0] # See PEP 427 for the rules on escaping the project name. if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: raise InvalidWheelFilename(f"Invalid project name: {filename}") name = canonicalize_name(name_part) try: version = Version(parts[1]) except InvalidVersion as e: raise InvalidWheelFilename( f"Invalid wheel filename (invalid version): {filename}" ) from e if dashes == 5: build_part = parts[2] build_match = _build_tag_regex.match(build_part) if build_match is None: raise InvalidWheelFilename( f"Invalid build number: {build_part} in '{filename}'" ) build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2))) else: build = () tags = parse_tag(parts[-1]) return (name, version, build, tags) def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]: if filename.endswith(".tar.gz"): file_stem = filename[: -len(".tar.gz")] elif filename.endswith(".zip"): file_stem = filename[: -len(".zip")] else: raise InvalidSdistFilename( f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" f" {filename}" ) # We are requiring a PEP 440 version, which cannot contain dashes, # so we split on the last dash. name_part, sep, version_part = file_stem.rpartition("-") if not sep: raise InvalidSdistFilename(f"Invalid sdist filename: {filename}") name = canonicalize_name(name_part) try: version = Version(version_part) except InvalidVersion as e: raise InvalidSdistFilename( f"Invalid sdist filename (invalid version): {filename}" ) from e return (name, version) # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. """ .. testsetup:: from packaging.version import parse, Version """ import itertools import re from typing import Any, Callable, NamedTuple, Optional, SupportsInt, Tuple, Union from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType __all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"] LocalType = Tuple[Union[int, str], ...] CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] CmpLocalType = Union[ NegativeInfinityType, Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], ] CmpKey = Tuple[ int, Tuple[int, ...], CmpPrePostDevType, CmpPrePostDevType, CmpPrePostDevType, CmpLocalType, ] VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] class _Version(NamedTuple): epoch: int release: Tuple[int, ...] dev: Optional[Tuple[str, int]] pre: Optional[Tuple[str, int]] post: Optional[Tuple[str, int]] local: Optional[LocalType] def parse(version: str) -> "Version": """Parse the given version string. >>> parse('1.0.dev1') :param version: The version string to parse. :raises InvalidVersion: When the version string is not a valid version. """ return Version(version) class InvalidVersion(ValueError): """Raised when a version string is not a valid version. >>> Version("invalid") Traceback (most recent call last): ... packaging.version.InvalidVersion: Invalid version: 'invalid' """ class _BaseVersion: _key: Tuple[Any, ...] def __hash__(self) -> int: return hash(self._key) # Please keep the duplicated `isinstance` check # in the six comparisons hereunder # unless you find a way to avoid adding overhead function calls. def __lt__(self, other: "_BaseVersion") -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key < other._key def __le__(self, other: "_BaseVersion") -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key <= other._key def __eq__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key == other._key def __ge__(self, other: "_BaseVersion") -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key >= other._key def __gt__(self, other: "_BaseVersion") -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key > other._key def __ne__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key != other._key # Deliberately not anchored to the start and end of the string, to make it # easier for 3rd party code to reuse _VERSION_PATTERN = r""" v? (?: (?:(?P[0-9]+)!)? # epoch (?P[0-9]+(?:\.[0-9]+)*) # release segment (?P
                                          # pre-release
            [-_\.]?
            (?Palpha|a|beta|b|preview|pre|c|rc)
            [-_\.]?
            (?P[0-9]+)?
        )?
        (?P                                         # post release
            (?:-(?P[0-9]+))
            |
            (?:
                [-_\.]?
                (?Ppost|rev|r)
                [-_\.]?
                (?P[0-9]+)?
            )
        )?
        (?P                                          # dev release
            [-_\.]?
            (?Pdev)
            [-_\.]?
            (?P[0-9]+)?
        )?
    )
    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
"""

VERSION_PATTERN = _VERSION_PATTERN
"""
A string containing the regular expression used to match a valid version.

The pattern is not anchored at either end, and is intended for embedding in larger
expressions (for example, matching a version number as part of a file name). The
regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
flags set.

:meta hide-value:
"""


class Version(_BaseVersion):
    """This class abstracts handling of a project's versions.

    A :class:`Version` instance is comparison aware and can be compared and
    sorted using the standard Python interfaces.

    >>> v1 = Version("1.0a5")
    >>> v2 = Version("1.0")
    >>> v1
    
    >>> v2
    
    >>> v1 < v2
    True
    >>> v1 == v2
    False
    >>> v1 > v2
    False
    >>> v1 >= v2
    False
    >>> v1 <= v2
    True
    """

    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
    _key: CmpKey

    def __init__(self, version: str) -> None:
        """Initialize a Version object.

        :param version:
            The string representation of a version which will be parsed and normalized
            before use.
        :raises InvalidVersion:
            If the ``version`` does not conform to PEP 440 in any way then this
            exception will be raised.
        """

        # Validate the version and parse it into pieces
        match = self._regex.search(version)
        if not match:
            raise InvalidVersion(f"Invalid version: '{version}'")

        # Store the parsed out pieces of the version
        self._version = _Version(
            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
            release=tuple(int(i) for i in match.group("release").split(".")),
            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
            post=_parse_letter_version(
                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
            ),
            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
            local=_parse_local_version(match.group("local")),
        )

        # Generate a key which will be used for sorting
        self._key = _cmpkey(
            self._version.epoch,
            self._version.release,
            self._version.pre,
            self._version.post,
            self._version.dev,
            self._version.local,
        )

    def __repr__(self) -> str:
        """A representation of the Version that shows all internal state.

        >>> Version('1.0.0')
        
        """
        return f""

    def __str__(self) -> str:
        """A string representation of the version that can be rounded-tripped.

        >>> str(Version("1.0a5"))
        '1.0a5'
        """
        parts = []

        # Epoch
        if self.epoch != 0:
            parts.append(f"{self.epoch}!")

        # Release segment
        parts.append(".".join(str(x) for x in self.release))

        # Pre-release
        if self.pre is not None:
            parts.append("".join(str(x) for x in self.pre))

        # Post-release
        if self.post is not None:
            parts.append(f".post{self.post}")

        # Development release
        if self.dev is not None:
            parts.append(f".dev{self.dev}")

        # Local version segment
        if self.local is not None:
            parts.append(f"+{self.local}")

        return "".join(parts)

    @property
    def epoch(self) -> int:
        """The epoch of the version.

        >>> Version("2.0.0").epoch
        0
        >>> Version("1!2.0.0").epoch
        1
        """
        return self._version.epoch

    @property
    def release(self) -> Tuple[int, ...]:
        """The components of the "release" segment of the version.

        >>> Version("1.2.3").release
        (1, 2, 3)
        >>> Version("2.0.0").release
        (2, 0, 0)
        >>> Version("1!2.0.0.post0").release
        (2, 0, 0)

        Includes trailing zeroes but not the epoch or any pre-release / development /
        post-release suffixes.
        """
        return self._version.release

    @property
    def pre(self) -> Optional[Tuple[str, int]]:
        """The pre-release segment of the version.

        >>> print(Version("1.2.3").pre)
        None
        >>> Version("1.2.3a1").pre
        ('a', 1)
        >>> Version("1.2.3b1").pre
        ('b', 1)
        >>> Version("1.2.3rc1").pre
        ('rc', 1)
        """
        return self._version.pre

    @property
    def post(self) -> Optional[int]:
        """The post-release number of the version.

        >>> print(Version("1.2.3").post)
        None
        >>> Version("1.2.3.post1").post
        1
        """
        return self._version.post[1] if self._version.post else None

    @property
    def dev(self) -> Optional[int]:
        """The development number of the version.

        >>> print(Version("1.2.3").dev)
        None
        >>> Version("1.2.3.dev1").dev
        1
        """
        return self._version.dev[1] if self._version.dev else None

    @property
    def local(self) -> Optional[str]:
        """The local version segment of the version.

        >>> print(Version("1.2.3").local)
        None
        >>> Version("1.2.3+abc").local
        'abc'
        """
        if self._version.local:
            return ".".join(str(x) for x in self._version.local)
        else:
            return None

    @property
    def public(self) -> str:
        """The public portion of the version.

        >>> Version("1.2.3").public
        '1.2.3'
        >>> Version("1.2.3+abc").public
        '1.2.3'
        >>> Version("1.2.3+abc.dev1").public
        '1.2.3'
        """
        return str(self).split("+", 1)[0]

    @property
    def base_version(self) -> str:
        """The "base version" of the version.

        >>> Version("1.2.3").base_version
        '1.2.3'
        >>> Version("1.2.3+abc").base_version
        '1.2.3'
        >>> Version("1!1.2.3+abc.dev1").base_version
        '1!1.2.3'

        The "base version" is the public version of the project without any pre or post
        release markers.
        """
        parts = []

        # Epoch
        if self.epoch != 0:
            parts.append(f"{self.epoch}!")

        # Release segment
        parts.append(".".join(str(x) for x in self.release))

        return "".join(parts)

    @property
    def is_prerelease(self) -> bool:
        """Whether this version is a pre-release.

        >>> Version("1.2.3").is_prerelease
        False
        >>> Version("1.2.3a1").is_prerelease
        True
        >>> Version("1.2.3b1").is_prerelease
        True
        >>> Version("1.2.3rc1").is_prerelease
        True
        >>> Version("1.2.3dev1").is_prerelease
        True
        """
        return self.dev is not None or self.pre is not None

    @property
    def is_postrelease(self) -> bool:
        """Whether this version is a post-release.

        >>> Version("1.2.3").is_postrelease
        False
        >>> Version("1.2.3.post1").is_postrelease
        True
        """
        return self.post is not None

    @property
    def is_devrelease(self) -> bool:
        """Whether this version is a development release.

        >>> Version("1.2.3").is_devrelease
        False
        >>> Version("1.2.3.dev1").is_devrelease
        True
        """
        return self.dev is not None

    @property
    def major(self) -> int:
        """The first item of :attr:`release` or ``0`` if unavailable.

        >>> Version("1.2.3").major
        1
        """
        return self.release[0] if len(self.release) >= 1 else 0

    @property
    def minor(self) -> int:
        """The second item of :attr:`release` or ``0`` if unavailable.

        >>> Version("1.2.3").minor
        2
        >>> Version("1").minor
        0
        """
        return self.release[1] if len(self.release) >= 2 else 0

    @property
    def micro(self) -> int:
        """The third item of :attr:`release` or ``0`` if unavailable.

        >>> Version("1.2.3").micro
        3
        >>> Version("1").micro
        0
        """
        return self.release[2] if len(self.release) >= 3 else 0


def _parse_letter_version(
    letter: Optional[str], number: Union[str, bytes, SupportsInt, None]
) -> Optional[Tuple[str, int]]:

    if letter:
        # We consider there to be an implicit 0 in a pre-release if there is
        # not a numeral associated with it.
        if number is None:
            number = 0

        # We normalize any letters to their lower case form
        letter = letter.lower()

        # We consider some words to be alternate spellings of other words and
        # in those cases we want to normalize the spellings to our preferred
        # spelling.
        if letter == "alpha":
            letter = "a"
        elif letter == "beta":
            letter = "b"
        elif letter in ["c", "pre", "preview"]:
            letter = "rc"
        elif letter in ["rev", "r"]:
            letter = "post"

        return letter, int(number)
    if not letter and number:
        # We assume if we are given a number, but we are not given a letter
        # then this is using the implicit post release syntax (e.g. 1.0-1)
        letter = "post"

        return letter, int(number)

    return None


_local_version_separators = re.compile(r"[\._-]")


def _parse_local_version(local: Optional[str]) -> Optional[LocalType]:
    """
    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
    """
    if local is not None:
        return tuple(
            part.lower() if not part.isdigit() else int(part)
            for part in _local_version_separators.split(local)
        )
    return None


def _cmpkey(
    epoch: int,
    release: Tuple[int, ...],
    pre: Optional[Tuple[str, int]],
    post: Optional[Tuple[str, int]],
    dev: Optional[Tuple[str, int]],
    local: Optional[LocalType],
) -> CmpKey:

    # When we compare a release version, we want to compare it with all of the
    # trailing zeros removed. So we'll use a reverse the list, drop all the now
    # leading zeros until we come to something non zero, then take the rest
    # re-reverse it back into the correct order and make it a tuple and use
    # that for our sorting key.
    _release = tuple(
        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
    )

    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
    # We'll do this by abusing the pre segment, but we _only_ want to do this
    # if there is not a pre or a post segment. If we have one of those then
    # the normal sorting rules will handle this case correctly.
    if pre is None and post is None and dev is not None:
        _pre: CmpPrePostDevType = NegativeInfinity
    # Versions without a pre-release (except as noted above) should sort after
    # those with one.
    elif pre is None:
        _pre = Infinity
    else:
        _pre = pre

    # Versions without a post segment should sort before those with one.
    if post is None:
        _post: CmpPrePostDevType = NegativeInfinity

    else:
        _post = post

    # Versions without a development segment should sort after those with one.
    if dev is None:
        _dev: CmpPrePostDevType = Infinity

    else:
        _dev = dev

    if local is None:
        # Versions without a local segment should sort before those with one.
        _local: CmpLocalType = NegativeInfinity
    else:
        # Versions with a local segment need that segment parsed to implement
        # the sorting rules in PEP440.
        # - Alpha numeric segments sort before numeric segments
        # - Alpha numeric segments sort lexicographically
        # - Numeric segments sort numerically
        # - Shorter versions sort before longer versions when the prefixes
        #   match exactly
        _local = tuple(
            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
        )

    return epoch, _release, _pre, _post, _dev, _local
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "gyp-next"
version = "0.18.1"
authors = [
  { name="Node.js contributors", email="ryzokuken@disroot.org" },
]
description = "A fork of the GYP build system for use in the Node.js projects"
readme = "README.md"
license = { file="LICENSE" }
requires-python = ">=3.8"
dependencies = ["packaging>=24.0", "setuptools>=69.5.1"]
classifiers = [
    "Development Status :: 3 - Alpha",
    "Environment :: Console",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: BSD License",
    "Natural Language :: English",
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.8",
    "Programming Language :: Python :: 3.9",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.11",
]

[project.optional-dependencies]
dev = ["pytest", "ruff"]

[project.scripts]
gyp = "gyp:script_main"

[project.urls]
"Homepage" = "https://github.com/nodejs/gyp-next"

[tool.ruff]
extend-exclude = ["pylib/packaging"]
line-length = 88
target-version = "py37"

[tool.ruff.lint]
select = [
  "C4",   # flake8-comprehensions
  "C90",  # McCabe cyclomatic complexity
  "DTZ",  # flake8-datetimez
  "E",    # pycodestyle
  "F",    # Pyflakes
  "G",    # flake8-logging-format
  "ICN",  # flake8-import-conventions
  "INT",  # flake8-gettext
  "PL",   # Pylint
  "PYI",  # flake8-pyi
  "RSE",  # flake8-raise
  "RUF",  # Ruff-specific rules
  "T10",  # flake8-debugger
  "TCH",  # flake8-type-checking
  "TID",  # flake8-tidy-imports
  "UP",   # pyupgrade
  "W",    # pycodestyle
  "YTT",  # flake8-2020
  # "A",    # flake8-builtins
  # "ANN",  # flake8-annotations
  # "ARG",  # flake8-unused-arguments
  # "B",    # flake8-bugbear
  # "BLE",  # flake8-blind-except
  # "COM",  # flake8-commas
  # "D",    # pydocstyle
  # "DJ",   # flake8-django
  # "EM",   # flake8-errmsg
  # "ERA",  # eradicate
  # "EXE",  # flake8-executable
  # "FBT",  # flake8-boolean-trap
  # "I",    # isort
  # "INP",  # flake8-no-pep420
  # "ISC",  # flake8-implicit-str-concat
  # "N",    # pep8-naming
  # "NPY",  # NumPy-specific rules
  # "PD",   # pandas-vet
  # "PGH",  # pygrep-hooks
  # "PIE",  # flake8-pie
  # "PT",   # flake8-pytest-style
  # "PTH",  # flake8-use-pathlib
  # "Q",    # flake8-quotes
  # "RET",  # flake8-return
  # "S",    # flake8-bandit
  # "SIM",  # flake8-simplify
  # "SLF",  # flake8-self
  # "T20",  # flake8-print
  # "TRY",  # tryceratops
]
ignore = [
  "E721",
  "PLC1901",
  "PLR0402",
  "PLR1714",
  "PLR2004",
  "PLR5501",
  "PLW0603",
  "PLW2901",
  "PYI024",
  "RUF005",
  "RUF012",
  "UP031",
]

[tool.ruff.lint.mccabe]
max-complexity = 101

[tool.ruff.lint.pylint]
max-args = 11
max-branches = 108
max-returns = 10
max-statements = 286

[tool.setuptools]
package-dir = {"" = "pylib"}
packages = ["gyp", "gyp.generator"]
{
    "last-release-sha": "78756421b0d7bb335992a9c7d26ba3cc8b619708",
    "packages": {
        ".": {
          "release-type": "python",
          "package-name": "gyp-next",
          "bump-minor-pre-major": true,
          "include-component-in-tag": false
        }
    }
}
#!/usr/bin/env python3
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""gyptest.py -- test runner for GYP tests."""


import argparse
import os
import platform
import subprocess
import sys
import time


def is_test_name(f):
    return f.startswith("gyptest") and f.endswith(".py")


def find_all_gyptest_files(directory):
    result = []
    for root, dirs, files in os.walk(directory):
        result.extend([os.path.join(root, f) for f in files if is_test_name(f)])
    result.sort()
    return result


def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--all", action="store_true", help="run all tests")
    parser.add_argument("-C", "--chdir", action="store", help="change to directory")
    parser.add_argument(
        "-f",
        "--format",
        action="store",
        default="",
        help="run tests with the specified formats",
    )
    parser.add_argument(
        "-G",
        "--gyp_option",
        action="append",
        default=[],
        help="Add -G options to the gyp command line",
    )
    parser.add_argument(
        "-l", "--list", action="store_true", help="list available tests and exit"
    )
    parser.add_argument(
        "-n",
        "--no-exec",
        action="store_true",
        help="no execute, just print the command line",
    )
    parser.add_argument(
        "--path", action="append", default=[], help="additional $PATH directory"
    )
    parser.add_argument(
        "-q",
        "--quiet",
        action="store_true",
        help="quiet, don't print anything unless there are failures",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="print configuration info and test results.",
    )
    parser.add_argument("tests", nargs="*")
    args = parser.parse_args(argv[1:])

    if args.chdir:
        os.chdir(args.chdir)

    if args.path:
        extra_path = [os.path.abspath(p) for p in args.path]
        extra_path = os.pathsep.join(extra_path)
        os.environ["PATH"] = extra_path + os.pathsep + os.environ["PATH"]

    if not args.tests:
        if not args.all:
            sys.stderr.write("Specify -a to get all tests.\n")
            return 1
        args.tests = ["test"]

    tests = []
    for arg in args.tests:
        if os.path.isdir(arg):
            tests.extend(find_all_gyptest_files(os.path.normpath(arg)))
        else:
            if not is_test_name(os.path.basename(arg)):
                print(arg, "is not a valid gyp test name.", file=sys.stderr)
                sys.exit(1)
            tests.append(arg)

    if args.list:
        for test in tests:
            print(test)
        sys.exit(0)

    os.environ["PYTHONPATH"] = os.path.abspath("test/lib")

    if args.verbose:
        print_configuration_info()

    if args.gyp_option and not args.quiet:
        print("Extra Gyp options: %s\n" % args.gyp_option)

    if args.format:
        format_list = args.format.split(",")
    else:
        format_list = {
            "aix5": ["make"],
            "os400": ["make"],
            "freebsd7": ["make"],
            "freebsd8": ["make"],
            "openbsd5": ["make"],
            "cygwin": ["msvs"],
            "win32": ["msvs", "ninja"],
            "linux": ["make", "ninja"],
            "linux2": ["make", "ninja"],
            "linux3": ["make", "ninja"],
            # TODO: Re-enable xcode-ninja.
            # https://bugs.chromium.org/p/gyp/issues/detail?id=530
            # 'darwin':   ['make', 'ninja', 'xcode', 'xcode-ninja'],
            "darwin": ["make", "ninja", "xcode"],
        }[sys.platform]

    gyp_options = []
    for option in args.gyp_option:
        gyp_options += ["-G", option]

    runner = Runner(format_list, tests, gyp_options, args.verbose)
    runner.run()

    if not args.quiet:
        runner.print_results()

    return 1 if runner.failures else 0


def print_configuration_info():
    print("Test configuration:")
    if sys.platform == "darwin":
        sys.path.append(os.path.abspath("test/lib"))
        import TestMac

        print(f"  Mac {platform.mac_ver()[0]} {platform.mac_ver()[2]}")
        print(f"  Xcode {TestMac.Xcode.Version()}")
    elif sys.platform == "win32":
        sys.path.append(os.path.abspath("pylib"))
        import gyp.MSVSVersion

        print("  Win %s %s\n" % platform.win32_ver()[0:2])
        print("  MSVS %s" % gyp.MSVSVersion.SelectVisualStudioVersion().Description())
    elif sys.platform in ("linux", "linux2"):
        print("  Linux %s" % " ".join(platform.linux_distribution()))
    print(f"  Python {platform.python_version()}")
    print(f"  PYTHONPATH={os.environ['PYTHONPATH']}")
    print()


class Runner:
    def __init__(self, formats, tests, gyp_options, verbose):
        self.formats = formats
        self.tests = tests
        self.verbose = verbose
        self.gyp_options = gyp_options
        self.failures = []
        self.num_tests = len(formats) * len(tests)
        num_digits = len(str(self.num_tests))
        self.fmt_str = "[%%%dd/%%%dd] (%%s) %%s" % (num_digits, num_digits)
        self.isatty = sys.stdout.isatty() and not self.verbose
        self.env = os.environ.copy()
        self.hpos = 0

    def run(self):
        run_start = time.time()

        i = 1
        for fmt in self.formats:
            for test in self.tests:
                self.run_test(test, fmt, i)
                i += 1

        if self.isatty:
            self.erase_current_line()

        self.took = time.time() - run_start

    def run_test(self, test, fmt, i):
        if self.isatty:
            self.erase_current_line()

        msg = self.fmt_str % (i, self.num_tests, fmt, test)
        self.print_(msg)

        start = time.time()
        cmd = [sys.executable, test] + self.gyp_options
        self.env["TESTGYP_FORMAT"] = fmt
        proc = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=self.env
        )
        proc.wait()
        took = time.time() - start

        stdout = proc.stdout.read().decode("utf8")
        if proc.returncode == 2:
            res = "skipped"
        elif proc.returncode:
            res = "failed"
            self.failures.append(f"({test}) {fmt}")
        else:
            res = "passed"
        res_msg = f" {res} {took:.3f}s"
        self.print_(res_msg)

        if stdout and not stdout.endswith(("PASSED\n", "NO RESULT\n")):
            print()
            print("\n".join(f"    {line}" for line in stdout.splitlines()))
        elif not self.isatty:
            print()

    def print_(self, msg):
        print(msg, end="")
        index = msg.rfind("\n")
        if index == -1:
            self.hpos += len(msg)
        else:
            self.hpos = len(msg) - index
        sys.stdout.flush()

    def erase_current_line(self):
        print("\b" * self.hpos + " " * self.hpos + "\b" * self.hpos, end="")
        sys.stdout.flush()
        self.hpos = 0

    def print_results(self):
        num_failures = len(self.failures)
        if num_failures:
            print()
            if num_failures == 1:
                print("Failed the following test:")
            else:
                print("Failed the following %d tests:" % num_failures)
            print("\t" + "\n\t".join(sorted(self.failures)))
            print()
        print(
            "Ran %d tests in %.3fs, %d failed."
            % (self.num_tests, self.took, num_failures)
        )
        print()


if __name__ == "__main__":
    sys.exit(main())
// Copyright 2017 - Refael Ackermann
// Distributed under MIT style license
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf

// Usage:
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace VisualStudioConfiguration
{
    [Flags]
    public enum InstanceState : uint
    {
        None = 0,
        Local = 1,
        Registered = 2,
        NoRebootRequired = 4,
        NoErrors = 8,
        Complete = 4294967295,
    }

    [Guid("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface IEnumSetupInstances
    {

        void Next([MarshalAs(UnmanagedType.U4), In] int celt,
            [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface), Out] ISetupInstance[] rgelt,
            [MarshalAs(UnmanagedType.U4)] out int pceltFetched);

        void Skip([MarshalAs(UnmanagedType.U4), In] int celt);

        void Reset();

        [return: MarshalAs(UnmanagedType.Interface)]
        IEnumSetupInstances Clone();
    }

    [Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface ISetupConfiguration
    {
    }

    [Guid("26AAB78C-4A60-49D6-AF3B-3C35BC93365D")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface ISetupConfiguration2 : ISetupConfiguration
    {

        [return: MarshalAs(UnmanagedType.Interface)]
        IEnumSetupInstances EnumInstances();

        [return: MarshalAs(UnmanagedType.Interface)]
        ISetupInstance GetInstanceForCurrentProcess();

        [return: MarshalAs(UnmanagedType.Interface)]
        ISetupInstance GetInstanceForPath([MarshalAs(UnmanagedType.LPWStr), In] string path);

        [return: MarshalAs(UnmanagedType.Interface)]
        IEnumSetupInstances EnumAllInstances();
    }

    [Guid("B41463C3-8866-43B5-BC33-2B0676F7F42E")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface ISetupInstance
    {
    }

    [Guid("89143C9A-05AF-49B0-B717-72E218A2185C")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface ISetupInstance2 : ISetupInstance
    {
        [return: MarshalAs(UnmanagedType.BStr)]
        string GetInstanceId();

        [return: MarshalAs(UnmanagedType.Struct)]
        System.Runtime.InteropServices.ComTypes.FILETIME GetInstallDate();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetInstallationName();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetInstallationPath();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetInstallationVersion();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetDisplayName([MarshalAs(UnmanagedType.U4), In] int lcid);

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetDescription([MarshalAs(UnmanagedType.U4), In] int lcid);

        [return: MarshalAs(UnmanagedType.BStr)]
        string ResolvePath([MarshalAs(UnmanagedType.LPWStr), In] string pwszRelativePath);

        [return: MarshalAs(UnmanagedType.U4)]
        InstanceState GetState();

        [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
        ISetupPackageReference[] GetPackages();

        ISetupPackageReference GetProduct();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetProductPath();

        [return: MarshalAs(UnmanagedType.VariantBool)]
        bool IsLaunchable();

        [return: MarshalAs(UnmanagedType.VariantBool)]
        bool IsComplete();

        [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
        ISetupPropertyStore GetProperties();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetEnginePath();
    }

    [Guid("DA8D8A16-B2B6-4487-A2F1-594CCCCD6BF5")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface ISetupPackageReference
    {

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetId();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetVersion();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetChip();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetLanguage();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetBranch();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetType();

        [return: MarshalAs(UnmanagedType.BStr)]
        string GetUniqueId();

        [return: MarshalAs(UnmanagedType.VariantBool)]
        bool GetIsExtension();
    }

    [Guid("c601c175-a3be-44bc-91f6-4568d230fc83")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface ISetupPropertyStore
    {

        [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
        string[] GetNames();

        object GetValue([MarshalAs(UnmanagedType.LPWStr), In] string pwszName);
    }

    [Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")]
    [CoClass(typeof(SetupConfigurationClass))]
    [ComImport]
    public interface SetupConfiguration : ISetupConfiguration2, ISetupConfiguration
    {
    }

    [Guid("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComImport]
    public class SetupConfigurationClass
    {
    }

    public static class Main
    {
        public static void PrintJson()
        {
            ISetupConfiguration query = new SetupConfiguration();
            ISetupConfiguration2 query2 = (ISetupConfiguration2)query;
            IEnumSetupInstances e = query2.EnumAllInstances();

            int pceltFetched;
            ISetupInstance2[] rgelt = new ISetupInstance2[1];
            List instances = new List();
            while (true)
            {
                e.Next(1, rgelt, out pceltFetched);
                if (pceltFetched <= 0)
                {
                    Console.WriteLine(String.Format("[{0}]", string.Join(",", instances.ToArray())));
                    return;
                }

                try
                {
                    instances.Add(InstanceJson(rgelt[0]));
                }
                catch (COMException)
                {
                    // Ignore instances that can't be queried.
                }
            }
        }

        private static string JsonString(string s)
        {
            return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
        }

        private static string InstanceJson(ISetupInstance2 setupInstance2)
        {
            // Visual Studio component directory:
            // https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids

            StringBuilder json = new StringBuilder();
            json.Append("{");

            string path = JsonString(setupInstance2.GetInstallationPath());
            json.Append(String.Format("\"path\":{0},", path));

            string version = JsonString(setupInstance2.GetInstallationVersion());
            json.Append(String.Format("\"version\":{0},", version));

            List packages = new List();
            foreach (ISetupPackageReference package in setupInstance2.GetPackages())
            {
                string id = JsonString(package.GetId());
                packages.Add(id);
            }
            json.Append(String.Format("\"packages\":[{0}]", string.Join(",", packages.ToArray())));

            json.Append("}");
            return json.ToString();
        }
    }
}
'use strict'

const gracefulFs = require('graceful-fs')
const fs = gracefulFs.promises
const path = require('path')
const { glob } = require('glob')
const log = require('./log')
const which = require('which')
const win = process.platform === 'win32'

async function build (gyp, argv) {
  let platformMake = 'make'
  if (process.platform === 'aix') {
    platformMake = 'gmake'
  } else if (process.platform === 'os400') {
    platformMake = 'gmake'
  } else if (process.platform.indexOf('bsd') !== -1) {
    platformMake = 'gmake'
  } else if (win && argv.length > 0) {
    argv = argv.map(function (target) {
      return '/t:' + target
    })
  }

  const makeCommand = gyp.opts.make || process.env.MAKE || platformMake
  let command = win ? 'msbuild' : makeCommand
  const jobs = gyp.opts.jobs || process.env.JOBS
  let buildType
  let config
  let arch
  let nodeDir
  let guessedSolution
  let python
  let buildBinsDir

  await loadConfigGypi()

  /**
   * Load the "config.gypi" file that was generated during "configure".
   */

  async function loadConfigGypi () {
    let data
    try {
      const configPath = path.resolve('build', 'config.gypi')
      data = await fs.readFile(configPath, 'utf8')
    } catch (err) {
      if (err.code === 'ENOENT') {
        throw new Error('You must run `node-gyp configure` first!')
      } else {
        throw err
      }
    }

    config = JSON.parse(data.replace(/#.+\n/, ''))

    // get the 'arch', 'buildType', and 'nodeDir' vars from the config
    buildType = config.target_defaults.default_configuration
    arch = config.variables.target_arch
    nodeDir = config.variables.nodedir
    python = config.variables.python

    if ('debug' in gyp.opts) {
      buildType = gyp.opts.debug ? 'Debug' : 'Release'
    }
    if (!buildType) {
      buildType = 'Release'
    }

    log.verbose('build type', buildType)
    log.verbose('architecture', arch)
    log.verbose('node dev dir', nodeDir)
    log.verbose('python', python)

    if (win) {
      await findSolutionFile()
    } else {
      await doWhich()
    }
  }

  /**
   * On Windows, find the first build/*.sln file.
   */

  async function findSolutionFile () {
    const files = await glob('build/*.sln')
    if (files.length === 0) {
      if (gracefulFs.existsSync('build/Makefile') || (await glob('build/*.mk')).length !== 0) {
        command = makeCommand
        await doWhich(false)
        return
      } else {
        throw new Error('Could not find *.sln file or Makefile. Did you run "configure"?')
      }
    }
    guessedSolution = files[0]
    log.verbose('found first Solution file', guessedSolution)
    await doWhich(true)
  }

  /**
   * Uses node-which to locate the msbuild / make executable.
   */

  async function doWhich (msvs) {
    // On Windows use msbuild provided by node-gyp configure
    if (msvs) {
      if (!config.variables.msbuild_path) {
        throw new Error('MSBuild is not set, please run `node-gyp configure`.')
      }
      command = config.variables.msbuild_path
      log.verbose('using MSBuild:', command)
      await doBuild(msvs)
      return
    }

    // First make sure we have the build command in the PATH
    const execPath = await which(command)
    log.verbose('`which` succeeded for `' + command + '`', execPath)
    await doBuild(msvs)
  }

  /**
   * Actually spawn the process and compile the module.
   */

  async function doBuild (msvs) {
    // Enable Verbose build
    const verbose = log.logger.isVisible('verbose')
    let j

    if (!msvs && verbose) {
      argv.push('V=1')
    }

    if (msvs && !verbose) {
      argv.push('/clp:Verbosity=minimal')
    }

    if (msvs) {
      // Turn off the Microsoft logo on Windows
      argv.push('/nologo')
    }

    // Specify the build type, Release by default
    if (msvs) {
      // Convert .gypi config target_arch to MSBuild /Platform
      // Since there are many ways to state '32-bit Intel', default to it.
      // N.B. msbuild's Condition string equality tests are case-insensitive.
      const archLower = arch.toLowerCase()
      const p = archLower === 'x64'
        ? 'x64'
        : (archLower === 'arm'
            ? 'ARM'
            : (archLower === 'arm64' ? 'ARM64' : 'Win32'))
      argv.push('/p:Configuration=' + buildType + ';Platform=' + p)
      if (jobs) {
        j = parseInt(jobs, 10)
        if (!isNaN(j) && j > 0) {
          argv.push('/m:' + j)
        } else if (jobs.toUpperCase() === 'MAX') {
          argv.push('/m:' + require('os').cpus().length)
        }
      }
    } else {
      argv.push('BUILDTYPE=' + buildType)
      // Invoke the Makefile in the 'build' dir.
      argv.push('-C')
      argv.push('build')
      if (jobs) {
        j = parseInt(jobs, 10)
        if (!isNaN(j) && j > 0) {
          argv.push('--jobs')
          argv.push(j)
        } else if (jobs.toUpperCase() === 'MAX') {
          argv.push('--jobs')
          argv.push(require('os').cpus().length)
        }
      }
    }

    if (msvs) {
      // did the user specify their own .sln file?
      const hasSln = argv.some(function (arg) {
        return path.extname(arg) === '.sln'
      })
      if (!hasSln) {
        argv.unshift(gyp.opts.solution || guessedSolution)
      }
    }

    if (!win) {
      // Add build-time dependency symlinks (such as Python) to PATH
      buildBinsDir = path.resolve('build', 'node_gyp_bins')
      process.env.PATH = `${buildBinsDir}:${process.env.PATH}`
      await fs.mkdir(buildBinsDir, { recursive: true })
      const symlinkDestination = path.join(buildBinsDir, 'python3')
      try {
        await fs.unlink(symlinkDestination)
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
      await fs.symlink(python, symlinkDestination)
      log.verbose('bin symlinks', `created symlink to "${python}" in "${buildBinsDir}" and added to PATH`)
    }

    const proc = gyp.spawn(command, argv)
    await new Promise((resolve, reject) => proc.on('exit', async (code, signal) => {
      if (buildBinsDir) {
        // Clean up the build-time dependency symlinks:
        await fs.rm(buildBinsDir, { recursive: true })
      }

      if (code !== 0) {
        return reject(new Error('`' + command + '` failed with exit code: ' + code))
      }
      if (signal) {
        return reject(new Error('`' + command + '` got signal: ' + signal))
      }
      resolve()
    }))
  }
}

module.exports = build
module.exports.usage = 'Invokes `' + (win ? 'msbuild' : 'make') + '` and builds the module'
'use strict'

const fs = require('graceful-fs').promises
const log = require('./log')

async function clean (gyp, argv) {
  // Remove the 'build' dir
  const buildDir = 'build'

  log.verbose('clean', 'removing "%s" directory', buildDir)
  await fs.rm(buildDir, { recursive: true, force: true })
}

module.exports = clean
module.exports.usage = 'Removes any generated build files and the "out" dir'
'use strict'

const { promises: fs, readFileSync } = require('graceful-fs')
const path = require('path')
const log = require('./log')
const os = require('os')
const processRelease = require('./process-release')
const win = process.platform === 'win32'
const findNodeDirectory = require('./find-node-directory')
const { createConfigGypi } = require('./create-config-gypi')
const { format: msgFormat } = require('util')
const { findAccessibleSync } = require('./util')
const { findPython } = require('./find-python')
const { findVisualStudio } = win ? require('./find-visualstudio') : {}

const majorRe = /^#define NODE_MAJOR_VERSION (\d+)/m
const minorRe = /^#define NODE_MINOR_VERSION (\d+)/m
const patchRe = /^#define NODE_PATCH_VERSION (\d+)/m

async function configure (gyp, argv) {
  const buildDir = path.resolve('build')
  const configNames = ['config.gypi', 'common.gypi']
  const configs = []
  let nodeDir
  const release = processRelease(argv, gyp, process.version, process.release)

  const python = await findPython(gyp.opts.python)
  return getNodeDir()

  async function getNodeDir () {
    // 'python' should be set by now
    process.env.PYTHON = python

    if (!gyp.opts.nodedir &&
        process.config.variables.use_prefix_to_find_headers) {
      // check if the headers can be found using the prefix specified
      // at build time. Use them if they match the version expected
      const prefix = process.config.variables.node_prefix
      let availVersion
      try {
        const nodeVersionH = readFileSync(path.join(prefix,
          'include', 'node', 'node_version.h'), { encoding: 'utf8' })
        const major = nodeVersionH.match(majorRe)[1]
        const minor = nodeVersionH.match(minorRe)[1]
        const patch = nodeVersionH.match(patchRe)[1]
        availVersion = major + '.' + minor + '.' + patch
      } catch {}
      if (availVersion === release.version) {
        // ok version matches, use the headers
        gyp.opts.nodedir = prefix
        log.verbose('using local node headers based on prefix',
          'setting nodedir to ' + gyp.opts.nodedir)
      }
    }

    if (gyp.opts.nodedir) {
      // --nodedir was specified. use that for the dev files
      nodeDir = gyp.opts.nodedir.replace(/^~/, os.homedir())
      log.verbose('get node dir', 'compiling against specified --nodedir dev files: %s', nodeDir)
    } else {
      // if no --nodedir specified, ensure node dependencies are installed
      if ('v' + release.version !== process.version) {
        // if --target was given, then determine a target version to compile for
        log.verbose('get node dir', 'compiling against --target node version: %s', release.version)
      } else {
        // if no --target was specified then use the current host node version
        log.verbose('get node dir', 'no --target version specified, falling back to host node version: %s', release.version)
      }

      if (!release.semver) {
        // could not parse the version string with semver
        throw new Error('Invalid version number: ' + release.version)
      }

      // If the tarball option is set, always remove and reinstall the headers
      // into devdir. Otherwise only install if they're not already there.
      gyp.opts.ensure = !gyp.opts.tarball

      await gyp.commands.install([release.version])

      log.verbose('get node dir', 'target node version installed:', release.versionDir)
      nodeDir = path.resolve(gyp.devDir, release.versionDir)
    }

    return createBuildDir()
  }

  async function createBuildDir () {
    log.verbose('build dir', 'attempting to create "build" dir: %s', buildDir)

    const isNew = await fs.mkdir(buildDir, { recursive: true })
    log.verbose(
      'build dir', '"build" dir needed to be created?', isNew ? 'Yes' : 'No'
    )
    if (win) {
      let usingMakeGenerator = false
      for (let i = argv.length - 1; i >= 0; --i) {
        const arg = argv[i]
        if (arg === '-f' || arg === '--format') {
          const format = argv[i + 1]
          if (typeof format === 'string' && format.startsWith('make')) {
            usingMakeGenerator = true
            break
          }
        } else if (arg.startsWith('--format=make')) {
          usingMakeGenerator = true
          break
        }
      }
      let vsInfo = {}
      if (!usingMakeGenerator) {
        vsInfo = await findVisualStudio(release.semver, gyp.opts['msvs-version'])
      }
      return createConfigFile(vsInfo)
    }
    return createConfigFile(null)
  }

  async function createConfigFile (vsInfo) {
    if (win) {
      process.env.GYP_MSVS_VERSION = Math.min(vsInfo.versionYear, 2015)
      process.env.GYP_MSVS_OVERRIDE_PATH = vsInfo.path
    }
    const configPath = await createConfigGypi({ gyp, buildDir, nodeDir, vsInfo, python })
    configs.push(configPath)
    return findConfigs()
  }

  async function findConfigs () {
    const name = configNames.shift()
    if (!name) {
      return runGyp()
    }

    const fullPath = path.resolve(name)
    log.verbose(name, 'checking for gypi file: %s', fullPath)
    try {
      await fs.stat(fullPath)
      log.verbose(name, 'found gypi file')
      configs.push(fullPath)
    } catch (err) {
      // ENOENT will check next gypi filename
      if (err.code !== 'ENOENT') {
        throw err
      }
    }

    return findConfigs()
  }

  async function runGyp () {
    if (!~argv.indexOf('-f') && !~argv.indexOf('--format')) {
      if (win) {
        log.verbose('gyp', 'gyp format was not specified; forcing "msvs"')
        // force the 'make' target for non-Windows
        argv.push('-f', 'msvs')
      } else {
        log.verbose('gyp', 'gyp format was not specified; forcing "make"')
        // force the 'make' target for non-Windows
        argv.push('-f', 'make')
      }
    }

    // include all the ".gypi" files that were found
    configs.forEach(function (config) {
      argv.push('-I', config)
    })

    // For AIX and z/OS we need to set up the path to the exports file
    // which contains the symbols needed for linking.
    let nodeExpFile
    let nodeRootDir
    let candidates
    let logprefix = 'find exports file'
    if (process.platform === 'aix' || process.platform === 'os390' || process.platform === 'os400') {
      const ext = process.platform === 'os390' ? 'x' : 'exp'
      nodeRootDir = findNodeDirectory()

      if (process.platform === 'aix' || process.platform === 'os400') {
        candidates = [
          'include/node/node',
          'out/Release/node',
          'out/Debug/node',
          'node'
        ].map(function (file) {
          return file + '.' + ext
        })
      } else {
        candidates = [
          'out/Release/lib.target/libnode',
          'out/Debug/lib.target/libnode',
          'out/Release/obj.target/libnode',
          'out/Debug/obj.target/libnode',
          'lib/libnode'
        ].map(function (file) {
          return file + '.' + ext
        })
      }

      nodeExpFile = findAccessibleSync(logprefix, nodeRootDir, candidates)
      if (nodeExpFile !== undefined) {
        log.verbose(logprefix, 'Found exports file: %s', nodeExpFile)
      } else {
        const msg = msgFormat('Could not find node.%s file in %s', ext, nodeRootDir)
        log.error(logprefix, 'Could not find exports file')
        throw new Error(msg)
      }
    }

    // For z/OS we need to set up the path to zoslib include directory,
    // which contains headers included in v8config.h.
    let zoslibIncDir
    if (process.platform === 'os390') {
      logprefix = "find zoslib's zos-base.h:"
      let msg
      let zoslibIncPath = process.env.ZOSLIB_INCLUDES
      if (zoslibIncPath) {
        zoslibIncPath = findAccessibleSync(logprefix, zoslibIncPath, ['zos-base.h'])
        if (zoslibIncPath === undefined) {
          msg = msgFormat('Could not find zos-base.h file in the directory set ' +
                          'in ZOSLIB_INCLUDES environment variable: %s; set it ' +
                          'to the correct path, or unset it to search %s', process.env.ZOSLIB_INCLUDES, nodeRootDir)
        }
      } else {
        candidates = [
          'include/node/zoslib/zos-base.h',
          'include/zoslib/zos-base.h',
          'zoslib/include/zos-base.h',
          'install/include/node/zoslib/zos-base.h'
        ]
        zoslibIncPath = findAccessibleSync(logprefix, nodeRootDir, candidates)
        if (zoslibIncPath === undefined) {
          msg = msgFormat('Could not find any of %s in directory %s; set ' +
                          'environmant variable ZOSLIB_INCLUDES to the path ' +
                          'that contains zos-base.h', candidates.toString(), nodeRootDir)
        }
      }
      if (zoslibIncPath !== undefined) {
        zoslibIncDir = path.dirname(zoslibIncPath)
        log.verbose(logprefix, "Found zoslib's zos-base.h in: %s", zoslibIncDir)
      } else if (release.version.split('.')[0] >= 16) {
        // zoslib is only shipped in Node v16 and above.
        log.error(logprefix, msg)
        throw new Error(msg)
      }
    }

    // this logic ported from the old `gyp_addon` python file
    const gypScript = path.resolve(__dirname, '..', 'gyp', 'gyp_main.py')
    const addonGypi = path.resolve(__dirname, '..', 'addon.gypi')
    let commonGypi = path.resolve(nodeDir, 'include/node/common.gypi')
    try {
      await fs.stat(commonGypi)
    } catch (err) {
      commonGypi = path.resolve(nodeDir, 'common.gypi')
    }

    let outputDir = 'build'
    if (win) {
      // Windows expects an absolute path
      outputDir = buildDir
    }
    const nodeGypDir = path.resolve(__dirname, '..')

    let nodeLibFile = path.join(nodeDir,
      !gyp.opts.nodedir ? '<(target_arch)' : '$(Configuration)',
      release.name + '.lib')

    argv.push('-I', addonGypi)
    argv.push('-I', commonGypi)
    argv.push('-Dlibrary=shared_library')
    argv.push('-Dvisibility=default')
    argv.push('-Dnode_root_dir=' + nodeDir)
    if (process.platform === 'aix' || process.platform === 'os390' || process.platform === 'os400') {
      argv.push('-Dnode_exp_file=' + nodeExpFile)
      if (process.platform === 'os390' && zoslibIncDir) {
        argv.push('-Dzoslib_include_dir=' + zoslibIncDir)
      }
    }
    argv.push('-Dnode_gyp_dir=' + nodeGypDir)

    // Do this to keep Cygwin environments happy, else the unescaped '\' gets eaten up,
    // resulting in bad paths, Ex c:parentFolderfolderanotherFolder instead of c:\parentFolder\folder\anotherFolder
    if (win) {
      nodeLibFile = nodeLibFile.replace(/\\/g, '\\\\')
    }
    argv.push('-Dnode_lib_file=' + nodeLibFile)
    argv.push('-Dmodule_root_dir=' + process.cwd())
    argv.push('-Dnode_engine=' +
        (gyp.opts.node_engine || process.jsEngine || 'v8'))
    argv.push('--depth=.')
    argv.push('--no-parallel')

    // tell gyp to write the Makefile/Solution files into output_dir
    argv.push('--generator-output', outputDir)

    // tell make to write its output into the same dir
    argv.push('-Goutput_dir=.')

    // enforce use of the "binding.gyp" file
    argv.unshift('binding.gyp')

    // execute `gyp` from the current target nodedir
    argv.unshift(gypScript)

    // make sure python uses files that came with this particular node package
    const pypath = [path.join(__dirname, '..', 'gyp', 'pylib')]
    if (process.env.PYTHONPATH) {
      pypath.push(process.env.PYTHONPATH)
    }
    process.env.PYTHONPATH = pypath.join(win ? ';' : ':')

    await new Promise((resolve, reject) => {
      const cp = gyp.spawn(python, argv)
      cp.on('exit', (code) => {
        if (code !== 0) {
          reject(new Error('`gyp` failed with exit code: ' + code))
        } else {
          // we're done
          resolve()
        }
      })
    })
  }
}

module.exports = configure
module.exports.usage = 'Generates ' + (win ? 'MSVC project files' : 'a Makefile') + ' for the current module'
'use strict'

const fs = require('graceful-fs').promises
const log = require('./log')
const path = require('path')

function parseConfigGypi (config) {
  // translated from tools/js2c.py of Node.js
  // 1. string comments
  config = config.replace(/#.*/g, '')
  // 2. join multiline strings
  config = config.replace(/'$\s+'/mg, '')
  // 3. normalize string literals from ' into "
  config = config.replace(/'/g, '"')
  return JSON.parse(config)
}

async function getBaseConfigGypi ({ gyp, nodeDir }) {
  // try reading $nodeDir/include/node/config.gypi first when:
  // 1. --dist-url or --nodedir is specified
  // 2. and --force-process-config is not specified
  const useCustomHeaders = gyp.opts.nodedir || gyp.opts.disturl || gyp.opts['dist-url']
  const shouldReadConfigGypi = useCustomHeaders && !gyp.opts['force-process-config']
  if (shouldReadConfigGypi && nodeDir) {
    try {
      const baseConfigGypiPath = path.resolve(nodeDir, 'include/node/config.gypi')
      const baseConfigGypi = await fs.readFile(baseConfigGypiPath)
      return parseConfigGypi(baseConfigGypi.toString())
    } catch (err) {
      log.warn('read config.gypi', err.message)
    }
  }

  // fallback to process.config if it is invalid
  return JSON.parse(JSON.stringify(process.config))
}

async function getCurrentConfigGypi ({ gyp, nodeDir, vsInfo, python }) {
  const config = await getBaseConfigGypi({ gyp, nodeDir })
  if (!config.target_defaults) {
    config.target_defaults = {}
  }
  if (!config.variables) {
    config.variables = {}
  }

  const defaults = config.target_defaults
  const variables = config.variables

  // don't inherit the "defaults" from the base config.gypi.
  // doing so could cause problems in cases where the `node` executable was
  // compiled on a different machine (with different lib/include paths) than
  // the machine where the addon is being built to
  defaults.cflags = []
  defaults.defines = []
  defaults.include_dirs = []
  defaults.libraries = []

  // set the default_configuration prop
  if ('debug' in gyp.opts) {
    defaults.default_configuration = gyp.opts.debug ? 'Debug' : 'Release'
  }

  if (!defaults.default_configuration) {
    defaults.default_configuration = 'Release'
  }

  // set the target_arch variable
  variables.target_arch = gyp.opts.arch || process.arch || 'ia32'
  if (variables.target_arch === 'arm64') {
    defaults.msvs_configuration_platform = 'ARM64'
    defaults.xcode_configuration_platform = 'arm64'
  }

  // set the node development directory
  variables.nodedir = nodeDir

  // set the configured Python path
  variables.python = python

  // disable -T "thin" static archives by default
  variables.standalone_static_library = gyp.opts.thin ? 0 : 1

  if (process.platform === 'win32') {
    defaults.msbuild_toolset = vsInfo.toolset
    if (vsInfo.sdk) {
      defaults.msvs_windows_target_platform_version = vsInfo.sdk
    }
    if (variables.target_arch === 'arm64') {
      if (vsInfo.versionMajor > 15 ||
          (vsInfo.versionMajor === 15 && vsInfo.versionMajor >= 9)) {
        defaults.msvs_enable_marmasm = 1
      } else {
        log.warn('Compiling ARM64 assembly is only available in\n' +
          'Visual Studio 2017 version 15.9 and above')
      }
    }
    variables.msbuild_path = vsInfo.msBuild
    if (config.variables.clang === 1) {
      config.variables.clang = 0
    }
  }

  // loop through the rest of the opts and add the unknown ones as variables.
  // this allows for module-specific configure flags like:
  //
  //   $ node-gyp configure --shared-libxml2
  Object.keys(gyp.opts).forEach(function (opt) {
    if (opt === 'argv') {
      return
    }
    if (opt in gyp.configDefs) {
      return
    }
    variables[opt.replace(/-/g, '_')] = gyp.opts[opt]
  })

  return config
}

async function createConfigGypi ({ gyp, buildDir, nodeDir, vsInfo, python }) {
  const configFilename = 'config.gypi'
  const configPath = path.resolve(buildDir, configFilename)

  log.verbose('build/' + configFilename, 'creating config file')

  const config = await getCurrentConfigGypi({ gyp, nodeDir, vsInfo, python })

  // ensures that any boolean values in config.gypi get stringified
  function boolsToString (k, v) {
    if (typeof v === 'boolean') {
      return String(v)
    }
    return v
  }

  log.silly('build/' + configFilename, config)

  // now write out the config.gypi file to the build/ dir
  const prefix = '# Do not edit. File was generated by node-gyp\'s "configure" step'

  const json = JSON.stringify(config, boolsToString, 2)
  log.verbose('build/' + configFilename, 'writing out config file: %s', configPath)
  await fs.writeFile(configPath, [prefix, json, ''].join('\n'))

  return configPath
}

module.exports = {
  createConfigGypi,
  parseConfigGypi,
  getCurrentConfigGypi
}
const fetch = require('make-fetch-happen')
const { promises: fs } = require('graceful-fs')
const log = require('./log')

async function download (gyp, url) {
  log.http('GET', url)

  const requestOpts = {
    headers: {
      'User-Agent': `node-gyp v${gyp.version} (node ${process.version})`,
      Connection: 'keep-alive'
    },
    proxy: gyp.opts.proxy,
    noProxy: gyp.opts.noproxy
  }

  const cafile = gyp.opts.cafile
  if (cafile) {
    requestOpts.ca = await readCAFile(cafile)
  }

  const res = await fetch(url, requestOpts)
  log.http(res.status, res.url)

  return res
}

async function readCAFile (filename) {
  // The CA file can contain multiple certificates so split on certificate
  // boundaries.  [\S\s]*? is used to match everything including newlines.
  const ca = await fs.readFile(filename, 'utf8')
  const re = /(-----BEGIN CERTIFICATE-----[\S\s]*?-----END CERTIFICATE-----)/g
  return ca.match(re)
}

module.exports = {
  download,
  readCAFile
}
'use strict'

const path = require('path')
const log = require('./log')

function findNodeDirectory (scriptLocation, processObj) {
  // set dirname and process if not passed in
  // this facilitates regression tests
  if (scriptLocation === undefined) {
    scriptLocation = __dirname
  }
  if (processObj === undefined) {
    processObj = process
  }

  // Have a look to see what is above us, to try and work out where we are
  const npmParentDirectory = path.join(scriptLocation, '../../../..')
  log.verbose('node-gyp root', 'npm_parent_directory is ' +
              path.basename(npmParentDirectory))
  let nodeRootDir = ''

  log.verbose('node-gyp root', 'Finding node root directory')
  if (path.basename(npmParentDirectory) === 'deps') {
    // We are in a build directory where this script lives in
    // deps/npm/node_modules/node-gyp/lib
    nodeRootDir = path.join(npmParentDirectory, '..')
    log.verbose('node-gyp root', 'in build directory, root = ' +
                nodeRootDir)
  } else if (path.basename(npmParentDirectory) === 'node_modules') {
    // We are in a node install directory where this script lives in
    // lib/node_modules/npm/node_modules/node-gyp/lib or
    // node_modules/npm/node_modules/node-gyp/lib depending on the
    // platform
    if (processObj.platform === 'win32') {
      nodeRootDir = path.join(npmParentDirectory, '..')
    } else {
      nodeRootDir = path.join(npmParentDirectory, '../..')
    }
    log.verbose('node-gyp root', 'in install directory, root = ' +
                nodeRootDir)
  } else {
    // We don't know where we are, try working it out from the location
    // of the node binary
    const nodeDir = path.dirname(processObj.execPath)
    const directoryUp = path.basename(nodeDir)
    if (directoryUp === 'bin') {
      nodeRootDir = path.join(nodeDir, '..')
    } else if (directoryUp === 'Release' || directoryUp === 'Debug') {
      // If we are a recently built node, and the directory structure
      // is that of a repository. If we are on Windows then we only need
      // to go one level up, everything else, two
      if (processObj.platform === 'win32') {
        nodeRootDir = path.join(nodeDir, '..')
      } else {
        nodeRootDir = path.join(nodeDir, '../..')
      }
    }
    // Else return the default blank, "".
  }
  return nodeRootDir
}

module.exports = findNodeDirectory
'use strict'

const log = require('./log')
const semver = require('semver')
const { execFile } = require('./util')
const win = process.platform === 'win32'

function getOsUserInfo () {
  try {
    return require('os').userInfo().username
  } catch {}
}

const systemDrive = process.env.SystemDrive || 'C:'
const username = process.env.USERNAME || process.env.USER || getOsUserInfo()
const localAppData = process.env.LOCALAPPDATA || `${systemDrive}\\${username}\\AppData\\Local`
const foundLocalAppData = process.env.LOCALAPPDATA || username
const programFiles = process.env.ProgramW6432 || process.env.ProgramFiles || `${systemDrive}\\Program Files`
const programFilesX86 = process.env['ProgramFiles(x86)'] || `${programFiles} (x86)`

const winDefaultLocationsArray = []
for (const majorMinor of ['311', '310', '39', '38']) {
  if (foundLocalAppData) {
    winDefaultLocationsArray.push(
      `${localAppData}\\Programs\\Python\\Python${majorMinor}\\python.exe`,
      `${programFiles}\\Python${majorMinor}\\python.exe`,
      `${localAppData}\\Programs\\Python\\Python${majorMinor}-32\\python.exe`,
      `${programFiles}\\Python${majorMinor}-32\\python.exe`,
      `${programFilesX86}\\Python${majorMinor}-32\\python.exe`
    )
  } else {
    winDefaultLocationsArray.push(
      `${programFiles}\\Python${majorMinor}\\python.exe`,
      `${programFiles}\\Python${majorMinor}-32\\python.exe`,
      `${programFilesX86}\\Python${majorMinor}-32\\python.exe`
    )
  }
}

class PythonFinder {
  static findPython = (...args) => new PythonFinder(...args).findPython()

  log = log.withPrefix('find Python')
  argsExecutable = ['-c', 'import sys; sys.stdout.buffer.write(sys.executable.encode(\'utf-8\'));']
  argsVersion = ['-c', 'import sys; print("%s.%s.%s" % sys.version_info[:3]);']
  semverRange = '>=3.6.0'

  // These can be overridden for testing:
  execFile = execFile
  env = process.env
  win = win
  pyLauncher = 'py.exe'
  winDefaultLocations = winDefaultLocationsArray

  constructor (configPython) {
    this.configPython = configPython
    this.errorLog = []
  }

  // Logs a message at verbose level, but also saves it to be displayed later
  // at error level if an error occurs. This should help diagnose the problem.
  addLog (message) {
    this.log.verbose(message)
    this.errorLog.push(message)
  }

  // Find Python by trying a sequence of possibilities.
  // Ignore errors, keep trying until Python is found.
  async findPython () {
    const SKIP = 0
    const FAIL = 1
    const toCheck = (() => {
      if (this.env.NODE_GYP_FORCE_PYTHON) {
        return [{
          before: () => {
            this.addLog(
              'checking Python explicitly set from NODE_GYP_FORCE_PYTHON')
            this.addLog('- process.env.NODE_GYP_FORCE_PYTHON is ' +
              `"${this.env.NODE_GYP_FORCE_PYTHON}"`)
          },
          check: () => this.checkCommand(this.env.NODE_GYP_FORCE_PYTHON)
        }]
      }

      const checks = [
        {
          before: () => {
            if (!this.configPython) {
              this.addLog(
                'Python is not set from command line or npm configuration')
              return SKIP
            }
            this.addLog('checking Python explicitly set from command line or ' +
              'npm configuration')
            this.addLog('- "--python=" or "npm config get python" is ' +
              `"${this.configPython}"`)
          },
          check: () => this.checkCommand(this.configPython)
        },
        {
          before: () => {
            if (!this.env.PYTHON) {
              this.addLog('Python is not set from environment variable ' +
                'PYTHON')
              return SKIP
            }
            this.addLog('checking Python explicitly set from environment ' +
              'variable PYTHON')
            this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`)
          },
          check: () => this.checkCommand(this.env.PYTHON)
        }
      ]

      if (this.win) {
        checks.push({
          before: () => {
            this.addLog(
              'checking if the py launcher can be used to find Python 3')
          },
          check: () => this.checkPyLauncher()
        })
      }

      checks.push(...[
        {
          before: () => { this.addLog('checking if "python3" can be used') },
          check: () => this.checkCommand('python3')
        },
        {
          before: () => { this.addLog('checking if "python" can be used') },
          check: () => this.checkCommand('python')
        }
      ])

      if (this.win) {
        for (let i = 0; i < this.winDefaultLocations.length; ++i) {
          const location = this.winDefaultLocations[i]
          checks.push({
            before: () => this.addLog(`checking if Python is ${location}`),
            check: () => this.checkExecPath(location)
          })
        }
      }

      return checks
    })()

    for (const check of toCheck) {
      const before = check.before()
      if (before === SKIP) {
        continue
      }
      if (before === FAIL) {
        return this.fail()
      }
      try {
        return await check.check()
      } catch (err) {
        this.log.silly('runChecks: err = %j', (err && err.stack) || err)
      }
    }

    return this.fail()
  }

  // Check if command is a valid Python to use.
  // Will exit the Python finder on success.
  // If on Windows, run in a CMD shell to support BAT/CMD launchers.
  async checkCommand (command) {
    let exec = command
    let args = this.argsExecutable
    let shell = false
    if (this.win) {
      // Arguments have to be manually quoted
      exec = `"${exec}"`
      args = args.map(a => `"${a}"`)
      shell = true
    }

    this.log.verbose(`- executing "${command}" to get executable path`)
    // Possible outcomes:
    // - Error: not in PATH, not executable or execution fails
    // - Gibberish: the next command to check version will fail
    // - Absolute path to executable
    try {
      const execPath = await this.run(exec, args, shell)
      this.addLog(`- executable path is "${execPath}"`)
      return this.checkExecPath(execPath)
    } catch (err) {
      this.addLog(`- "${command}" is not in PATH or produced an error`)
      throw err
    }
  }

  // Check if the py launcher can find a valid Python to use.
  // Will exit the Python finder on success.
  // Distributions of Python on Windows by default install with the "py.exe"
  // Python launcher which is more likely to exist than the Python executable
  // being in the $PATH.
  // Because the Python launcher supports Python 2 and Python 3, we should
  // explicitly request a Python 3 version. This is done by supplying "-3" as
  // the first command line argument. Since "py.exe -3" would be an invalid
  // executable for "execFile", we have to use the launcher to figure out
  // where the actual "python.exe" executable is located.
  async checkPyLauncher () {
    this.log.verbose(`- executing "${this.pyLauncher}" to get Python 3 executable path`)
    // Possible outcomes: same as checkCommand
    try {
      const execPath = await this.run(this.pyLauncher, ['-3', ...this.argsExecutable], false)
      this.addLog(`- executable path is "${execPath}"`)
      return this.checkExecPath(execPath)
    } catch (err) {
      this.addLog(`- "${this.pyLauncher}" is not in PATH or produced an error`)
      throw err
    }
  }

  // Check if a Python executable is the correct version to use.
  // Will exit the Python finder on success.
  async checkExecPath (execPath) {
    this.log.verbose(`- executing "${execPath}" to get version`)
    // Possible outcomes:
    // - Error: executable can not be run (likely meaning the command wasn't
    //   a Python executable and the previous command produced gibberish)
    // - Gibberish: somehow the last command produced an executable path,
    //   this will fail when verifying the version
    // - Version of the Python executable
    try {
      const version = await this.run(execPath, this.argsVersion, false)
      this.addLog(`- version is "${version}"`)

      const range = new semver.Range(this.semverRange)
      let valid = false
      try {
        valid = range.test(version)
      } catch (err) {
        this.log.silly('range.test() threw:\n%s', err.stack)
        this.addLog(`- "${execPath}" does not have a valid version`)
        this.addLog('- is it a Python executable?')
        throw err
      }
      if (!valid) {
        this.addLog(`- version is ${version} - should be ${this.semverRange}`)
        this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED')
        throw new Error(`Found unsupported Python version ${version}`)
      }
      return this.succeed(execPath, version)
    } catch (err) {
      this.addLog(`- "${execPath}" could not be run`)
      throw err
    }
  }

  // Run an executable or shell command, trimming the output.
  async run (exec, args, shell) {
    const env = Object.assign({}, this.env)
    env.TERM = 'dumb'
    const opts = { env, shell }

    this.log.silly('execFile: exec = %j', exec)
    this.log.silly('execFile: args = %j', args)
    this.log.silly('execFile: opts = %j', opts)
    try {
      const [err, stdout, stderr] = await this.execFile(exec, args, opts)
      this.log.silly('execFile result: err = %j', (err && err.stack) || err)
      this.log.silly('execFile result: stdout = %j', stdout)
      this.log.silly('execFile result: stderr = %j', stderr)
      return stdout.trim()
    } catch (err) {
      this.log.silly('execFile: threw:\n%s', err.stack)
      throw err
    }
  }

  succeed (execPath, version) {
    this.log.info(`using Python version ${version} found at "${execPath}"`)
    return execPath
  }

  fail () {
    const errorLog = this.errorLog.join('\n')

    const pathExample = this.win
      ? 'C:\\Path\\To\\python.exe'
      : '/path/to/pythonexecutable'
    // For Windows 80 col console, use up to the column before the one marked
    // with X (total 79 chars including logger prefix, 58 chars usable here):
    //                                                           X
    const info = [
      '**********************************************************',
      'You need to install the latest version of Python.',
      'Node-gyp should be able to find and use Python. If not,',
      'you can try one of the following options:',
      `- Use the switch --python="${pathExample}"`,
      '  (accepted by both node-gyp and npm)',
      '- Set the environment variable PYTHON',
      '- Set the npm configuration variable python:',
      `  npm config set python "${pathExample}"`,
      'For more information consult the documentation at:',
      'https://github.com/nodejs/node-gyp#installation',
      '**********************************************************'
    ].join('\n')

    this.log.error(`\n${errorLog}\n\n${info}\n`)
    throw new Error('Could not find any Python installation to use')
  }
}

module.exports = PythonFinder
'use strict'

const log = require('./log')
const { existsSync } = require('fs')
const { win32: path } = require('path')
const { regSearchKeys, execFile } = require('./util')

class VisualStudioFinder {
  static findVisualStudio = (...args) => new VisualStudioFinder(...args).findVisualStudio()

  log = log.withPrefix('find VS')

  regSearchKeys = regSearchKeys

  constructor (nodeSemver, configMsvsVersion) {
    this.nodeSemver = nodeSemver
    this.configMsvsVersion = configMsvsVersion
    this.errorLog = []
    this.validVersions = []
  }

  // Logs a message at verbose level, but also saves it to be displayed later
  // at error level if an error occurs. This should help diagnose the problem.
  addLog (message) {
    this.log.verbose(message)
    this.errorLog.push(message)
  }

  async findVisualStudio () {
    this.configVersionYear = null
    this.configPath = null
    if (this.configMsvsVersion) {
      this.addLog('msvs_version was set from command line or npm config')
      if (this.configMsvsVersion.match(/^\d{4}$/)) {
        this.configVersionYear = parseInt(this.configMsvsVersion, 10)
        this.addLog(
          `- looking for Visual Studio version ${this.configVersionYear}`)
      } else {
        this.configPath = path.resolve(this.configMsvsVersion)
        this.addLog(
          `- looking for Visual Studio installed in "${this.configPath}"`)
      }
    } else {
      this.addLog('msvs_version not set from command line or npm config')
    }

    if (process.env.VCINSTALLDIR) {
      this.envVcInstallDir =
        path.resolve(process.env.VCINSTALLDIR, '..')
      this.addLog('running in VS Command Prompt, installation path is:\n' +
        `"${this.envVcInstallDir}"\n- will only use this version`)
    } else {
      this.addLog('VCINSTALLDIR not set, not running in VS Command Prompt')
    }

    const checks = [
      () => this.findVisualStudio2019OrNewerFromSpecifiedLocation(),
      () => this.findVisualStudio2019OrNewerUsingSetupModule(),
      () => this.findVisualStudio2019OrNewer(),
      () => this.findVisualStudio2017FromSpecifiedLocation(),
      () => this.findVisualStudio2017UsingSetupModule(),
      () => this.findVisualStudio2017(),
      () => this.findVisualStudio2015(),
      () => this.findVisualStudio2013()
    ]

    for (const check of checks) {
      const info = await check()
      if (info) {
        return this.succeed(info)
      }
    }

    return this.fail()
  }

  succeed (info) {
    this.log.info(`using VS${info.versionYear} (${info.version}) found at:` +
                  `\n"${info.path}"` +
                  '\nrun with --verbose for detailed information')
    return info
  }

  fail () {
    if (this.configMsvsVersion && this.envVcInstallDir) {
      this.errorLog.push(
        'msvs_version does not match this VS Command Prompt or the',
        'installation cannot be used.')
    } else if (this.configMsvsVersion) {
      // If msvs_version was specified but finding VS failed, print what would
      // have been accepted
      this.errorLog.push('')
      if (this.validVersions) {
        this.errorLog.push('valid versions for msvs_version:')
        this.validVersions.forEach((version) => {
          this.errorLog.push(`- "${version}"`)
        })
      } else {
        this.errorLog.push('no valid versions for msvs_version were found')
      }
    }

    const errorLog = this.errorLog.join('\n')

    // For Windows 80 col console, use up to the column before the one marked
    // with X (total 79 chars including logger prefix, 62 chars usable here):
    //                                                               X
    const infoLog = [
      '**************************************************************',
      'You need to install the latest version of Visual Studio',
      'including the "Desktop development with C++" workload.',
      'For more information consult the documentation at:',
      'https://github.com/nodejs/node-gyp#on-windows',
      '**************************************************************'
    ].join('\n')

    this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
    throw new Error('Could not find any Visual Studio installation to use')
  }

  async findVisualStudio2019OrNewerFromSpecifiedLocation () {
    return this.findVSFromSpecifiedLocation([2019, 2022])
  }

  async findVisualStudio2017FromSpecifiedLocation () {
    if (this.nodeSemver.major >= 22) {
      this.addLog(
        'not looking for VS2017 as it is only supported up to Node.js 21')
      return null
    }
    return this.findVSFromSpecifiedLocation([2017])
  }

  async findVSFromSpecifiedLocation (supportedYears) {
    if (!this.envVcInstallDir) {
      return null
    }
    const info = {
      path: path.resolve(this.envVcInstallDir),
      // Assume the version specified by the user is correct.
      // Since Visual Studio 2015, the Developer Command Prompt sets the
      // VSCMD_VER environment variable which contains the version information
      // for Visual Studio.
      // https://learn.microsoft.com/en-us/visualstudio/ide/reference/command-prompt-powershell?view=vs-2022
      version: process.env.VSCMD_VER,
      packages: [
        'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
        // Assume MSBuild exists. It will be checked in processing.
        'Microsoft.VisualStudio.VC.MSBuild.Base'
      ]
    }

    // Is there a better way to get SDK information?
    const envWindowsSDKVersion = process.env.WindowsSDKVersion
    const sdkVersionMatched = envWindowsSDKVersion?.match(/^(\d+)\.(\d+)\.(\d+)\..*/)
    if (sdkVersionMatched) {
      info.packages.push(`Microsoft.VisualStudio.Component.Windows10SDK.${sdkVersionMatched[3]}.Desktop`)
    }
    // pass for further processing
    return this.processData([info], supportedYears)
  }

  async findVisualStudio2019OrNewerUsingSetupModule () {
    return this.findNewVSUsingSetupModule([2019, 2022])
  }

  async findVisualStudio2017UsingSetupModule () {
    if (this.nodeSemver.major >= 22) {
      this.addLog(
        'not looking for VS2017 as it is only supported up to Node.js 21')
      return null
    }
    return this.findNewVSUsingSetupModule([2017])
  }

  async findNewVSUsingSetupModule (supportedYears) {
    const ps = path.join(process.env.SystemRoot, 'System32',
      'WindowsPowerShell', 'v1.0', 'powershell.exe')
    const vcInstallDir = this.envVcInstallDir

    const checkModuleArgs = [
      '-NoProfile',
      '-Command',
      '&{@(Get-Module -ListAvailable -Name VSSetup).Version.ToString()}'
    ]
    this.log.silly('Running', ps, checkModuleArgs)
    const [cErr] = await this.execFile(ps, checkModuleArgs)
    if (cErr) {
      this.addLog('VSSetup module doesn\'t seem to exist. You can install it via: "Install-Module VSSetup -Scope CurrentUser"')
      this.log.silly('VSSetup error = %j', cErr && (cErr.stack || cErr))
      return null
    }
    const filterArg = vcInstallDir !== undefined ? `| where {$_.InstallationPath -eq '${vcInstallDir}' }` : ''
    const psArgs = [
      '-NoProfile',
      '-Command',
      `&{Get-VSSetupInstance ${filterArg} | ConvertTo-Json -Depth 3}`
    ]

    this.log.silly('Running', ps, psArgs)
    const [err, stdout, stderr] = await this.execFile(ps, psArgs)
    let parsedData = this.parseData(err, stdout, stderr)
    if (parsedData === null) {
      return null
    }
    this.log.silly('Parsed data', parsedData)
    if (!Array.isArray(parsedData)) {
      // if there are only 1 result, then Powershell will output non-array
      parsedData = [parsedData]
    }
    // normalize output
    parsedData = parsedData.map((info) => {
      info.path = info.InstallationPath
      info.version = `${info.InstallationVersion.Major}.${info.InstallationVersion.Minor}.${info.InstallationVersion.Build}.${info.InstallationVersion.Revision}`
      info.packages = info.Packages.map((p) => p.Id)
      return info
    })
    // pass for further processing
    return this.processData(parsedData, supportedYears)
  }

  // Invoke the PowerShell script to get information about Visual Studio 2019
  // or newer installations
  async findVisualStudio2019OrNewer () {
    return this.findNewVS([2019, 2022])
  }

  // Invoke the PowerShell script to get information about Visual Studio 2017
  async findVisualStudio2017 () {
    if (this.nodeSemver.major >= 22) {
      this.addLog(
        'not looking for VS2017 as it is only supported up to Node.js 21')
      return null
    }
    return this.findNewVS([2017])
  }

  // Invoke the PowerShell script to get information about Visual Studio 2017
  // or newer installations
  async findNewVS (supportedYears) {
    const ps = path.join(process.env.SystemRoot, 'System32',
      'WindowsPowerShell', 'v1.0', 'powershell.exe')
    const csFile = path.join(__dirname, 'Find-VisualStudio.cs')
    const psArgs = [
      '-ExecutionPolicy',
      'Unrestricted',
      '-NoProfile',
      '-Command',
      '&{Add-Type -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}'
    ]

    this.log.silly('Running', ps, psArgs)
    const [err, stdout, stderr] = await this.execFile(ps, psArgs)
    const parsedData = this.parseData(err, stdout, stderr, { checkIsArray: true })
    if (parsedData === null) {
      return null
    }
    return this.processData(parsedData, supportedYears)
  }

  // Parse the output of the PowerShell script, make sanity checks
  parseData (err, stdout, stderr, sanityCheckOptions) {
    const defaultOptions = {
      checkIsArray: false
    }

    // Merging provided options with the default options
    const sanityOptions = { ...defaultOptions, ...sanityCheckOptions }

    this.log.silly('PS stderr = %j', stderr)

    const failPowershell = (failureDetails) => {
      this.addLog(
        `could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details. \n
        Failure details: ${failureDetails}`)
      return null
    }

    if (err) {
      this.log.silly('PS err = %j', err && (err.stack || err))
      return failPowershell(`${err}`.substring(0, 40))
    }

    let vsInfo
    try {
      vsInfo = JSON.parse(stdout)
    } catch (e) {
      this.log.silly('PS stdout = %j', stdout)
      this.log.silly(e)
      return failPowershell()
    }

    if (sanityOptions.checkIsArray && !Array.isArray(vsInfo)) {
      this.log.silly('PS stdout = %j', stdout)
      return failPowershell('Expected array as output of the PS script')
    }
    return vsInfo
  }

  // Process parsed data containing information about VS installations
  // Look for the required parts, extract and output them back
  processData (vsInfo, supportedYears) {
    vsInfo = vsInfo.map((info) => {
      this.log.silly(`processing installation: "${info.path}"`)
      info.path = path.resolve(info.path)
      const ret = this.getVersionInfo(info)
      ret.path = info.path
      ret.msBuild = this.getMSBuild(info, ret.versionYear)
      ret.toolset = this.getToolset(info, ret.versionYear)
      ret.sdk = this.getSDK(info)
      return ret
    })
    this.log.silly('vsInfo:', vsInfo)

    // Remove future versions or errors parsing version number
    // Also remove any unsupported versions
    vsInfo = vsInfo.filter((info) => {
      if (info.versionYear && supportedYears.indexOf(info.versionYear) !== -1) {
        return true
      }
      this.addLog(`${info.versionYear ? 'unsupported' : 'unknown'} version "${info.version}" found at "${info.path}"`)
      return false
    })

    // Sort to place newer versions first
    vsInfo.sort((a, b) => b.versionYear - a.versionYear)

    for (let i = 0; i < vsInfo.length; ++i) {
      const info = vsInfo[i]
      this.addLog(`checking VS${info.versionYear} (${info.version}) found ` +
                  `at:\n"${info.path}"`)

      if (info.msBuild) {
        this.addLog('- found "Visual Studio C++ core features"')
      } else {
        this.addLog('- "Visual Studio C++ core features" missing')
        continue
      }

      if (info.toolset) {
        this.addLog(`- found VC++ toolset: ${info.toolset}`)
      } else {
        this.addLog('- missing any VC++ toolset')
        continue
      }

      if (info.sdk) {
        this.addLog(`- found Windows SDK: ${info.sdk}`)
      } else {
        this.addLog('- missing any Windows SDK')
        continue
      }

      if (!this.checkConfigVersion(info.versionYear, info.path)) {
        continue
      }

      return info
    }

    this.addLog(
      'could not find a version of Visual Studio 2017 or newer to use')
    return null
  }

  // Helper - process version information
  getVersionInfo (info) {
    const match = /^(\d+)\.(\d+)(?:\..*)?/.exec(info.version)
    if (!match) {
      this.log.silly('- failed to parse version:', info.version)
      return {}
    }
    this.log.silly('- version match = %j', match)
    const ret = {
      version: info.version,
      versionMajor: parseInt(match[1], 10),
      versionMinor: parseInt(match[2], 10)
    }
    if (ret.versionMajor === 15) {
      ret.versionYear = 2017
      return ret
    }
    if (ret.versionMajor === 16) {
      ret.versionYear = 2019
      return ret
    }
    if (ret.versionMajor === 17) {
      ret.versionYear = 2022
      return ret
    }
    this.log.silly('- unsupported version:', ret.versionMajor)
    return {}
  }

  msBuildPathExists (path) {
    return existsSync(path)
  }

  // Helper - process MSBuild information
  getMSBuild (info, versionYear) {
    const pkg = 'Microsoft.VisualStudio.VC.MSBuild.Base'
    const msbuildPath = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'MSBuild.exe')
    const msbuildPathArm64 = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'arm64', 'MSBuild.exe')
    if (info.packages.indexOf(pkg) !== -1) {
      this.log.silly('- found VC.MSBuild.Base')
      if (versionYear === 2017) {
        return path.join(info.path, 'MSBuild', '15.0', 'Bin', 'MSBuild.exe')
      }
      if (versionYear === 2019) {
        if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) {
          return msbuildPathArm64
        } else {
          return msbuildPath
        }
      }
    }
    /**
     * Visual Studio 2022 doesn't have the MSBuild package.
     * Support for compiling _on_ ARM64 was added in MSVC 14.32.31326,
     * so let's leverage it if the user has an ARM64 device.
     */
    if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) {
      return msbuildPathArm64
    } else if (this.msBuildPathExists(msbuildPath)) {
      return msbuildPath
    }
    return null
  }

  // Helper - process toolset information
  getToolset (info, versionYear) {
    const pkg = 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
    const express = 'Microsoft.VisualStudio.WDExpress'

    if (info.packages.indexOf(pkg) !== -1) {
      this.log.silly('- found VC.Tools.x86.x64')
    } else if (info.packages.indexOf(express) !== -1) {
      this.log.silly('- found Visual Studio Express (looking for toolset)')
    } else {
      return null
    }

    if (versionYear === 2017) {
      return 'v141'
    } else if (versionYear === 2019) {
      return 'v142'
    } else if (versionYear === 2022) {
      return 'v143'
    }
    this.log.silly('- invalid versionYear:', versionYear)
    return null
  }

  // Helper - process Windows SDK information
  getSDK (info) {
    const win8SDK = 'Microsoft.VisualStudio.Component.Windows81SDK'
    const win10SDKPrefix = 'Microsoft.VisualStudio.Component.Windows10SDK.'
    const win11SDKPrefix = 'Microsoft.VisualStudio.Component.Windows11SDK.'

    let Win10or11SDKVer = 0
    info.packages.forEach((pkg) => {
      if (!pkg.startsWith(win10SDKPrefix) && !pkg.startsWith(win11SDKPrefix)) {
        return
      }
      const parts = pkg.split('.')
      if (parts.length > 5 && parts[5] !== 'Desktop') {
        this.log.silly('- ignoring non-Desktop Win10/11SDK:', pkg)
        return
      }
      const foundSdkVer = parseInt(parts[4], 10)
      if (isNaN(foundSdkVer)) {
        // Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
        this.log.silly('- failed to parse Win10/11SDK number:', pkg)
        return
      }
      this.log.silly('- found Win10/11SDK:', foundSdkVer)
      Win10or11SDKVer = Math.max(Win10or11SDKVer, foundSdkVer)
    })

    if (Win10or11SDKVer !== 0) {
      return `10.0.${Win10or11SDKVer}.0`
    } else if (info.packages.indexOf(win8SDK) !== -1) {
      this.log.silly('- found Win8SDK')
      return '8.1'
    }
    return null
  }

  // Find an installation of Visual Studio 2015 to use
  async findVisualStudio2015 () {
    if (this.nodeSemver.major >= 19) {
      this.addLog(
        'not looking for VS2015 as it is only supported up to Node.js 18')
      return null
    }
    return this.findOldVS({
      version: '14.0',
      versionMajor: 14,
      versionMinor: 0,
      versionYear: 2015,
      toolset: 'v140'
    })
  }

  // Find an installation of Visual Studio 2013 to use
  async findVisualStudio2013 () {
    if (this.nodeSemver.major >= 9) {
      this.addLog(
        'not looking for VS2013 as it is only supported up to Node.js 8')
      return null
    }
    return this.findOldVS({
      version: '12.0',
      versionMajor: 12,
      versionMinor: 0,
      versionYear: 2013,
      toolset: 'v120'
    })
  }

  // Helper - common code for VS2013 and VS2015
  async findOldVS (info) {
    const regVC7 = ['HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7',
      'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7']
    const regMSBuild = 'HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions'

    this.addLog(`looking for Visual Studio ${info.versionYear}`)
    try {
      let res = await this.regSearchKeys(regVC7, info.version, [])
      const vsPath = path.resolve(res, '..')
      this.addLog(`- found in "${vsPath}"`)
      const msBuildRegOpts = process.arch === 'ia32' ? [] : ['/reg:32']

      try {
        res = await this.regSearchKeys([`${regMSBuild}\\${info.version}`], 'MSBuildToolsPath', msBuildRegOpts)
      } catch (err) {
        this.addLog('- could not find MSBuild in registry for this version')
        return null
      }

      const msBuild = path.join(res, 'MSBuild.exe')
      this.addLog(`- MSBuild in "${msBuild}"`)

      if (!this.checkConfigVersion(info.versionYear, vsPath)) {
        return null
      }

      info.path = vsPath
      info.msBuild = msBuild
      info.sdk = null
      return info
    } catch (err) {
      this.addLog('- not found')
      return null
    }
  }

  // After finding a usable version of Visual Studio:
  // - add it to validVersions to be displayed at the end if a specific
  //   version was requested and not found;
  // - check if this is the version that was requested.
  // - check if this matches the Visual Studio Command Prompt
  checkConfigVersion (versionYear, vsPath) {
    this.validVersions.push(versionYear)
    this.validVersions.push(vsPath)

    if (this.configVersionYear && this.configVersionYear !== versionYear) {
      this.addLog('- msvs_version does not match this version')
      return false
    }
    if (this.configPath &&
        path.relative(this.configPath, vsPath) !== '') {
      this.addLog('- msvs_version does not point to this installation')
      return false
    }
    if (this.envVcInstallDir &&
        path.relative(this.envVcInstallDir, vsPath) !== '') {
      this.addLog('- does not match this Visual Studio Command Prompt')
      return false
    }

    return true
  }

  async execFile (exec, args) {
    return await execFile(exec, args, { encoding: 'utf8' })
  }
}

module.exports = VisualStudioFinder
'use strict'

const { createWriteStream, promises: fs } = require('graceful-fs')
const os = require('os')
const { backOff } = require('exponential-backoff')
const tar = require('tar')
const path = require('path')
const { Transform, promises: { pipeline } } = require('stream')
const crypto = require('crypto')
const log = require('./log')
const semver = require('semver')
const { download } = require('./download')
const processRelease = require('./process-release')

const win = process.platform === 'win32'

async function install (gyp, argv) {
  log.stdout()
  const release = processRelease(argv, gyp, process.version, process.release)
  // Detecting target_arch based on logic from create-cnfig-gyp.js. Used on Windows only.
  const arch = win ? (gyp.opts.target_arch || gyp.opts.arch || process.arch || 'ia32') : ''
  // Used to prevent downloading tarball if only new node.lib is required on Windows.
  let shouldDownloadTarball = true

  // Determine which node dev files version we are installing
  log.verbose('install', 'input version string %j', release.version)

  if (!release.semver) {
    // could not parse the version string with semver
    throw new Error('Invalid version number: ' + release.version)
  }

  if (semver.lt(release.version, '0.8.0')) {
    throw new Error('Minimum target version is `0.8.0` or greater. Got: ' + release.version)
  }

  // 0.x.y-pre versions are not published yet and cannot be installed. Bail.
  if (release.semver.prerelease[0] === 'pre') {
    log.verbose('detected "pre" node version', release.version)
    if (!gyp.opts.nodedir) {
      throw new Error('"pre" versions of node cannot be installed, use the --nodedir flag instead')
    }
    log.verbose('--nodedir flag was passed; skipping install', gyp.opts.nodedir)
    return
  }

  // flatten version into String
  log.verbose('install', 'installing version: %s', release.versionDir)

  // the directory where the dev files will be installed
  const devDir = path.resolve(gyp.devDir, release.versionDir)

  // If '--ensure' was passed, then don't *always* install the version;
  // check if it is already installed, and only install when needed
  if (gyp.opts.ensure) {
    log.verbose('install', '--ensure was passed, so won\'t reinstall if already installed')
    try {
      await fs.stat(devDir)
    } catch (err) {
      if (err.code === 'ENOENT') {
        log.verbose('install', 'version not already installed, continuing with install', release.version)
        try {
          return await go()
        } catch (err) {
          return rollback(err)
        }
      } else if (err.code === 'EACCES') {
        return eaccesFallback(err)
      }
      throw err
    }
    log.verbose('install', 'version is already installed, need to check "installVersion"')
    const installVersionFile = path.resolve(devDir, 'installVersion')
    let installVersion = 0
    try {
      const ver = await fs.readFile(installVersionFile, 'ascii')
      installVersion = parseInt(ver, 10) || 0
    } catch (err) {
      if (err.code !== 'ENOENT') {
        throw err
      }
    }
    log.verbose('got "installVersion"', installVersion)
    log.verbose('needs "installVersion"', gyp.package.installVersion)
    if (installVersion < gyp.package.installVersion) {
      log.verbose('install', 'version is no good; reinstalling')
      try {
        return await go()
      } catch (err) {
        return rollback(err)
      }
    }
    log.verbose('install', 'version is good')
    if (win) {
      log.verbose('on Windows; need to check node.lib')
      const nodeLibPath = path.resolve(devDir, arch, 'node.lib')
      try {
        await fs.stat(nodeLibPath)
      } catch (err) {
        if (err.code === 'ENOENT') {
          log.verbose('install', `version not already installed for ${arch}, continuing with install`, release.version)
          try {
            shouldDownloadTarball = false
            return await go()
          } catch (err) {
            return rollback(err)
          }
        } else if (err.code === 'EACCES') {
          return eaccesFallback(err)
        }
        throw err
      }
    }
  } else {
    try {
      return await go()
    } catch (err) {
      return rollback(err)
    }
  }

  async function copyDirectory (src, dest) {
    try {
      await fs.stat(src)
    } catch {
      throw new Error(`Missing source directory for copy: ${src}`)
    }
    await fs.mkdir(dest, { recursive: true })
    const entries = await fs.readdir(src, { withFileTypes: true })
    for (const entry of entries) {
      if (entry.isDirectory()) {
        await copyDirectory(path.join(src, entry.name), path.join(dest, entry.name))
      } else if (entry.isFile()) {
        // with parallel installs, copying files may cause file errors on
        // Windows so use an exponential backoff to resolve collisions
        await backOff(async () => {
          try {
            await fs.copyFile(path.join(src, entry.name), path.join(dest, entry.name))
          } catch (err) {
            // if ensure, check if file already exists and that's good enough
            if (gyp.opts.ensure && err.code === 'EBUSY') {
              try {
                await fs.stat(path.join(dest, entry.name))
                return
              } catch {}
            }
            throw err
          }
        })
      } else {
        throw new Error('Unexpected file directory entry type')
      }
    }
  }

  async function go () {
    log.verbose('ensuring devDir is created', devDir)

    // first create the dir for the node dev files
    try {
      const created = await fs.mkdir(devDir, { recursive: true })

      if (created) {
        log.verbose('created devDir', created)
      }
    } catch (err) {
      if (err.code === 'EACCES') {
        return eaccesFallback(err)
      }

      throw err
    }

    // now download the node tarball
    const tarPath = gyp.opts.tarball
    let extractErrors = false
    let extractCount = 0
    const contentShasums = {}
    const expectShasums = {}

    // checks if a file to be extracted from the tarball is valid.
    // only .h header files and the gyp files get extracted
    function isValid (path) {
      const isValid = valid(path)
      if (isValid) {
        log.verbose('extracted file from tarball', path)
        extractCount++
      } else {
        // invalid
        log.silly('ignoring from tarball', path)
      }
      return isValid
    }

    function onwarn (code, message) {
      extractErrors = true
      log.error('error while extracting tarball', code, message)
    }

    // download the tarball and extract!
    // Ommited on Windows if only new node.lib is required

    // on Windows there can be file errors from tar if parallel installs
    // are happening (not uncommon with multiple native modules) so
    // extract the tarball to a temp directory first and then copy over
    const tarExtractDir = win ? await fs.mkdtemp(path.join(os.tmpdir(), 'node-gyp-tmp-')) : devDir

    try {
      if (shouldDownloadTarball) {
        if (tarPath) {
          await tar.extract({
            file: tarPath,
            strip: 1,
            filter: isValid,
            onwarn,
            cwd: tarExtractDir
          })
        } else {
          try {
            const res = await download(gyp, release.tarballUrl)

            if (res.status !== 200) {
              throw new Error(`${res.status} response downloading ${release.tarballUrl}`)
            }

            await pipeline(
              res.body,
              // content checksum
              new ShaSum((_, checksum) => {
                const filename = path.basename(release.tarballUrl).trim()
                contentShasums[filename] = checksum
                log.verbose('content checksum', filename, checksum)
              }),
              tar.extract({
                strip: 1,
                cwd: tarExtractDir,
                filter: isValid,
                onwarn
              })
            )
          } catch (err) {
          // something went wrong downloading the tarball?
            if (err.code === 'ENOTFOUND') {
              throw new Error('This is most likely not a problem with node-gyp or the package itself and\n' +
              'is related to network connectivity. In most cases you are behind a proxy or have bad \n' +
              'network settings.')
            }
            throw err
          }
        }

        // invoked after the tarball has finished being extracted
        if (extractErrors || extractCount === 0) {
          throw new Error('There was a fatal problem while downloading/extracting the tarball')
        }

        log.verbose('tarball', 'done parsing tarball')
      }

      const installVersionPath = path.resolve(tarExtractDir, 'installVersion')
      await Promise.all([
      // need to download node.lib
        ...(win ? [downloadNodeLib()] : []),
        // write the "installVersion" file
        fs.writeFile(installVersionPath, gyp.package.installVersion + '\n'),
        // Only download SHASUMS.txt if we downloaded something in need of SHA verification
        ...(!tarPath || win ? [downloadShasums()] : [])
      ])

      log.verbose('download contents checksum', JSON.stringify(contentShasums))
      // check content shasums
      for (const k in contentShasums) {
        log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k])
        if (contentShasums[k] !== expectShasums[k]) {
          throw new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k])
        }
      }

      // copy over the files from the temp tarball extract directory to devDir
      if (tarExtractDir !== devDir) {
        await copyDirectory(tarExtractDir, devDir)
      }
    } finally {
      if (tarExtractDir !== devDir) {
        try {
          // try to cleanup temp dir
          await fs.rm(tarExtractDir, { recursive: true })
        } catch {
          log.warn('failed to clean up temp tarball extract directory')
        }
      }
    }

    async function downloadShasums () {
      log.verbose('check download content checksum, need to download `SHASUMS256.txt`...')
      log.verbose('checksum url', release.shasumsUrl)

      const res = await download(gyp, release.shasumsUrl)

      if (res.status !== 200) {
        throw new Error(`${res.status}  status code downloading checksum`)
      }

      for (const line of (await res.text()).trim().split('\n')) {
        const items = line.trim().split(/\s+/)
        if (items.length !== 2) {
          return
        }

        // 0035d18e2dcf9aad669b1c7c07319e17abfe3762  ./node-v0.11.4.tar.gz
        const name = items[1].replace(/^\.\//, '')
        expectShasums[name] = items[0]
      }

      log.verbose('checksum data', JSON.stringify(expectShasums))
    }

    async function downloadNodeLib () {
      log.verbose('on Windows; need to download `' + release.name + '.lib`...')
      const dir = path.resolve(tarExtractDir, arch)
      const targetLibPath = path.resolve(dir, release.name + '.lib')
      const { libUrl, libPath } = release[arch]
      const name = `${arch} ${release.name}.lib`
      log.verbose(name, 'dir', dir)
      log.verbose(name, 'url', libUrl)

      await fs.mkdir(dir, { recursive: true })
      log.verbose('streaming', name, 'to:', targetLibPath)

      const res = await download(gyp, libUrl)

      // Since only required node.lib is downloaded throw error if it is not fetched
      if (res.status !== 200) {
        throw new Error(`${res.status} status code downloading ${name}`)
      }

      return pipeline(
        res.body,
        new ShaSum((_, checksum) => {
          contentShasums[libPath] = checksum
          log.verbose('content checksum', libPath, checksum)
        }),
        createWriteStream(targetLibPath)
      )
    } // downloadNodeLib()
  } // go()

  /**
   * Checks if a given filename is "valid" for this installation.
   */

  function valid (file) {
    // header files
    const extname = path.extname(file)
    return extname === '.h' || extname === '.gypi'
  }

  async function rollback (err) {
    log.warn('install', 'got an error, rolling back install')
    // roll-back the install if anything went wrong
    await gyp.commands.remove([release.versionDir])
    throw err
  }

  /**
   * The EACCES fallback is a workaround for npm's `sudo` behavior, where
   * it drops the permissions before invoking any child processes (like
   * node-gyp). So what happens is the "nobody" user doesn't have
   * permission to create the dev dir. As a fallback, make the tmpdir() be
   * the dev dir for this installation. This is not ideal, but at least
   * the compilation will succeed...
   */

  async function eaccesFallback (err) {
    const noretry = '--node_gyp_internal_noretry'
    if (argv.indexOf(noretry) !== -1) {
      throw err
    }
    const tmpdir = os.tmpdir()
    gyp.devDir = path.resolve(tmpdir, '.node-gyp')
    let userString = ''
    try {
      // os.userInfo can fail on some systems, it's not critical here
      userString = ` ("${os.userInfo().username}")`
    } catch (e) {}
    log.warn('EACCES', 'current user%s does not have permission to access the dev dir "%s"', userString, devDir)
    log.warn('EACCES', 'attempting to reinstall using temporary dev dir "%s"', gyp.devDir)
    if (process.cwd() === tmpdir) {
      log.verbose('tmpdir == cwd', 'automatically will remove dev files after to save disk space')
      gyp.todo.push({ name: 'remove', args: argv })
    }
    return gyp.commands.install([noretry].concat(argv))
  }
}

class ShaSum extends Transform {
  constructor (callback) {
    super()
    this._callback = callback
    this._digester = crypto.createHash('sha256')
  }

  _transform (chunk, _, callback) {
    this._digester.update(chunk)
    callback(null, chunk)
  }

  _flush (callback) {
    this._callback(null, this._digester.digest('hex'))
    callback()
  }
}

module.exports = install
module.exports.usage = 'Install node development files for the specified node version.'
'use strict'

const fs = require('graceful-fs').promises
const log = require('./log')

async function list (gyp, args) {
  const devDir = gyp.devDir
  log.verbose('list', 'using node-gyp dir:', devDir)

  let versions = []
  try {
    const dir = await fs.readdir(devDir)
    if (Array.isArray(dir)) {
      versions = dir.filter((v) => v !== 'current')
    }
  } catch (err) {
    if (err && err.code !== 'ENOENT') {
      throw err
    }
  }

  return versions
}

module.exports = list
module.exports.usage = 'Prints a listing of the currently installed node development files'
'use strict'

const { log } = require('proc-log')
const { format } = require('util')

// helper to emit log messages with a predefined prefix
const withPrefix = (prefix) => log.LEVELS.reduce((acc, level) => {
  acc[level] = (...args) => log[level](prefix, ...args)
  return acc
}, {})

// very basic ansi color generator
const COLORS = {
  wrap: (str, colors) => {
    const codes = colors.filter(c => typeof c === 'number')
    return `\x1b[${codes.join(';')}m${str}\x1b[0m`
  },
  inverse: 7,
  fg: {
    black: 30,
    red: 31,
    green: 32,
    yellow: 33,
    blue: 34,
    magenta: 35,
    cyan: 36,
    white: 37
  },
  bg: {
    black: 40,
    red: 41,
    green: 42,
    yellow: 43,
    blue: 44,
    magenta: 45,
    cyan: 46,
    white: 47
  }
}

class Logger {
  #buffer = []
  #paused = null
  #level = null
  #stream = null

  // ordered from loudest to quietest
  #levels = [{
    id: 'silly',
    display: 'sill',
    style: { inverse: true }
  }, {
    id: 'verbose',
    display: 'verb',
    style: { fg: 'cyan', bg: 'black' }
  }, {
    id: 'info',
    style: { fg: 'green' }
  }, {
    id: 'http',
    style: { fg: 'green', bg: 'black' }
  }, {
    id: 'notice',
    style: { fg: 'cyan', bg: 'black' }
  }, {
    id: 'warn',
    display: 'WARN',
    style: { fg: 'black', bg: 'yellow' }
  }, {
    id: 'error',
    display: 'ERR!',
    style: { fg: 'red', bg: 'black' }
  }]

  constructor (stream) {
    process.on('log', (...args) => this.#onLog(...args))
    this.#levels = new Map(this.#levels.map((level, index) => [level.id, { ...level, index }]))
    this.level = 'info'
    this.stream = stream
    log.pause()
  }

  get stream () {
    return this.#stream
  }

  set stream (stream) {
    this.#stream = stream
  }

  get level () {
    return this.#levels.get(this.#level) ?? null
  }

  set level (level) {
    this.#level = this.#levels.get(level)?.id ?? null
  }

  isVisible (level) {
    return this.level?.index <= this.#levels.get(level)?.index ?? -1
  }

  #onLog (...args) {
    const [level] = args

    if (level === 'pause') {
      this.#paused = true
      return
    }

    if (level === 'resume') {
      this.#paused = false
      this.#buffer.forEach((b) => this.#log(...b))
      this.#buffer.length = 0
      return
    }

    if (this.#paused) {
      this.#buffer.push(args)
      return
    }

    this.#log(...args)
  }

  #color (str, { fg, bg, inverse }) {
    if (!this.#stream?.isTTY) {
      return str
    }

    return COLORS.wrap(str, [
      COLORS.fg[fg],
      COLORS.bg[bg],
      inverse && COLORS.inverse
    ])
  }

  #log (levelId, msgPrefix, ...args) {
    if (!this.isVisible(levelId) || typeof this.#stream?.write !== 'function') {
      return
    }

    const level = this.#levels.get(levelId)

    const prefixParts = [
      this.#color('gyp', { fg: 'white', bg: 'black' }),
      this.#color(level.display ?? level.id, level.style)
    ]
    if (msgPrefix) {
      prefixParts.push(this.#color(msgPrefix, { fg: 'magenta' }))
    }

    const prefix = prefixParts.join(' ').trim() + ' '
    const lines = format(...args).split(/\r?\n/).map(l => prefix + l.trim())

    this.#stream.write(lines.join('\n') + '\n')
  }
}

// used to suppress logs in tests
const NULL_LOGGER = !!process.env.NODE_GYP_NULL_LOGGER

module.exports = {
  logger: new Logger(NULL_LOGGER ? null : process.stderr),
  stdout: NULL_LOGGER ? () => {} : (...args) => console.log(...args),
  withPrefix,
  ...log
}
'use strict'

const path = require('path')
const nopt = require('nopt')
const log = require('./log')
const childProcess = require('child_process')
const { EventEmitter } = require('events')

const commands = [
  // Module build commands
  'build',
  'clean',
  'configure',
  'rebuild',
  // Development Header File management commands
  'install',
  'list',
  'remove'
]

class Gyp extends EventEmitter {
  /**
   * Export the contents of the package.json.
   */
  package = require('../package.json')

  /**
   * nopt configuration definitions
   */
  configDefs = {
    help: Boolean, // everywhere
    arch: String, // 'configure'
    cafile: String, // 'install'
    debug: Boolean, // 'build'
    directory: String, // bin
    make: String, // 'build'
    'msvs-version': String, // 'configure'
    ensure: Boolean, // 'install'
    solution: String, // 'build' (windows only)
    proxy: String, // 'install'
    noproxy: String, // 'install'
    devdir: String, // everywhere
    nodedir: String, // 'configure'
    loglevel: String, // everywhere
    python: String, // 'configure'
    'dist-url': String, // 'install'
    tarball: String, // 'install'
    jobs: String, // 'build'
    thin: String, // 'configure'
    'force-process-config': Boolean // 'configure'
  }

  /**
   * nopt shorthands
   */
  shorthands = {
    release: '--no-debug',
    C: '--directory',
    debug: '--debug',
    j: '--jobs',
    silly: '--loglevel=silly',
    verbose: '--loglevel=verbose',
    silent: '--loglevel=silent'
  }

  /**
   * expose the command aliases for the bin file to use.
   */
  aliases = {
    ls: 'list',
    rm: 'remove'
  }

  constructor (...args) {
    super(...args)

    this.devDir = ''

    this.commands = commands.reduce((acc, command) => {
      acc[command] = (argv) => require('./' + command)(this, argv)
      return acc
    }, {})

    Object.defineProperty(this, 'version', {
      enumerable: true,
      get: function () { return this.package.version }
    })
  }

  /**
   * Parses the given argv array and sets the 'opts',
   * 'argv' and 'command' properties.
   */
  parseArgv (argv) {
    this.opts = nopt(this.configDefs, this.shorthands, argv)
    this.argv = this.opts.argv.remain.slice()

    const commands = this.todo = []

    // create a copy of the argv array with aliases mapped
    argv = this.argv.map((arg) => {
    // is this an alias?
      if (arg in this.aliases) {
        arg = this.aliases[arg]
      }
      return arg
    })

    // process the mapped args into "command" objects ("name" and "args" props)
    argv.slice().forEach((arg) => {
      if (arg in this.commands) {
        const args = argv.splice(0, argv.indexOf(arg))
        argv.shift()
        if (commands.length > 0) {
          commands[commands.length - 1].args = args
        }
        commands.push({ name: arg, args: [] })
      }
    })
    if (commands.length > 0) {
      commands[commands.length - 1].args = argv.splice(0)
    }

    // support for inheriting config env variables from npm
    const npmConfigPrefix = 'npm_config_'
    Object.keys(process.env).forEach((name) => {
      if (name.indexOf(npmConfigPrefix) !== 0) {
        return
      }
      const val = process.env[name]
      if (name === npmConfigPrefix + 'loglevel') {
        log.logger.level = val
      } else {
      // add the user-defined options to the config
        name = name.substring(npmConfigPrefix.length)
        // gyp@741b7f1 enters an infinite loop when it encounters
        // zero-length options so ensure those don't get through.
        if (name) {
        // convert names like force_process_config to force-process-config
          if (name.includes('_')) {
            name = name.replace(/_/g, '-')
          }
          this.opts[name] = val
        }
      }
    })

    if (this.opts.loglevel) {
      log.logger.level = this.opts.loglevel
    }
    log.resume()
  }

  /**
   * Spawns a child process and emits a 'spawn' event.
   */
  spawn (command, args, opts) {
    if (!opts) {
      opts = {}
    }
    if (!opts.silent && !opts.stdio) {
      opts.stdio = [0, 1, 2]
    }
    const cp = childProcess.spawn(command, args, opts)
    log.info('spawn', command)
    log.info('spawn args', args)
    return cp
  }

  /**
   * Returns the usage instructions for node-gyp.
   */
  usage () {
    return [
      '',
      '  Usage: node-gyp  [options]',
      '',
      '  where  is one of:',
      commands.map((c) => '    - ' + c + ' - ' + require('./' + c).usage).join('\n'),
      '',
      'node-gyp@' + this.version + '  ' + path.resolve(__dirname, '..'),
      'node@' + process.versions.node
    ].join('\n')
  }
}

module.exports = () => new Gyp()
module.exports.Gyp = Gyp
/* eslint-disable n/no-deprecated-api */

'use strict'

const semver = require('semver')
const url = require('url')
const path = require('path')
const log = require('./log')

// versions where -headers.tar.gz started shipping
const headersTarballRange = '>= 3.0.0 || ~0.12.10 || ~0.10.42'
const bitsre = /\/win-(x86|x64|arm64)\//
const bitsreV3 = /\/win-(x86|ia32|x64)\// // io.js v3.x.x shipped with "ia32" but should
// have been "x86"

// Captures all the logic required to determine download URLs, local directory and
// file names. Inputs come from command-line switches (--target, --dist-url),
// `process.version` and `process.release` where it exists.
function processRelease (argv, gyp, defaultVersion, defaultRelease) {
  let version = (semver.valid(argv[0]) && argv[0]) || gyp.opts.target || defaultVersion
  const versionSemver = semver.parse(version)
  let overrideDistUrl = gyp.opts['dist-url'] || gyp.opts.disturl
  let isNamedForLegacyIojs
  let name
  let distBaseUrl
  let baseUrl
  let libUrl32
  let libUrl64
  let libUrlArm64
  let tarballUrl
  let canGetHeaders

  if (!versionSemver) {
    // not a valid semver string, nothing we can do
    return { version }
  }
  // flatten version into String
  version = versionSemver.version

  // defaultVersion should come from process.version so ought to be valid semver
  const isDefaultVersion = version === semver.parse(defaultVersion).version

  // can't use process.release if we're using --target=x.y.z
  if (!isDefaultVersion) {
    defaultRelease = null
  }

  if (defaultRelease) {
    // v3 onward, has process.release
    name = defaultRelease.name.replace(/io\.js/, 'iojs') // remove the '.' for directory naming purposes
  } else {
    // old node or alternative --target=
    // semver.satisfies() doesn't like prerelease tags so test major directly
    isNamedForLegacyIojs = versionSemver.major >= 1 && versionSemver.major < 4
    // isNamedForLegacyIojs is required to support Electron < 4 (in particular Electron 3)
    // as previously this logic was used to ensure "iojs" was used to download iojs releases
    // and "node" for node releases.  Unfortunately the logic was broad enough that electron@3
    // published release assets as "iojs" so that the node-gyp logic worked.  Once Electron@3 has
    // been EOL for a while (late 2019) we should remove this hack.
    name = isNamedForLegacyIojs ? 'iojs' : 'node'
  }

  // check for the nvm.sh standard mirror env variables
  if (!overrideDistUrl && process.env.NODEJS_ORG_MIRROR) {
    overrideDistUrl = process.env.NODEJS_ORG_MIRROR
  }

  if (overrideDistUrl) {
    log.verbose('download', 'using dist-url', overrideDistUrl)
  }

  if (overrideDistUrl) {
    distBaseUrl = overrideDistUrl.replace(/\/+$/, '')
  } else {
    distBaseUrl = 'https://nodejs.org/dist'
  }
  distBaseUrl += '/v' + version + '/'

  // new style, based on process.release so we have a lot of the data we need
  if (defaultRelease && defaultRelease.headersUrl && !overrideDistUrl) {
    baseUrl = url.resolve(defaultRelease.headersUrl, './')
    libUrl32 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'x86', versionSemver.major)
    libUrl64 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'x64', versionSemver.major)
    libUrlArm64 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'arm64', versionSemver.major)
    tarballUrl = defaultRelease.headersUrl
  } else {
    // older versions without process.release are captured here and we have to make
    // a lot of assumptions, additionally if you --target=x.y.z then we can't use the
    // current process.release
    baseUrl = distBaseUrl
    libUrl32 = resolveLibUrl(name, baseUrl, 'x86', versionSemver.major)
    libUrl64 = resolveLibUrl(name, baseUrl, 'x64', versionSemver.major)
    libUrlArm64 = resolveLibUrl(name, baseUrl, 'arm64', versionSemver.major)

    // making the bold assumption that anything with a version number >3.0.0 will
    // have a *-headers.tar.gz file in its dist location, even some frankenstein
    // custom version
    canGetHeaders = semver.satisfies(versionSemver, headersTarballRange)
    tarballUrl = url.resolve(baseUrl, name + '-v' + version + (canGetHeaders ? '-headers' : '') + '.tar.gz')
  }

  return {
    version,
    semver: versionSemver,
    name,
    baseUrl,
    tarballUrl,
    shasumsUrl: url.resolve(baseUrl, 'SHASUMS256.txt'),
    versionDir: (name !== 'node' ? name + '-' : '') + version,
    ia32: {
      libUrl: libUrl32,
      libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrl32).path))
    },
    x64: {
      libUrl: libUrl64,
      libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrl64).path))
    },
    arm64: {
      libUrl: libUrlArm64,
      libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrlArm64).path))
    }
  }
}

function normalizePath (p) {
  return path.normalize(p).replace(/\\/g, '/')
}

function resolveLibUrl (name, defaultUrl, arch, versionMajor) {
  const base = url.resolve(defaultUrl, './')
  const hasLibUrl = bitsre.test(defaultUrl) || (versionMajor === 3 && bitsreV3.test(defaultUrl))

  if (!hasLibUrl) {
    // let's assume it's a baseUrl then
    if (versionMajor >= 1) {
      return url.resolve(base, 'win-' + arch + '/' + name + '.lib')
    }
    // prior to io.js@1.0.0 32-bit node.lib lives in /, 64-bit lives in /x64/
    return url.resolve(base, (arch === 'x86' ? '' : arch + '/') + name + '.lib')
  }

  // else we have a proper url to a .lib, just make sure it's the right arch
  return defaultUrl.replace(versionMajor === 3 ? bitsreV3 : bitsre, '/win-' + arch + '/')
}

module.exports = processRelease
'use strict'

async function rebuild (gyp, argv) {
  gyp.todo.push(
    { name: 'clean', args: [] }
    , { name: 'configure', args: argv }
    , { name: 'build', args: [] }
  )
}

module.exports = rebuild
module.exports.usage = 'Runs "clean", "configure" and "build" all at once'
'use strict'

const fs = require('graceful-fs').promises
const path = require('path')
const log = require('./log')
const semver = require('semver')

async function remove (gyp, argv) {
  const devDir = gyp.devDir
  log.verbose('remove', 'using node-gyp dir:', devDir)

  // get the user-specified version to remove
  let version = argv[0] || gyp.opts.target
  log.verbose('remove', 'removing target version:', version)

  if (!version) {
    throw new Error('You must specify a version number to remove. Ex: "' + process.version + '"')
  }

  const versionSemver = semver.parse(version)
  if (versionSemver) {
    // flatten the version Array into a String
    version = versionSemver.version
  }

  const versionPath = path.resolve(gyp.devDir, version)
  log.verbose('remove', 'removing development files for version:', version)

  // first check if its even installed
  try {
    await fs.stat(versionPath)
  } catch (err) {
    if (err.code === 'ENOENT') {
      return 'version was already uninstalled: ' + version
    }
    throw err
  }

  await fs.rm(versionPath, { recursive: true, force: true })
}

module.exports = remove
module.exports.usage = 'Removes the node development files for the specified version'
'use strict'

const cp = require('child_process')
const path = require('path')
const { openSync, closeSync } = require('graceful-fs')
const log = require('./log')

const execFile = async (...args) => new Promise((resolve) => {
  const child = cp.execFile(...args, (...a) => resolve(a))
  child.stdin.end()
})

async function regGetValue (key, value, addOpts) {
  const outReValue = value.replace(/\W/g, '.')
  const outRe = new RegExp(`^\\s+${outReValue}\\s+REG_\\w+\\s+(\\S.*)$`, 'im')
  const reg = path.join(process.env.SystemRoot, 'System32', 'reg.exe')
  const regArgs = ['query', key, '/v', value].concat(addOpts)

  log.silly('reg', 'running', reg, regArgs)
  const [err, stdout, stderr] = await execFile(reg, regArgs, { encoding: 'utf8' })

  log.silly('reg', 'reg.exe stdout = %j', stdout)
  if (err || stderr.trim() !== '') {
    log.silly('reg', 'reg.exe err = %j', err && (err.stack || err))
    log.silly('reg', 'reg.exe stderr = %j', stderr)
    if (err) {
      throw err
    }
    throw new Error(stderr)
  }

  const result = outRe.exec(stdout)
  if (!result) {
    log.silly('reg', 'error parsing stdout')
    throw new Error('Could not parse output of reg.exe')
  }

  log.silly('reg', 'found: %j', result[1])
  return result[1]
}

async function regSearchKeys (keys, value, addOpts) {
  for (const key of keys) {
    try {
      return await regGetValue(key, value, addOpts)
    } catch {
      continue
    }
  }
}

/**
 * Returns the first file or directory from an array of candidates that is
 * readable by the current user, or undefined if none of the candidates are
 * readable.
 */
function findAccessibleSync (logprefix, dir, candidates) {
  for (let next = 0; next < candidates.length; next++) {
    const candidate = path.resolve(dir, candidates[next])
    let fd
    try {
      fd = openSync(candidate, 'r')
    } catch (e) {
      // this candidate was not found or not readable, do nothing
      log.silly(logprefix, 'Could not open %s: %s', candidate, e.message)
      continue
    }
    closeSync(fd)
    log.silly(logprefix, 'Found readable %s', candidate)
    return candidate
  }

  return undefined
}

module.exports = {
  execFile,
  regGetValue,
  regSearchKeys,
  findAccessibleSync
}
#!/bin/bash

pkgs=(
  "com.apple.pkg.DeveloperToolsCLILeo" # standalone
  "com.apple.pkg.DeveloperToolsCLI"    # from XCode
  "com.apple.pkg.CLTools_Executables"  # Mavericks
)

for pkg in "${pkgs[@]}"; do
  output=$(/usr/sbin/pkgutil --pkg-info "$pkg" 2>/dev/null)
  if [ "$output" ]; then
    version=$(echo "$output" | grep 'version' | cut -d' ' -f2)
    break
  fi
done

if [ "$version" ]; then
  echo "Command Line Tools version: $version"
else
  echo >&2 'Command Line Tools not found'
fi
All packages under `src/` are licensed according to the terms in
their respective `LICENSE` or `LICENSE.md` files.

The remainder of this project is licensed under the Blue Oak
Model License, as follows:

-----

# Blue Oak Model License

Version 1.0.0

## Purpose

This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.

## Acceptance

In order to receive this license, you must agree to its
rules.  The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.

## Copyright

Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.

## Notices

You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
.

## Excuse

If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice.  If you do not do so, your license
ends immediately.

## Patent

Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.

## Reliability

No contributor can revoke this license.

## No Liability

***As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim.***
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.chownrSync = exports.chownr = void 0;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const lchownSync = (path, uid, gid) => {
    try {
        return node_fs_1.default.lchownSync(path, uid, gid);
    }
    catch (er) {
        if (er?.code !== 'ENOENT')
            throw er;
    }
};
const chown = (cpath, uid, gid, cb) => {
    node_fs_1.default.lchown(cpath, uid, gid, er => {
        // Skip ENOENT error
        cb(er && er?.code !== 'ENOENT' ? er : null);
    });
};
const chownrKid = (p, child, uid, gid, cb) => {
    if (child.isDirectory()) {
        (0, exports.chownr)(node_path_1.default.resolve(p, child.name), uid, gid, (er) => {
            if (er)
                return cb(er);
            const cpath = node_path_1.default.resolve(p, child.name);
            chown(cpath, uid, gid, cb);
        });
    }
    else {
        const cpath = node_path_1.default.resolve(p, child.name);
        chown(cpath, uid, gid, cb);
    }
};
const chownr = (p, uid, gid, cb) => {
    node_fs_1.default.readdir(p, { withFileTypes: true }, (er, children) => {
        // any error other than ENOTDIR or ENOTSUP means it's not readable,
        // or doesn't exist.  give up.
        if (er) {
            if (er.code === 'ENOENT')
                return cb();
            else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')
                return cb(er);
        }
        if (er || !children.length)
            return chown(p, uid, gid, cb);
        let len = children.length;
        let errState = null;
        const then = (er) => {
            /* c8 ignore start */
            if (errState)
                return;
            /* c8 ignore stop */
            if (er)
                return cb((errState = er));
            if (--len === 0)
                return chown(p, uid, gid, cb);
        };
        for (const child of children) {
            chownrKid(p, child, uid, gid, then);
        }
    });
};
exports.chownr = chownr;
const chownrKidSync = (p, child, uid, gid) => {
    if (child.isDirectory())
        (0, exports.chownrSync)(node_path_1.default.resolve(p, child.name), uid, gid);
    lchownSync(node_path_1.default.resolve(p, child.name), uid, gid);
};
const chownrSync = (p, uid, gid) => {
    let children;
    try {
        children = node_fs_1.default.readdirSync(p, { withFileTypes: true });
    }
    catch (er) {
        const e = er;
        if (e?.code === 'ENOENT')
            return;
        else if (e?.code === 'ENOTDIR' || e?.code === 'ENOTSUP')
            return lchownSync(p, uid, gid);
        else
            throw e;
    }
    for (const child of children) {
        chownrKidSync(p, child, uid, gid);
    }
    return lchownSync(p, uid, gid);
};
exports.chownrSync = chownrSync;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
import fs from 'node:fs';
import path from 'node:path';
const lchownSync = (path, uid, gid) => {
    try {
        return fs.lchownSync(path, uid, gid);
    }
    catch (er) {
        if (er?.code !== 'ENOENT')
            throw er;
    }
};
const chown = (cpath, uid, gid, cb) => {
    fs.lchown(cpath, uid, gid, er => {
        // Skip ENOENT error
        cb(er && er?.code !== 'ENOENT' ? er : null);
    });
};
const chownrKid = (p, child, uid, gid, cb) => {
    if (child.isDirectory()) {
        chownr(path.resolve(p, child.name), uid, gid, (er) => {
            if (er)
                return cb(er);
            const cpath = path.resolve(p, child.name);
            chown(cpath, uid, gid, cb);
        });
    }
    else {
        const cpath = path.resolve(p, child.name);
        chown(cpath, uid, gid, cb);
    }
};
export const chownr = (p, uid, gid, cb) => {
    fs.readdir(p, { withFileTypes: true }, (er, children) => {
        // any error other than ENOTDIR or ENOTSUP means it's not readable,
        // or doesn't exist.  give up.
        if (er) {
            if (er.code === 'ENOENT')
                return cb();
            else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')
                return cb(er);
        }
        if (er || !children.length)
            return chown(p, uid, gid, cb);
        let len = children.length;
        let errState = null;
        const then = (er) => {
            /* c8 ignore start */
            if (errState)
                return;
            /* c8 ignore stop */
            if (er)
                return cb((errState = er));
            if (--len === 0)
                return chown(p, uid, gid, cb);
        };
        for (const child of children) {
            chownrKid(p, child, uid, gid, then);
        }
    });
};
const chownrKidSync = (p, child, uid, gid) => {
    if (child.isDirectory())
        chownrSync(path.resolve(p, child.name), uid, gid);
    lchownSync(path.resolve(p, child.name), uid, gid);
};
export const chownrSync = (p, uid, gid) => {
    let children;
    try {
        children = fs.readdirSync(p, { withFileTypes: true });
    }
    catch (er) {
        const e = er;
        if (e?.code === 'ENOENT')
            return;
        else if (e?.code === 'ENOTDIR' || e?.code === 'ENOTSUP')
            return lchownSync(p, uid, gid);
        else
            throw e;
    }
    for (const child of children) {
        chownrKidSync(p, child, uid, gid);
    }
    return lchownSync(p, uid, gid);
};
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "name": "chownr",
  "description": "like `chown -R`",
  "version": "3.0.0",
  "repository": {
    "type": "git",
    "url": "git://github.com/isaacs/chownr.git"
  },
  "files": [
    "dist"
  ],
  "devDependencies": {
    "@types/node": "^20.12.5",
    "mkdirp": "^3.0.1",
    "prettier": "^3.2.5",
    "rimraf": "^5.0.5",
    "tap": "^18.7.2",
    "tshy": "^1.13.1",
    "typedoc": "^0.25.12"
  },
  "scripts": {
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "format": "prettier --write . --loglevel warn",
    "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
  },
  "license": "BlueOak-1.0.0",
  "engines": {
    "node": ">=18"
  },
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "main": "./dist/commonjs/index.js",
  "types": "./dist/commonjs/index.d.ts",
  "type": "module",
  "prettier": {
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  }
}
Minizlib was created by Isaac Z. Schlueter.
It is a derivative work of the Node.js project.

"""
Copyright (c) 2017-2023 Isaac Z. Schlueter and Contributors
Copyright (c) 2017-2023 Node.js contributors. All rights reserved.
Copyright (c) 2017-2023 Joyent, Inc. and other Node contributors. All rights reserved.

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.
"""
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.constants = void 0;
// Update with any zlib constants that are added or changed in the future.
// Node v6 didn't export this, so we just hard code the version and rely
// on all the other hard-coded values from zlib v4736.  When node v6
// support drops, we can just export the realZlibConstants object.
const zlib_1 = __importDefault(require("zlib"));
/* c8 ignore start */
const realZlibConstants = zlib_1.default.constants || { ZLIB_VERNUM: 4736 };
/* c8 ignore stop */
exports.constants = Object.freeze(Object.assign(Object.create(null), {
    Z_NO_FLUSH: 0,
    Z_PARTIAL_FLUSH: 1,
    Z_SYNC_FLUSH: 2,
    Z_FULL_FLUSH: 3,
    Z_FINISH: 4,
    Z_BLOCK: 5,
    Z_OK: 0,
    Z_STREAM_END: 1,
    Z_NEED_DICT: 2,
    Z_ERRNO: -1,
    Z_STREAM_ERROR: -2,
    Z_DATA_ERROR: -3,
    Z_MEM_ERROR: -4,
    Z_BUF_ERROR: -5,
    Z_VERSION_ERROR: -6,
    Z_NO_COMPRESSION: 0,
    Z_BEST_SPEED: 1,
    Z_BEST_COMPRESSION: 9,
    Z_DEFAULT_COMPRESSION: -1,
    Z_FILTERED: 1,
    Z_HUFFMAN_ONLY: 2,
    Z_RLE: 3,
    Z_FIXED: 4,
    Z_DEFAULT_STRATEGY: 0,
    DEFLATE: 1,
    INFLATE: 2,
    GZIP: 3,
    GUNZIP: 4,
    DEFLATERAW: 5,
    INFLATERAW: 6,
    UNZIP: 7,
    BROTLI_DECODE: 8,
    BROTLI_ENCODE: 9,
    Z_MIN_WINDOWBITS: 8,
    Z_MAX_WINDOWBITS: 15,
    Z_DEFAULT_WINDOWBITS: 15,
    Z_MIN_CHUNK: 64,
    Z_MAX_CHUNK: Infinity,
    Z_DEFAULT_CHUNK: 16384,
    Z_MIN_MEMLEVEL: 1,
    Z_MAX_MEMLEVEL: 9,
    Z_DEFAULT_MEMLEVEL: 8,
    Z_MIN_LEVEL: -1,
    Z_MAX_LEVEL: 9,
    Z_DEFAULT_LEVEL: -1,
    BROTLI_OPERATION_PROCESS: 0,
    BROTLI_OPERATION_FLUSH: 1,
    BROTLI_OPERATION_FINISH: 2,
    BROTLI_OPERATION_EMIT_METADATA: 3,
    BROTLI_MODE_GENERIC: 0,
    BROTLI_MODE_TEXT: 1,
    BROTLI_MODE_FONT: 2,
    BROTLI_DEFAULT_MODE: 0,
    BROTLI_MIN_QUALITY: 0,
    BROTLI_MAX_QUALITY: 11,
    BROTLI_DEFAULT_QUALITY: 11,
    BROTLI_MIN_WINDOW_BITS: 10,
    BROTLI_MAX_WINDOW_BITS: 24,
    BROTLI_LARGE_MAX_WINDOW_BITS: 30,
    BROTLI_DEFAULT_WINDOW: 22,
    BROTLI_MIN_INPUT_BLOCK_BITS: 16,
    BROTLI_MAX_INPUT_BLOCK_BITS: 24,
    BROTLI_PARAM_MODE: 0,
    BROTLI_PARAM_QUALITY: 1,
    BROTLI_PARAM_LGWIN: 2,
    BROTLI_PARAM_LGBLOCK: 3,
    BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
    BROTLI_PARAM_SIZE_HINT: 5,
    BROTLI_PARAM_LARGE_WINDOW: 6,
    BROTLI_PARAM_NPOSTFIX: 7,
    BROTLI_PARAM_NDIRECT: 8,
    BROTLI_DECODER_RESULT_ERROR: 0,
    BROTLI_DECODER_RESULT_SUCCESS: 1,
    BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
    BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
    BROTLI_DECODER_NO_ERROR: 0,
    BROTLI_DECODER_SUCCESS: 1,
    BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
    BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
    BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
    BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
    BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
    BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
    BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
    BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
    BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
    BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
    BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
    BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
    BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
    BROTLI_DECODER_ERROR_UNREACHABLE: -31,
}, realZlibConstants));
//# sourceMappingURL=constants.js.map"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrotliDecompress = exports.BrotliCompress = exports.Brotli = exports.Unzip = exports.InflateRaw = exports.DeflateRaw = exports.Gunzip = exports.Gzip = exports.Inflate = exports.Deflate = exports.Zlib = exports.ZlibError = exports.constants = void 0;
const assert_1 = __importDefault(require("assert"));
const buffer_1 = require("buffer");
const minipass_1 = require("minipass");
const zlib_1 = __importDefault(require("zlib"));
const constants_js_1 = require("./constants.js");
var constants_js_2 = require("./constants.js");
Object.defineProperty(exports, "constants", { enumerable: true, get: function () { return constants_js_2.constants; } });
const OriginalBufferConcat = buffer_1.Buffer.concat;
const _superWrite = Symbol('_superWrite');
class ZlibError extends Error {
    code;
    errno;
    constructor(err) {
        super('zlib: ' + err.message);
        this.code = err.code;
        this.errno = err.errno;
        /* c8 ignore next */
        if (!this.code)
            this.code = 'ZLIB_ERROR';
        this.message = 'zlib: ' + err.message;
        Error.captureStackTrace(this, this.constructor);
    }
    get name() {
        return 'ZlibError';
    }
}
exports.ZlibError = ZlibError;
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
const _flushFlag = Symbol('flushFlag');
class ZlibBase extends minipass_1.Minipass {
    #sawError = false;
    #ended = false;
    #flushFlag;
    #finishFlushFlag;
    #fullFlushFlag;
    #handle;
    #onError;
    get sawError() {
        return this.#sawError;
    }
    get handle() {
        return this.#handle;
    }
    /* c8 ignore start */
    get flushFlag() {
        return this.#flushFlag;
    }
    /* c8 ignore stop */
    constructor(opts, mode) {
        if (!opts || typeof opts !== 'object')
            throw new TypeError('invalid options for ZlibBase constructor');
        //@ts-ignore
        super(opts);
        /* c8 ignore start */
        this.#flushFlag = opts.flush ?? 0;
        this.#finishFlushFlag = opts.finishFlush ?? 0;
        this.#fullFlushFlag = opts.fullFlushFlag ?? 0;
        /* c8 ignore stop */
        // this will throw if any options are invalid for the class selected
        try {
            // @types/node doesn't know that it exports the classes, but they're there
            //@ts-ignore
            this.#handle = new zlib_1.default[mode](opts);
        }
        catch (er) {
            // make sure that all errors get decorated properly
            throw new ZlibError(er);
        }
        this.#onError = err => {
            // no sense raising multiple errors, since we abort on the first one.
            if (this.#sawError)
                return;
            this.#sawError = true;
            // there is no way to cleanly recover.
            // continuing only obscures problems.
            this.close();
            this.emit('error', err);
        };
        this.#handle?.on('error', er => this.#onError(new ZlibError(er)));
        this.once('end', () => this.close);
    }
    close() {
        if (this.#handle) {
            this.#handle.close();
            this.#handle = undefined;
            this.emit('close');
        }
    }
    reset() {
        if (!this.#sawError) {
            (0, assert_1.default)(this.#handle, 'zlib binding closed');
            //@ts-ignore
            return this.#handle.reset?.();
        }
    }
    flush(flushFlag) {
        if (this.ended)
            return;
        if (typeof flushFlag !== 'number')
            flushFlag = this.#fullFlushFlag;
        this.write(Object.assign(buffer_1.Buffer.alloc(0), { [_flushFlag]: flushFlag }));
    }
    end(chunk, encoding, cb) {
        /* c8 ignore start */
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (chunk) {
            if (encoding)
                this.write(chunk, encoding);
            else
                this.write(chunk);
        }
        this.flush(this.#finishFlushFlag);
        this.#ended = true;
        return super.end(cb);
    }
    get ended() {
        return this.#ended;
    }
    // overridden in the gzip classes to do portable writes
    [_superWrite](data) {
        return super.write(data);
    }
    write(chunk, encoding, cb) {
        // process the chunk using the sync process
        // then super.write() all the outputted chunks
        if (typeof encoding === 'function')
            (cb = encoding), (encoding = 'utf8');
        if (typeof chunk === 'string')
            chunk = buffer_1.Buffer.from(chunk, encoding);
        if (this.#sawError)
            return;
        (0, assert_1.default)(this.#handle, 'zlib binding closed');
        // _processChunk tries to .close() the native handle after it's done, so we
        // intercept that by temporarily making it a no-op.
        // diving into the node:zlib internals a bit here
        const nativeHandle = this.#handle
            ._handle;
        const originalNativeClose = nativeHandle.close;
        nativeHandle.close = () => { };
        const originalClose = this.#handle.close;
        this.#handle.close = () => { };
        // It also calls `Buffer.concat()` at the end, which may be convenient
        // for some, but which we are not interested in as it slows us down.
        buffer_1.Buffer.concat = args => args;
        let result = undefined;
        try {
            const flushFlag = typeof chunk[_flushFlag] === 'number'
                ? chunk[_flushFlag]
                : this.#flushFlag;
            result = this.#handle._processChunk(chunk, flushFlag);
            // if we don't throw, reset it back how it was
            buffer_1.Buffer.concat = OriginalBufferConcat;
        }
        catch (err) {
            // or if we do, put Buffer.concat() back before we emit error
            // Error events call into user code, which may call Buffer.concat()
            buffer_1.Buffer.concat = OriginalBufferConcat;
            this.#onError(new ZlibError(err));
        }
        finally {
            if (this.#handle) {
                // Core zlib resets `_handle` to null after attempting to close the
                // native handle. Our no-op handler prevented actual closure, but we
                // need to restore the `._handle` property.
                ;
                this.#handle._handle =
                    nativeHandle;
                nativeHandle.close = originalNativeClose;
                this.#handle.close = originalClose;
                // `_processChunk()` adds an 'error' listener. If we don't remove it
                // after each call, these handlers start piling up.
                this.#handle.removeAllListeners('error');
                // make sure OUR error listener is still attached tho
            }
        }
        if (this.#handle)
            this.#handle.on('error', er => this.#onError(new ZlibError(er)));
        let writeReturn;
        if (result) {
            if (Array.isArray(result) && result.length > 0) {
                const r = result[0];
                // The first buffer is always `handle._outBuffer`, which would be
                // re-used for later invocations; so, we always have to copy that one.
                writeReturn = this[_superWrite](buffer_1.Buffer.from(r));
                for (let i = 1; i < result.length; i++) {
                    writeReturn = this[_superWrite](result[i]);
                }
            }
            else {
                // either a single Buffer or an empty array
                writeReturn = this[_superWrite](buffer_1.Buffer.from(result));
            }
        }
        if (cb)
            cb();
        return writeReturn;
    }
}
class Zlib extends ZlibBase {
    #level;
    #strategy;
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants_js_1.constants.Z_NO_FLUSH;
        opts.finishFlush = opts.finishFlush || constants_js_1.constants.Z_FINISH;
        opts.fullFlushFlag = constants_js_1.constants.Z_FULL_FLUSH;
        super(opts, mode);
        this.#level = opts.level;
        this.#strategy = opts.strategy;
    }
    params(level, strategy) {
        if (this.sawError)
            return;
        if (!this.handle)
            throw new Error('cannot switch params when binding is closed');
        // no way to test this without also not supporting params at all
        /* c8 ignore start */
        if (!this.handle.params)
            throw new Error('not supported in this implementation');
        /* c8 ignore stop */
        if (this.#level !== level || this.#strategy !== strategy) {
            this.flush(constants_js_1.constants.Z_SYNC_FLUSH);
            (0, assert_1.default)(this.handle, 'zlib binding closed');
            // .params() calls .flush(), but the latter is always async in the
            // core zlib. We override .flush() temporarily to intercept that and
            // flush synchronously.
            const origFlush = this.handle.flush;
            this.handle.flush = (flushFlag, cb) => {
                /* c8 ignore start */
                if (typeof flushFlag === 'function') {
                    cb = flushFlag;
                    flushFlag = this.flushFlag;
                }
                /* c8 ignore stop */
                this.flush(flushFlag);
                cb?.();
            };
            try {
                ;
                this.handle.params(level, strategy);
            }
            finally {
                this.handle.flush = origFlush;
            }
            /* c8 ignore start */
            if (this.handle) {
                this.#level = level;
                this.#strategy = strategy;
            }
            /* c8 ignore stop */
        }
    }
}
exports.Zlib = Zlib;
// minimal 2-byte header
class Deflate extends Zlib {
    constructor(opts) {
        super(opts, 'Deflate');
    }
}
exports.Deflate = Deflate;
class Inflate extends Zlib {
    constructor(opts) {
        super(opts, 'Inflate');
    }
}
exports.Inflate = Inflate;
class Gzip extends Zlib {
    #portable;
    constructor(opts) {
        super(opts, 'Gzip');
        this.#portable = opts && !!opts.portable;
    }
    [_superWrite](data) {
        if (!this.#portable)
            return super[_superWrite](data);
        // we'll always get the header emitted in one first chunk
        // overwrite the OS indicator byte with 0xFF
        this.#portable = false;
        data[9] = 255;
        return super[_superWrite](data);
    }
}
exports.Gzip = Gzip;
class Gunzip extends Zlib {
    constructor(opts) {
        super(opts, 'Gunzip');
    }
}
exports.Gunzip = Gunzip;
// raw - no header
class DeflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'DeflateRaw');
    }
}
exports.DeflateRaw = DeflateRaw;
class InflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'InflateRaw');
    }
}
exports.InflateRaw = InflateRaw;
// auto-detect header.
class Unzip extends Zlib {
    constructor(opts) {
        super(opts, 'Unzip');
    }
}
exports.Unzip = Unzip;
class Brotli extends ZlibBase {
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants_js_1.constants.BROTLI_OPERATION_PROCESS;
        opts.finishFlush =
            opts.finishFlush || constants_js_1.constants.BROTLI_OPERATION_FINISH;
        opts.fullFlushFlag = constants_js_1.constants.BROTLI_OPERATION_FLUSH;
        super(opts, mode);
    }
}
exports.Brotli = Brotli;
class BrotliCompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliCompress');
    }
}
exports.BrotliCompress = BrotliCompress;
class BrotliDecompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliDecompress');
    }
}
exports.BrotliDecompress = BrotliDecompress;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
// Update with any zlib constants that are added or changed in the future.
// Node v6 didn't export this, so we just hard code the version and rely
// on all the other hard-coded values from zlib v4736.  When node v6
// support drops, we can just export the realZlibConstants object.
import realZlib from 'zlib';
/* c8 ignore start */
const realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 };
/* c8 ignore stop */
export const constants = Object.freeze(Object.assign(Object.create(null), {
    Z_NO_FLUSH: 0,
    Z_PARTIAL_FLUSH: 1,
    Z_SYNC_FLUSH: 2,
    Z_FULL_FLUSH: 3,
    Z_FINISH: 4,
    Z_BLOCK: 5,
    Z_OK: 0,
    Z_STREAM_END: 1,
    Z_NEED_DICT: 2,
    Z_ERRNO: -1,
    Z_STREAM_ERROR: -2,
    Z_DATA_ERROR: -3,
    Z_MEM_ERROR: -4,
    Z_BUF_ERROR: -5,
    Z_VERSION_ERROR: -6,
    Z_NO_COMPRESSION: 0,
    Z_BEST_SPEED: 1,
    Z_BEST_COMPRESSION: 9,
    Z_DEFAULT_COMPRESSION: -1,
    Z_FILTERED: 1,
    Z_HUFFMAN_ONLY: 2,
    Z_RLE: 3,
    Z_FIXED: 4,
    Z_DEFAULT_STRATEGY: 0,
    DEFLATE: 1,
    INFLATE: 2,
    GZIP: 3,
    GUNZIP: 4,
    DEFLATERAW: 5,
    INFLATERAW: 6,
    UNZIP: 7,
    BROTLI_DECODE: 8,
    BROTLI_ENCODE: 9,
    Z_MIN_WINDOWBITS: 8,
    Z_MAX_WINDOWBITS: 15,
    Z_DEFAULT_WINDOWBITS: 15,
    Z_MIN_CHUNK: 64,
    Z_MAX_CHUNK: Infinity,
    Z_DEFAULT_CHUNK: 16384,
    Z_MIN_MEMLEVEL: 1,
    Z_MAX_MEMLEVEL: 9,
    Z_DEFAULT_MEMLEVEL: 8,
    Z_MIN_LEVEL: -1,
    Z_MAX_LEVEL: 9,
    Z_DEFAULT_LEVEL: -1,
    BROTLI_OPERATION_PROCESS: 0,
    BROTLI_OPERATION_FLUSH: 1,
    BROTLI_OPERATION_FINISH: 2,
    BROTLI_OPERATION_EMIT_METADATA: 3,
    BROTLI_MODE_GENERIC: 0,
    BROTLI_MODE_TEXT: 1,
    BROTLI_MODE_FONT: 2,
    BROTLI_DEFAULT_MODE: 0,
    BROTLI_MIN_QUALITY: 0,
    BROTLI_MAX_QUALITY: 11,
    BROTLI_DEFAULT_QUALITY: 11,
    BROTLI_MIN_WINDOW_BITS: 10,
    BROTLI_MAX_WINDOW_BITS: 24,
    BROTLI_LARGE_MAX_WINDOW_BITS: 30,
    BROTLI_DEFAULT_WINDOW: 22,
    BROTLI_MIN_INPUT_BLOCK_BITS: 16,
    BROTLI_MAX_INPUT_BLOCK_BITS: 24,
    BROTLI_PARAM_MODE: 0,
    BROTLI_PARAM_QUALITY: 1,
    BROTLI_PARAM_LGWIN: 2,
    BROTLI_PARAM_LGBLOCK: 3,
    BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
    BROTLI_PARAM_SIZE_HINT: 5,
    BROTLI_PARAM_LARGE_WINDOW: 6,
    BROTLI_PARAM_NPOSTFIX: 7,
    BROTLI_PARAM_NDIRECT: 8,
    BROTLI_DECODER_RESULT_ERROR: 0,
    BROTLI_DECODER_RESULT_SUCCESS: 1,
    BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
    BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
    BROTLI_DECODER_NO_ERROR: 0,
    BROTLI_DECODER_SUCCESS: 1,
    BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
    BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
    BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
    BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
    BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
    BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
    BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
    BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
    BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
    BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
    BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
    BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
    BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
    BROTLI_DECODER_ERROR_UNREACHABLE: -31,
}, realZlibConstants));
//# sourceMappingURL=constants.js.mapimport assert from 'assert';
import { Buffer } from 'buffer';
import { Minipass } from 'minipass';
import realZlib from 'zlib';
import { constants } from './constants.js';
export { constants } from './constants.js';
const OriginalBufferConcat = Buffer.concat;
const _superWrite = Symbol('_superWrite');
export class ZlibError extends Error {
    code;
    errno;
    constructor(err) {
        super('zlib: ' + err.message);
        this.code = err.code;
        this.errno = err.errno;
        /* c8 ignore next */
        if (!this.code)
            this.code = 'ZLIB_ERROR';
        this.message = 'zlib: ' + err.message;
        Error.captureStackTrace(this, this.constructor);
    }
    get name() {
        return 'ZlibError';
    }
}
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
const _flushFlag = Symbol('flushFlag');
class ZlibBase extends Minipass {
    #sawError = false;
    #ended = false;
    #flushFlag;
    #finishFlushFlag;
    #fullFlushFlag;
    #handle;
    #onError;
    get sawError() {
        return this.#sawError;
    }
    get handle() {
        return this.#handle;
    }
    /* c8 ignore start */
    get flushFlag() {
        return this.#flushFlag;
    }
    /* c8 ignore stop */
    constructor(opts, mode) {
        if (!opts || typeof opts !== 'object')
            throw new TypeError('invalid options for ZlibBase constructor');
        //@ts-ignore
        super(opts);
        /* c8 ignore start */
        this.#flushFlag = opts.flush ?? 0;
        this.#finishFlushFlag = opts.finishFlush ?? 0;
        this.#fullFlushFlag = opts.fullFlushFlag ?? 0;
        /* c8 ignore stop */
        // this will throw if any options are invalid for the class selected
        try {
            // @types/node doesn't know that it exports the classes, but they're there
            //@ts-ignore
            this.#handle = new realZlib[mode](opts);
        }
        catch (er) {
            // make sure that all errors get decorated properly
            throw new ZlibError(er);
        }
        this.#onError = err => {
            // no sense raising multiple errors, since we abort on the first one.
            if (this.#sawError)
                return;
            this.#sawError = true;
            // there is no way to cleanly recover.
            // continuing only obscures problems.
            this.close();
            this.emit('error', err);
        };
        this.#handle?.on('error', er => this.#onError(new ZlibError(er)));
        this.once('end', () => this.close);
    }
    close() {
        if (this.#handle) {
            this.#handle.close();
            this.#handle = undefined;
            this.emit('close');
        }
    }
    reset() {
        if (!this.#sawError) {
            assert(this.#handle, 'zlib binding closed');
            //@ts-ignore
            return this.#handle.reset?.();
        }
    }
    flush(flushFlag) {
        if (this.ended)
            return;
        if (typeof flushFlag !== 'number')
            flushFlag = this.#fullFlushFlag;
        this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }));
    }
    end(chunk, encoding, cb) {
        /* c8 ignore start */
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (chunk) {
            if (encoding)
                this.write(chunk, encoding);
            else
                this.write(chunk);
        }
        this.flush(this.#finishFlushFlag);
        this.#ended = true;
        return super.end(cb);
    }
    get ended() {
        return this.#ended;
    }
    // overridden in the gzip classes to do portable writes
    [_superWrite](data) {
        return super.write(data);
    }
    write(chunk, encoding, cb) {
        // process the chunk using the sync process
        // then super.write() all the outputted chunks
        if (typeof encoding === 'function')
            (cb = encoding), (encoding = 'utf8');
        if (typeof chunk === 'string')
            chunk = Buffer.from(chunk, encoding);
        if (this.#sawError)
            return;
        assert(this.#handle, 'zlib binding closed');
        // _processChunk tries to .close() the native handle after it's done, so we
        // intercept that by temporarily making it a no-op.
        // diving into the node:zlib internals a bit here
        const nativeHandle = this.#handle
            ._handle;
        const originalNativeClose = nativeHandle.close;
        nativeHandle.close = () => { };
        const originalClose = this.#handle.close;
        this.#handle.close = () => { };
        // It also calls `Buffer.concat()` at the end, which may be convenient
        // for some, but which we are not interested in as it slows us down.
        Buffer.concat = args => args;
        let result = undefined;
        try {
            const flushFlag = typeof chunk[_flushFlag] === 'number'
                ? chunk[_flushFlag]
                : this.#flushFlag;
            result = this.#handle._processChunk(chunk, flushFlag);
            // if we don't throw, reset it back how it was
            Buffer.concat = OriginalBufferConcat;
        }
        catch (err) {
            // or if we do, put Buffer.concat() back before we emit error
            // Error events call into user code, which may call Buffer.concat()
            Buffer.concat = OriginalBufferConcat;
            this.#onError(new ZlibError(err));
        }
        finally {
            if (this.#handle) {
                // Core zlib resets `_handle` to null after attempting to close the
                // native handle. Our no-op handler prevented actual closure, but we
                // need to restore the `._handle` property.
                ;
                this.#handle._handle =
                    nativeHandle;
                nativeHandle.close = originalNativeClose;
                this.#handle.close = originalClose;
                // `_processChunk()` adds an 'error' listener. If we don't remove it
                // after each call, these handlers start piling up.
                this.#handle.removeAllListeners('error');
                // make sure OUR error listener is still attached tho
            }
        }
        if (this.#handle)
            this.#handle.on('error', er => this.#onError(new ZlibError(er)));
        let writeReturn;
        if (result) {
            if (Array.isArray(result) && result.length > 0) {
                const r = result[0];
                // The first buffer is always `handle._outBuffer`, which would be
                // re-used for later invocations; so, we always have to copy that one.
                writeReturn = this[_superWrite](Buffer.from(r));
                for (let i = 1; i < result.length; i++) {
                    writeReturn = this[_superWrite](result[i]);
                }
            }
            else {
                // either a single Buffer or an empty array
                writeReturn = this[_superWrite](Buffer.from(result));
            }
        }
        if (cb)
            cb();
        return writeReturn;
    }
}
export class Zlib extends ZlibBase {
    #level;
    #strategy;
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.Z_NO_FLUSH;
        opts.finishFlush = opts.finishFlush || constants.Z_FINISH;
        opts.fullFlushFlag = constants.Z_FULL_FLUSH;
        super(opts, mode);
        this.#level = opts.level;
        this.#strategy = opts.strategy;
    }
    params(level, strategy) {
        if (this.sawError)
            return;
        if (!this.handle)
            throw new Error('cannot switch params when binding is closed');
        // no way to test this without also not supporting params at all
        /* c8 ignore start */
        if (!this.handle.params)
            throw new Error('not supported in this implementation');
        /* c8 ignore stop */
        if (this.#level !== level || this.#strategy !== strategy) {
            this.flush(constants.Z_SYNC_FLUSH);
            assert(this.handle, 'zlib binding closed');
            // .params() calls .flush(), but the latter is always async in the
            // core zlib. We override .flush() temporarily to intercept that and
            // flush synchronously.
            const origFlush = this.handle.flush;
            this.handle.flush = (flushFlag, cb) => {
                /* c8 ignore start */
                if (typeof flushFlag === 'function') {
                    cb = flushFlag;
                    flushFlag = this.flushFlag;
                }
                /* c8 ignore stop */
                this.flush(flushFlag);
                cb?.();
            };
            try {
                ;
                this.handle.params(level, strategy);
            }
            finally {
                this.handle.flush = origFlush;
            }
            /* c8 ignore start */
            if (this.handle) {
                this.#level = level;
                this.#strategy = strategy;
            }
            /* c8 ignore stop */
        }
    }
}
// minimal 2-byte header
export class Deflate extends Zlib {
    constructor(opts) {
        super(opts, 'Deflate');
    }
}
export class Inflate extends Zlib {
    constructor(opts) {
        super(opts, 'Inflate');
    }
}
export class Gzip extends Zlib {
    #portable;
    constructor(opts) {
        super(opts, 'Gzip');
        this.#portable = opts && !!opts.portable;
    }
    [_superWrite](data) {
        if (!this.#portable)
            return super[_superWrite](data);
        // we'll always get the header emitted in one first chunk
        // overwrite the OS indicator byte with 0xFF
        this.#portable = false;
        data[9] = 255;
        return super[_superWrite](data);
    }
}
export class Gunzip extends Zlib {
    constructor(opts) {
        super(opts, 'Gunzip');
    }
}
// raw - no header
export class DeflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'DeflateRaw');
    }
}
export class InflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'InflateRaw');
    }
}
// auto-detect header.
export class Unzip extends Zlib {
    constructor(opts) {
        super(opts, 'Unzip');
    }
}
export class Brotli extends ZlibBase {
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS;
        opts.finishFlush =
            opts.finishFlush || constants.BROTLI_OPERATION_FINISH;
        opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH;
        super(opts, mode);
    }
}
export class BrotliCompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliCompress');
    }
}
export class BrotliDecompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliDecompress');
    }
}
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "name": "minizlib",
  "version": "3.0.1",
  "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.",
  "main": "./dist/commonjs/index.js",
  "dependencies": {
    "minipass": "^7.0.4",
    "rimraf": "^5.0.5"
  },
  "scripts": {
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "format": "prettier --write . --loglevel warn",
    "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minizlib.git"
  },
  "keywords": [
    "zlib",
    "gzip",
    "gunzip",
    "deflate",
    "inflate",
    "compression",
    "zip",
    "unzip"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "MIT",
  "devDependencies": {
    "@types/node": "^20.11.29",
    "mkdirp": "^3.0.1",
    "tap": "^18.7.1",
    "tshy": "^1.12.0",
    "typedoc": "^0.25.12"
  },
  "files": [
    "dist"
  ],
  "engines": {
    "node": ">= 18"
  },
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "types": "./dist/commonjs/index.d.ts",
  "type": "module",
  "prettier": {
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  }
}
Copyright (c) 2011-2023 James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me)

This project is free software released under the MIT license:

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.
{
    "name": "mkdirp",
    "description": "Recursively mkdir, like `mkdir -p`",
    "version": "3.0.1",
    "keywords": [
        "mkdir",
        "directory",
        "make dir",
        "make",
        "dir",
        "recursive",
        "native"
    ],
    "bin": "./dist/cjs/src/bin.js",
    "main": "./dist/cjs/src/index.js",
    "module": "./dist/mjs/index.js",
    "types": "./dist/mjs/index.d.ts",
    "exports": {
        ".": {
            "import": {
                "types": "./dist/mjs/index.d.ts",
                "default": "./dist/mjs/index.js"
            },
            "require": {
                "types": "./dist/cjs/src/index.d.ts",
                "default": "./dist/cjs/src/index.js"
            }
        }
    },
    "files": [
        "dist"
    ],
    "scripts": {
        "preversion": "npm test",
        "postversion": "npm publish",
        "prepublishOnly": "git push origin --follow-tags",
        "preprepare": "rm -rf dist",
        "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json",
        "postprepare": "bash fixup.sh",
        "pretest": "npm run prepare",
        "presnap": "npm run prepare",
        "test": "c8 tap",
        "snap": "c8 tap",
        "format": "prettier --write . --loglevel warn",
        "benchmark": "node benchmark/index.js",
        "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
    },
    "prettier": {
        "semi": false,
        "printWidth": 80,
        "tabWidth": 2,
        "useTabs": false,
        "singleQuote": true,
        "jsxSingleQuote": false,
        "bracketSameLine": true,
        "arrowParens": "avoid",
        "endOfLine": "lf"
    },
    "devDependencies": {
        "@types/brace-expansion": "^1.1.0",
        "@types/node": "^18.11.9",
        "@types/tap": "^15.0.7",
        "c8": "^7.12.0",
        "eslint-config-prettier": "^8.6.0",
        "prettier": "^2.8.2",
        "tap": "^16.3.3",
        "ts-node": "^10.9.1",
        "typedoc": "^0.23.21",
        "typescript": "^4.9.3"
    },
    "tap": {
        "coverage": false,
        "node-arg": [
            "--no-warnings",
            "--loader",
            "ts-node/esm"
        ],
        "ts": false
    },
    "funding": {
        "url": "https://github.com/sponsors/isaacs"
    },
    "repository": {
        "type": "git",
        "url": "https://github.com/isaacs/node-mkdirp.git"
    },
    "license": "MIT",
    "engines": {
        "node": ">=10"
    }
}
#!/usr/bin/env node
export {};
//# sourceMappingURL=bin.d.ts.map{"version":3,"file":"bin.d.ts","sourceRoot":"","sources":["../../../src/bin.ts"],"names":[],"mappings":""}#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const package_json_1 = require("../package.json");
const usage = () => `
usage: mkdirp [DIR1,DIR2..] {OPTIONS}

  Create each supplied directory including any necessary parent directories
  that don't yet exist.

  If the directory already exists, do nothing.

OPTIONS are:

  -m       If a directory needs to be created, set the mode as an octal
  --mode=  permission string.

  -v --version   Print the mkdirp version number

  -h --help      Print this helpful banner

  -p --print     Print the first directories created for each path provided

  --manual       Use manual implementation, even if native is available
`;
const dirs = [];
const opts = {};
let doPrint = false;
let dashdash = false;
let manual = false;
for (const arg of process.argv.slice(2)) {
    if (dashdash)
        dirs.push(arg);
    else if (arg === '--')
        dashdash = true;
    else if (arg === '--manual')
        manual = true;
    else if (/^-h/.test(arg) || /^--help/.test(arg)) {
        console.log(usage());
        process.exit(0);
    }
    else if (arg === '-v' || arg === '--version') {
        console.log(package_json_1.version);
        process.exit(0);
    }
    else if (arg === '-p' || arg === '--print') {
        doPrint = true;
    }
    else if (/^-m/.test(arg) || /^--mode=/.test(arg)) {
        // these don't get covered in CI, but work locally
        // weird because the tests below show as passing in the output.
        /* c8 ignore start */
        const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8);
        if (isNaN(mode)) {
            console.error(`invalid mode argument: ${arg}\nMust be an octal number.`);
            process.exit(1);
        }
        /* c8 ignore stop */
        opts.mode = mode;
    }
    else
        dirs.push(arg);
}
const index_js_1 = require("./index.js");
const impl = manual ? index_js_1.mkdirp.manual : index_js_1.mkdirp;
if (dirs.length === 0) {
    console.error(usage());
}
// these don't get covered in CI, but work locally
/* c8 ignore start */
Promise.all(dirs.map(dir => impl(dir, opts)))
    .then(made => (doPrint ? made.forEach(m => m && console.log(m)) : null))
    .catch(er => {
    console.error(er.message);
    if (er.code)
        console.error('  code: ' + er.code);
    process.exit(1);
});
/* c8 ignore stop */
//# sourceMappingURL=bin.js.map{"version":3,"file":"bin.js","sourceRoot":"","sources":["../../../src/bin.ts"],"names":[],"mappings":";;;AAEA,kDAAyC;AAGzC,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC;;;;;;;;;;;;;;;;;;;;CAoBnB,CAAA;AAED,MAAM,IAAI,GAAa,EAAE,CAAA;AACzB,MAAM,IAAI,GAAkB,EAAE,CAAA;AAC9B,IAAI,OAAO,GAAY,KAAK,CAAA;AAC5B,IAAI,QAAQ,GAAG,KAAK,CAAA;AACpB,IAAI,MAAM,GAAG,KAAK,CAAA;AAClB,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IACvC,IAAI,QAAQ;QAAE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;SACvB,IAAI,GAAG,KAAK,IAAI;QAAE,QAAQ,GAAG,IAAI,CAAA;SACjC,IAAI,GAAG,KAAK,UAAU;QAAE,MAAM,GAAG,IAAI,CAAA;SACrC,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAC/C,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;QACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;KAChB;SAAM,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,WAAW,EAAE;QAC9C,OAAO,CAAC,GAAG,CAAC,sBAAO,CAAC,CAAA;QACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;KAChB;SAAM,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS,EAAE;QAC5C,OAAO,GAAG,IAAI,CAAA;KACf;SAAM,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAClD,kDAAkD;QAClD,+DAA+D;QAC/D,qBAAqB;QACrB,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;QAC1D,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE;YACf,OAAO,CAAC,KAAK,CAAC,0BAA0B,GAAG,4BAA4B,CAAC,CAAA;YACxE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;SAChB;QACD,oBAAoB;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;KACjB;;QAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;CACtB;AAED,yCAAmC;AACnC,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,iBAAM,CAAC,MAAM,CAAC,CAAC,CAAC,iBAAM,CAAA;AAC5C,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAA;CACvB;AAED,kDAAkD;AAClD,qBAAqB;AACrB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;KAC1C,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;KACvE,KAAK,CAAC,EAAE,CAAC,EAAE;IACV,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,CAAA;IACzB,IAAI,EAAE,CAAC,IAAI;QAAE,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,EAAE,CAAC,IAAI,CAAC,CAAA;IAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC,CAAC,CAAA;AACJ,oBAAoB","sourcesContent":["#!/usr/bin/env node\n\nimport { version } from '../package.json'\nimport { MkdirpOptions } from './opts-arg.js'\n\nconst usage = () => `\nusage: mkdirp [DIR1,DIR2..] {OPTIONS}\n\n  Create each supplied directory including any necessary parent directories\n  that don't yet exist.\n\n  If the directory already exists, do nothing.\n\nOPTIONS are:\n\n  -m       If a directory needs to be created, set the mode as an octal\n  --mode=  permission string.\n\n  -v --version   Print the mkdirp version number\n\n  -h --help      Print this helpful banner\n\n  -p --print     Print the first directories created for each path provided\n\n  --manual       Use manual implementation, even if native is available\n`\n\nconst dirs: string[] = []\nconst opts: MkdirpOptions = {}\nlet doPrint: boolean = false\nlet dashdash = false\nlet manual = false\nfor (const arg of process.argv.slice(2)) {\n  if (dashdash) dirs.push(arg)\n  else if (arg === '--') dashdash = true\n  else if (arg === '--manual') manual = true\n  else if (/^-h/.test(arg) || /^--help/.test(arg)) {\n    console.log(usage())\n    process.exit(0)\n  } else if (arg === '-v' || arg === '--version') {\n    console.log(version)\n    process.exit(0)\n  } else if (arg === '-p' || arg === '--print') {\n    doPrint = true\n  } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) {\n    // these don't get covered in CI, but work locally\n    // weird because the tests below show as passing in the output.\n    /* c8 ignore start */\n    const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8)\n    if (isNaN(mode)) {\n      console.error(`invalid mode argument: ${arg}\\nMust be an octal number.`)\n      process.exit(1)\n    }\n    /* c8 ignore stop */\n    opts.mode = mode\n  } else dirs.push(arg)\n}\n\nimport { mkdirp } from './index.js'\nconst impl = manual ? mkdirp.manual : mkdirp\nif (dirs.length === 0) {\n  console.error(usage())\n}\n\n// these don't get covered in CI, but work locally\n/* c8 ignore start */\nPromise.all(dirs.map(dir => impl(dir, opts)))\n  .then(made => (doPrint ? made.forEach(m => m && console.log(m)) : null))\n  .catch(er => {\n    console.error(er.message)\n    if (er.code) console.error('  code: ' + er.code)\n    process.exit(1)\n  })\n/* c8 ignore stop */\n"]}import { MkdirpOptionsResolved } from './opts-arg.js';
export declare const findMade: (opts: MkdirpOptionsResolved, parent: string, path?: string) => Promise;
export declare const findMadeSync: (opts: MkdirpOptionsResolved, parent: string, path?: string) => undefined | string;
//# sourceMappingURL=find-made.d.ts.map{"version":3,"file":"find-made.d.ts","sourceRoot":"","sources":["../../../src/find-made.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAA;AAErD,eAAO,MAAM,QAAQ,SACb,qBAAqB,UACnB,MAAM,SACP,MAAM,KACZ,QAAQ,SAAS,GAAG,MAAM,CAe5B,CAAA;AAED,eAAO,MAAM,YAAY,SACjB,qBAAqB,UACnB,MAAM,SACP,MAAM,KACZ,SAAS,GAAG,MAad,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findMadeSync = exports.findMade = void 0;
const path_1 = require("path");
const findMade = async (opts, parent, path) => {
    // we never want the 'made' return value to be a root directory
    if (path === parent) {
        return;
    }
    return opts.statAsync(parent).then(st => (st.isDirectory() ? path : undefined), // will fail later
    // will fail later
    er => {
        const fer = er;
        return fer && fer.code === 'ENOENT'
            ? (0, exports.findMade)(opts, (0, path_1.dirname)(parent), parent)
            : undefined;
    });
};
exports.findMade = findMade;
const findMadeSync = (opts, parent, path) => {
    if (path === parent) {
        return undefined;
    }
    try {
        return opts.statSync(parent).isDirectory() ? path : undefined;
    }
    catch (er) {
        const fer = er;
        return fer && fer.code === 'ENOENT'
            ? (0, exports.findMadeSync)(opts, (0, path_1.dirname)(parent), parent)
            : undefined;
    }
};
exports.findMadeSync = findMadeSync;
//# sourceMappingURL=find-made.js.map{"version":3,"file":"find-made.js","sourceRoot":"","sources":["../../../src/find-made.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAGvB,MAAM,QAAQ,GAAG,KAAK,EAC3B,IAA2B,EAC3B,MAAc,EACd,IAAa,EACgB,EAAE;IAC/B,+DAA+D;IAC/D,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAM;KACP;IAED,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,CAChC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,kBAAkB;IAC/D,AAD6C,kBAAkB;IAC/D,EAAE,CAAC,EAAE;QACH,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ;YACjC,CAAC,CAAC,IAAA,gBAAQ,EAAC,IAAI,EAAE,IAAA,cAAO,EAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YACzC,CAAC,CAAC,SAAS,CAAA;IACf,CAAC,CACF,CAAA;AACH,CAAC,CAAA;AAnBY,QAAA,QAAQ,YAmBpB;AAEM,MAAM,YAAY,GAAG,CAC1B,IAA2B,EAC3B,MAAc,EACd,IAAa,EACO,EAAE;IACtB,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAO,SAAS,CAAA;KACjB;IAED,IAAI;QACF,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;KAC9D;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ;YACjC,CAAC,CAAC,IAAA,oBAAY,EAAC,IAAI,EAAE,IAAA,cAAO,EAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YAC7C,CAAC,CAAC,SAAS,CAAA;KACd;AACH,CAAC,CAAA;AAjBY,QAAA,YAAY,gBAiBxB","sourcesContent":["import { dirname } from 'path'\nimport { MkdirpOptionsResolved } from './opts-arg.js'\n\nexport const findMade = async (\n  opts: MkdirpOptionsResolved,\n  parent: string,\n  path?: string\n): Promise => {\n  // we never want the 'made' return value to be a root directory\n  if (path === parent) {\n    return\n  }\n\n  return opts.statAsync(parent).then(\n    st => (st.isDirectory() ? path : undefined), // will fail later\n    er => {\n      const fer = er as NodeJS.ErrnoException\n      return fer && fer.code === 'ENOENT'\n        ? findMade(opts, dirname(parent), parent)\n        : undefined\n    }\n  )\n}\n\nexport const findMadeSync = (\n  opts: MkdirpOptionsResolved,\n  parent: string,\n  path?: string\n): undefined | string => {\n  if (path === parent) {\n    return undefined\n  }\n\n  try {\n    return opts.statSync(parent).isDirectory() ? path : undefined\n  } catch (er) {\n    const fer = er as NodeJS.ErrnoException\n    return fer && fer.code === 'ENOENT'\n      ? findMadeSync(opts, dirname(parent), parent)\n      : undefined\n  }\n}\n"]}import { MkdirpOptions } from './opts-arg.js';
export { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js';
export { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js';
export { useNative, useNativeSync } from './use-native.js';
export declare const mkdirpSync: (path: string, opts?: MkdirpOptions) => string | void;
export declare const sync: (path: string, opts?: MkdirpOptions) => string | void;
export declare const manual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & {
    sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
};
export declare const manualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
export declare const native: ((path: string, options?: MkdirpOptions | undefined) => Promise) & {
    sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
};
export declare const nativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
export declare const mkdirp: ((path: string, opts?: MkdirpOptions) => Promise) & {
    mkdirpSync: (path: string, opts?: MkdirpOptions) => string | void;
    mkdirpNative: ((path: string, options?: MkdirpOptions | undefined) => Promise) & {
        sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
    };
    mkdirpNativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
    mkdirpManual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & {
        sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
    };
    mkdirpManualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
    sync: (path: string, opts?: MkdirpOptions) => string | void;
    native: ((path: string, options?: MkdirpOptions | undefined) => Promise) & {
        sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
    };
    nativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
    manual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & {
        sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
    };
    manualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
    useNative: ((opts?: MkdirpOptions | undefined) => boolean) & {
        sync: (opts?: MkdirpOptions | undefined) => boolean;
    };
    useNativeSync: (opts?: MkdirpOptions | undefined) => boolean;
};
//# sourceMappingURL=index.d.ts.map{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAItD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAG1D,eAAO,MAAM,UAAU,SAAU,MAAM,SAAS,aAAa,kBAM5D,CAAA;AAED,eAAO,MAAM,IAAI,SARgB,MAAM,SAAS,aAAa,kBAQ/B,CAAA;AAC9B,eAAO,MAAM,MAAM;;CAAe,CAAA;AAClC,eAAO,MAAM,UAAU,oHAAmB,CAAA;AAC1C,eAAO,MAAM,MAAM;;CAAe,CAAA;AAClC,eAAO,MAAM,UAAU,kFAAmB,CAAA;AAC1C,eAAO,MAAM,MAAM,UACJ,MAAM,SAAS,aAAa;uBAdV,MAAM,SAAS,aAAa;;;;;;;;;iBAA5B,MAAM,SAAS,aAAa;;;;;;;;;;;;;CAoC5D,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mkdirp = exports.nativeSync = exports.native = exports.manualSync = exports.manual = exports.sync = exports.mkdirpSync = exports.useNativeSync = exports.useNative = exports.mkdirpNativeSync = exports.mkdirpNative = exports.mkdirpManualSync = exports.mkdirpManual = void 0;
const mkdirp_manual_js_1 = require("./mkdirp-manual.js");
const mkdirp_native_js_1 = require("./mkdirp-native.js");
const opts_arg_js_1 = require("./opts-arg.js");
const path_arg_js_1 = require("./path-arg.js");
const use_native_js_1 = require("./use-native.js");
/* c8 ignore start */
var mkdirp_manual_js_2 = require("./mkdirp-manual.js");
Object.defineProperty(exports, "mkdirpManual", { enumerable: true, get: function () { return mkdirp_manual_js_2.mkdirpManual; } });
Object.defineProperty(exports, "mkdirpManualSync", { enumerable: true, get: function () { return mkdirp_manual_js_2.mkdirpManualSync; } });
var mkdirp_native_js_2 = require("./mkdirp-native.js");
Object.defineProperty(exports, "mkdirpNative", { enumerable: true, get: function () { return mkdirp_native_js_2.mkdirpNative; } });
Object.defineProperty(exports, "mkdirpNativeSync", { enumerable: true, get: function () { return mkdirp_native_js_2.mkdirpNativeSync; } });
var use_native_js_2 = require("./use-native.js");
Object.defineProperty(exports, "useNative", { enumerable: true, get: function () { return use_native_js_2.useNative; } });
Object.defineProperty(exports, "useNativeSync", { enumerable: true, get: function () { return use_native_js_2.useNativeSync; } });
/* c8 ignore stop */
const mkdirpSync = (path, opts) => {
    path = (0, path_arg_js_1.pathArg)(path);
    const resolved = (0, opts_arg_js_1.optsArg)(opts);
    return (0, use_native_js_1.useNativeSync)(resolved)
        ? (0, mkdirp_native_js_1.mkdirpNativeSync)(path, resolved)
        : (0, mkdirp_manual_js_1.mkdirpManualSync)(path, resolved);
};
exports.mkdirpSync = mkdirpSync;
exports.sync = exports.mkdirpSync;
exports.manual = mkdirp_manual_js_1.mkdirpManual;
exports.manualSync = mkdirp_manual_js_1.mkdirpManualSync;
exports.native = mkdirp_native_js_1.mkdirpNative;
exports.nativeSync = mkdirp_native_js_1.mkdirpNativeSync;
exports.mkdirp = Object.assign(async (path, opts) => {
    path = (0, path_arg_js_1.pathArg)(path);
    const resolved = (0, opts_arg_js_1.optsArg)(opts);
    return (0, use_native_js_1.useNative)(resolved)
        ? (0, mkdirp_native_js_1.mkdirpNative)(path, resolved)
        : (0, mkdirp_manual_js_1.mkdirpManual)(path, resolved);
}, {
    mkdirpSync: exports.mkdirpSync,
    mkdirpNative: mkdirp_native_js_1.mkdirpNative,
    mkdirpNativeSync: mkdirp_native_js_1.mkdirpNativeSync,
    mkdirpManual: mkdirp_manual_js_1.mkdirpManual,
    mkdirpManualSync: mkdirp_manual_js_1.mkdirpManualSync,
    sync: exports.mkdirpSync,
    native: mkdirp_native_js_1.mkdirpNative,
    nativeSync: mkdirp_native_js_1.mkdirpNativeSync,
    manual: mkdirp_manual_js_1.mkdirpManual,
    manualSync: mkdirp_manual_js_1.mkdirpManualSync,
    useNative: use_native_js_1.useNative,
    useNativeSync: use_native_js_1.useNativeSync,
});
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":";;;AAAA,yDAAmE;AACnE,yDAAmE;AACnE,+CAAsD;AACtD,+CAAuC;AACvC,mDAA0D;AAC1D,qBAAqB;AACrB,uDAAmE;AAA1D,gHAAA,YAAY,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AACvC,uDAAmE;AAA1D,gHAAA,YAAY,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AACvC,iDAA0D;AAAjD,0GAAA,SAAS,OAAA;AAAE,8GAAA,aAAa,OAAA;AACjC,oBAAoB;AAEb,MAAM,UAAU,GAAG,CAAC,IAAY,EAAE,IAAoB,EAAE,EAAE;IAC/D,IAAI,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAA;IACpB,MAAM,QAAQ,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAA;IAC9B,OAAO,IAAA,6BAAa,EAAC,QAAQ,CAAC;QAC5B,CAAC,CAAC,IAAA,mCAAgB,EAAC,IAAI,EAAE,QAAQ,CAAC;QAClC,CAAC,CAAC,IAAA,mCAAgB,EAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AACtC,CAAC,CAAA;AANY,QAAA,UAAU,cAMtB;AAEY,QAAA,IAAI,GAAG,kBAAU,CAAA;AACjB,QAAA,MAAM,GAAG,+BAAY,CAAA;AACrB,QAAA,UAAU,GAAG,mCAAgB,CAAA;AAC7B,QAAA,MAAM,GAAG,+BAAY,CAAA;AACrB,QAAA,UAAU,GAAG,mCAAgB,CAAA;AAC7B,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CACjC,KAAK,EAAE,IAAY,EAAE,IAAoB,EAAE,EAAE;IAC3C,IAAI,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAA;IACpB,MAAM,QAAQ,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAA;IAC9B,OAAO,IAAA,yBAAS,EAAC,QAAQ,CAAC;QACxB,CAAC,CAAC,IAAA,+BAAY,EAAC,IAAI,EAAE,QAAQ,CAAC;QAC9B,CAAC,CAAC,IAAA,+BAAY,EAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AAClC,CAAC,EACD;IACE,UAAU,EAAV,kBAAU;IACV,YAAY,EAAZ,+BAAY;IACZ,gBAAgB,EAAhB,mCAAgB;IAChB,YAAY,EAAZ,+BAAY;IACZ,gBAAgB,EAAhB,mCAAgB;IAEhB,IAAI,EAAE,kBAAU;IAChB,MAAM,EAAE,+BAAY;IACpB,UAAU,EAAE,mCAAgB;IAC5B,MAAM,EAAE,+BAAY;IACpB,UAAU,EAAE,mCAAgB;IAC5B,SAAS,EAAT,yBAAS;IACT,aAAa,EAAb,6BAAa;CACd,CACF,CAAA","sourcesContent":["import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nimport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\nimport { pathArg } from './path-arg.js'\nimport { useNative, useNativeSync } from './use-native.js'\n/* c8 ignore start */\nexport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nexport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'\nexport { useNative, useNativeSync } from './use-native.js'\n/* c8 ignore stop */\n\nexport const mkdirpSync = (path: string, opts?: MkdirpOptions) => {\n  path = pathArg(path)\n  const resolved = optsArg(opts)\n  return useNativeSync(resolved)\n    ? mkdirpNativeSync(path, resolved)\n    : mkdirpManualSync(path, resolved)\n}\n\nexport const sync = mkdirpSync\nexport const manual = mkdirpManual\nexport const manualSync = mkdirpManualSync\nexport const native = mkdirpNative\nexport const nativeSync = mkdirpNativeSync\nexport const mkdirp = Object.assign(\n  async (path: string, opts?: MkdirpOptions) => {\n    path = pathArg(path)\n    const resolved = optsArg(opts)\n    return useNative(resolved)\n      ? mkdirpNative(path, resolved)\n      : mkdirpManual(path, resolved)\n  },\n  {\n    mkdirpSync,\n    mkdirpNative,\n    mkdirpNativeSync,\n    mkdirpManual,\n    mkdirpManualSync,\n\n    sync: mkdirpSync,\n    native: mkdirpNative,\n    nativeSync: mkdirpNativeSync,\n    manual: mkdirpManual,\n    manualSync: mkdirpManualSync,\n    useNative,\n    useNativeSync,\n  }\n)\n"]}import { MkdirpOptions } from './opts-arg.js';
export declare const mkdirpManualSync: (path: string, options?: MkdirpOptions, made?: string | undefined | void) => string | undefined | void;
export declare const mkdirpManual: ((path: string, options?: MkdirpOptions, made?: string | undefined | void) => Promise) & {
    sync: (path: string, options?: MkdirpOptions, made?: string | undefined | void) => string | undefined | void;
};
//# sourceMappingURL=mkdirp-manual.d.ts.map{"version":3,"file":"mkdirp-manual.d.ts","sourceRoot":"","sources":["../../../src/mkdirp-manual.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAEtD,eAAO,MAAM,gBAAgB,SACrB,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,MAAM,GAAG,SAAS,GAAG,IAmCvB,CAAA;AAED,eAAO,MAAM,YAAY,UAEf,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;iBA7C/B,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,MAAM,GAAG,SAAS,GAAG,IAAI;CAqF3B,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mkdirpManual = exports.mkdirpManualSync = void 0;
const path_1 = require("path");
const opts_arg_js_1 = require("./opts-arg.js");
const mkdirpManualSync = (path, options, made) => {
    const parent = (0, path_1.dirname)(path);
    const opts = { ...(0, opts_arg_js_1.optsArg)(options), recursive: false };
    if (parent === path) {
        try {
            return opts.mkdirSync(path, opts);
        }
        catch (er) {
            // swallowed by recursive implementation on posix systems
            // any other error is a failure
            const fer = er;
            if (fer && fer.code !== 'EISDIR') {
                throw er;
            }
            return;
        }
    }
    try {
        opts.mkdirSync(path, opts);
        return made || path;
    }
    catch (er) {
        const fer = er;
        if (fer && fer.code === 'ENOENT') {
            return (0, exports.mkdirpManualSync)(path, opts, (0, exports.mkdirpManualSync)(parent, opts, made));
        }
        if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') {
            throw er;
        }
        try {
            if (!opts.statSync(path).isDirectory())
                throw er;
        }
        catch (_) {
            throw er;
        }
    }
};
exports.mkdirpManualSync = mkdirpManualSync;
exports.mkdirpManual = Object.assign(async (path, options, made) => {
    const opts = (0, opts_arg_js_1.optsArg)(options);
    opts.recursive = false;
    const parent = (0, path_1.dirname)(path);
    if (parent === path) {
        return opts.mkdirAsync(path, opts).catch(er => {
            // swallowed by recursive implementation on posix systems
            // any other error is a failure
            const fer = er;
            if (fer && fer.code !== 'EISDIR') {
                throw er;
            }
        });
    }
    return opts.mkdirAsync(path, opts).then(() => made || path, async (er) => {
        const fer = er;
        if (fer && fer.code === 'ENOENT') {
            return (0, exports.mkdirpManual)(parent, opts).then((made) => (0, exports.mkdirpManual)(path, opts, made));
        }
        if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') {
            throw er;
        }
        return opts.statAsync(path).then(st => {
            if (st.isDirectory()) {
                return made;
            }
            else {
                throw er;
            }
        }, () => {
            throw er;
        });
    });
}, { sync: exports.mkdirpManualSync });
//# sourceMappingURL=mkdirp-manual.js.map{"version":3,"file":"mkdirp-manual.js","sourceRoot":"","sources":["../../../src/mkdirp-manual.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAC9B,+CAAsD;AAE/C,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAuB,EACvB,IAAgC,EACL,EAAE;IAC7B,MAAM,MAAM,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,IAAI,GAAG,EAAE,GAAG,IAAA,qBAAO,EAAC,OAAO,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,CAAA;IAEtD,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,IAAI;YACF,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAClC;QAAC,OAAO,EAAE,EAAE;YACX,yDAAyD;YACzD,+BAA+B;YAC/B,MAAM,GAAG,GAAG,EAA2B,CAAA;YACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAChC,MAAM,EAAE,CAAA;aACT;YACD,OAAM;SACP;KACF;IAED,IAAI;QACF,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAO,IAAI,IAAI,IAAI,CAAA;KACpB;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,IAAA,wBAAgB,EAAC,IAAI,EAAE,IAAI,EAAE,IAAA,wBAAgB,EAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;SAC1E;QACD,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE;YAC/D,MAAM,EAAE,CAAA;SACT;QACD,IAAI;YACF,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE;gBAAE,MAAM,EAAE,CAAA;SACjD;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,EAAE,CAAA;SACT;KACF;AACH,CAAC,CAAA;AAvCY,QAAA,gBAAgB,oBAuC5B;AAEY,QAAA,YAAY,GAAG,MAAM,CAAC,MAAM,CACvC,KAAK,EACH,IAAY,EACZ,OAAuB,EACvB,IAAgC,EACI,EAAE;IACtC,MAAM,IAAI,GAAG,IAAA,qBAAO,EAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAA;IACtB,MAAM,MAAM,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE;YAC5C,yDAAyD;YACzD,+BAA+B;YAC/B,MAAM,GAAG,GAAG,EAA2B,CAAA;YACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAChC,MAAM,EAAE,CAAA;aACT;QACH,CAAC,CAAC,CAAA;KACH;IAED,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CACrC,GAAG,EAAE,CAAC,IAAI,IAAI,IAAI,EAClB,KAAK,EAAC,EAAE,EAAC,EAAE;QACT,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,IAAA,oBAAY,EAAC,MAAM,EAAE,IAAI,CAAC,CAAC,IAAI,CACpC,CAAC,IAAgC,EAAE,EAAE,CAAC,IAAA,oBAAY,EAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CACrE,CAAA;SACF;QACD,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE;YACxD,MAAM,EAAE,CAAA;SACT;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,CAC9B,EAAE,CAAC,EAAE;YACH,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE;gBACpB,OAAO,IAAI,CAAA;aACZ;iBAAM;gBACL,MAAM,EAAE,CAAA;aACT;QACH,CAAC,EACD,GAAG,EAAE;YACH,MAAM,EAAE,CAAA;QACV,CAAC,CACF,CAAA;IACH,CAAC,CACF,CAAA;AACH,CAAC,EACD,EAAE,IAAI,EAAE,wBAAgB,EAAE,CAC3B,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nexport const mkdirpManualSync = (\n  path: string,\n  options?: MkdirpOptions,\n  made?: string | undefined | void\n): string | undefined | void => {\n  const parent = dirname(path)\n  const opts = { ...optsArg(options), recursive: false }\n\n  if (parent === path) {\n    try {\n      return opts.mkdirSync(path, opts)\n    } catch (er) {\n      // swallowed by recursive implementation on posix systems\n      // any other error is a failure\n      const fer = er as NodeJS.ErrnoException\n      if (fer && fer.code !== 'EISDIR') {\n        throw er\n      }\n      return\n    }\n  }\n\n  try {\n    opts.mkdirSync(path, opts)\n    return made || path\n  } catch (er) {\n    const fer = er as NodeJS.ErrnoException\n    if (fer && fer.code === 'ENOENT') {\n      return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made))\n    }\n    if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') {\n      throw er\n    }\n    try {\n      if (!opts.statSync(path).isDirectory()) throw er\n    } catch (_) {\n      throw er\n    }\n  }\n}\n\nexport const mkdirpManual = Object.assign(\n  async (\n    path: string,\n    options?: MkdirpOptions,\n    made?: string | undefined | void\n  ): Promise => {\n    const opts = optsArg(options)\n    opts.recursive = false\n    const parent = dirname(path)\n    if (parent === path) {\n      return opts.mkdirAsync(path, opts).catch(er => {\n        // swallowed by recursive implementation on posix systems\n        // any other error is a failure\n        const fer = er as NodeJS.ErrnoException\n        if (fer && fer.code !== 'EISDIR') {\n          throw er\n        }\n      })\n    }\n\n    return opts.mkdirAsync(path, opts).then(\n      () => made || path,\n      async er => {\n        const fer = er as NodeJS.ErrnoException\n        if (fer && fer.code === 'ENOENT') {\n          return mkdirpManual(parent, opts).then(\n            (made?: string | undefined | void) => mkdirpManual(path, opts, made)\n          )\n        }\n        if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') {\n          throw er\n        }\n        return opts.statAsync(path).then(\n          st => {\n            if (st.isDirectory()) {\n              return made\n            } else {\n              throw er\n            }\n          },\n          () => {\n            throw er\n          }\n        )\n      }\n    )\n  },\n  { sync: mkdirpManualSync }\n)\n"]}import { MkdirpOptions } from './opts-arg.js';
export declare const mkdirpNativeSync: (path: string, options?: MkdirpOptions) => string | void | undefined;
export declare const mkdirpNative: ((path: string, options?: MkdirpOptions) => Promise) & {
    sync: (path: string, options?: MkdirpOptions) => string | void | undefined;
};
//# sourceMappingURL=mkdirp-native.d.ts.map{"version":3,"file":"mkdirp-native.d.ts","sourceRoot":"","sources":["../../../src/mkdirp-native.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAEtD,eAAO,MAAM,gBAAgB,SACrB,MAAM,YACF,aAAa,KACtB,MAAM,GAAG,IAAI,GAAG,SAoBlB,CAAA;AAED,eAAO,MAAM,YAAY,UAEf,MAAM,YACF,aAAa,KACtB,QAAQ,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;iBA5B/B,MAAM,YACF,aAAa,KACtB,MAAM,GAAG,IAAI,GAAG,SAAS;CAgD3B,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mkdirpNative = exports.mkdirpNativeSync = void 0;
const path_1 = require("path");
const find_made_js_1 = require("./find-made.js");
const mkdirp_manual_js_1 = require("./mkdirp-manual.js");
const opts_arg_js_1 = require("./opts-arg.js");
const mkdirpNativeSync = (path, options) => {
    const opts = (0, opts_arg_js_1.optsArg)(options);
    opts.recursive = true;
    const parent = (0, path_1.dirname)(path);
    if (parent === path) {
        return opts.mkdirSync(path, opts);
    }
    const made = (0, find_made_js_1.findMadeSync)(opts, path);
    try {
        opts.mkdirSync(path, opts);
        return made;
    }
    catch (er) {
        const fer = er;
        if (fer && fer.code === 'ENOENT') {
            return (0, mkdirp_manual_js_1.mkdirpManualSync)(path, opts);
        }
        else {
            throw er;
        }
    }
};
exports.mkdirpNativeSync = mkdirpNativeSync;
exports.mkdirpNative = Object.assign(async (path, options) => {
    const opts = { ...(0, opts_arg_js_1.optsArg)(options), recursive: true };
    const parent = (0, path_1.dirname)(path);
    if (parent === path) {
        return await opts.mkdirAsync(path, opts);
    }
    return (0, find_made_js_1.findMade)(opts, path).then((made) => opts
        .mkdirAsync(path, opts)
        .then(m => made || m)
        .catch(er => {
        const fer = er;
        if (fer && fer.code === 'ENOENT') {
            return (0, mkdirp_manual_js_1.mkdirpManual)(path, opts);
        }
        else {
            throw er;
        }
    }));
}, { sync: exports.mkdirpNativeSync });
//# sourceMappingURL=mkdirp-native.js.map{"version":3,"file":"mkdirp-native.js","sourceRoot":"","sources":["../../../src/mkdirp-native.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAC9B,iDAAuD;AACvD,yDAAmE;AACnE,+CAAsD;AAE/C,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAuB,EACI,EAAE;IAC7B,MAAM,IAAI,GAAG,IAAA,qBAAO,EAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;IACrB,MAAM,MAAM,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;KAClC;IAED,MAAM,IAAI,GAAG,IAAA,2BAAY,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACrC,IAAI;QACF,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAO,IAAI,CAAA;KACZ;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,IAAA,mCAAgB,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SACpC;aAAM;YACL,MAAM,EAAE,CAAA;SACT;KACF;AACH,CAAC,CAAA;AAvBY,QAAA,gBAAgB,oBAuB5B;AAEY,QAAA,YAAY,GAAG,MAAM,CAAC,MAAM,CACvC,KAAK,EACH,IAAY,EACZ,OAAuB,EACa,EAAE;IACtC,MAAM,IAAI,GAAG,EAAE,GAAG,IAAA,qBAAO,EAAC,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAA;IACrD,MAAM,MAAM,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;KACzC;IAED,OAAO,IAAA,uBAAQ,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAyB,EAAE,EAAE,CAC7D,IAAI;SACD,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;SACtB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC;SACpB,KAAK,CAAC,EAAE,CAAC,EAAE;QACV,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAChC;aAAM;YACL,MAAM,EAAE,CAAA;SACT;IACH,CAAC,CAAC,CACL,CAAA;AACH,CAAC,EACD,EAAE,IAAI,EAAE,wBAAgB,EAAE,CAC3B,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { findMade, findMadeSync } from './find-made.js'\nimport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nexport const mkdirpNativeSync = (\n  path: string,\n  options?: MkdirpOptions\n): string | void | undefined => {\n  const opts = optsArg(options)\n  opts.recursive = true\n  const parent = dirname(path)\n  if (parent === path) {\n    return opts.mkdirSync(path, opts)\n  }\n\n  const made = findMadeSync(opts, path)\n  try {\n    opts.mkdirSync(path, opts)\n    return made\n  } catch (er) {\n    const fer = er as NodeJS.ErrnoException\n    if (fer && fer.code === 'ENOENT') {\n      return mkdirpManualSync(path, opts)\n    } else {\n      throw er\n    }\n  }\n}\n\nexport const mkdirpNative = Object.assign(\n  async (\n    path: string,\n    options?: MkdirpOptions\n  ): Promise => {\n    const opts = { ...optsArg(options), recursive: true }\n    const parent = dirname(path)\n    if (parent === path) {\n      return await opts.mkdirAsync(path, opts)\n    }\n\n    return findMade(opts, path).then((made?: string | undefined) =>\n      opts\n        .mkdirAsync(path, opts)\n        .then(m => made || m)\n        .catch(er => {\n          const fer = er as NodeJS.ErrnoException\n          if (fer && fer.code === 'ENOENT') {\n            return mkdirpManual(path, opts)\n          } else {\n            throw er\n          }\n        })\n    )\n  },\n  { sync: mkdirpNativeSync }\n)\n"]}/// 
/// 
import { MakeDirectoryOptions, Stats } from 'fs';
export interface FsProvider {
    stat?: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any;
    mkdir?: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any;
    statSync?: (path: string) => Stats;
    mkdirSync?: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }) => string | undefined;
}
interface Options extends FsProvider {
    mode?: number | string;
    fs?: FsProvider;
    mkdirAsync?: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }) => Promise;
    statAsync?: (path: string) => Promise;
}
export type MkdirpOptions = Options | number | string;
export interface MkdirpOptionsResolved {
    mode: number;
    fs: FsProvider;
    mkdirAsync: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }) => Promise;
    statAsync: (path: string) => Promise;
    stat: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any;
    mkdir: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any;
    statSync: (path: string) => Stats;
    mkdirSync: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }) => string | undefined;
    recursive?: boolean;
}
export declare const optsArg: (opts?: MkdirpOptions) => MkdirpOptionsResolved;
export {};
//# sourceMappingURL=opts-arg.d.ts.map{"version":3,"file":"opts-arg.d.ts","sourceRoot":"","sources":["../../../src/opts-arg.ts"],"names":[],"mappings":";;AAAA,OAAO,EACL,oBAAoB,EAIpB,KAAK,EAEN,MAAM,IAAI,CAAA;AAEX,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,EAAE,CACL,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK,GAAG,KAC/D,GAAG,CAAA;IACR,KAAK,CAAC,EAAE,CACN,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,EACpD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,KAChE,GAAG,CAAA;IACR,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IAClC,SAAS,CAAC,EAAE,CACV,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,MAAM,GAAG,SAAS,CAAA;CACxB;AAED,UAAU,OAAQ,SAAQ,UAAU;IAClC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IACtB,EAAE,CAAC,EAAE,UAAU,CAAA;IACf,UAAU,CAAC,EAAE,CACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAA;CAC7C;AAED,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAA;AAErD,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,EAAE,EAAE,UAAU,CAAA;IACd,UAAU,EAAE,CACV,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChC,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAA;IAC3C,IAAI,EAAE,CACJ,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK,GAAG,KAC/D,GAAG,CAAA;IACR,KAAK,EAAE,CACL,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,EACpD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,KAChE,GAAG,CAAA;IACR,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IACjC,SAAS,EAAE,CACT,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,MAAM,GAAG,SAAS,CAAA;IACvB,SAAS,CAAC,EAAE,OAAO,CAAA;CACpB;AAED,eAAO,MAAM,OAAO,UAAW,aAAa,KAAG,qBA2C9C,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.optsArg = void 0;
const fs_1 = require("fs");
const optsArg = (opts) => {
    if (!opts) {
        opts = { mode: 0o777 };
    }
    else if (typeof opts === 'object') {
        opts = { mode: 0o777, ...opts };
    }
    else if (typeof opts === 'number') {
        opts = { mode: opts };
    }
    else if (typeof opts === 'string') {
        opts = { mode: parseInt(opts, 8) };
    }
    else {
        throw new TypeError('invalid options argument');
    }
    const resolved = opts;
    const optsFs = opts.fs || {};
    opts.mkdir = opts.mkdir || optsFs.mkdir || fs_1.mkdir;
    opts.mkdirAsync = opts.mkdirAsync
        ? opts.mkdirAsync
        : async (path, options) => {
            return new Promise((res, rej) => resolved.mkdir(path, options, (er, made) => er ? rej(er) : res(made)));
        };
    opts.stat = opts.stat || optsFs.stat || fs_1.stat;
    opts.statAsync = opts.statAsync
        ? opts.statAsync
        : async (path) => new Promise((res, rej) => resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats))));
    opts.statSync = opts.statSync || optsFs.statSync || fs_1.statSync;
    opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || fs_1.mkdirSync;
    return resolved;
};
exports.optsArg = optsArg;
//# sourceMappingURL=opts-arg.js.map{"version":3,"file":"opts-arg.js","sourceRoot":"","sources":["../../../src/opts-arg.ts"],"names":[],"mappings":";;;AAAA,2BAOW;AAwDJ,MAAM,OAAO,GAAG,CAAC,IAAoB,EAAyB,EAAE;IACrE,IAAI,CAAC,IAAI,EAAE;QACT,IAAI,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;KACvB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,CAAA;KAChC;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;KACtB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,CAAA;KACnC;SAAM;QACL,MAAM,IAAI,SAAS,CAAC,0BAA0B,CAAC,CAAA;KAChD;IAED,MAAM,QAAQ,GAAG,IAA6B,CAAA;IAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,EAAE,IAAI,EAAE,CAAA;IAE5B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,IAAI,UAAK,CAAA;IAEhD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU;QAC/B,CAAC,CAAC,IAAI,CAAC,UAAU;QACjB,CAAC,CAAC,KAAK,EACH,IAAY,EACZ,OAAuD,EAC1B,EAAE;YAC/B,OAAO,IAAI,OAAO,CAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAClD,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CACzC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CACzB,CACF,CAAA;QACH,CAAC,CAAA;IAEL,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,SAAI,CAAA;IAC5C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS;QAC7B,CAAC,CAAC,IAAI,CAAC,SAAS;QAChB,CAAC,CAAC,KAAK,EAAE,IAAY,EAAE,EAAE,CACrB,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CACnE,CAAA;IAEP,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,MAAM,CAAC,QAAQ,IAAI,aAAQ,CAAA;IAC5D,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC,SAAS,IAAI,cAAS,CAAA;IAEhE,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA;AA3CY,QAAA,OAAO,WA2CnB","sourcesContent":["import {\n  MakeDirectoryOptions,\n  mkdir,\n  mkdirSync,\n  stat,\n  Stats,\n  statSync,\n} from 'fs'\n\nexport interface FsProvider {\n  stat?: (\n    path: string,\n    callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any\n  ) => any\n  mkdir?: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean },\n    callback: (err: NodeJS.ErrnoException | null, made?: string) => any\n  ) => any\n  statSync?: (path: string) => Stats\n  mkdirSync?: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean }\n  ) => string | undefined\n}\n\ninterface Options extends FsProvider {\n  mode?: number | string\n  fs?: FsProvider\n  mkdirAsync?: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean }\n  ) => Promise\n  statAsync?: (path: string) => Promise\n}\n\nexport type MkdirpOptions = Options | number | string\n\nexport interface MkdirpOptionsResolved {\n  mode: number\n  fs: FsProvider\n  mkdirAsync: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean }\n  ) => Promise\n  statAsync: (path: string) => Promise\n  stat: (\n    path: string,\n    callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any\n  ) => any\n  mkdir: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean },\n    callback: (err: NodeJS.ErrnoException | null, made?: string) => any\n  ) => any\n  statSync: (path: string) => Stats\n  mkdirSync: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean }\n  ) => string | undefined\n  recursive?: boolean\n}\n\nexport const optsArg = (opts?: MkdirpOptions): MkdirpOptionsResolved => {\n  if (!opts) {\n    opts = { mode: 0o777 }\n  } else if (typeof opts === 'object') {\n    opts = { mode: 0o777, ...opts }\n  } else if (typeof opts === 'number') {\n    opts = { mode: opts }\n  } else if (typeof opts === 'string') {\n    opts = { mode: parseInt(opts, 8) }\n  } else {\n    throw new TypeError('invalid options argument')\n  }\n\n  const resolved = opts as MkdirpOptionsResolved\n  const optsFs = opts.fs || {}\n\n  opts.mkdir = opts.mkdir || optsFs.mkdir || mkdir\n\n  opts.mkdirAsync = opts.mkdirAsync\n    ? opts.mkdirAsync\n    : async (\n        path: string,\n        options: MakeDirectoryOptions & { recursive?: boolean }\n      ): Promise => {\n        return new Promise((res, rej) =>\n          resolved.mkdir(path, options, (er, made) =>\n            er ? rej(er) : res(made)\n          )\n        )\n      }\n\n  opts.stat = opts.stat || optsFs.stat || stat\n  opts.statAsync = opts.statAsync\n    ? opts.statAsync\n    : async (path: string) =>\n        new Promise((res, rej) =>\n          resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats)))\n        )\n\n  opts.statSync = opts.statSync || optsFs.statSync || statSync\n  opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || mkdirSync\n\n  return resolved\n}\n"]}export declare const pathArg: (path: string) => string;
//# sourceMappingURL=path-arg.d.ts.map{"version":3,"file":"path-arg.d.ts","sourceRoot":"","sources":["../../../src/path-arg.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,SAAU,MAAM,WAyBnC,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pathArg = void 0;
const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform;
const path_1 = require("path");
const pathArg = (path) => {
    if (/\0/.test(path)) {
        // simulate same failure that node raises
        throw Object.assign(new TypeError('path must be a string without null bytes'), {
            path,
            code: 'ERR_INVALID_ARG_VALUE',
        });
    }
    path = (0, path_1.resolve)(path);
    if (platform === 'win32') {
        const badWinChars = /[*|"<>?:]/;
        const { root } = (0, path_1.parse)(path);
        if (badWinChars.test(path.substring(root.length))) {
            throw Object.assign(new Error('Illegal characters in path.'), {
                path,
                code: 'EINVAL',
            });
        }
    }
    return path;
};
exports.pathArg = pathArg;
//# sourceMappingURL=path-arg.js.map{"version":3,"file":"path-arg.js","sourceRoot":"","sources":["../../../src/path-arg.ts"],"names":[],"mappings":";;;AAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,2BAA2B,IAAI,OAAO,CAAC,QAAQ,CAAA;AAC5E,+BAAqC;AAC9B,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,EAAE;IACtC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QACnB,yCAAyC;QACzC,MAAM,MAAM,CAAC,MAAM,CACjB,IAAI,SAAS,CAAC,0CAA0C,CAAC,EACzD;YACE,IAAI;YACJ,IAAI,EAAE,uBAAuB;SAC9B,CACF,CAAA;KACF;IAED,IAAI,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IACpB,IAAI,QAAQ,KAAK,OAAO,EAAE;QACxB,MAAM,WAAW,GAAG,WAAW,CAAA;QAC/B,MAAM,EAAE,IAAI,EAAE,GAAG,IAAA,YAAK,EAAC,IAAI,CAAC,CAAA;QAC5B,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE;YACjD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,EAAE;gBAC5D,IAAI;gBACJ,IAAI,EAAE,QAAQ;aACf,CAAC,CAAA;SACH;KACF;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAzBY,QAAA,OAAO,WAyBnB","sourcesContent":["const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform\nimport { parse, resolve } from 'path'\nexport const pathArg = (path: string) => {\n  if (/\\0/.test(path)) {\n    // simulate same failure that node raises\n    throw Object.assign(\n      new TypeError('path must be a string without null bytes'),\n      {\n        path,\n        code: 'ERR_INVALID_ARG_VALUE',\n      }\n    )\n  }\n\n  path = resolve(path)\n  if (platform === 'win32') {\n    const badWinChars = /[*|\"<>?:]/\n    const { root } = parse(path)\n    if (badWinChars.test(path.substring(root.length))) {\n      throw Object.assign(new Error('Illegal characters in path.'), {\n        path,\n        code: 'EINVAL',\n      })\n    }\n  }\n\n  return path\n}\n"]}import { MkdirpOptions } from './opts-arg.js';
export declare const useNativeSync: (opts?: MkdirpOptions) => boolean;
export declare const useNative: ((opts?: MkdirpOptions) => boolean) & {
    sync: (opts?: MkdirpOptions) => boolean;
};
//# sourceMappingURL=use-native.d.ts.map{"version":3,"file":"use-native.d.ts","sourceRoot":"","sources":["../../../src/use-native.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAMtD,eAAO,MAAM,aAAa,UAEd,aAAa,YAA0C,CAAA;AAEnE,eAAO,MAAM,SAAS,WAGR,aAAa;kBALf,aAAa;CASxB,CAAA"}"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useNative = exports.useNativeSync = void 0;
const fs_1 = require("fs");
const opts_arg_js_1 = require("./opts-arg.js");
const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version;
const versArr = version.replace(/^v/, '').split('.');
const hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12);
exports.useNativeSync = !hasNative
    ? () => false
    : (opts) => (0, opts_arg_js_1.optsArg)(opts).mkdirSync === fs_1.mkdirSync;
exports.useNative = Object.assign(!hasNative
    ? () => false
    : (opts) => (0, opts_arg_js_1.optsArg)(opts).mkdir === fs_1.mkdir, {
    sync: exports.useNativeSync,
});
//# sourceMappingURL=use-native.js.map{"version":3,"file":"use-native.js","sourceRoot":"","sources":["../../../src/use-native.ts"],"names":[],"mappings":";;;AAAA,2BAAqC;AACrC,+CAAsD;AAEtD,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,IAAI,OAAO,CAAC,OAAO,CAAA;AAC9E,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AACpD,MAAM,SAAS,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;AAElE,QAAA,aAAa,GAAG,CAAC,SAAS;IACrC,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,CAAC,IAAoB,EAAE,EAAE,CAAC,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAC,SAAS,KAAK,cAAS,CAAA;AAEtD,QAAA,SAAS,GAAG,MAAM,CAAC,MAAM,CACpC,CAAC,SAAS;IACR,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,CAAC,IAAoB,EAAE,EAAE,CAAC,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAC,KAAK,KAAK,UAAK,EAC3D;IACE,IAAI,EAAE,qBAAa;CACpB,CACF,CAAA","sourcesContent":["import { mkdir, mkdirSync } from 'fs'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nconst version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version\nconst versArr = version.replace(/^v/, '').split('.')\nconst hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12)\n\nexport const useNativeSync = !hasNative\n  ? () => false\n  : (opts?: MkdirpOptions) => optsArg(opts).mkdirSync === mkdirSync\n\nexport const useNative = Object.assign(\n  !hasNative\n    ? () => false\n    : (opts?: MkdirpOptions) => optsArg(opts).mkdir === mkdir,\n  {\n    sync: useNativeSync,\n  }\n)\n"]}import { MkdirpOptionsResolved } from './opts-arg.js';
export declare const findMade: (opts: MkdirpOptionsResolved, parent: string, path?: string) => Promise;
export declare const findMadeSync: (opts: MkdirpOptionsResolved, parent: string, path?: string) => undefined | string;
//# sourceMappingURL=find-made.d.ts.map{"version":3,"file":"find-made.d.ts","sourceRoot":"","sources":["../../src/find-made.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAA;AAErD,eAAO,MAAM,QAAQ,SACb,qBAAqB,UACnB,MAAM,SACP,MAAM,KACZ,QAAQ,SAAS,GAAG,MAAM,CAe5B,CAAA;AAED,eAAO,MAAM,YAAY,SACjB,qBAAqB,UACnB,MAAM,SACP,MAAM,KACZ,SAAS,GAAG,MAad,CAAA"}import { dirname } from 'path';
export const findMade = async (opts, parent, path) => {
    // we never want the 'made' return value to be a root directory
    if (path === parent) {
        return;
    }
    return opts.statAsync(parent).then(st => (st.isDirectory() ? path : undefined), // will fail later
    // will fail later
    er => {
        const fer = er;
        return fer && fer.code === 'ENOENT'
            ? findMade(opts, dirname(parent), parent)
            : undefined;
    });
};
export const findMadeSync = (opts, parent, path) => {
    if (path === parent) {
        return undefined;
    }
    try {
        return opts.statSync(parent).isDirectory() ? path : undefined;
    }
    catch (er) {
        const fer = er;
        return fer && fer.code === 'ENOENT'
            ? findMadeSync(opts, dirname(parent), parent)
            : undefined;
    }
};
//# sourceMappingURL=find-made.js.map{"version":3,"file":"find-made.js","sourceRoot":"","sources":["../../src/find-made.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAG9B,MAAM,CAAC,MAAM,QAAQ,GAAG,KAAK,EAC3B,IAA2B,EAC3B,MAAc,EACd,IAAa,EACgB,EAAE;IAC/B,+DAA+D;IAC/D,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAM;KACP;IAED,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,CAChC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,kBAAkB;IAC/D,AAD6C,kBAAkB;IAC/D,EAAE,CAAC,EAAE;QACH,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ;YACjC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YACzC,CAAC,CAAC,SAAS,CAAA;IACf,CAAC,CACF,CAAA;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,CAC1B,IAA2B,EAC3B,MAAc,EACd,IAAa,EACO,EAAE;IACtB,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAO,SAAS,CAAA;KACjB;IAED,IAAI;QACF,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;KAC9D;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ;YACjC,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YAC7C,CAAC,CAAC,SAAS,CAAA;KACd;AACH,CAAC,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { MkdirpOptionsResolved } from './opts-arg.js'\n\nexport const findMade = async (\n  opts: MkdirpOptionsResolved,\n  parent: string,\n  path?: string\n): Promise => {\n  // we never want the 'made' return value to be a root directory\n  if (path === parent) {\n    return\n  }\n\n  return opts.statAsync(parent).then(\n    st => (st.isDirectory() ? path : undefined), // will fail later\n    er => {\n      const fer = er as NodeJS.ErrnoException\n      return fer && fer.code === 'ENOENT'\n        ? findMade(opts, dirname(parent), parent)\n        : undefined\n    }\n  )\n}\n\nexport const findMadeSync = (\n  opts: MkdirpOptionsResolved,\n  parent: string,\n  path?: string\n): undefined | string => {\n  if (path === parent) {\n    return undefined\n  }\n\n  try {\n    return opts.statSync(parent).isDirectory() ? path : undefined\n  } catch (er) {\n    const fer = er as NodeJS.ErrnoException\n    return fer && fer.code === 'ENOENT'\n      ? findMadeSync(opts, dirname(parent), parent)\n      : undefined\n  }\n}\n"]}import { MkdirpOptions } from './opts-arg.js';
export { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js';
export { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js';
export { useNative, useNativeSync } from './use-native.js';
export declare const mkdirpSync: (path: string, opts?: MkdirpOptions) => string | void;
export declare const sync: (path: string, opts?: MkdirpOptions) => string | void;
export declare const manual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & {
    sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
};
export declare const manualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
export declare const native: ((path: string, options?: MkdirpOptions | undefined) => Promise) & {
    sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
};
export declare const nativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
export declare const mkdirp: ((path: string, opts?: MkdirpOptions) => Promise) & {
    mkdirpSync: (path: string, opts?: MkdirpOptions) => string | void;
    mkdirpNative: ((path: string, options?: MkdirpOptions | undefined) => Promise) & {
        sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
    };
    mkdirpNativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
    mkdirpManual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & {
        sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
    };
    mkdirpManualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
    sync: (path: string, opts?: MkdirpOptions) => string | void;
    native: ((path: string, options?: MkdirpOptions | undefined) => Promise) & {
        sync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
    };
    nativeSync: (path: string, options?: MkdirpOptions | undefined) => string | void | undefined;
    manual: ((path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => Promise) & {
        sync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
    };
    manualSync: (path: string, options?: MkdirpOptions | undefined, made?: string | void | undefined) => string | void | undefined;
    useNative: ((opts?: MkdirpOptions | undefined) => boolean) & {
        sync: (opts?: MkdirpOptions | undefined) => boolean;
    };
    useNativeSync: (opts?: MkdirpOptions | undefined) => boolean;
};
//# sourceMappingURL=index.d.ts.map{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAItD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAG1D,eAAO,MAAM,UAAU,SAAU,MAAM,SAAS,aAAa,kBAM5D,CAAA;AAED,eAAO,MAAM,IAAI,SARgB,MAAM,SAAS,aAAa,kBAQ/B,CAAA;AAC9B,eAAO,MAAM,MAAM;;CAAe,CAAA;AAClC,eAAO,MAAM,UAAU,oHAAmB,CAAA;AAC1C,eAAO,MAAM,MAAM;;CAAe,CAAA;AAClC,eAAO,MAAM,UAAU,kFAAmB,CAAA;AAC1C,eAAO,MAAM,MAAM,UACJ,MAAM,SAAS,aAAa;uBAdV,MAAM,SAAS,aAAa;;;;;;;;;iBAA5B,MAAM,SAAS,aAAa;;;;;;;;;;;;;CAoC5D,CAAA"}import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js';
import { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js';
import { optsArg } from './opts-arg.js';
import { pathArg } from './path-arg.js';
import { useNative, useNativeSync } from './use-native.js';
/* c8 ignore start */
export { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js';
export { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js';
export { useNative, useNativeSync } from './use-native.js';
/* c8 ignore stop */
export const mkdirpSync = (path, opts) => {
    path = pathArg(path);
    const resolved = optsArg(opts);
    return useNativeSync(resolved)
        ? mkdirpNativeSync(path, resolved)
        : mkdirpManualSync(path, resolved);
};
export const sync = mkdirpSync;
export const manual = mkdirpManual;
export const manualSync = mkdirpManualSync;
export const native = mkdirpNative;
export const nativeSync = mkdirpNativeSync;
export const mkdirp = Object.assign(async (path, opts) => {
    path = pathArg(path);
    const resolved = optsArg(opts);
    return useNative(resolved)
        ? mkdirpNative(path, resolved)
        : mkdirpManual(path, resolved);
}, {
    mkdirpSync,
    mkdirpNative,
    mkdirpNativeSync,
    mkdirpManual,
    mkdirpManualSync,
    sync: mkdirpSync,
    native: mkdirpNative,
    nativeSync: mkdirpNativeSync,
    manual: mkdirpManual,
    manualSync: mkdirpManualSync,
    useNative,
    useNativeSync,
});
//# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAiB,OAAO,EAAE,MAAM,eAAe,CAAA;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAA;AACvC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC1D,qBAAqB;AACrB,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC1D,oBAAoB;AAEpB,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,IAAY,EAAE,IAAoB,EAAE,EAAE;IAC/D,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACpB,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9B,OAAO,aAAa,CAAC,QAAQ,CAAC;QAC5B,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC;QAClC,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AACtC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,IAAI,GAAG,UAAU,CAAA;AAC9B,MAAM,CAAC,MAAM,MAAM,GAAG,YAAY,CAAA;AAClC,MAAM,CAAC,MAAM,UAAU,GAAG,gBAAgB,CAAA;AAC1C,MAAM,CAAC,MAAM,MAAM,GAAG,YAAY,CAAA;AAClC,MAAM,CAAC,MAAM,UAAU,GAAG,gBAAgB,CAAA;AAC1C,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CACjC,KAAK,EAAE,IAAY,EAAE,IAAoB,EAAE,EAAE;IAC3C,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACpB,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9B,OAAO,SAAS,CAAC,QAAQ,CAAC;QACxB,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC;QAC9B,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AAClC,CAAC,EACD;IACE,UAAU;IACV,YAAY;IACZ,gBAAgB;IAChB,YAAY;IACZ,gBAAgB;IAEhB,IAAI,EAAE,UAAU;IAChB,MAAM,EAAE,YAAY;IACpB,UAAU,EAAE,gBAAgB;IAC5B,MAAM,EAAE,YAAY;IACpB,UAAU,EAAE,gBAAgB;IAC5B,SAAS;IACT,aAAa;CACd,CACF,CAAA","sourcesContent":["import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nimport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\nimport { pathArg } from './path-arg.js'\nimport { useNative, useNativeSync } from './use-native.js'\n/* c8 ignore start */\nexport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nexport { mkdirpNative, mkdirpNativeSync } from './mkdirp-native.js'\nexport { useNative, useNativeSync } from './use-native.js'\n/* c8 ignore stop */\n\nexport const mkdirpSync = (path: string, opts?: MkdirpOptions) => {\n  path = pathArg(path)\n  const resolved = optsArg(opts)\n  return useNativeSync(resolved)\n    ? mkdirpNativeSync(path, resolved)\n    : mkdirpManualSync(path, resolved)\n}\n\nexport const sync = mkdirpSync\nexport const manual = mkdirpManual\nexport const manualSync = mkdirpManualSync\nexport const native = mkdirpNative\nexport const nativeSync = mkdirpNativeSync\nexport const mkdirp = Object.assign(\n  async (path: string, opts?: MkdirpOptions) => {\n    path = pathArg(path)\n    const resolved = optsArg(opts)\n    return useNative(resolved)\n      ? mkdirpNative(path, resolved)\n      : mkdirpManual(path, resolved)\n  },\n  {\n    mkdirpSync,\n    mkdirpNative,\n    mkdirpNativeSync,\n    mkdirpManual,\n    mkdirpManualSync,\n\n    sync: mkdirpSync,\n    native: mkdirpNative,\n    nativeSync: mkdirpNativeSync,\n    manual: mkdirpManual,\n    manualSync: mkdirpManualSync,\n    useNative,\n    useNativeSync,\n  }\n)\n"]}import { MkdirpOptions } from './opts-arg.js';
export declare const mkdirpManualSync: (path: string, options?: MkdirpOptions, made?: string | undefined | void) => string | undefined | void;
export declare const mkdirpManual: ((path: string, options?: MkdirpOptions, made?: string | undefined | void) => Promise) & {
    sync: (path: string, options?: MkdirpOptions, made?: string | undefined | void) => string | undefined | void;
};
//# sourceMappingURL=mkdirp-manual.d.ts.map{"version":3,"file":"mkdirp-manual.d.ts","sourceRoot":"","sources":["../../src/mkdirp-manual.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAEtD,eAAO,MAAM,gBAAgB,SACrB,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,MAAM,GAAG,SAAS,GAAG,IAmCvB,CAAA;AAED,eAAO,MAAM,YAAY,UAEf,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;iBA7C/B,MAAM,YACF,aAAa,SAChB,MAAM,GAAG,SAAS,GAAG,IAAI,KAC/B,MAAM,GAAG,SAAS,GAAG,IAAI;CAqF3B,CAAA"}import { dirname } from 'path';
import { optsArg } from './opts-arg.js';
export const mkdirpManualSync = (path, options, made) => {
    const parent = dirname(path);
    const opts = { ...optsArg(options), recursive: false };
    if (parent === path) {
        try {
            return opts.mkdirSync(path, opts);
        }
        catch (er) {
            // swallowed by recursive implementation on posix systems
            // any other error is a failure
            const fer = er;
            if (fer && fer.code !== 'EISDIR') {
                throw er;
            }
            return;
        }
    }
    try {
        opts.mkdirSync(path, opts);
        return made || path;
    }
    catch (er) {
        const fer = er;
        if (fer && fer.code === 'ENOENT') {
            return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made));
        }
        if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') {
            throw er;
        }
        try {
            if (!opts.statSync(path).isDirectory())
                throw er;
        }
        catch (_) {
            throw er;
        }
    }
};
export const mkdirpManual = Object.assign(async (path, options, made) => {
    const opts = optsArg(options);
    opts.recursive = false;
    const parent = dirname(path);
    if (parent === path) {
        return opts.mkdirAsync(path, opts).catch(er => {
            // swallowed by recursive implementation on posix systems
            // any other error is a failure
            const fer = er;
            if (fer && fer.code !== 'EISDIR') {
                throw er;
            }
        });
    }
    return opts.mkdirAsync(path, opts).then(() => made || path, async (er) => {
        const fer = er;
        if (fer && fer.code === 'ENOENT') {
            return mkdirpManual(parent, opts).then((made) => mkdirpManual(path, opts, made));
        }
        if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') {
            throw er;
        }
        return opts.statAsync(path).then(st => {
            if (st.isDirectory()) {
                return made;
            }
            else {
                throw er;
            }
        }, () => {
            throw er;
        });
    });
}, { sync: mkdirpManualSync });
//# sourceMappingURL=mkdirp-manual.js.map{"version":3,"file":"mkdirp-manual.js","sourceRoot":"","sources":["../../src/mkdirp-manual.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAC9B,OAAO,EAAiB,OAAO,EAAE,MAAM,eAAe,CAAA;AAEtD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAuB,EACvB,IAAgC,EACL,EAAE;IAC7B,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,CAAA;IAEtD,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,IAAI;YACF,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAClC;QAAC,OAAO,EAAE,EAAE;YACX,yDAAyD;YACzD,+BAA+B;YAC/B,MAAM,GAAG,GAAG,EAA2B,CAAA;YACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAChC,MAAM,EAAE,CAAA;aACT;YACD,OAAM;SACP;KACF;IAED,IAAI;QACF,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAO,IAAI,IAAI,IAAI,CAAA;KACpB;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,gBAAgB,CAAC,IAAI,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;SAC1E;QACD,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE;YAC/D,MAAM,EAAE,CAAA;SACT;QACD,IAAI;YACF,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE;gBAAE,MAAM,EAAE,CAAA;SACjD;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,EAAE,CAAA;SACT;KACF;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CACvC,KAAK,EACH,IAAY,EACZ,OAAuB,EACvB,IAAgC,EACI,EAAE;IACtC,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAA;IACtB,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE;YAC5C,yDAAyD;YACzD,+BAA+B;YAC/B,MAAM,GAAG,GAAG,EAA2B,CAAA;YACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAChC,MAAM,EAAE,CAAA;aACT;QACH,CAAC,CAAC,CAAA;KACH;IAED,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CACrC,GAAG,EAAE,CAAC,IAAI,IAAI,IAAI,EAClB,KAAK,EAAC,EAAE,EAAC,EAAE;QACT,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,IAAI,CACpC,CAAC,IAAgC,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CACrE,CAAA;SACF;QACD,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE;YACxD,MAAM,EAAE,CAAA;SACT;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,CAC9B,EAAE,CAAC,EAAE;YACH,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE;gBACpB,OAAO,IAAI,CAAA;aACZ;iBAAM;gBACL,MAAM,EAAE,CAAA;aACT;QACH,CAAC,EACD,GAAG,EAAE;YACH,MAAM,EAAE,CAAA;QACV,CAAC,CACF,CAAA;IACH,CAAC,CACF,CAAA;AACH,CAAC,EACD,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAC3B,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nexport const mkdirpManualSync = (\n  path: string,\n  options?: MkdirpOptions,\n  made?: string | undefined | void\n): string | undefined | void => {\n  const parent = dirname(path)\n  const opts = { ...optsArg(options), recursive: false }\n\n  if (parent === path) {\n    try {\n      return opts.mkdirSync(path, opts)\n    } catch (er) {\n      // swallowed by recursive implementation on posix systems\n      // any other error is a failure\n      const fer = er as NodeJS.ErrnoException\n      if (fer && fer.code !== 'EISDIR') {\n        throw er\n      }\n      return\n    }\n  }\n\n  try {\n    opts.mkdirSync(path, opts)\n    return made || path\n  } catch (er) {\n    const fer = er as NodeJS.ErrnoException\n    if (fer && fer.code === 'ENOENT') {\n      return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made))\n    }\n    if (fer && fer.code !== 'EEXIST' && fer && fer.code !== 'EROFS') {\n      throw er\n    }\n    try {\n      if (!opts.statSync(path).isDirectory()) throw er\n    } catch (_) {\n      throw er\n    }\n  }\n}\n\nexport const mkdirpManual = Object.assign(\n  async (\n    path: string,\n    options?: MkdirpOptions,\n    made?: string | undefined | void\n  ): Promise => {\n    const opts = optsArg(options)\n    opts.recursive = false\n    const parent = dirname(path)\n    if (parent === path) {\n      return opts.mkdirAsync(path, opts).catch(er => {\n        // swallowed by recursive implementation on posix systems\n        // any other error is a failure\n        const fer = er as NodeJS.ErrnoException\n        if (fer && fer.code !== 'EISDIR') {\n          throw er\n        }\n      })\n    }\n\n    return opts.mkdirAsync(path, opts).then(\n      () => made || path,\n      async er => {\n        const fer = er as NodeJS.ErrnoException\n        if (fer && fer.code === 'ENOENT') {\n          return mkdirpManual(parent, opts).then(\n            (made?: string | undefined | void) => mkdirpManual(path, opts, made)\n          )\n        }\n        if (fer && fer.code !== 'EEXIST' && fer.code !== 'EROFS') {\n          throw er\n        }\n        return opts.statAsync(path).then(\n          st => {\n            if (st.isDirectory()) {\n              return made\n            } else {\n              throw er\n            }\n          },\n          () => {\n            throw er\n          }\n        )\n      }\n    )\n  },\n  { sync: mkdirpManualSync }\n)\n"]}import { MkdirpOptions } from './opts-arg.js';
export declare const mkdirpNativeSync: (path: string, options?: MkdirpOptions) => string | void | undefined;
export declare const mkdirpNative: ((path: string, options?: MkdirpOptions) => Promise) & {
    sync: (path: string, options?: MkdirpOptions) => string | void | undefined;
};
//# sourceMappingURL=mkdirp-native.d.ts.map{"version":3,"file":"mkdirp-native.d.ts","sourceRoot":"","sources":["../../src/mkdirp-native.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAEtD,eAAO,MAAM,gBAAgB,SACrB,MAAM,YACF,aAAa,KACtB,MAAM,GAAG,IAAI,GAAG,SAoBlB,CAAA;AAED,eAAO,MAAM,YAAY,UAEf,MAAM,YACF,aAAa,KACtB,QAAQ,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;iBA5B/B,MAAM,YACF,aAAa,KACtB,MAAM,GAAG,IAAI,GAAG,SAAS;CAgD3B,CAAA"}import { dirname } from 'path';
import { findMade, findMadeSync } from './find-made.js';
import { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js';
import { optsArg } from './opts-arg.js';
export const mkdirpNativeSync = (path, options) => {
    const opts = optsArg(options);
    opts.recursive = true;
    const parent = dirname(path);
    if (parent === path) {
        return opts.mkdirSync(path, opts);
    }
    const made = findMadeSync(opts, path);
    try {
        opts.mkdirSync(path, opts);
        return made;
    }
    catch (er) {
        const fer = er;
        if (fer && fer.code === 'ENOENT') {
            return mkdirpManualSync(path, opts);
        }
        else {
            throw er;
        }
    }
};
export const mkdirpNative = Object.assign(async (path, options) => {
    const opts = { ...optsArg(options), recursive: true };
    const parent = dirname(path);
    if (parent === path) {
        return await opts.mkdirAsync(path, opts);
    }
    return findMade(opts, path).then((made) => opts
        .mkdirAsync(path, opts)
        .then(m => made || m)
        .catch(er => {
        const fer = er;
        if (fer && fer.code === 'ENOENT') {
            return mkdirpManual(path, opts);
        }
        else {
            throw er;
        }
    }));
}, { sync: mkdirpNativeSync });
//# sourceMappingURL=mkdirp-native.js.map{"version":3,"file":"mkdirp-native.js","sourceRoot":"","sources":["../../src/mkdirp-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAC9B,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AACvD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAiB,OAAO,EAAE,MAAM,eAAe,CAAA;AAEtD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAuB,EACI,EAAE;IAC7B,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;IACrB,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;KAClC;IAED,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACrC,IAAI;QACF,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAC1B,OAAO,IAAI,CAAA;KACZ;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SACpC;aAAM;YACL,MAAM,EAAE,CAAA;SACT;KACF;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CACvC,KAAK,EACH,IAAY,EACZ,OAAuB,EACa,EAAE;IACtC,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAA;IACrD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;KACzC;IAED,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAyB,EAAE,EAAE,CAC7D,IAAI;SACD,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;SACtB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC;SACpB,KAAK,CAAC,EAAE,CAAC,EAAE;QACV,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,OAAO,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAChC;aAAM;YACL,MAAM,EAAE,CAAA;SACT;IACH,CAAC,CAAC,CACL,CAAA;AACH,CAAC,EACD,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAC3B,CAAA","sourcesContent":["import { dirname } from 'path'\nimport { findMade, findMadeSync } from './find-made.js'\nimport { mkdirpManual, mkdirpManualSync } from './mkdirp-manual.js'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nexport const mkdirpNativeSync = (\n  path: string,\n  options?: MkdirpOptions\n): string | void | undefined => {\n  const opts = optsArg(options)\n  opts.recursive = true\n  const parent = dirname(path)\n  if (parent === path) {\n    return opts.mkdirSync(path, opts)\n  }\n\n  const made = findMadeSync(opts, path)\n  try {\n    opts.mkdirSync(path, opts)\n    return made\n  } catch (er) {\n    const fer = er as NodeJS.ErrnoException\n    if (fer && fer.code === 'ENOENT') {\n      return mkdirpManualSync(path, opts)\n    } else {\n      throw er\n    }\n  }\n}\n\nexport const mkdirpNative = Object.assign(\n  async (\n    path: string,\n    options?: MkdirpOptions\n  ): Promise => {\n    const opts = { ...optsArg(options), recursive: true }\n    const parent = dirname(path)\n    if (parent === path) {\n      return await opts.mkdirAsync(path, opts)\n    }\n\n    return findMade(opts, path).then((made?: string | undefined) =>\n      opts\n        .mkdirAsync(path, opts)\n        .then(m => made || m)\n        .catch(er => {\n          const fer = er as NodeJS.ErrnoException\n          if (fer && fer.code === 'ENOENT') {\n            return mkdirpManual(path, opts)\n          } else {\n            throw er\n          }\n        })\n    )\n  },\n  { sync: mkdirpNativeSync }\n)\n"]}/// 
/// 
import { MakeDirectoryOptions, Stats } from 'fs';
export interface FsProvider {
    stat?: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any;
    mkdir?: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any;
    statSync?: (path: string) => Stats;
    mkdirSync?: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }) => string | undefined;
}
interface Options extends FsProvider {
    mode?: number | string;
    fs?: FsProvider;
    mkdirAsync?: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }) => Promise;
    statAsync?: (path: string) => Promise;
}
export type MkdirpOptions = Options | number | string;
export interface MkdirpOptionsResolved {
    mode: number;
    fs: FsProvider;
    mkdirAsync: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }) => Promise;
    statAsync: (path: string) => Promise;
    stat: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any;
    mkdir: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any;
    statSync: (path: string) => Stats;
    mkdirSync: (path: string, opts: MakeDirectoryOptions & {
        recursive?: boolean;
    }) => string | undefined;
    recursive?: boolean;
}
export declare const optsArg: (opts?: MkdirpOptions) => MkdirpOptionsResolved;
export {};
//# sourceMappingURL=opts-arg.d.ts.map{"version":3,"file":"opts-arg.d.ts","sourceRoot":"","sources":["../../src/opts-arg.ts"],"names":[],"mappings":";;AAAA,OAAO,EACL,oBAAoB,EAIpB,KAAK,EAEN,MAAM,IAAI,CAAA;AAEX,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,EAAE,CACL,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK,GAAG,KAC/D,GAAG,CAAA;IACR,KAAK,CAAC,EAAE,CACN,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,EACpD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,KAChE,GAAG,CAAA;IACR,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IAClC,SAAS,CAAC,EAAE,CACV,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,MAAM,GAAG,SAAS,CAAA;CACxB;AAED,UAAU,OAAQ,SAAQ,UAAU;IAClC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IACtB,EAAE,CAAC,EAAE,UAAU,CAAA;IACf,UAAU,CAAC,EAAE,CACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAA;CAC7C;AAED,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAA;AAErD,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,EAAE,EAAE,UAAU,CAAA;IACd,UAAU,EAAE,CACV,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAChC,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAA;IAC3C,IAAI,EAAE,CACJ,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK,GAAG,KAC/D,GAAG,CAAA;IACR,KAAK,EAAE,CACL,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,EACpD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,KAChE,GAAG,CAAA;IACR,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IACjC,SAAS,EAAE,CACT,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KACjD,MAAM,GAAG,SAAS,CAAA;IACvB,SAAS,CAAC,EAAE,OAAO,CAAA;CACpB;AAED,eAAO,MAAM,OAAO,UAAW,aAAa,KAAG,qBA2C9C,CAAA"}import { mkdir, mkdirSync, stat, statSync, } from 'fs';
export const optsArg = (opts) => {
    if (!opts) {
        opts = { mode: 0o777 };
    }
    else if (typeof opts === 'object') {
        opts = { mode: 0o777, ...opts };
    }
    else if (typeof opts === 'number') {
        opts = { mode: opts };
    }
    else if (typeof opts === 'string') {
        opts = { mode: parseInt(opts, 8) };
    }
    else {
        throw new TypeError('invalid options argument');
    }
    const resolved = opts;
    const optsFs = opts.fs || {};
    opts.mkdir = opts.mkdir || optsFs.mkdir || mkdir;
    opts.mkdirAsync = opts.mkdirAsync
        ? opts.mkdirAsync
        : async (path, options) => {
            return new Promise((res, rej) => resolved.mkdir(path, options, (er, made) => er ? rej(er) : res(made)));
        };
    opts.stat = opts.stat || optsFs.stat || stat;
    opts.statAsync = opts.statAsync
        ? opts.statAsync
        : async (path) => new Promise((res, rej) => resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats))));
    opts.statSync = opts.statSync || optsFs.statSync || statSync;
    opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || mkdirSync;
    return resolved;
};
//# sourceMappingURL=opts-arg.js.map{"version":3,"file":"opts-arg.js","sourceRoot":"","sources":["../../src/opts-arg.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,EACL,SAAS,EACT,IAAI,EAEJ,QAAQ,GACT,MAAM,IAAI,CAAA;AAwDX,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAoB,EAAyB,EAAE;IACrE,IAAI,CAAC,IAAI,EAAE;QACT,IAAI,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;KACvB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,CAAA;KAChC;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;KACtB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,IAAI,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,CAAA;KACnC;SAAM;QACL,MAAM,IAAI,SAAS,CAAC,0BAA0B,CAAC,CAAA;KAChD;IAED,MAAM,QAAQ,GAAG,IAA6B,CAAA;IAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,EAAE,IAAI,EAAE,CAAA;IAE5B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,IAAI,KAAK,CAAA;IAEhD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU;QAC/B,CAAC,CAAC,IAAI,CAAC,UAAU;QACjB,CAAC,CAAC,KAAK,EACH,IAAY,EACZ,OAAuD,EAC1B,EAAE;YAC/B,OAAO,IAAI,OAAO,CAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAClD,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CACzC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CACzB,CACF,CAAA;QACH,CAAC,CAAA;IAEL,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,IAAI,CAAA;IAC5C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS;QAC7B,CAAC,CAAC,IAAI,CAAC,SAAS;QAChB,CAAC,CAAC,KAAK,EAAE,IAAY,EAAE,EAAE,CACrB,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CACnE,CAAA;IAEP,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,MAAM,CAAC,QAAQ,IAAI,QAAQ,CAAA;IAC5D,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC,SAAS,IAAI,SAAS,CAAA;IAEhE,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA","sourcesContent":["import {\n  MakeDirectoryOptions,\n  mkdir,\n  mkdirSync,\n  stat,\n  Stats,\n  statSync,\n} from 'fs'\n\nexport interface FsProvider {\n  stat?: (\n    path: string,\n    callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any\n  ) => any\n  mkdir?: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean },\n    callback: (err: NodeJS.ErrnoException | null, made?: string) => any\n  ) => any\n  statSync?: (path: string) => Stats\n  mkdirSync?: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean }\n  ) => string | undefined\n}\n\ninterface Options extends FsProvider {\n  mode?: number | string\n  fs?: FsProvider\n  mkdirAsync?: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean }\n  ) => Promise\n  statAsync?: (path: string) => Promise\n}\n\nexport type MkdirpOptions = Options | number | string\n\nexport interface MkdirpOptionsResolved {\n  mode: number\n  fs: FsProvider\n  mkdirAsync: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean }\n  ) => Promise\n  statAsync: (path: string) => Promise\n  stat: (\n    path: string,\n    callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any\n  ) => any\n  mkdir: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean },\n    callback: (err: NodeJS.ErrnoException | null, made?: string) => any\n  ) => any\n  statSync: (path: string) => Stats\n  mkdirSync: (\n    path: string,\n    opts: MakeDirectoryOptions & { recursive?: boolean }\n  ) => string | undefined\n  recursive?: boolean\n}\n\nexport const optsArg = (opts?: MkdirpOptions): MkdirpOptionsResolved => {\n  if (!opts) {\n    opts = { mode: 0o777 }\n  } else if (typeof opts === 'object') {\n    opts = { mode: 0o777, ...opts }\n  } else if (typeof opts === 'number') {\n    opts = { mode: opts }\n  } else if (typeof opts === 'string') {\n    opts = { mode: parseInt(opts, 8) }\n  } else {\n    throw new TypeError('invalid options argument')\n  }\n\n  const resolved = opts as MkdirpOptionsResolved\n  const optsFs = opts.fs || {}\n\n  opts.mkdir = opts.mkdir || optsFs.mkdir || mkdir\n\n  opts.mkdirAsync = opts.mkdirAsync\n    ? opts.mkdirAsync\n    : async (\n        path: string,\n        options: MakeDirectoryOptions & { recursive?: boolean }\n      ): Promise => {\n        return new Promise((res, rej) =>\n          resolved.mkdir(path, options, (er, made) =>\n            er ? rej(er) : res(made)\n          )\n        )\n      }\n\n  opts.stat = opts.stat || optsFs.stat || stat\n  opts.statAsync = opts.statAsync\n    ? opts.statAsync\n    : async (path: string) =>\n        new Promise((res, rej) =>\n          resolved.stat(path, (err, stats) => (err ? rej(err) : res(stats)))\n        )\n\n  opts.statSync = opts.statSync || optsFs.statSync || statSync\n  opts.mkdirSync = opts.mkdirSync || optsFs.mkdirSync || mkdirSync\n\n  return resolved\n}\n"]}{
  "type": "module"
}
export declare const pathArg: (path: string) => string;
//# sourceMappingURL=path-arg.d.ts.map{"version":3,"file":"path-arg.d.ts","sourceRoot":"","sources":["../../src/path-arg.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,SAAU,MAAM,WAyBnC,CAAA"}const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform;
import { parse, resolve } from 'path';
export const pathArg = (path) => {
    if (/\0/.test(path)) {
        // simulate same failure that node raises
        throw Object.assign(new TypeError('path must be a string without null bytes'), {
            path,
            code: 'ERR_INVALID_ARG_VALUE',
        });
    }
    path = resolve(path);
    if (platform === 'win32') {
        const badWinChars = /[*|"<>?:]/;
        const { root } = parse(path);
        if (badWinChars.test(path.substring(root.length))) {
            throw Object.assign(new Error('Illegal characters in path.'), {
                path,
                code: 'EINVAL',
            });
        }
    }
    return path;
};
//# sourceMappingURL=path-arg.js.map{"version":3,"file":"path-arg.js","sourceRoot":"","sources":["../../src/path-arg.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,2BAA2B,IAAI,OAAO,CAAC,QAAQ,CAAA;AAC5E,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AACrC,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,EAAE;IACtC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QACnB,yCAAyC;QACzC,MAAM,MAAM,CAAC,MAAM,CACjB,IAAI,SAAS,CAAC,0CAA0C,CAAC,EACzD;YACE,IAAI;YACJ,IAAI,EAAE,uBAAuB;SAC9B,CACF,CAAA;KACF;IAED,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACpB,IAAI,QAAQ,KAAK,OAAO,EAAE;QACxB,MAAM,WAAW,GAAG,WAAW,CAAA;QAC/B,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,CAAA;QAC5B,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE;YACjD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,EAAE;gBAC5D,IAAI;gBACJ,IAAI,EAAE,QAAQ;aACf,CAAC,CAAA;SACH;KACF;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA","sourcesContent":["const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform\nimport { parse, resolve } from 'path'\nexport const pathArg = (path: string) => {\n  if (/\\0/.test(path)) {\n    // simulate same failure that node raises\n    throw Object.assign(\n      new TypeError('path must be a string without null bytes'),\n      {\n        path,\n        code: 'ERR_INVALID_ARG_VALUE',\n      }\n    )\n  }\n\n  path = resolve(path)\n  if (platform === 'win32') {\n    const badWinChars = /[*|\"<>?:]/\n    const { root } = parse(path)\n    if (badWinChars.test(path.substring(root.length))) {\n      throw Object.assign(new Error('Illegal characters in path.'), {\n        path,\n        code: 'EINVAL',\n      })\n    }\n  }\n\n  return path\n}\n"]}import { MkdirpOptions } from './opts-arg.js';
export declare const useNativeSync: (opts?: MkdirpOptions) => boolean;
export declare const useNative: ((opts?: MkdirpOptions) => boolean) & {
    sync: (opts?: MkdirpOptions) => boolean;
};
//# sourceMappingURL=use-native.d.ts.map{"version":3,"file":"use-native.d.ts","sourceRoot":"","sources":["../../src/use-native.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAW,MAAM,eAAe,CAAA;AAMtD,eAAO,MAAM,aAAa,UAEd,aAAa,YAA0C,CAAA;AAEnE,eAAO,MAAM,SAAS,WAGR,aAAa;kBALf,aAAa;CASxB,CAAA"}import { mkdir, mkdirSync } from 'fs';
import { optsArg } from './opts-arg.js';
const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version;
const versArr = version.replace(/^v/, '').split('.');
const hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12);
export const useNativeSync = !hasNative
    ? () => false
    : (opts) => optsArg(opts).mkdirSync === mkdirSync;
export const useNative = Object.assign(!hasNative
    ? () => false
    : (opts) => optsArg(opts).mkdir === mkdir, {
    sync: useNativeSync,
});
//# sourceMappingURL=use-native.js.map{"version":3,"file":"use-native.js","sourceRoot":"","sources":["../../src/use-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAA;AACrC,OAAO,EAAiB,OAAO,EAAE,MAAM,eAAe,CAAA;AAEtD,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,IAAI,OAAO,CAAC,OAAO,CAAA;AAC9E,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AACpD,MAAM,SAAS,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;AAE/E,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,SAAS;IACrC,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,CAAC,IAAoB,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,KAAK,SAAS,CAAA;AAEnE,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CACpC,CAAC,SAAS;IACR,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,CAAC,IAAoB,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,KAAK,KAAK,EAC3D;IACE,IAAI,EAAE,aAAa;CACpB,CACF,CAAA","sourcesContent":["import { mkdir, mkdirSync } from 'fs'\nimport { MkdirpOptions, optsArg } from './opts-arg.js'\n\nconst version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version\nconst versArr = version.replace(/^v/, '').split('.')\nconst hasNative = +versArr[0] > 10 || (+versArr[0] === 10 && +versArr[1] >= 12)\n\nexport const useNativeSync = !hasNative\n  ? () => false\n  : (opts?: MkdirpOptions) => optsArg(opts).mkdirSync === mkdirSync\n\nexport const useNative = Object.assign(\n  !hasNative\n    ? () => false\n    : (opts?: MkdirpOptions) => optsArg(opts).mkdir === mkdir,\n  {\n    sync: useNativeSync,\n  }\n)\n"]}{
  "name": "mkdirp",
  "description": "Recursively mkdir, like `mkdir -p`",
  "version": "3.0.1",
  "keywords": [
    "mkdir",
    "directory",
    "make dir",
    "make",
    "dir",
    "recursive",
    "native"
  ],
  "bin": "./dist/cjs/src/bin.js",
  "main": "./dist/cjs/src/index.js",
  "module": "./dist/mjs/index.js",
  "types": "./dist/mjs/index.d.ts",
  "exports": {
    ".": {
      "import": {
        "types": "./dist/mjs/index.d.ts",
        "default": "./dist/mjs/index.js"
      },
      "require": {
        "types": "./dist/cjs/src/index.d.ts",
        "default": "./dist/cjs/src/index.js"
      }
    }
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "preprepare": "rm -rf dist",
    "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json",
    "postprepare": "bash fixup.sh",
    "pretest": "npm run prepare",
    "presnap": "npm run prepare",
    "test": "c8 tap",
    "snap": "c8 tap",
    "format": "prettier --write . --loglevel warn",
    "benchmark": "node benchmark/index.js",
    "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
  },
  "prettier": {
    "semi": false,
    "printWidth": 80,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "devDependencies": {
    "@types/brace-expansion": "^1.1.0",
    "@types/node": "^18.11.9",
    "@types/tap": "^15.0.7",
    "c8": "^7.12.0",
    "eslint-config-prettier": "^8.6.0",
    "prettier": "^2.8.2",
    "tap": "^16.3.3",
    "ts-node": "^10.9.1",
    "typedoc": "^0.23.21",
    "typescript": "^4.9.3"
  },
  "tap": {
    "coverage": false,
    "node-arg": [
      "--no-warnings",
      "--loader",
      "ts-node/esm"
    ],
    "ts": false
  },
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/isaacs/node-mkdirp.git"
  },
  "license": "MIT",
  "engines": {
    "node": ">=10"
  }
}
# mkdirp

Like `mkdir -p`, but in Node.js!

Now with a modern API and no\* bugs!

\* may contain some bugs

# example

## pow.js

```js
// hybrid module, import or require() both work
import { mkdirp } from 'mkdirp'
// or:
const { mkdirp } = require('mkdirp')

// return value is a Promise resolving to the first directory created
mkdirp('/tmp/foo/bar/baz').then(made =>
  console.log(`made directories, starting with ${made}`)
)
```

Output (where `/tmp/foo` already exists)

```
made directories, starting with /tmp/foo/bar
```

Or, if you don't have time to wait around for promises:

```js
import { mkdirp } from 'mkdirp'

// return value is the first directory created
const made = mkdirp.sync('/tmp/foo/bar/baz')
console.log(`made directories, starting with ${made}`)
```

And now /tmp/foo/bar/baz exists, huzzah!

# methods

```js
import { mkdirp } from 'mkdirp'
```

## `mkdirp(dir: string, opts?: MkdirpOptions) => Promise`

Create a new directory and any necessary subdirectories at `dir`
with octal permission string `opts.mode`. If `opts` is a string
or number, it will be treated as the `opts.mode`.

If `opts.mode` isn't specified, it defaults to `0o777`.

Promise resolves to first directory `made` that had to be
created, or `undefined` if everything already exists. Promise
rejects if any errors are encountered. Note that, in the case of
promise rejection, some directories _may_ have been created, as
recursive directory creation is not an atomic operation.

You can optionally pass in an alternate `fs` implementation by
passing in `opts.fs`. Your implementation should have
`opts.fs.mkdir(path, opts, cb)` and `opts.fs.stat(path, cb)`.

You can also override just one or the other of `mkdir` and `stat`
by passing in `opts.stat` or `opts.mkdir`, or providing an `fs`
option that only overrides one of these.

## `mkdirp.sync(dir: string, opts: MkdirpOptions) => string|undefined`

Synchronously create a new directory and any necessary
subdirectories at `dir` with octal permission string `opts.mode`.
If `opts` is a string or number, it will be treated as the
`opts.mode`.

If `opts.mode` isn't specified, it defaults to `0o777`.

Returns the first directory that had to be created, or undefined
if everything already exists.

You can optionally pass in an alternate `fs` implementation by
passing in `opts.fs`. Your implementation should have
`opts.fs.mkdirSync(path, mode)` and `opts.fs.statSync(path)`.

You can also override just one or the other of `mkdirSync` and
`statSync` by passing in `opts.statSync` or `opts.mkdirSync`, or
providing an `fs` option that only overrides one of these.

## `mkdirp.manual`, `mkdirp.manualSync`

Use the manual implementation (not the native one). This is the
default when the native implementation is not available or the
stat/mkdir implementation is overridden.

## `mkdirp.native`, `mkdirp.nativeSync`

Use the native implementation (not the manual one). This is the
default when the native implementation is available and
stat/mkdir are not overridden.

# implementation

On Node.js v10.12.0 and above, use the native `fs.mkdir(p,
{recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has
been overridden by an option.

## native implementation

- If the path is a root directory, then pass it to the underlying
  implementation and return the result/error. (In this case,
  it'll either succeed or fail, but we aren't actually creating
  any dirs.)
- Walk up the path statting each directory, to find the first
  path that will be created, `made`.
- Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`)
- If error, raise it to the caller.
- Return `made`.

## manual implementation

- Call underlying `fs.mkdir` implementation, with `recursive:
false`
- If error:
  - If path is a root directory, raise to the caller and do not
    handle it
  - If ENOENT, mkdirp parent dir, store result as `made`
  - stat(path)
    - If error, raise original `mkdir` error
    - If directory, return `made`
    - Else, raise original `mkdir` error
- else
  - return `undefined` if a root dir, or `made` if set, or `path`

## windows vs unix caveat

On Windows file systems, attempts to create a root directory (ie,
a drive letter or root UNC path) will fail. If the root
directory exists, then it will fail with `EPERM`. If the root
directory does not exist, then it will fail with `ENOENT`.

On posix file systems, attempts to create a root directory (in
recursive mode) will succeed silently, as it is treated like just
another directory that already exists. (In non-recursive mode,
of course, it fails with `EEXIST`.)

In order to preserve this system-specific behavior (and because
it's not as if we can create the parent of a root directory
anyway), attempts to create a root directory are passed directly
to the `fs` implementation, and any errors encountered are not
handled.

## native error caveat

The native implementation (as of at least Node.js v13.4.0) does
not provide appropriate errors in some cases (see
[nodejs/node#31481](https://github.com/nodejs/node/issues/31481)
and
[nodejs/node#28015](https://github.com/nodejs/node/issues/28015)).

In order to work around this issue, the native implementation
will fall back to the manual implementation if an `ENOENT` error
is encountered.

# choosing a recursive mkdir implementation

There are a few to choose from! Use the one that suits your
needs best :D

## use `fs.mkdir(path, {recursive: true}, cb)` if:

- You wish to optimize performance even at the expense of other
  factors.
- You don't need to know the first dir created.
- You are ok with getting `ENOENT` as the error when some other
  problem is the actual cause.
- You can limit your platforms to Node.js v10.12 and above.
- You're ok with using callbacks instead of promises.
- You don't need/want a CLI.
- You don't need to override the `fs` methods in use.

## use this module (mkdirp 1.x or 2.x) if:

- You need to know the first directory that was created.
- You wish to use the native implementation if available, but
  fall back when it's not.
- You prefer promise-returning APIs to callback-taking APIs.
- You want more useful error messages than the native recursive
  mkdir provides (at least as of Node.js v13.4), and are ok with
  re-trying on `ENOENT` to achieve this.
- You need (or at least, are ok with) a CLI.
- You need to override the `fs` methods in use.

## use [`make-dir`](http://npm.im/make-dir) if:

- You do not need to know the first dir created (and wish to save
  a few `stat` calls when using the native implementation for
  this reason).
- You wish to use the native implementation if available, but
  fall back when it's not.
- You prefer promise-returning APIs to callback-taking APIs.
- You are ok with occasionally getting `ENOENT` errors for
  failures that are actually related to something other than a
  missing file system entry.
- You don't need/want a CLI.
- You need to override the `fs` methods in use.

## use mkdirp 0.x if:

- You need to know the first directory that was created.
- You need (or at least, are ok with) a CLI.
- You need to override the `fs` methods in use.
- You're ok with using callbacks instead of promises.
- You are not running on Windows, where the root-level ENOENT
  errors can lead to infinite regress.
- You think vinyl just sounds warmer and richer for some weird
  reason.
- You are supporting truly ancient Node.js versions, before even
  the advent of a `Promise` language primitive. (Please don't.
  You deserve better.)

# cli

This package also ships with a `mkdirp` command.

```
$ mkdirp -h

usage: mkdirp [DIR1,DIR2..] {OPTIONS}

  Create each supplied directory including any necessary parent directories
  that don't yet exist.

  If the directory already exists, do nothing.

OPTIONS are:

  -m       If a directory needs to be created, set the mode as an octal
  --mode=  permission string.

  -v --version   Print the mkdirp version number

  -h --help      Print this helpful banner

  -p --print     Print the first directories created for each path provided

  --manual       Use manual implementation, even if native is available
```

# install

With [npm](http://npmjs.org) do:

```
npm install mkdirp
```

to get the library locally, or

```
npm install -g mkdirp
```

to get the command everywhere, or

```
npx mkdirp ...
```

to run the command without installing it globally.

# platform support

This module works on node v8, but only v10 and above are officially
supported, as Node v8 reached its LTS end of life 2020-01-01, which is in
the past, as of this writing.

# license

MIT
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = void 0;
const fs_minipass_1 = require("@isaacs/fs-minipass");
const node_path_1 = __importDefault(require("node:path"));
const list_js_1 = require("./list.js");
const make_command_js_1 = require("./make-command.js");
const pack_js_1 = require("./pack.js");
const createFileSync = (opt, files) => {
    const p = new pack_js_1.PackSync(opt);
    const stream = new fs_minipass_1.WriteStreamSync(opt.file, {
        mode: opt.mode || 0o666,
    });
    p.pipe(stream);
    addFilesSync(p, files);
};
const createFile = (opt, files) => {
    const p = new pack_js_1.Pack(opt);
    const stream = new fs_minipass_1.WriteStream(opt.file, {
        mode: opt.mode || 0o666,
    });
    p.pipe(stream);
    const promise = new Promise((res, rej) => {
        stream.on('error', rej);
        stream.on('close', res);
        p.on('error', rej);
    });
    addFilesAsync(p, files);
    return promise;
};
const addFilesSync = (p, files) => {
    files.forEach(file => {
        if (file.charAt(0) === '@') {
            (0, list_js_1.list)({
                file: node_path_1.default.resolve(p.cwd, file.slice(1)),
                sync: true,
                noResume: true,
                onReadEntry: entry => p.add(entry),
            });
        }
        else {
            p.add(file);
        }
    });
    p.end();
};
const addFilesAsync = async (p, files) => {
    for (let i = 0; i < files.length; i++) {
        const file = String(files[i]);
        if (file.charAt(0) === '@') {
            await (0, list_js_1.list)({
                file: node_path_1.default.resolve(String(p.cwd), file.slice(1)),
                noResume: true,
                onReadEntry: entry => {
                    p.add(entry);
                },
            });
        }
        else {
            p.add(file);
        }
    }
    p.end();
};
const createSync = (opt, files) => {
    const p = new pack_js_1.PackSync(opt);
    addFilesSync(p, files);
    return p;
};
const createAsync = (opt, files) => {
    const p = new pack_js_1.Pack(opt);
    addFilesAsync(p, files);
    return p;
};
exports.create = (0, make_command_js_1.makeCommand)(createFileSync, createFile, createSync, createAsync, (_opt, files) => {
    if (!files?.length) {
        throw new TypeError('no paths specified to add to archive');
    }
});
//# sourceMappingURL=create.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CwdError = void 0;
class CwdError extends Error {
    path;
    code;
    syscall = 'chdir';
    constructor(path, code) {
        super(`${code}: Cannot cd into '${path}'`);
        this.path = path;
        this.code = code;
    }
    get name() {
        return 'CwdError';
    }
}
exports.CwdError = CwdError;
//# sourceMappingURL=cwd-error.js.map"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.extract = void 0;
// tar -x
const fsm = __importStar(require("@isaacs/fs-minipass"));
const node_fs_1 = __importDefault(require("node:fs"));
const list_js_1 = require("./list.js");
const make_command_js_1 = require("./make-command.js");
const unpack_js_1 = require("./unpack.js");
const extractFileSync = (opt) => {
    const u = new unpack_js_1.UnpackSync(opt);
    const file = opt.file;
    const stat = node_fs_1.default.statSync(file);
    // This trades a zero-byte read() syscall for a stat
    // However, it will usually result in less memory allocation
    const readSize = opt.maxReadSize || 16 * 1024 * 1024;
    const stream = new fsm.ReadStreamSync(file, {
        readSize: readSize,
        size: stat.size,
    });
    stream.pipe(u);
};
const extractFile = (opt, _) => {
    const u = new unpack_js_1.Unpack(opt);
    const readSize = opt.maxReadSize || 16 * 1024 * 1024;
    const file = opt.file;
    const p = new Promise((resolve, reject) => {
        u.on('error', reject);
        u.on('close', resolve);
        // This trades a zero-byte read() syscall for a stat
        // However, it will usually result in less memory allocation
        node_fs_1.default.stat(file, (er, stat) => {
            if (er) {
                reject(er);
            }
            else {
                const stream = new fsm.ReadStream(file, {
                    readSize: readSize,
                    size: stat.size,
                });
                stream.on('error', reject);
                stream.pipe(u);
            }
        });
    });
    return p;
};
exports.extract = (0, make_command_js_1.makeCommand)(extractFileSync, extractFile, opt => new unpack_js_1.UnpackSync(opt), opt => new unpack_js_1.Unpack(opt), (opt, files) => {
    if (files?.length)
        (0, list_js_1.filesFilter)(opt, files);
});
//# sourceMappingURL=extract.js.map"use strict";
// Get the appropriate flag to use for creating files
// We use fmap on Windows platforms for files less than
// 512kb.  This is a fairly low limit, but avoids making
// things slower in some cases.  Since most of what this
// library is used for is extracting tarballs of many
// relatively small files in npm packages and the like,
// it can be a big boost on Windows platforms.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getWriteFlag = void 0;
const fs_1 = __importDefault(require("fs"));
const platform = process.env.__FAKE_PLATFORM__ || process.platform;
const isWindows = platform === 'win32';
/* c8 ignore start */
const { O_CREAT, O_TRUNC, O_WRONLY } = fs_1.default.constants;
const UV_FS_O_FILEMAP = Number(process.env.__FAKE_FS_O_FILENAME__) ||
    fs_1.default.constants.UV_FS_O_FILEMAP ||
    0;
/* c8 ignore stop */
const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP;
const fMapLimit = 512 * 1024;
const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY;
exports.getWriteFlag = !fMapEnabled ?
    () => 'w'
    : (size) => (size < fMapLimit ? fMapFlag : 'w');
//# sourceMappingURL=get-write-flag.js.map"use strict";
// parse a 512-byte header block to a data object, or vice-versa
// encode returns `true` if a pax extended header is needed, because
// the data could not be faithfully encoded in a simple header.
// (Also, check header.needPax to see if it needs a pax header.)
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Header = void 0;
const node_path_1 = require("node:path");
const large = __importStar(require("./large-numbers.js"));
const types = __importStar(require("./types.js"));
class Header {
    cksumValid = false;
    needPax = false;
    nullBlock = false;
    block;
    path;
    mode;
    uid;
    gid;
    size;
    cksum;
    #type = 'Unsupported';
    linkpath;
    uname;
    gname;
    devmaj = 0;
    devmin = 0;
    atime;
    ctime;
    mtime;
    charset;
    comment;
    constructor(data, off = 0, ex, gex) {
        if (Buffer.isBuffer(data)) {
            this.decode(data, off || 0, ex, gex);
        }
        else if (data) {
            this.#slurp(data);
        }
    }
    decode(buf, off, ex, gex) {
        if (!off) {
            off = 0;
        }
        if (!buf || !(buf.length >= off + 512)) {
            throw new Error('need 512 bytes for header');
        }
        this.path = decString(buf, off, 100);
        this.mode = decNumber(buf, off + 100, 8);
        this.uid = decNumber(buf, off + 108, 8);
        this.gid = decNumber(buf, off + 116, 8);
        this.size = decNumber(buf, off + 124, 12);
        this.mtime = decDate(buf, off + 136, 12);
        this.cksum = decNumber(buf, off + 148, 12);
        // if we have extended or global extended headers, apply them now
        // See https://github.com/npm/node-tar/pull/187
        // Apply global before local, so it overrides
        if (gex)
            this.#slurp(gex, true);
        if (ex)
            this.#slurp(ex);
        // old tar versions marked dirs as a file with a trailing /
        const t = decString(buf, off + 156, 1);
        if (types.isCode(t)) {
            this.#type = t || '0';
        }
        if (this.#type === '0' && this.path.slice(-1) === '/') {
            this.#type = '5';
        }
        // tar implementations sometimes incorrectly put the stat(dir).size
        // as the size in the tarball, even though Directory entries are
        // not able to have any body at all.  In the very rare chance that
        // it actually DOES have a body, we weren't going to do anything with
        // it anyway, and it'll just be a warning about an invalid header.
        if (this.#type === '5') {
            this.size = 0;
        }
        this.linkpath = decString(buf, off + 157, 100);
        if (buf.subarray(off + 257, off + 265).toString() ===
            'ustar\u000000') {
            this.uname = decString(buf, off + 265, 32);
            this.gname = decString(buf, off + 297, 32);
            /* c8 ignore start */
            this.devmaj = decNumber(buf, off + 329, 8) ?? 0;
            this.devmin = decNumber(buf, off + 337, 8) ?? 0;
            /* c8 ignore stop */
            if (buf[off + 475] !== 0) {
                // definitely a prefix, definitely >130 chars.
                const prefix = decString(buf, off + 345, 155);
                this.path = prefix + '/' + this.path;
            }
            else {
                const prefix = decString(buf, off + 345, 130);
                if (prefix) {
                    this.path = prefix + '/' + this.path;
                }
                this.atime = decDate(buf, off + 476, 12);
                this.ctime = decDate(buf, off + 488, 12);
            }
        }
        let sum = 8 * 0x20;
        for (let i = off; i < off + 148; i++) {
            sum += buf[i];
        }
        for (let i = off + 156; i < off + 512; i++) {
            sum += buf[i];
        }
        this.cksumValid = sum === this.cksum;
        if (this.cksum === undefined && sum === 8 * 0x20) {
            this.nullBlock = true;
        }
    }
    #slurp(ex, gex = false) {
        Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => {
            // we slurp in everything except for the path attribute in
            // a global extended header, because that's weird. Also, any
            // null/undefined values are ignored.
            return !(v === null ||
                v === undefined ||
                (k === 'path' && gex) ||
                (k === 'linkpath' && gex) ||
                k === 'global');
        })));
    }
    encode(buf, off = 0) {
        if (!buf) {
            buf = this.block = Buffer.alloc(512);
        }
        if (this.#type === 'Unsupported') {
            this.#type = '0';
        }
        if (!(buf.length >= off + 512)) {
            throw new Error('need 512 bytes for header');
        }
        const prefixSize = this.ctime || this.atime ? 130 : 155;
        const split = splitPrefix(this.path || '', prefixSize);
        const path = split[0];
        const prefix = split[1];
        this.needPax = !!split[2];
        this.needPax = encString(buf, off, 100, path) || this.needPax;
        this.needPax =
            encNumber(buf, off + 100, 8, this.mode) || this.needPax;
        this.needPax =
            encNumber(buf, off + 108, 8, this.uid) || this.needPax;
        this.needPax =
            encNumber(buf, off + 116, 8, this.gid) || this.needPax;
        this.needPax =
            encNumber(buf, off + 124, 12, this.size) || this.needPax;
        this.needPax =
            encDate(buf, off + 136, 12, this.mtime) || this.needPax;
        buf[off + 156] = this.#type.charCodeAt(0);
        this.needPax =
            encString(buf, off + 157, 100, this.linkpath) || this.needPax;
        buf.write('ustar\u000000', off + 257, 8);
        this.needPax =
            encString(buf, off + 265, 32, this.uname) || this.needPax;
        this.needPax =
            encString(buf, off + 297, 32, this.gname) || this.needPax;
        this.needPax =
            encNumber(buf, off + 329, 8, this.devmaj) || this.needPax;
        this.needPax =
            encNumber(buf, off + 337, 8, this.devmin) || this.needPax;
        this.needPax =
            encString(buf, off + 345, prefixSize, prefix) || this.needPax;
        if (buf[off + 475] !== 0) {
            this.needPax =
                encString(buf, off + 345, 155, prefix) || this.needPax;
        }
        else {
            this.needPax =
                encString(buf, off + 345, 130, prefix) || this.needPax;
            this.needPax =
                encDate(buf, off + 476, 12, this.atime) || this.needPax;
            this.needPax =
                encDate(buf, off + 488, 12, this.ctime) || this.needPax;
        }
        let sum = 8 * 0x20;
        for (let i = off; i < off + 148; i++) {
            sum += buf[i];
        }
        for (let i = off + 156; i < off + 512; i++) {
            sum += buf[i];
        }
        this.cksum = sum;
        encNumber(buf, off + 148, 8, this.cksum);
        this.cksumValid = true;
        return this.needPax;
    }
    get type() {
        return (this.#type === 'Unsupported' ?
            this.#type
            : types.name.get(this.#type));
    }
    get typeKey() {
        return this.#type;
    }
    set type(type) {
        const c = String(types.code.get(type));
        if (types.isCode(c) || c === 'Unsupported') {
            this.#type = c;
        }
        else if (types.isCode(type)) {
            this.#type = type;
        }
        else {
            throw new TypeError('invalid entry type: ' + type);
        }
    }
}
exports.Header = Header;
const splitPrefix = (p, prefixSize) => {
    const pathSize = 100;
    let pp = p;
    let prefix = '';
    let ret = undefined;
    const root = node_path_1.posix.parse(p).root || '.';
    if (Buffer.byteLength(pp) < pathSize) {
        ret = [pp, prefix, false];
    }
    else {
        // first set prefix to the dir, and path to the base
        prefix = node_path_1.posix.dirname(pp);
        pp = node_path_1.posix.basename(pp);
        do {
            if (Buffer.byteLength(pp) <= pathSize &&
                Buffer.byteLength(prefix) <= prefixSize) {
                // both fit!
                ret = [pp, prefix, false];
            }
            else if (Buffer.byteLength(pp) > pathSize &&
                Buffer.byteLength(prefix) <= prefixSize) {
                // prefix fits in prefix, but path doesn't fit in path
                ret = [pp.slice(0, pathSize - 1), prefix, true];
            }
            else {
                // make path take a bit from prefix
                pp = node_path_1.posix.join(node_path_1.posix.basename(prefix), pp);
                prefix = node_path_1.posix.dirname(prefix);
            }
        } while (prefix !== root && ret === undefined);
        // at this point, found no resolution, just truncate
        if (!ret) {
            ret = [p.slice(0, pathSize - 1), '', true];
        }
    }
    return ret;
};
const decString = (buf, off, size) => buf
    .subarray(off, off + size)
    .toString('utf8')
    .replace(/\0.*/, '');
const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size));
const numToDate = (num) => num === undefined ? undefined : new Date(num * 1000);
const decNumber = (buf, off, size) => Number(buf[off]) & 0x80 ?
    large.parse(buf.subarray(off, off + size))
    : decSmallNumber(buf, off, size);
const nanUndef = (value) => (isNaN(value) ? undefined : value);
const decSmallNumber = (buf, off, size) => nanUndef(parseInt(buf
    .subarray(off, off + size)
    .toString('utf8')
    .replace(/\0.*$/, '')
    .trim(), 8));
// the maximum encodable as a null-terminated octal, by field size
const MAXNUM = {
    12: 0o77777777777,
    8: 0o7777777,
};
const encNumber = (buf, off, size, num) => num === undefined ? false
    : num > MAXNUM[size] || num < 0 ?
        (large.encode(num, buf.subarray(off, off + size)), true)
        : (encSmallNumber(buf, off, size, num), false);
const encSmallNumber = (buf, off, size, num) => buf.write(octalString(num, size), off, size, 'ascii');
const octalString = (num, size) => padOctal(Math.floor(num).toString(8), size);
const padOctal = (str, size) => (str.length === size - 1 ?
    str
    : new Array(size - str.length - 1).join('0') + str + ' ') + '\0';
const encDate = (buf, off, size, date) => date === undefined ? false : (encNumber(buf, off, size, date.getTime() / 1000));
// enough to fill the longest string we've got
const NULLS = new Array(156).join('\0');
// pad with nulls, return true if it's longer or non-ascii
const encString = (buf, off, size, str) => str === undefined ? false : ((buf.write(str + NULLS, off, size, 'utf8'),
    str.length !== Buffer.byteLength(str) || str.length > size));
//# sourceMappingURL=header.js.map"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.u = exports.types = exports.r = exports.t = exports.x = exports.c = void 0;
__exportStar(require("./create.js"), exports);
var create_js_1 = require("./create.js");
Object.defineProperty(exports, "c", { enumerable: true, get: function () { return create_js_1.create; } });
__exportStar(require("./extract.js"), exports);
var extract_js_1 = require("./extract.js");
Object.defineProperty(exports, "x", { enumerable: true, get: function () { return extract_js_1.extract; } });
__exportStar(require("./header.js"), exports);
__exportStar(require("./list.js"), exports);
var list_js_1 = require("./list.js");
Object.defineProperty(exports, "t", { enumerable: true, get: function () { return list_js_1.list; } });
// classes
__exportStar(require("./pack.js"), exports);
__exportStar(require("./parse.js"), exports);
__exportStar(require("./pax.js"), exports);
__exportStar(require("./read-entry.js"), exports);
__exportStar(require("./replace.js"), exports);
var replace_js_1 = require("./replace.js");
Object.defineProperty(exports, "r", { enumerable: true, get: function () { return replace_js_1.replace; } });
exports.types = __importStar(require("./types.js"));
__exportStar(require("./unpack.js"), exports);
__exportStar(require("./update.js"), exports);
var update_js_1 = require("./update.js");
Object.defineProperty(exports, "u", { enumerable: true, get: function () { return update_js_1.update; } });
__exportStar(require("./write-entry.js"), exports);
//# sourceMappingURL=index.js.map"use strict";
// Tar can encode large and negative numbers using a leading byte of
// 0xff for negative, and 0x80 for positive.
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = exports.encode = void 0;
const encode = (num, buf) => {
    if (!Number.isSafeInteger(num)) {
        // The number is so large that javascript cannot represent it with integer
        // precision.
        throw Error('cannot encode number outside of javascript safe integer range');
    }
    else if (num < 0) {
        encodeNegative(num, buf);
    }
    else {
        encodePositive(num, buf);
    }
    return buf;
};
exports.encode = encode;
const encodePositive = (num, buf) => {
    buf[0] = 0x80;
    for (var i = buf.length; i > 1; i--) {
        buf[i - 1] = num & 0xff;
        num = Math.floor(num / 0x100);
    }
};
const encodeNegative = (num, buf) => {
    buf[0] = 0xff;
    var flipped = false;
    num = num * -1;
    for (var i = buf.length; i > 1; i--) {
        var byte = num & 0xff;
        num = Math.floor(num / 0x100);
        if (flipped) {
            buf[i - 1] = onesComp(byte);
        }
        else if (byte === 0) {
            buf[i - 1] = 0;
        }
        else {
            flipped = true;
            buf[i - 1] = twosComp(byte);
        }
    }
};
const parse = (buf) => {
    const pre = buf[0];
    const value = pre === 0x80 ? pos(buf.subarray(1, buf.length))
        : pre === 0xff ? twos(buf)
            : null;
    if (value === null) {
        throw Error('invalid base256 encoding');
    }
    if (!Number.isSafeInteger(value)) {
        // The number is so large that javascript cannot represent it with integer
        // precision.
        throw Error('parsed number outside of javascript safe integer range');
    }
    return value;
};
exports.parse = parse;
const twos = (buf) => {
    var len = buf.length;
    var sum = 0;
    var flipped = false;
    for (var i = len - 1; i > -1; i--) {
        var byte = Number(buf[i]);
        var f;
        if (flipped) {
            f = onesComp(byte);
        }
        else if (byte === 0) {
            f = byte;
        }
        else {
            flipped = true;
            f = twosComp(byte);
        }
        if (f !== 0) {
            sum -= f * Math.pow(256, len - i - 1);
        }
    }
    return sum;
};
const pos = (buf) => {
    var len = buf.length;
    var sum = 0;
    for (var i = len - 1; i > -1; i--) {
        var byte = Number(buf[i]);
        if (byte !== 0) {
            sum += byte * Math.pow(256, len - i - 1);
        }
    }
    return sum;
};
const onesComp = (byte) => (0xff ^ byte) & 0xff;
const twosComp = (byte) => ((0xff ^ byte) + 1) & 0xff;
//# sourceMappingURL=large-numbers.js.map"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.list = exports.filesFilter = void 0;
// tar -t
const fsm = __importStar(require("@isaacs/fs-minipass"));
const node_fs_1 = __importDefault(require("node:fs"));
const path_1 = require("path");
const make_command_js_1 = require("./make-command.js");
const parse_js_1 = require("./parse.js");
const strip_trailing_slashes_js_1 = require("./strip-trailing-slashes.js");
const onReadEntryFunction = (opt) => {
    const onReadEntry = opt.onReadEntry;
    opt.onReadEntry =
        onReadEntry ?
            e => {
                onReadEntry(e);
                e.resume();
            }
            : e => e.resume();
};
// construct a filter that limits the file entries listed
// include child entries if a dir is included
const filesFilter = (opt, files) => {
    const map = new Map(files.map(f => [(0, strip_trailing_slashes_js_1.stripTrailingSlashes)(f), true]));
    const filter = opt.filter;
    const mapHas = (file, r = '') => {
        const root = r || (0, path_1.parse)(file).root || '.';
        let ret;
        if (file === root)
            ret = false;
        else {
            const m = map.get(file);
            if (m !== undefined) {
                ret = m;
            }
            else {
                ret = mapHas((0, path_1.dirname)(file), root);
            }
        }
        map.set(file, ret);
        return ret;
    };
    opt.filter =
        filter ?
            (file, entry) => filter(file, entry) && mapHas((0, strip_trailing_slashes_js_1.stripTrailingSlashes)(file))
            : file => mapHas((0, strip_trailing_slashes_js_1.stripTrailingSlashes)(file));
};
exports.filesFilter = filesFilter;
const listFileSync = (opt) => {
    const p = new parse_js_1.Parser(opt);
    const file = opt.file;
    let fd;
    try {
        const stat = node_fs_1.default.statSync(file);
        const readSize = opt.maxReadSize || 16 * 1024 * 1024;
        if (stat.size < readSize) {
            p.end(node_fs_1.default.readFileSync(file));
        }
        else {
            let pos = 0;
            const buf = Buffer.allocUnsafe(readSize);
            fd = node_fs_1.default.openSync(file, 'r');
            while (pos < stat.size) {
                const bytesRead = node_fs_1.default.readSync(fd, buf, 0, readSize, pos);
                pos += bytesRead;
                p.write(buf.subarray(0, bytesRead));
            }
            p.end();
        }
    }
    finally {
        if (typeof fd === 'number') {
            try {
                node_fs_1.default.closeSync(fd);
                /* c8 ignore next */
            }
            catch (er) { }
        }
    }
};
const listFile = (opt, _files) => {
    const parse = new parse_js_1.Parser(opt);
    const readSize = opt.maxReadSize || 16 * 1024 * 1024;
    const file = opt.file;
    const p = new Promise((resolve, reject) => {
        parse.on('error', reject);
        parse.on('end', resolve);
        node_fs_1.default.stat(file, (er, stat) => {
            if (er) {
                reject(er);
            }
            else {
                const stream = new fsm.ReadStream(file, {
                    readSize: readSize,
                    size: stat.size,
                });
                stream.on('error', reject);
                stream.pipe(parse);
            }
        });
    });
    return p;
};
exports.list = (0, make_command_js_1.makeCommand)(listFileSync, listFile, opt => new parse_js_1.Parser(opt), opt => new parse_js_1.Parser(opt), (opt, files) => {
    if (files?.length)
        (0, exports.filesFilter)(opt, files);
    if (!opt.noResume)
        onReadEntryFunction(opt);
});
//# sourceMappingURL=list.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeCommand = void 0;
const options_js_1 = require("./options.js");
const makeCommand = (syncFile, asyncFile, syncNoFile, asyncNoFile, validate) => {
    return Object.assign((opt_ = [], entries, cb) => {
        if (Array.isArray(opt_)) {
            entries = opt_;
            opt_ = {};
        }
        if (typeof entries === 'function') {
            cb = entries;
            entries = undefined;
        }
        if (!entries) {
            entries = [];
        }
        else {
            entries = Array.from(entries);
        }
        const opt = (0, options_js_1.dealias)(opt_);
        validate?.(opt, entries);
        if ((0, options_js_1.isSyncFile)(opt)) {
            if (typeof cb === 'function') {
                throw new TypeError('callback not supported for sync tar functions');
            }
            return syncFile(opt, entries);
        }
        else if ((0, options_js_1.isAsyncFile)(opt)) {
            const p = asyncFile(opt, entries);
            // weirdness to make TS happy
            const c = cb ? cb : undefined;
            return c ? p.then(() => c(), c) : p;
        }
        else if ((0, options_js_1.isSyncNoFile)(opt)) {
            if (typeof cb === 'function') {
                throw new TypeError('callback not supported for sync tar functions');
            }
            return syncNoFile(opt, entries);
        }
        else if ((0, options_js_1.isAsyncNoFile)(opt)) {
            if (typeof cb === 'function') {
                throw new TypeError('callback only supported with file option');
            }
            return asyncNoFile(opt, entries);
            /* c8 ignore start */
        }
        else {
            throw new Error('impossible options??');
        }
        /* c8 ignore stop */
    }, {
        syncFile,
        asyncFile,
        syncNoFile,
        asyncNoFile,
        validate,
    });
};
exports.makeCommand = makeCommand;
//# sourceMappingURL=make-command.js.map"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mkdirSync = exports.mkdir = void 0;
const chownr_1 = require("chownr");
const fs_1 = __importDefault(require("fs"));
const mkdirp_1 = require("mkdirp");
const node_path_1 = __importDefault(require("node:path"));
const cwd_error_js_1 = require("./cwd-error.js");
const normalize_windows_path_js_1 = require("./normalize-windows-path.js");
const symlink_error_js_1 = require("./symlink-error.js");
const cGet = (cache, key) => cache.get((0, normalize_windows_path_js_1.normalizeWindowsPath)(key));
const cSet = (cache, key, val) => cache.set((0, normalize_windows_path_js_1.normalizeWindowsPath)(key), val);
const checkCwd = (dir, cb) => {
    fs_1.default.stat(dir, (er, st) => {
        if (er || !st.isDirectory()) {
            er = new cwd_error_js_1.CwdError(dir, er?.code || 'ENOTDIR');
        }
        cb(er);
    });
};
/**
 * Wrapper around mkdirp for tar's needs.
 *
 * The main purpose is to avoid creating directories if we know that
 * they already exist (and track which ones exist for this purpose),
 * and prevent entries from being extracted into symlinked folders,
 * if `preservePaths` is not set.
 */
const mkdir = (dir, opt, cb) => {
    dir = (0, normalize_windows_path_js_1.normalizeWindowsPath)(dir);
    // if there's any overlap between mask and mode,
    // then we'll need an explicit chmod
    /* c8 ignore next */
    const umask = opt.umask ?? 0o22;
    const mode = opt.mode | 0o0700;
    const needChmod = (mode & umask) !== 0;
    const uid = opt.uid;
    const gid = opt.gid;
    const doChown = typeof uid === 'number' &&
        typeof gid === 'number' &&
        (uid !== opt.processUid || gid !== opt.processGid);
    const preserve = opt.preserve;
    const unlink = opt.unlink;
    const cache = opt.cache;
    const cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.cwd);
    const done = (er, created) => {
        if (er) {
            cb(er);
        }
        else {
            cSet(cache, dir, true);
            if (created && doChown) {
                (0, chownr_1.chownr)(created, uid, gid, er => done(er));
            }
            else if (needChmod) {
                fs_1.default.chmod(dir, mode, cb);
            }
            else {
                cb();
            }
        }
    };
    if (cache && cGet(cache, dir) === true) {
        return done();
    }
    if (dir === cwd) {
        return checkCwd(dir, done);
    }
    if (preserve) {
        return (0, mkdirp_1.mkdirp)(dir, { mode }).then(made => done(null, made ?? undefined), // oh, ts
        done);
    }
    const sub = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.relative(cwd, dir));
    const parts = sub.split('/');
    mkdir_(cwd, parts, mode, cache, unlink, cwd, undefined, done);
};
exports.mkdir = mkdir;
const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => {
    if (!parts.length) {
        return cb(null, created);
    }
    const p = parts.shift();
    const part = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(base + '/' + p));
    if (cGet(cache, part)) {
        return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb);
    }
    fs_1.default.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb));
};
const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => (er) => {
    if (er) {
        fs_1.default.lstat(part, (statEr, st) => {
            if (statEr) {
                statEr.path =
                    statEr.path && (0, normalize_windows_path_js_1.normalizeWindowsPath)(statEr.path);
                cb(statEr);
            }
            else if (st.isDirectory()) {
                mkdir_(part, parts, mode, cache, unlink, cwd, created, cb);
            }
            else if (unlink) {
                fs_1.default.unlink(part, er => {
                    if (er) {
                        return cb(er);
                    }
                    fs_1.default.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb));
                });
            }
            else if (st.isSymbolicLink()) {
                return cb(new symlink_error_js_1.SymlinkError(part, part + '/' + parts.join('/')));
            }
            else {
                cb(er);
            }
        });
    }
    else {
        created = created || part;
        mkdir_(part, parts, mode, cache, unlink, cwd, created, cb);
    }
};
const checkCwdSync = (dir) => {
    let ok = false;
    let code = undefined;
    try {
        ok = fs_1.default.statSync(dir).isDirectory();
    }
    catch (er) {
        code = er?.code;
    }
    finally {
        if (!ok) {
            throw new cwd_error_js_1.CwdError(dir, code ?? 'ENOTDIR');
        }
    }
};
const mkdirSync = (dir, opt) => {
    dir = (0, normalize_windows_path_js_1.normalizeWindowsPath)(dir);
    // if there's any overlap between mask and mode,
    // then we'll need an explicit chmod
    /* c8 ignore next */
    const umask = opt.umask ?? 0o22;
    const mode = opt.mode | 0o700;
    const needChmod = (mode & umask) !== 0;
    const uid = opt.uid;
    const gid = opt.gid;
    const doChown = typeof uid === 'number' &&
        typeof gid === 'number' &&
        (uid !== opt.processUid || gid !== opt.processGid);
    const preserve = opt.preserve;
    const unlink = opt.unlink;
    const cache = opt.cache;
    const cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.cwd);
    const done = (created) => {
        cSet(cache, dir, true);
        if (created && doChown) {
            (0, chownr_1.chownrSync)(created, uid, gid);
        }
        if (needChmod) {
            fs_1.default.chmodSync(dir, mode);
        }
    };
    if (cache && cGet(cache, dir) === true) {
        return done();
    }
    if (dir === cwd) {
        checkCwdSync(cwd);
        return done();
    }
    if (preserve) {
        return done((0, mkdirp_1.mkdirpSync)(dir, mode) ?? undefined);
    }
    const sub = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.relative(cwd, dir));
    const parts = sub.split('/');
    let created = undefined;
    for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) {
        part = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(part));
        if (cGet(cache, part)) {
            continue;
        }
        try {
            fs_1.default.mkdirSync(part, mode);
            created = created || part;
            cSet(cache, part, true);
        }
        catch (er) {
            const st = fs_1.default.lstatSync(part);
            if (st.isDirectory()) {
                cSet(cache, part, true);
                continue;
            }
            else if (unlink) {
                fs_1.default.unlinkSync(part);
                fs_1.default.mkdirSync(part, mode);
                created = created || part;
                cSet(cache, part, true);
                continue;
            }
            else if (st.isSymbolicLink()) {
                return new symlink_error_js_1.SymlinkError(part, part + '/' + parts.join('/'));
            }
        }
    }
    return done(created);
};
exports.mkdirSync = mkdirSync;
//# sourceMappingURL=mkdir.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.modeFix = void 0;
const modeFix = (mode, isDir, portable) => {
    mode &= 0o7777;
    // in portable mode, use the minimum reasonable umask
    // if this system creates files with 0o664 by default
    // (as some linux distros do), then we'll write the
    // archive with 0o644 instead.  Also, don't ever create
    // a file that is not readable/writable by the owner.
    if (portable) {
        mode = (mode | 0o600) & ~0o22;
    }
    // if dirs are readable, then they should be listable
    if (isDir) {
        if (mode & 0o400) {
            mode |= 0o100;
        }
        if (mode & 0o40) {
            mode |= 0o10;
        }
        if (mode & 0o4) {
            mode |= 0o1;
        }
    }
    return mode;
};
exports.modeFix = modeFix;
//# sourceMappingURL=mode-fix.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeUnicode = void 0;
// warning: extremely hot code path.
// This has been meticulously optimized for use
// within npm install on large package trees.
// Do not edit without careful benchmarking.
const normalizeCache = Object.create(null);
const { hasOwnProperty } = Object.prototype;
const normalizeUnicode = (s) => {
    if (!hasOwnProperty.call(normalizeCache, s)) {
        normalizeCache[s] = s.normalize('NFD');
    }
    return normalizeCache[s];
};
exports.normalizeUnicode = normalizeUnicode;
//# sourceMappingURL=normalize-unicode.js.map"use strict";
// on windows, either \ or / are valid directory separators.
// on unix, \ is a valid character in filenames.
// so, on windows, and only on windows, we replace all \ chars with /,
// so that we can use / as our one and only directory separator char.
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeWindowsPath = void 0;
const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
exports.normalizeWindowsPath = platform !== 'win32' ?
    (p) => p
    : (p) => p && p.replace(/\\/g, '/');
//# sourceMappingURL=normalize-windows-path.js.map"use strict";
// turn tar(1) style args like `C` into the more verbose things like `cwd`
Object.defineProperty(exports, "__esModule", { value: true });
exports.dealias = exports.isNoFile = exports.isFile = exports.isAsync = exports.isSync = exports.isAsyncNoFile = exports.isSyncNoFile = exports.isAsyncFile = exports.isSyncFile = void 0;
const argmap = new Map([
    ['C', 'cwd'],
    ['f', 'file'],
    ['z', 'gzip'],
    ['P', 'preservePaths'],
    ['U', 'unlink'],
    ['strip-components', 'strip'],
    ['stripComponents', 'strip'],
    ['keep-newer', 'newer'],
    ['keepNewer', 'newer'],
    ['keep-newer-files', 'newer'],
    ['keepNewerFiles', 'newer'],
    ['k', 'keep'],
    ['keep-existing', 'keep'],
    ['keepExisting', 'keep'],
    ['m', 'noMtime'],
    ['no-mtime', 'noMtime'],
    ['p', 'preserveOwner'],
    ['L', 'follow'],
    ['h', 'follow'],
    ['onentry', 'onReadEntry'],
]);
const isSyncFile = (o) => !!o.sync && !!o.file;
exports.isSyncFile = isSyncFile;
const isAsyncFile = (o) => !o.sync && !!o.file;
exports.isAsyncFile = isAsyncFile;
const isSyncNoFile = (o) => !!o.sync && !o.file;
exports.isSyncNoFile = isSyncNoFile;
const isAsyncNoFile = (o) => !o.sync && !o.file;
exports.isAsyncNoFile = isAsyncNoFile;
const isSync = (o) => !!o.sync;
exports.isSync = isSync;
const isAsync = (o) => !o.sync;
exports.isAsync = isAsync;
const isFile = (o) => !!o.file;
exports.isFile = isFile;
const isNoFile = (o) => !o.file;
exports.isNoFile = isNoFile;
const dealiasKey = (k) => {
    const d = argmap.get(k);
    if (d)
        return d;
    return k;
};
const dealias = (opt = {}) => {
    if (!opt)
        return {};
    const result = {};
    for (const [key, v] of Object.entries(opt)) {
        // TS doesn't know that aliases are going to always be the same type
        const k = dealiasKey(key);
        result[k] = v;
    }
    // affordance for deprecated noChmod -> chmod
    if (result.chmod === undefined && result.noChmod === false) {
        result.chmod = true;
    }
    delete result.noChmod;
    return result;
};
exports.dealias = dealias;
//# sourceMappingURL=options.js.map"use strict";
// A readable tar stream creator
// Technically, this is a transform stream that you write paths into,
// and tar format comes out of.
// The `add()` method is like `write()` but returns this,
// and end() return `this` as well, so you can
// do `new Pack(opt).add('files').add('dir').end().pipe(output)
// You could also do something like:
// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackSync = exports.Pack = exports.PackJob = void 0;
const fs_1 = __importDefault(require("fs"));
const write_entry_js_1 = require("./write-entry.js");
class PackJob {
    path;
    absolute;
    entry;
    stat;
    readdir;
    pending = false;
    ignore = false;
    piped = false;
    constructor(path, absolute) {
        this.path = path || './';
        this.absolute = absolute;
    }
}
exports.PackJob = PackJob;
const minipass_1 = require("minipass");
const zlib = __importStar(require("minizlib"));
const yallist_1 = require("yallist");
const read_entry_js_1 = require("./read-entry.js");
const warn_method_js_1 = require("./warn-method.js");
const EOF = Buffer.alloc(1024);
const ONSTAT = Symbol('onStat');
const ENDED = Symbol('ended');
const QUEUE = Symbol('queue');
const CURRENT = Symbol('current');
const PROCESS = Symbol('process');
const PROCESSING = Symbol('processing');
const PROCESSJOB = Symbol('processJob');
const JOBS = Symbol('jobs');
const JOBDONE = Symbol('jobDone');
const ADDFSENTRY = Symbol('addFSEntry');
const ADDTARENTRY = Symbol('addTarEntry');
const STAT = Symbol('stat');
const READDIR = Symbol('readdir');
const ONREADDIR = Symbol('onreaddir');
const PIPE = Symbol('pipe');
const ENTRY = Symbol('entry');
const ENTRYOPT = Symbol('entryOpt');
const WRITEENTRYCLASS = Symbol('writeEntryClass');
const WRITE = Symbol('write');
const ONDRAIN = Symbol('ondrain');
const path_1 = __importDefault(require("path"));
const normalize_windows_path_js_1 = require("./normalize-windows-path.js");
class Pack extends minipass_1.Minipass {
    opt;
    cwd;
    maxReadSize;
    preservePaths;
    strict;
    noPax;
    prefix;
    linkCache;
    statCache;
    file;
    portable;
    zip;
    readdirCache;
    noDirRecurse;
    follow;
    noMtime;
    mtime;
    filter;
    jobs;
    [WRITEENTRYCLASS];
    onWriteEntry;
    [QUEUE];
    [JOBS] = 0;
    [PROCESSING] = false;
    [ENDED] = false;
    constructor(opt = {}) {
        //@ts-ignore
        super();
        this.opt = opt;
        this.file = opt.file || '';
        this.cwd = opt.cwd || process.cwd();
        this.maxReadSize = opt.maxReadSize;
        this.preservePaths = !!opt.preservePaths;
        this.strict = !!opt.strict;
        this.noPax = !!opt.noPax;
        this.prefix = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.prefix || '');
        this.linkCache = opt.linkCache || new Map();
        this.statCache = opt.statCache || new Map();
        this.readdirCache = opt.readdirCache || new Map();
        this.onWriteEntry = opt.onWriteEntry;
        this[WRITEENTRYCLASS] = write_entry_js_1.WriteEntry;
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        this.portable = !!opt.portable;
        if (opt.gzip || opt.brotli) {
            if (opt.gzip && opt.brotli) {
                throw new TypeError('gzip and brotli are mutually exclusive');
            }
            if (opt.gzip) {
                if (typeof opt.gzip !== 'object') {
                    opt.gzip = {};
                }
                if (this.portable) {
                    opt.gzip.portable = true;
                }
                this.zip = new zlib.Gzip(opt.gzip);
            }
            if (opt.brotli) {
                if (typeof opt.brotli !== 'object') {
                    opt.brotli = {};
                }
                this.zip = new zlib.BrotliCompress(opt.brotli);
            }
            /* c8 ignore next */
            if (!this.zip)
                throw new Error('impossible');
            const zip = this.zip;
            zip.on('data', chunk => super.write(chunk));
            zip.on('end', () => super.end());
            zip.on('drain', () => this[ONDRAIN]());
            this.on('resume', () => zip.resume());
        }
        else {
            this.on('drain', this[ONDRAIN]);
        }
        this.noDirRecurse = !!opt.noDirRecurse;
        this.follow = !!opt.follow;
        this.noMtime = !!opt.noMtime;
        if (opt.mtime)
            this.mtime = opt.mtime;
        this.filter =
            typeof opt.filter === 'function' ? opt.filter : () => true;
        this[QUEUE] = new yallist_1.Yallist();
        this[JOBS] = 0;
        this.jobs = Number(opt.jobs) || 4;
        this[PROCESSING] = false;
        this[ENDED] = false;
    }
    [WRITE](chunk) {
        return super.write(chunk);
    }
    add(path) {
        this.write(path);
        return this;
    }
    end(path, encoding, cb) {
        /* c8 ignore start */
        if (typeof path === 'function') {
            cb = path;
            path = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (path) {
            this.add(path);
        }
        this[ENDED] = true;
        this[PROCESS]();
        /* c8 ignore next */
        if (cb)
            cb();
        return this;
    }
    write(path) {
        if (this[ENDED]) {
            throw new Error('write after end');
        }
        if (path instanceof read_entry_js_1.ReadEntry) {
            this[ADDTARENTRY](path);
        }
        else {
            this[ADDFSENTRY](path);
        }
        return this.flowing;
    }
    [ADDTARENTRY](p) {
        const absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(path_1.default.resolve(this.cwd, p.path));
        // in this case, we don't have to wait for the stat
        if (!this.filter(p.path, p)) {
            p.resume();
        }
        else {
            const job = new PackJob(p.path, absolute);
            job.entry = new write_entry_js_1.WriteEntryTar(p, this[ENTRYOPT](job));
            job.entry.on('end', () => this[JOBDONE](job));
            this[JOBS] += 1;
            this[QUEUE].push(job);
        }
        this[PROCESS]();
    }
    [ADDFSENTRY](p) {
        const absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(path_1.default.resolve(this.cwd, p));
        this[QUEUE].push(new PackJob(p, absolute));
        this[PROCESS]();
    }
    [STAT](job) {
        job.pending = true;
        this[JOBS] += 1;
        const stat = this.follow ? 'stat' : 'lstat';
        fs_1.default[stat](job.absolute, (er, stat) => {
            job.pending = false;
            this[JOBS] -= 1;
            if (er) {
                this.emit('error', er);
            }
            else {
                this[ONSTAT](job, stat);
            }
        });
    }
    [ONSTAT](job, stat) {
        this.statCache.set(job.absolute, stat);
        job.stat = stat;
        // now we have the stat, we can filter it.
        if (!this.filter(job.path, stat)) {
            job.ignore = true;
        }
        this[PROCESS]();
    }
    [READDIR](job) {
        job.pending = true;
        this[JOBS] += 1;
        fs_1.default.readdir(job.absolute, (er, entries) => {
            job.pending = false;
            this[JOBS] -= 1;
            if (er) {
                return this.emit('error', er);
            }
            this[ONREADDIR](job, entries);
        });
    }
    [ONREADDIR](job, entries) {
        this.readdirCache.set(job.absolute, entries);
        job.readdir = entries;
        this[PROCESS]();
    }
    [PROCESS]() {
        if (this[PROCESSING]) {
            return;
        }
        this[PROCESSING] = true;
        for (let w = this[QUEUE].head; !!w && this[JOBS] < this.jobs; w = w.next) {
            this[PROCESSJOB](w.value);
            if (w.value.ignore) {
                const p = w.next;
                this[QUEUE].removeNode(w);
                w.next = p;
            }
        }
        this[PROCESSING] = false;
        if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) {
            if (this.zip) {
                this.zip.end(EOF);
            }
            else {
                super.write(EOF);
                super.end();
            }
        }
    }
    get [CURRENT]() {
        return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value;
    }
    [JOBDONE](_job) {
        this[QUEUE].shift();
        this[JOBS] -= 1;
        this[PROCESS]();
    }
    [PROCESSJOB](job) {
        if (job.pending) {
            return;
        }
        if (job.entry) {
            if (job === this[CURRENT] && !job.piped) {
                this[PIPE](job);
            }
            return;
        }
        if (!job.stat) {
            const sc = this.statCache.get(job.absolute);
            if (sc) {
                this[ONSTAT](job, sc);
            }
            else {
                this[STAT](job);
            }
        }
        if (!job.stat) {
            return;
        }
        // filtered out!
        if (job.ignore) {
            return;
        }
        if (!this.noDirRecurse &&
            job.stat.isDirectory() &&
            !job.readdir) {
            const rc = this.readdirCache.get(job.absolute);
            if (rc) {
                this[ONREADDIR](job, rc);
            }
            else {
                this[READDIR](job);
            }
            if (!job.readdir) {
                return;
            }
        }
        // we know it doesn't have an entry, because that got checked above
        job.entry = this[ENTRY](job);
        if (!job.entry) {
            job.ignore = true;
            return;
        }
        if (job === this[CURRENT] && !job.piped) {
            this[PIPE](job);
        }
    }
    [ENTRYOPT](job) {
        return {
            onwarn: (code, msg, data) => this.warn(code, msg, data),
            noPax: this.noPax,
            cwd: this.cwd,
            absolute: job.absolute,
            preservePaths: this.preservePaths,
            maxReadSize: this.maxReadSize,
            strict: this.strict,
            portable: this.portable,
            linkCache: this.linkCache,
            statCache: this.statCache,
            noMtime: this.noMtime,
            mtime: this.mtime,
            prefix: this.prefix,
            onWriteEntry: this.onWriteEntry,
        };
    }
    [ENTRY](job) {
        this[JOBS] += 1;
        try {
            const e = new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job));
            return e
                .on('end', () => this[JOBDONE](job))
                .on('error', er => this.emit('error', er));
        }
        catch (er) {
            this.emit('error', er);
        }
    }
    [ONDRAIN]() {
        if (this[CURRENT] && this[CURRENT].entry) {
            this[CURRENT].entry.resume();
        }
    }
    // like .pipe() but using super, because our write() is special
    [PIPE](job) {
        job.piped = true;
        if (job.readdir) {
            job.readdir.forEach(entry => {
                const p = job.path;
                const base = p === './' ? '' : p.replace(/\/*$/, '/');
                this[ADDFSENTRY](base + entry);
            });
        }
        const source = job.entry;
        const zip = this.zip;
        /* c8 ignore start */
        if (!source)
            throw new Error('cannot pipe without source');
        /* c8 ignore stop */
        if (zip) {
            source.on('data', chunk => {
                if (!zip.write(chunk)) {
                    source.pause();
                }
            });
        }
        else {
            source.on('data', chunk => {
                if (!super.write(chunk)) {
                    source.pause();
                }
            });
        }
    }
    pause() {
        if (this.zip) {
            this.zip.pause();
        }
        return super.pause();
    }
    warn(code, message, data = {}) {
        (0, warn_method_js_1.warnMethod)(this, code, message, data);
    }
}
exports.Pack = Pack;
class PackSync extends Pack {
    sync = true;
    constructor(opt) {
        super(opt);
        this[WRITEENTRYCLASS] = write_entry_js_1.WriteEntrySync;
    }
    // pause/resume are no-ops in sync streams.
    pause() { }
    resume() { }
    [STAT](job) {
        const stat = this.follow ? 'statSync' : 'lstatSync';
        this[ONSTAT](job, fs_1.default[stat](job.absolute));
    }
    [READDIR](job) {
        this[ONREADDIR](job, fs_1.default.readdirSync(job.absolute));
    }
    // gotta get it all in this tick
    [PIPE](job) {
        const source = job.entry;
        const zip = this.zip;
        if (job.readdir) {
            job.readdir.forEach(entry => {
                const p = job.path;
                const base = p === './' ? '' : p.replace(/\/*$/, '/');
                this[ADDFSENTRY](base + entry);
            });
        }
        /* c8 ignore start */
        if (!source)
            throw new Error('Cannot pipe without source');
        /* c8 ignore stop */
        if (zip) {
            source.on('data', chunk => {
                zip.write(chunk);
            });
        }
        else {
            source.on('data', chunk => {
                super[WRITE](chunk);
            });
        }
    }
}
exports.PackSync = PackSync;
//# sourceMappingURL=pack.js.map{
  "type": "commonjs"
}
"use strict";
// this[BUFFER] is the remainder of a chunk if we're waiting for
// the full 512 bytes of a header to come in.  We will Buffer.concat()
// it to the next write(), which is a mem copy, but a small one.
//
// this[QUEUE] is a Yallist of entries that haven't been emitted
// yet this can only get filled up if the user keeps write()ing after
// a write() returns false, or does a write() with more than one entry
//
// We don't buffer chunks, we always parse them and either create an
// entry, or push it into the active entry.  The ReadEntry class knows
// to throw data away if .ignore=true
//
// Shift entry off the buffer when it emits 'end', and emit 'entry' for
// the next one in the list.
//
// At any time, we're pushing body chunks into the entry at WRITEENTRY,
// and waiting for 'end' on the entry at READENTRY
//
// ignored entries get .resume() called on them straight away
Object.defineProperty(exports, "__esModule", { value: true });
exports.Parser = void 0;
const events_1 = require("events");
const minizlib_1 = require("minizlib");
const yallist_1 = require("yallist");
const header_js_1 = require("./header.js");
const pax_js_1 = require("./pax.js");
const read_entry_js_1 = require("./read-entry.js");
const warn_method_js_1 = require("./warn-method.js");
const maxMetaEntrySize = 1024 * 1024;
const gzipHeader = Buffer.from([0x1f, 0x8b]);
const STATE = Symbol('state');
const WRITEENTRY = Symbol('writeEntry');
const READENTRY = Symbol('readEntry');
const NEXTENTRY = Symbol('nextEntry');
const PROCESSENTRY = Symbol('processEntry');
const EX = Symbol('extendedHeader');
const GEX = Symbol('globalExtendedHeader');
const META = Symbol('meta');
const EMITMETA = Symbol('emitMeta');
const BUFFER = Symbol('buffer');
const QUEUE = Symbol('queue');
const ENDED = Symbol('ended');
const EMITTEDEND = Symbol('emittedEnd');
const EMIT = Symbol('emit');
const UNZIP = Symbol('unzip');
const CONSUMECHUNK = Symbol('consumeChunk');
const CONSUMECHUNKSUB = Symbol('consumeChunkSub');
const CONSUMEBODY = Symbol('consumeBody');
const CONSUMEMETA = Symbol('consumeMeta');
const CONSUMEHEADER = Symbol('consumeHeader');
const CONSUMING = Symbol('consuming');
const BUFFERCONCAT = Symbol('bufferConcat');
const MAYBEEND = Symbol('maybeEnd');
const WRITING = Symbol('writing');
const ABORTED = Symbol('aborted');
const DONE = Symbol('onDone');
const SAW_VALID_ENTRY = Symbol('sawValidEntry');
const SAW_NULL_BLOCK = Symbol('sawNullBlock');
const SAW_EOF = Symbol('sawEOF');
const CLOSESTREAM = Symbol('closeStream');
const noop = () => true;
class Parser extends events_1.EventEmitter {
    file;
    strict;
    maxMetaEntrySize;
    filter;
    brotli;
    writable = true;
    readable = false;
    [QUEUE] = new yallist_1.Yallist();
    [BUFFER];
    [READENTRY];
    [WRITEENTRY];
    [STATE] = 'begin';
    [META] = '';
    [EX];
    [GEX];
    [ENDED] = false;
    [UNZIP];
    [ABORTED] = false;
    [SAW_VALID_ENTRY];
    [SAW_NULL_BLOCK] = false;
    [SAW_EOF] = false;
    [WRITING] = false;
    [CONSUMING] = false;
    [EMITTEDEND] = false;
    constructor(opt = {}) {
        super();
        this.file = opt.file || '';
        // these BADARCHIVE errors can't be detected early. listen on DONE.
        this.on(DONE, () => {
            if (this[STATE] === 'begin' ||
                this[SAW_VALID_ENTRY] === false) {
                // either less than 1 block of data, or all entries were invalid.
                // Either way, probably not even a tarball.
                this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format');
            }
        });
        if (opt.ondone) {
            this.on(DONE, opt.ondone);
        }
        else {
            this.on(DONE, () => {
                this.emit('prefinish');
                this.emit('finish');
                this.emit('end');
            });
        }
        this.strict = !!opt.strict;
        this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize;
        this.filter = typeof opt.filter === 'function' ? opt.filter : noop;
        // Unlike gzip, brotli doesn't have any magic bytes to identify it
        // Users need to explicitly tell us they're extracting a brotli file
        // Or we infer from the file extension
        const isTBR = opt.file &&
            (opt.file.endsWith('.tar.br') || opt.file.endsWith('.tbr'));
        // if it's a tbr file it MIGHT be brotli, but we don't know until
        // we look at it and verify it's not a valid tar file.
        this.brotli =
            !opt.gzip && opt.brotli !== undefined ? opt.brotli
                : isTBR ? undefined
                    : false;
        // have to set this so that streams are ok piping into it
        this.on('end', () => this[CLOSESTREAM]());
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        if (typeof opt.onReadEntry === 'function') {
            this.on('entry', opt.onReadEntry);
        }
    }
    warn(code, message, data = {}) {
        (0, warn_method_js_1.warnMethod)(this, code, message, data);
    }
    [CONSUMEHEADER](chunk, position) {
        if (this[SAW_VALID_ENTRY] === undefined) {
            this[SAW_VALID_ENTRY] = false;
        }
        let header;
        try {
            header = new header_js_1.Header(chunk, position, this[EX], this[GEX]);
        }
        catch (er) {
            return this.warn('TAR_ENTRY_INVALID', er);
        }
        if (header.nullBlock) {
            if (this[SAW_NULL_BLOCK]) {
                this[SAW_EOF] = true;
                // ending an archive with no entries.  pointless, but legal.
                if (this[STATE] === 'begin') {
                    this[STATE] = 'header';
                }
                this[EMIT]('eof');
            }
            else {
                this[SAW_NULL_BLOCK] = true;
                this[EMIT]('nullBlock');
            }
        }
        else {
            this[SAW_NULL_BLOCK] = false;
            if (!header.cksumValid) {
                this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header });
            }
            else if (!header.path) {
                this.warn('TAR_ENTRY_INVALID', 'path is required', { header });
            }
            else {
                const type = header.type;
                if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) {
                    this.warn('TAR_ENTRY_INVALID', 'linkpath required', {
                        header,
                    });
                }
                else if (!/^(Symbolic)?Link$/.test(type) &&
                    !/^(Global)?ExtendedHeader$/.test(type) &&
                    header.linkpath) {
                    this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {
                        header,
                    });
                }
                else {
                    const entry = (this[WRITEENTRY] = new read_entry_js_1.ReadEntry(header, this[EX], this[GEX]));
                    // we do this for meta & ignored entries as well, because they
                    // are still valid tar, or else we wouldn't know to ignore them
                    if (!this[SAW_VALID_ENTRY]) {
                        if (entry.remain) {
                            // this might be the one!
                            const onend = () => {
                                if (!entry.invalid) {
                                    this[SAW_VALID_ENTRY] = true;
                                }
                            };
                            entry.on('end', onend);
                        }
                        else {
                            this[SAW_VALID_ENTRY] = true;
                        }
                    }
                    if (entry.meta) {
                        if (entry.size > this.maxMetaEntrySize) {
                            entry.ignore = true;
                            this[EMIT]('ignoredEntry', entry);
                            this[STATE] = 'ignore';
                            entry.resume();
                        }
                        else if (entry.size > 0) {
                            this[META] = '';
                            entry.on('data', c => (this[META] += c));
                            this[STATE] = 'meta';
                        }
                    }
                    else {
                        this[EX] = undefined;
                        entry.ignore =
                            entry.ignore || !this.filter(entry.path, entry);
                        if (entry.ignore) {
                            // probably valid, just not something we care about
                            this[EMIT]('ignoredEntry', entry);
                            this[STATE] = entry.remain ? 'ignore' : 'header';
                            entry.resume();
                        }
                        else {
                            if (entry.remain) {
                                this[STATE] = 'body';
                            }
                            else {
                                this[STATE] = 'header';
                                entry.end();
                            }
                            if (!this[READENTRY]) {
                                this[QUEUE].push(entry);
                                this[NEXTENTRY]();
                            }
                            else {
                                this[QUEUE].push(entry);
                            }
                        }
                    }
                }
            }
        }
    }
    [CLOSESTREAM]() {
        queueMicrotask(() => this.emit('close'));
    }
    [PROCESSENTRY](entry) {
        let go = true;
        if (!entry) {
            this[READENTRY] = undefined;
            go = false;
        }
        else if (Array.isArray(entry)) {
            const [ev, ...args] = entry;
            this.emit(ev, ...args);
        }
        else {
            this[READENTRY] = entry;
            this.emit('entry', entry);
            if (!entry.emittedEnd) {
                entry.on('end', () => this[NEXTENTRY]());
                go = false;
            }
        }
        return go;
    }
    [NEXTENTRY]() {
        do { } while (this[PROCESSENTRY](this[QUEUE].shift()));
        if (!this[QUEUE].length) {
            // At this point, there's nothing in the queue, but we may have an
            // entry which is being consumed (readEntry).
            // If we don't, then we definitely can handle more data.
            // If we do, and either it's flowing, or it has never had any data
            // written to it, then it needs more.
            // The only other possibility is that it has returned false from a
            // write() call, so we wait for the next drain to continue.
            const re = this[READENTRY];
            const drainNow = !re || re.flowing || re.size === re.remain;
            if (drainNow) {
                if (!this[WRITING]) {
                    this.emit('drain');
                }
            }
            else {
                re.once('drain', () => this.emit('drain'));
            }
        }
    }
    [CONSUMEBODY](chunk, position) {
        // write up to but no  more than writeEntry.blockRemain
        const entry = this[WRITEENTRY];
        /* c8 ignore start */
        if (!entry) {
            throw new Error('attempt to consume body without entry??');
        }
        const br = entry.blockRemain ?? 0;
        /* c8 ignore stop */
        const c = br >= chunk.length && position === 0 ?
            chunk
            : chunk.subarray(position, position + br);
        entry.write(c);
        if (!entry.blockRemain) {
            this[STATE] = 'header';
            this[WRITEENTRY] = undefined;
            entry.end();
        }
        return c.length;
    }
    [CONSUMEMETA](chunk, position) {
        const entry = this[WRITEENTRY];
        const ret = this[CONSUMEBODY](chunk, position);
        // if we finished, then the entry is reset
        if (!this[WRITEENTRY] && entry) {
            this[EMITMETA](entry);
        }
        return ret;
    }
    [EMIT](ev, data, extra) {
        if (!this[QUEUE].length && !this[READENTRY]) {
            this.emit(ev, data, extra);
        }
        else {
            this[QUEUE].push([ev, data, extra]);
        }
    }
    [EMITMETA](entry) {
        this[EMIT]('meta', this[META]);
        switch (entry.type) {
            case 'ExtendedHeader':
            case 'OldExtendedHeader':
                this[EX] = pax_js_1.Pax.parse(this[META], this[EX], false);
                break;
            case 'GlobalExtendedHeader':
                this[GEX] = pax_js_1.Pax.parse(this[META], this[GEX], true);
                break;
            case 'NextFileHasLongPath':
            case 'OldGnuLongPath': {
                const ex = this[EX] ?? Object.create(null);
                this[EX] = ex;
                ex.path = this[META].replace(/\0.*/, '');
                break;
            }
            case 'NextFileHasLongLinkpath': {
                const ex = this[EX] || Object.create(null);
                this[EX] = ex;
                ex.linkpath = this[META].replace(/\0.*/, '');
                break;
            }
            /* c8 ignore start */
            default:
                throw new Error('unknown meta: ' + entry.type);
            /* c8 ignore stop */
        }
    }
    abort(error) {
        this[ABORTED] = true;
        this.emit('abort', error);
        // always throws, even in non-strict mode
        this.warn('TAR_ABORT', error, { recoverable: false });
    }
    write(chunk, encoding, cb) {
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, 
            /* c8 ignore next */
            typeof encoding === 'string' ? encoding : 'utf8');
        }
        if (this[ABORTED]) {
            /* c8 ignore next */
            cb?.();
            return false;
        }
        // first write, might be gzipped
        const needSniff = this[UNZIP] === undefined ||
            (this.brotli === undefined && this[UNZIP] === false);
        if (needSniff && chunk) {
            if (this[BUFFER]) {
                chunk = Buffer.concat([this[BUFFER], chunk]);
                this[BUFFER] = undefined;
            }
            if (chunk.length < gzipHeader.length) {
                this[BUFFER] = chunk;
                /* c8 ignore next */
                cb?.();
                return true;
            }
            // look for gzip header
            for (let i = 0; this[UNZIP] === undefined && i < gzipHeader.length; i++) {
                if (chunk[i] !== gzipHeader[i]) {
                    this[UNZIP] = false;
                }
            }
            const maybeBrotli = this.brotli === undefined;
            if (this[UNZIP] === false && maybeBrotli) {
                // read the first header to see if it's a valid tar file. If so,
                // we can safely assume that it's not actually brotli, despite the
                // .tbr or .tar.br file extension.
                // if we ended before getting a full chunk, yes, def brotli
                if (chunk.length < 512) {
                    if (this[ENDED]) {
                        this.brotli = true;
                    }
                    else {
                        this[BUFFER] = chunk;
                        /* c8 ignore next */
                        cb?.();
                        return true;
                    }
                }
                else {
                    // if it's tar, it's pretty reliably not brotli, chances of
                    // that happening are astronomical.
                    try {
                        new header_js_1.Header(chunk.subarray(0, 512));
                        this.brotli = false;
                    }
                    catch (_) {
                        this.brotli = true;
                    }
                }
            }
            if (this[UNZIP] === undefined ||
                (this[UNZIP] === false && this.brotli)) {
                const ended = this[ENDED];
                this[ENDED] = false;
                this[UNZIP] =
                    this[UNZIP] === undefined ?
                        new minizlib_1.Unzip({})
                        : new minizlib_1.BrotliDecompress({});
                this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk));
                this[UNZIP].on('error', er => this.abort(er));
                this[UNZIP].on('end', () => {
                    this[ENDED] = true;
                    this[CONSUMECHUNK]();
                });
                this[WRITING] = true;
                const ret = !!this[UNZIP][ended ? 'end' : 'write'](chunk);
                this[WRITING] = false;
                cb?.();
                return ret;
            }
        }
        this[WRITING] = true;
        if (this[UNZIP]) {
            this[UNZIP].write(chunk);
        }
        else {
            this[CONSUMECHUNK](chunk);
        }
        this[WRITING] = false;
        // return false if there's a queue, or if the current entry isn't flowing
        const ret = this[QUEUE].length ? false
            : this[READENTRY] ? this[READENTRY].flowing
                : true;
        // if we have no queue, then that means a clogged READENTRY
        if (!ret && !this[QUEUE].length) {
            this[READENTRY]?.once('drain', () => this.emit('drain'));
        }
        /* c8 ignore next */
        cb?.();
        return ret;
    }
    [BUFFERCONCAT](c) {
        if (c && !this[ABORTED]) {
            this[BUFFER] =
                this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c;
        }
    }
    [MAYBEEND]() {
        if (this[ENDED] &&
            !this[EMITTEDEND] &&
            !this[ABORTED] &&
            !this[CONSUMING]) {
            this[EMITTEDEND] = true;
            const entry = this[WRITEENTRY];
            if (entry && entry.blockRemain) {
                // truncated, likely a damaged file
                const have = this[BUFFER] ? this[BUFFER].length : 0;
                this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${entry.blockRemain} more bytes, only ${have} available)`, { entry });
                if (this[BUFFER]) {
                    entry.write(this[BUFFER]);
                }
                entry.end();
            }
            this[EMIT](DONE);
        }
    }
    [CONSUMECHUNK](chunk) {
        if (this[CONSUMING] && chunk) {
            this[BUFFERCONCAT](chunk);
        }
        else if (!chunk && !this[BUFFER]) {
            this[MAYBEEND]();
        }
        else if (chunk) {
            this[CONSUMING] = true;
            if (this[BUFFER]) {
                this[BUFFERCONCAT](chunk);
                const c = this[BUFFER];
                this[BUFFER] = undefined;
                this[CONSUMECHUNKSUB](c);
            }
            else {
                this[CONSUMECHUNKSUB](chunk);
            }
            while (this[BUFFER] &&
                this[BUFFER]?.length >= 512 &&
                !this[ABORTED] &&
                !this[SAW_EOF]) {
                const c = this[BUFFER];
                this[BUFFER] = undefined;
                this[CONSUMECHUNKSUB](c);
            }
            this[CONSUMING] = false;
        }
        if (!this[BUFFER] || this[ENDED]) {
            this[MAYBEEND]();
        }
    }
    [CONSUMECHUNKSUB](chunk) {
        // we know that we are in CONSUMING mode, so anything written goes into
        // the buffer.  Advance the position and put any remainder in the buffer.
        let position = 0;
        const length = chunk.length;
        while (position + 512 <= length &&
            !this[ABORTED] &&
            !this[SAW_EOF]) {
            switch (this[STATE]) {
                case 'begin':
                case 'header':
                    this[CONSUMEHEADER](chunk, position);
                    position += 512;
                    break;
                case 'ignore':
                case 'body':
                    position += this[CONSUMEBODY](chunk, position);
                    break;
                case 'meta':
                    position += this[CONSUMEMETA](chunk, position);
                    break;
                /* c8 ignore start */
                default:
                    throw new Error('invalid state: ' + this[STATE]);
                /* c8 ignore stop */
            }
        }
        if (position < length) {
            if (this[BUFFER]) {
                this[BUFFER] = Buffer.concat([
                    chunk.subarray(position),
                    this[BUFFER],
                ]);
            }
            else {
                this[BUFFER] = chunk.subarray(position);
            }
        }
    }
    end(chunk, encoding, cb) {
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, encoding);
        }
        if (cb)
            this.once('finish', cb);
        if (!this[ABORTED]) {
            if (this[UNZIP]) {
                /* c8 ignore start */
                if (chunk)
                    this[UNZIP].write(chunk);
                /* c8 ignore stop */
                this[UNZIP].end();
            }
            else {
                this[ENDED] = true;
                if (this.brotli === undefined)
                    chunk = chunk || Buffer.alloc(0);
                if (chunk)
                    this.write(chunk);
                this[MAYBEEND]();
            }
        }
        return this;
    }
}
exports.Parser = Parser;
//# sourceMappingURL=parse.js.map"use strict";
// A path exclusive reservation system
// reserve([list, of, paths], fn)
// When the fn is first in line for all its paths, it
// is called with a cb that clears the reservation.
//
// Used by async unpack to avoid clobbering paths in use,
// while still allowing maximal safe parallelization.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PathReservations = void 0;
const node_path_1 = require("node:path");
const normalize_unicode_js_1 = require("./normalize-unicode.js");
const strip_trailing_slashes_js_1 = require("./strip-trailing-slashes.js");
const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
const isWindows = platform === 'win32';
// return a set of parent dirs for a given path
// '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d']
const getDirs = (path) => {
    const dirs = path
        .split('/')
        .slice(0, -1)
        .reduce((set, path) => {
        const s = set[set.length - 1];
        if (s !== undefined) {
            path = (0, node_path_1.join)(s, path);
        }
        set.push(path || '/');
        return set;
    }, []);
    return dirs;
};
class PathReservations {
    // path => [function or Set]
    // A Set object means a directory reservation
    // A fn is a direct reservation on that path
    #queues = new Map();
    // fn => {paths:[path,...], dirs:[path, ...]}
    #reservations = new Map();
    // functions currently running
    #running = new Set();
    reserve(paths, fn) {
        paths =
            isWindows ?
                ['win32 parallelization disabled']
                : paths.map(p => {
                    // don't need normPath, because we skip this entirely for windows
                    return (0, strip_trailing_slashes_js_1.stripTrailingSlashes)((0, node_path_1.join)((0, normalize_unicode_js_1.normalizeUnicode)(p))).toLowerCase();
                });
        const dirs = new Set(paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)));
        this.#reservations.set(fn, { dirs, paths });
        for (const p of paths) {
            const q = this.#queues.get(p);
            if (!q) {
                this.#queues.set(p, [fn]);
            }
            else {
                q.push(fn);
            }
        }
        for (const dir of dirs) {
            const q = this.#queues.get(dir);
            if (!q) {
                this.#queues.set(dir, [new Set([fn])]);
            }
            else {
                const l = q[q.length - 1];
                if (l instanceof Set) {
                    l.add(fn);
                }
                else {
                    q.push(new Set([fn]));
                }
            }
        }
        return this.#run(fn);
    }
    // return the queues for each path the function cares about
    // fn => {paths, dirs}
    #getQueues(fn) {
        const res = this.#reservations.get(fn);
        /* c8 ignore start */
        if (!res) {
            throw new Error('function does not have any path reservations');
        }
        /* c8 ignore stop */
        return {
            paths: res.paths.map((path) => this.#queues.get(path)),
            dirs: [...res.dirs].map(path => this.#queues.get(path)),
        };
    }
    // check if fn is first in line for all its paths, and is
    // included in the first set for all its dir queues
    check(fn) {
        const { paths, dirs } = this.#getQueues(fn);
        return (paths.every(q => q && q[0] === fn) &&
            dirs.every(q => q && q[0] instanceof Set && q[0].has(fn)));
    }
    // run the function if it's first in line and not already running
    #run(fn) {
        if (this.#running.has(fn) || !this.check(fn)) {
            return false;
        }
        this.#running.add(fn);
        fn(() => this.#clear(fn));
        return true;
    }
    #clear(fn) {
        if (!this.#running.has(fn)) {
            return false;
        }
        const res = this.#reservations.get(fn);
        /* c8 ignore start */
        if (!res) {
            throw new Error('invalid reservation');
        }
        /* c8 ignore stop */
        const { paths, dirs } = res;
        const next = new Set();
        for (const path of paths) {
            const q = this.#queues.get(path);
            /* c8 ignore start */
            if (!q || q?.[0] !== fn) {
                continue;
            }
            /* c8 ignore stop */
            const q0 = q[1];
            if (!q0) {
                this.#queues.delete(path);
                continue;
            }
            q.shift();
            if (typeof q0 === 'function') {
                next.add(q0);
            }
            else {
                for (const f of q0) {
                    next.add(f);
                }
            }
        }
        for (const dir of dirs) {
            const q = this.#queues.get(dir);
            const q0 = q?.[0];
            /* c8 ignore next - type safety only */
            if (!q || !(q0 instanceof Set))
                continue;
            if (q0.size === 1 && q.length === 1) {
                this.#queues.delete(dir);
                continue;
            }
            else if (q0.size === 1) {
                q.shift();
                // next one must be a function,
                // or else the Set would've been reused
                const n = q[0];
                if (typeof n === 'function') {
                    next.add(n);
                }
            }
            else {
                q0.delete(fn);
            }
        }
        this.#running.delete(fn);
        next.forEach(fn => this.#run(fn));
        return true;
    }
}
exports.PathReservations = PathReservations;
//# sourceMappingURL=path-reservations.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Pax = void 0;
const node_path_1 = require("node:path");
const header_js_1 = require("./header.js");
class Pax {
    atime;
    mtime;
    ctime;
    charset;
    comment;
    gid;
    uid;
    gname;
    uname;
    linkpath;
    dev;
    ino;
    nlink;
    path;
    size;
    mode;
    global;
    constructor(obj, global = false) {
        this.atime = obj.atime;
        this.charset = obj.charset;
        this.comment = obj.comment;
        this.ctime = obj.ctime;
        this.dev = obj.dev;
        this.gid = obj.gid;
        this.global = global;
        this.gname = obj.gname;
        this.ino = obj.ino;
        this.linkpath = obj.linkpath;
        this.mtime = obj.mtime;
        this.nlink = obj.nlink;
        this.path = obj.path;
        this.size = obj.size;
        this.uid = obj.uid;
        this.uname = obj.uname;
    }
    encode() {
        const body = this.encodeBody();
        if (body === '') {
            return Buffer.allocUnsafe(0);
        }
        const bodyLen = Buffer.byteLength(body);
        // round up to 512 bytes
        // add 512 for header
        const bufLen = 512 * Math.ceil(1 + bodyLen / 512);
        const buf = Buffer.allocUnsafe(bufLen);
        // 0-fill the header section, it might not hit every field
        for (let i = 0; i < 512; i++) {
            buf[i] = 0;
        }
        new header_js_1.Header({
            // XXX split the path
            // then the path should be PaxHeader + basename, but less than 99,
            // prepend with the dirname
            /* c8 ignore start */
            path: ('PaxHeader/' + (0, node_path_1.basename)(this.path ?? '')).slice(0, 99),
            /* c8 ignore stop */
            mode: this.mode || 0o644,
            uid: this.uid,
            gid: this.gid,
            size: bodyLen,
            mtime: this.mtime,
            type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader',
            linkpath: '',
            uname: this.uname || '',
            gname: this.gname || '',
            devmaj: 0,
            devmin: 0,
            atime: this.atime,
            ctime: this.ctime,
        }).encode(buf);
        buf.write(body, 512, bodyLen, 'utf8');
        // null pad after the body
        for (let i = bodyLen + 512; i < buf.length; i++) {
            buf[i] = 0;
        }
        return buf;
    }
    encodeBody() {
        return (this.encodeField('path') +
            this.encodeField('ctime') +
            this.encodeField('atime') +
            this.encodeField('dev') +
            this.encodeField('ino') +
            this.encodeField('nlink') +
            this.encodeField('charset') +
            this.encodeField('comment') +
            this.encodeField('gid') +
            this.encodeField('gname') +
            this.encodeField('linkpath') +
            this.encodeField('mtime') +
            this.encodeField('size') +
            this.encodeField('uid') +
            this.encodeField('uname'));
    }
    encodeField(field) {
        if (this[field] === undefined) {
            return '';
        }
        const r = this[field];
        const v = r instanceof Date ? r.getTime() / 1000 : r;
        const s = ' ' +
            (field === 'dev' || field === 'ino' || field === 'nlink' ?
                'SCHILY.'
                : '') +
            field +
            '=' +
            v +
            '\n';
        const byteLen = Buffer.byteLength(s);
        // the digits includes the length of the digits in ascii base-10
        // so if it's 9 characters, then adding 1 for the 9 makes it 10
        // which makes it 11 chars.
        let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1;
        if (byteLen + digits >= Math.pow(10, digits)) {
            digits += 1;
        }
        const len = digits + byteLen;
        return len + s;
    }
    static parse(str, ex, g = false) {
        return new Pax(merge(parseKV(str), ex), g);
    }
}
exports.Pax = Pax;
const merge = (a, b) => b ? Object.assign({}, b, a) : a;
const parseKV = (str) => str
    .replace(/\n$/, '')
    .split('\n')
    .reduce(parseKVLine, Object.create(null));
const parseKVLine = (set, line) => {
    const n = parseInt(line, 10);
    // XXX Values with \n in them will fail this.
    // Refactor to not be a naive line-by-line parse.
    if (n !== Buffer.byteLength(line) + 1) {
        return set;
    }
    line = line.slice((n + ' ').length);
    const kv = line.split('=');
    const r = kv.shift();
    if (!r) {
        return set;
    }
    const k = r.replace(/^SCHILY\.(dev|ino|nlink)/, '$1');
    const v = kv.join('=');
    set[k] =
        /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ?
            new Date(Number(v) * 1000)
            : /^[0-9]+$/.test(v) ? +v
                : v;
    return set;
};
//# sourceMappingURL=pax.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReadEntry = void 0;
const minipass_1 = require("minipass");
const normalize_windows_path_js_1 = require("./normalize-windows-path.js");
class ReadEntry extends minipass_1.Minipass {
    extended;
    globalExtended;
    header;
    startBlockSize;
    blockRemain;
    remain;
    type;
    meta = false;
    ignore = false;
    path;
    mode;
    uid;
    gid;
    uname;
    gname;
    size = 0;
    mtime;
    atime;
    ctime;
    linkpath;
    dev;
    ino;
    nlink;
    invalid = false;
    absolute;
    unsupported = false;
    constructor(header, ex, gex) {
        super({});
        // read entries always start life paused.  this is to avoid the
        // situation where Minipass's auto-ending empty streams results
        // in an entry ending before we're ready for it.
        this.pause();
        this.extended = ex;
        this.globalExtended = gex;
        this.header = header;
        /* c8 ignore start */
        this.remain = header.size ?? 0;
        /* c8 ignore stop */
        this.startBlockSize = 512 * Math.ceil(this.remain / 512);
        this.blockRemain = this.startBlockSize;
        this.type = header.type;
        switch (this.type) {
            case 'File':
            case 'OldFile':
            case 'Link':
            case 'SymbolicLink':
            case 'CharacterDevice':
            case 'BlockDevice':
            case 'Directory':
            case 'FIFO':
            case 'ContiguousFile':
            case 'GNUDumpDir':
                break;
            case 'NextFileHasLongLinkpath':
            case 'NextFileHasLongPath':
            case 'OldGnuLongPath':
            case 'GlobalExtendedHeader':
            case 'ExtendedHeader':
            case 'OldExtendedHeader':
                this.meta = true;
                break;
            // NOTE: gnutar and bsdtar treat unrecognized types as 'File'
            // it may be worth doing the same, but with a warning.
            default:
                this.ignore = true;
        }
        /* c8 ignore start */
        if (!header.path) {
            throw new Error('no path provided for tar.ReadEntry');
        }
        /* c8 ignore stop */
        this.path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(header.path);
        this.mode = header.mode;
        if (this.mode) {
            this.mode = this.mode & 0o7777;
        }
        this.uid = header.uid;
        this.gid = header.gid;
        this.uname = header.uname;
        this.gname = header.gname;
        this.size = this.remain;
        this.mtime = header.mtime;
        this.atime = header.atime;
        this.ctime = header.ctime;
        /* c8 ignore start */
        this.linkpath =
            header.linkpath ?
                (0, normalize_windows_path_js_1.normalizeWindowsPath)(header.linkpath)
                : undefined;
        /* c8 ignore stop */
        this.uname = header.uname;
        this.gname = header.gname;
        if (ex) {
            this.#slurp(ex);
        }
        if (gex) {
            this.#slurp(gex, true);
        }
    }
    write(data) {
        const writeLen = data.length;
        if (writeLen > this.blockRemain) {
            throw new Error('writing more to entry than is appropriate');
        }
        const r = this.remain;
        const br = this.blockRemain;
        this.remain = Math.max(0, r - writeLen);
        this.blockRemain = Math.max(0, br - writeLen);
        if (this.ignore) {
            return true;
        }
        if (r >= writeLen) {
            return super.write(data);
        }
        // r < writeLen
        return super.write(data.subarray(0, r));
    }
    #slurp(ex, gex = false) {
        if (ex.path)
            ex.path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(ex.path);
        if (ex.linkpath)
            ex.linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(ex.linkpath);
        Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => {
            // we slurp in everything except for the path attribute in
            // a global extended header, because that's weird. Also, any
            // null/undefined values are ignored.
            return !(v === null ||
                v === undefined ||
                (k === 'path' && gex));
        })));
    }
}
exports.ReadEntry = ReadEntry;
//# sourceMappingURL=read-entry.js.map"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.replace = void 0;
// tar -r
const fs_minipass_1 = require("@isaacs/fs-minipass");
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const header_js_1 = require("./header.js");
const list_js_1 = require("./list.js");
const make_command_js_1 = require("./make-command.js");
const options_js_1 = require("./options.js");
const pack_js_1 = require("./pack.js");
// starting at the head of the file, read a Header
// If the checksum is invalid, that's our position to start writing
// If it is, jump forward by the specified size (round up to 512)
// and try again.
// Write the new Pack stream starting there.
const replaceSync = (opt, files) => {
    const p = new pack_js_1.PackSync(opt);
    let threw = true;
    let fd;
    let position;
    try {
        try {
            fd = node_fs_1.default.openSync(opt.file, 'r+');
        }
        catch (er) {
            if (er?.code === 'ENOENT') {
                fd = node_fs_1.default.openSync(opt.file, 'w+');
            }
            else {
                throw er;
            }
        }
        const st = node_fs_1.default.fstatSync(fd);
        const headBuf = Buffer.alloc(512);
        POSITION: for (position = 0; position < st.size; position += 512) {
            for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) {
                bytes = node_fs_1.default.readSync(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos);
                if (position === 0 &&
                    headBuf[0] === 0x1f &&
                    headBuf[1] === 0x8b) {
                    throw new Error('cannot append to compressed archives');
                }
                if (!bytes) {
                    break POSITION;
                }
            }
            const h = new header_js_1.Header(headBuf);
            if (!h.cksumValid) {
                break;
            }
            const entryBlockSize = 512 * Math.ceil((h.size || 0) / 512);
            if (position + entryBlockSize + 512 > st.size) {
                break;
            }
            // the 512 for the header we just parsed will be added as well
            // also jump ahead all the blocks for the body
            position += entryBlockSize;
            if (opt.mtimeCache && h.mtime) {
                opt.mtimeCache.set(String(h.path), h.mtime);
            }
        }
        threw = false;
        streamSync(opt, p, position, fd, files);
    }
    finally {
        if (threw) {
            try {
                node_fs_1.default.closeSync(fd);
            }
            catch (er) { }
        }
    }
};
const streamSync = (opt, p, position, fd, files) => {
    const stream = new fs_minipass_1.WriteStreamSync(opt.file, {
        fd: fd,
        start: position,
    });
    p.pipe(stream);
    addFilesSync(p, files);
};
const replaceAsync = (opt, files) => {
    files = Array.from(files);
    const p = new pack_js_1.Pack(opt);
    const getPos = (fd, size, cb_) => {
        const cb = (er, pos) => {
            if (er) {
                node_fs_1.default.close(fd, _ => cb_(er));
            }
            else {
                cb_(null, pos);
            }
        };
        let position = 0;
        if (size === 0) {
            return cb(null, 0);
        }
        let bufPos = 0;
        const headBuf = Buffer.alloc(512);
        const onread = (er, bytes) => {
            if (er || typeof bytes === 'undefined') {
                return cb(er);
            }
            bufPos += bytes;
            if (bufPos < 512 && bytes) {
                return node_fs_1.default.read(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread);
            }
            if (position === 0 &&
                headBuf[0] === 0x1f &&
                headBuf[1] === 0x8b) {
                return cb(new Error('cannot append to compressed archives'));
            }
            // truncated header
            if (bufPos < 512) {
                return cb(null, position);
            }
            const h = new header_js_1.Header(headBuf);
            if (!h.cksumValid) {
                return cb(null, position);
            }
            /* c8 ignore next */
            const entryBlockSize = 512 * Math.ceil((h.size ?? 0) / 512);
            if (position + entryBlockSize + 512 > size) {
                return cb(null, position);
            }
            position += entryBlockSize + 512;
            if (position >= size) {
                return cb(null, position);
            }
            if (opt.mtimeCache && h.mtime) {
                opt.mtimeCache.set(String(h.path), h.mtime);
            }
            bufPos = 0;
            node_fs_1.default.read(fd, headBuf, 0, 512, position, onread);
        };
        node_fs_1.default.read(fd, headBuf, 0, 512, position, onread);
    };
    const promise = new Promise((resolve, reject) => {
        p.on('error', reject);
        let flag = 'r+';
        const onopen = (er, fd) => {
            if (er && er.code === 'ENOENT' && flag === 'r+') {
                flag = 'w+';
                return node_fs_1.default.open(opt.file, flag, onopen);
            }
            if (er || !fd) {
                return reject(er);
            }
            node_fs_1.default.fstat(fd, (er, st) => {
                if (er) {
                    return node_fs_1.default.close(fd, () => reject(er));
                }
                getPos(fd, st.size, (er, position) => {
                    if (er) {
                        return reject(er);
                    }
                    const stream = new fs_minipass_1.WriteStream(opt.file, {
                        fd: fd,
                        start: position,
                    });
                    p.pipe(stream);
                    stream.on('error', reject);
                    stream.on('close', resolve);
                    addFilesAsync(p, files);
                });
            });
        };
        node_fs_1.default.open(opt.file, flag, onopen);
    });
    return promise;
};
const addFilesSync = (p, files) => {
    files.forEach(file => {
        if (file.charAt(0) === '@') {
            (0, list_js_1.list)({
                file: node_path_1.default.resolve(p.cwd, file.slice(1)),
                sync: true,
                noResume: true,
                onReadEntry: entry => p.add(entry),
            });
        }
        else {
            p.add(file);
        }
    });
    p.end();
};
const addFilesAsync = async (p, files) => {
    for (let i = 0; i < files.length; i++) {
        const file = String(files[i]);
        if (file.charAt(0) === '@') {
            await (0, list_js_1.list)({
                file: node_path_1.default.resolve(String(p.cwd), file.slice(1)),
                noResume: true,
                onReadEntry: entry => p.add(entry),
            });
        }
        else {
            p.add(file);
        }
    }
    p.end();
};
exports.replace = (0, make_command_js_1.makeCommand)(replaceSync, replaceAsync, 
/* c8 ignore start */
() => {
    throw new TypeError('file is required');
}, () => {
    throw new TypeError('file is required');
}, 
/* c8 ignore stop */
(opt, entries) => {
    if (!(0, options_js_1.isFile)(opt)) {
        throw new TypeError('file is required');
    }
    if (opt.gzip ||
        opt.brotli ||
        opt.file.endsWith('.br') ||
        opt.file.endsWith('.tbr')) {
        throw new TypeError('cannot append to compressed archives');
    }
    if (!entries?.length) {
        throw new TypeError('no paths specified to add/replace');
    }
});
//# sourceMappingURL=replace.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.stripAbsolutePath = void 0;
// unix absolute paths are also absolute on win32, so we use this for both
const node_path_1 = require("node:path");
const { isAbsolute, parse } = node_path_1.win32;
// returns [root, stripped]
// Note that windows will think that //x/y/z/a has a "root" of //x/y, and in
// those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip /
// explicitly if it's the first character.
// drive-specific relative paths on Windows get their root stripped off even
// though they are not absolute, so `c:../foo` becomes ['c:', '../foo']
const stripAbsolutePath = (path) => {
    let r = '';
    let parsed = parse(path);
    while (isAbsolute(path) || parsed.root) {
        // windows will think that //x/y/z has a "root" of //x/y/
        // but strip the //?/C:/ off of //?/C:/path
        const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ?
            '/'
            : parsed.root;
        path = path.slice(root.length);
        r += root;
        parsed = parse(path);
    }
    return [r, path];
};
exports.stripAbsolutePath = stripAbsolutePath;
//# sourceMappingURL=strip-absolute-path.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.stripTrailingSlashes = void 0;
// warning: extremely hot code path.
// This has been meticulously optimized for use
// within npm install on large package trees.
// Do not edit without careful benchmarking.
const stripTrailingSlashes = (str) => {
    let i = str.length - 1;
    let slashesStart = -1;
    while (i > -1 && str.charAt(i) === '/') {
        slashesStart = i;
        i--;
    }
    return slashesStart === -1 ? str : str.slice(0, slashesStart);
};
exports.stripTrailingSlashes = stripTrailingSlashes;
//# sourceMappingURL=strip-trailing-slashes.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SymlinkError = void 0;
class SymlinkError extends Error {
    path;
    symlink;
    syscall = 'symlink';
    code = 'TAR_SYMLINK_ERROR';
    constructor(symlink, path) {
        super('TAR_SYMLINK_ERROR: Cannot extract through symbolic link');
        this.symlink = symlink;
        this.path = path;
    }
    get name() {
        return 'SymlinkError';
    }
}
exports.SymlinkError = SymlinkError;
//# sourceMappingURL=symlink-error.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.code = exports.name = exports.isName = exports.isCode = void 0;
const isCode = (c) => exports.name.has(c);
exports.isCode = isCode;
const isName = (c) => exports.code.has(c);
exports.isName = isName;
// map types from key to human-friendly name
exports.name = new Map([
    ['0', 'File'],
    // same as File
    ['', 'OldFile'],
    ['1', 'Link'],
    ['2', 'SymbolicLink'],
    // Devices and FIFOs aren't fully supported
    // they are parsed, but skipped when unpacking
    ['3', 'CharacterDevice'],
    ['4', 'BlockDevice'],
    ['5', 'Directory'],
    ['6', 'FIFO'],
    // same as File
    ['7', 'ContiguousFile'],
    // pax headers
    ['g', 'GlobalExtendedHeader'],
    ['x', 'ExtendedHeader'],
    // vendor-specific stuff
    // skip
    ['A', 'SolarisACL'],
    // like 5, but with data, which should be skipped
    ['D', 'GNUDumpDir'],
    // metadata only, skip
    ['I', 'Inode'],
    // data = link path of next file
    ['K', 'NextFileHasLongLinkpath'],
    // data = path of next file
    ['L', 'NextFileHasLongPath'],
    // skip
    ['M', 'ContinuationFile'],
    // like L
    ['N', 'OldGnuLongPath'],
    // skip
    ['S', 'SparseFile'],
    // skip
    ['V', 'TapeVolumeHeader'],
    // like x
    ['X', 'OldExtendedHeader'],
]);
// map the other direction
exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]]));
//# sourceMappingURL=types.js.map"use strict";
// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet.
// but the path reservations are required to avoid race conditions where
// parallelized unpack ops may mess with one another, due to dependencies
// (like a Link depending on its target) or destructive operations (like
// clobbering an fs object to create one of a different type.)
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnpackSync = exports.Unpack = void 0;
const fsm = __importStar(require("@isaacs/fs-minipass"));
const node_assert_1 = __importDefault(require("node:assert"));
const node_crypto_1 = require("node:crypto");
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const get_write_flag_js_1 = require("./get-write-flag.js");
const mkdir_js_1 = require("./mkdir.js");
const normalize_unicode_js_1 = require("./normalize-unicode.js");
const normalize_windows_path_js_1 = require("./normalize-windows-path.js");
const parse_js_1 = require("./parse.js");
const strip_absolute_path_js_1 = require("./strip-absolute-path.js");
const strip_trailing_slashes_js_1 = require("./strip-trailing-slashes.js");
const wc = __importStar(require("./winchars.js"));
const path_reservations_js_1 = require("./path-reservations.js");
const ONENTRY = Symbol('onEntry');
const CHECKFS = Symbol('checkFs');
const CHECKFS2 = Symbol('checkFs2');
const PRUNECACHE = Symbol('pruneCache');
const ISREUSABLE = Symbol('isReusable');
const MAKEFS = Symbol('makeFs');
const FILE = Symbol('file');
const DIRECTORY = Symbol('directory');
const LINK = Symbol('link');
const SYMLINK = Symbol('symlink');
const HARDLINK = Symbol('hardlink');
const UNSUPPORTED = Symbol('unsupported');
const CHECKPATH = Symbol('checkPath');
const MKDIR = Symbol('mkdir');
const ONERROR = Symbol('onError');
const PENDING = Symbol('pending');
const PEND = Symbol('pend');
const UNPEND = Symbol('unpend');
const ENDED = Symbol('ended');
const MAYBECLOSE = Symbol('maybeClose');
const SKIP = Symbol('skip');
const DOCHOWN = Symbol('doChown');
const UID = Symbol('uid');
const GID = Symbol('gid');
const CHECKED_CWD = Symbol('checkedCwd');
const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
const isWindows = platform === 'win32';
const DEFAULT_MAX_DEPTH = 1024;
// Unlinks on Windows are not atomic.
//
// This means that if you have a file entry, followed by another
// file entry with an identical name, and you cannot re-use the file
// (because it's a hardlink, or because unlink:true is set, or it's
// Windows, which does not have useful nlink values), then the unlink
// will be committed to the disk AFTER the new file has been written
// over the old one, deleting the new file.
//
// To work around this, on Windows systems, we rename the file and then
// delete the renamed file.  It's a sloppy kludge, but frankly, I do not
// know of a better way to do this, given windows' non-atomic unlink
// semantics.
//
// See: https://github.com/npm/node-tar/issues/183
/* c8 ignore start */
const unlinkFile = (path, cb) => {
    if (!isWindows) {
        return node_fs_1.default.unlink(path, cb);
    }
    const name = path + '.DELETE.' + (0, node_crypto_1.randomBytes)(16).toString('hex');
    node_fs_1.default.rename(path, name, er => {
        if (er) {
            return cb(er);
        }
        node_fs_1.default.unlink(name, cb);
    });
};
/* c8 ignore stop */
/* c8 ignore start */
const unlinkFileSync = (path) => {
    if (!isWindows) {
        return node_fs_1.default.unlinkSync(path);
    }
    const name = path + '.DELETE.' + (0, node_crypto_1.randomBytes)(16).toString('hex');
    node_fs_1.default.renameSync(path, name);
    node_fs_1.default.unlinkSync(name);
};
/* c8 ignore stop */
// this.gid, entry.gid, this.processUid
const uint32 = (a, b, c) => a !== undefined && a === a >>> 0 ? a
    : b !== undefined && b === b >>> 0 ? b
        : c;
// clear the cache if it's a case-insensitive unicode-squashing match.
// we can't know if the current file system is case-sensitive or supports
// unicode fully, so we check for similarity on the maximally compatible
// representation.  Err on the side of pruning, since all it's doing is
// preventing lstats, and it's not the end of the world if we get a false
// positive.
// Note that on windows, we always drop the entire cache whenever a
// symbolic link is encountered, because 8.3 filenames are impossible
// to reason about, and collisions are hazards rather than just failures.
const cacheKeyNormalize = (path) => (0, strip_trailing_slashes_js_1.stripTrailingSlashes)((0, normalize_windows_path_js_1.normalizeWindowsPath)((0, normalize_unicode_js_1.normalizeUnicode)(path))).toLowerCase();
// remove all cache entries matching ${abs}/**
const pruneCache = (cache, abs) => {
    abs = cacheKeyNormalize(abs);
    for (const path of cache.keys()) {
        const pnorm = cacheKeyNormalize(path);
        if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) {
            cache.delete(path);
        }
    }
};
const dropCache = (cache) => {
    for (const key of cache.keys()) {
        cache.delete(key);
    }
};
class Unpack extends parse_js_1.Parser {
    [ENDED] = false;
    [CHECKED_CWD] = false;
    [PENDING] = 0;
    reservations = new path_reservations_js_1.PathReservations();
    transform;
    writable = true;
    readable = false;
    dirCache;
    uid;
    gid;
    setOwner;
    preserveOwner;
    processGid;
    processUid;
    maxDepth;
    forceChown;
    win32;
    newer;
    keep;
    noMtime;
    preservePaths;
    unlink;
    cwd;
    strip;
    processUmask;
    umask;
    dmode;
    fmode;
    chmod;
    constructor(opt = {}) {
        opt.ondone = () => {
            this[ENDED] = true;
            this[MAYBECLOSE]();
        };
        super(opt);
        this.transform = opt.transform;
        this.dirCache = opt.dirCache || new Map();
        this.chmod = !!opt.chmod;
        if (typeof opt.uid === 'number' || typeof opt.gid === 'number') {
            // need both or neither
            if (typeof opt.uid !== 'number' ||
                typeof opt.gid !== 'number') {
                throw new TypeError('cannot set owner without number uid and gid');
            }
            if (opt.preserveOwner) {
                throw new TypeError('cannot preserve owner in archive and also set owner explicitly');
            }
            this.uid = opt.uid;
            this.gid = opt.gid;
            this.setOwner = true;
        }
        else {
            this.uid = undefined;
            this.gid = undefined;
            this.setOwner = false;
        }
        // default true for root
        if (opt.preserveOwner === undefined &&
            typeof opt.uid !== 'number') {
            this.preserveOwner = !!(process.getuid && process.getuid() === 0);
        }
        else {
            this.preserveOwner = !!opt.preserveOwner;
        }
        this.processUid =
            (this.preserveOwner || this.setOwner) && process.getuid ?
                process.getuid()
                : undefined;
        this.processGid =
            (this.preserveOwner || this.setOwner) && process.getgid ?
                process.getgid()
                : undefined;
        // prevent excessively deep nesting of subfolders
        // set to `Infinity` to remove this restriction
        this.maxDepth =
            typeof opt.maxDepth === 'number' ?
                opt.maxDepth
                : DEFAULT_MAX_DEPTH;
        // mostly just for testing, but useful in some cases.
        // Forcibly trigger a chown on every entry, no matter what
        this.forceChown = opt.forceChown === true;
        // turn > this[ONENTRY](entry));
    }
    // a bad or damaged archive is a warning for Parser, but an error
    // when extracting.  Mark those errors as unrecoverable, because
    // the Unpack contract cannot be met.
    warn(code, msg, data = {}) {
        if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') {
            data.recoverable = false;
        }
        return super.warn(code, msg, data);
    }
    [MAYBECLOSE]() {
        if (this[ENDED] && this[PENDING] === 0) {
            this.emit('prefinish');
            this.emit('finish');
            this.emit('end');
        }
    }
    [CHECKPATH](entry) {
        const p = (0, normalize_windows_path_js_1.normalizeWindowsPath)(entry.path);
        const parts = p.split('/');
        if (this.strip) {
            if (parts.length < this.strip) {
                return false;
            }
            if (entry.type === 'Link') {
                const linkparts = (0, normalize_windows_path_js_1.normalizeWindowsPath)(String(entry.linkpath)).split('/');
                if (linkparts.length >= this.strip) {
                    entry.linkpath = linkparts.slice(this.strip).join('/');
                }
                else {
                    return false;
                }
            }
            parts.splice(0, this.strip);
            entry.path = parts.join('/');
        }
        if (isFinite(this.maxDepth) && parts.length > this.maxDepth) {
            this.warn('TAR_ENTRY_ERROR', 'path excessively deep', {
                entry,
                path: p,
                depth: parts.length,
                maxDepth: this.maxDepth,
            });
            return false;
        }
        if (!this.preservePaths) {
            if (parts.includes('..') ||
                /* c8 ignore next */
                (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) {
                this.warn('TAR_ENTRY_ERROR', `path contains '..'`, {
                    entry,
                    path: p,
                });
                return false;
            }
            // strip off the root
            const [root, stripped] = (0, strip_absolute_path_js_1.stripAbsolutePath)(p);
            if (root) {
                entry.path = String(stripped);
                this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, {
                    entry,
                    path: p,
                });
            }
        }
        if (node_path_1.default.isAbsolute(entry.path)) {
            entry.absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(entry.path));
        }
        else {
            entry.absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(this.cwd, entry.path));
        }
        // if we somehow ended up with a path that escapes the cwd, and we are
        // not in preservePaths mode, then something is fishy!  This should have
        // been prevented above, so ignore this for coverage.
        /* c8 ignore start - defense in depth */
        if (!this.preservePaths &&
            typeof entry.absolute === 'string' &&
            entry.absolute.indexOf(this.cwd + '/') !== 0 &&
            entry.absolute !== this.cwd) {
            this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', {
                entry,
                path: (0, normalize_windows_path_js_1.normalizeWindowsPath)(entry.path),
                resolvedPath: entry.absolute,
                cwd: this.cwd,
            });
            return false;
        }
        /* c8 ignore stop */
        // an archive can set properties on the extraction directory, but it
        // may not replace the cwd with a different kind of thing entirely.
        if (entry.absolute === this.cwd &&
            entry.type !== 'Directory' &&
            entry.type !== 'GNUDumpDir') {
            return false;
        }
        // only encode : chars that aren't drive letter indicators
        if (this.win32) {
            const { root: aRoot } = node_path_1.default.win32.parse(String(entry.absolute));
            entry.absolute =
                aRoot + wc.encode(String(entry.absolute).slice(aRoot.length));
            const { root: pRoot } = node_path_1.default.win32.parse(entry.path);
            entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length));
        }
        return true;
    }
    [ONENTRY](entry) {
        if (!this[CHECKPATH](entry)) {
            return entry.resume();
        }
        node_assert_1.default.equal(typeof entry.absolute, 'string');
        switch (entry.type) {
            case 'Directory':
            case 'GNUDumpDir':
                if (entry.mode) {
                    entry.mode = entry.mode | 0o700;
                }
            // eslint-disable-next-line no-fallthrough
            case 'File':
            case 'OldFile':
            case 'ContiguousFile':
            case 'Link':
            case 'SymbolicLink':
                return this[CHECKFS](entry);
            case 'CharacterDevice':
            case 'BlockDevice':
            case 'FIFO':
            default:
                return this[UNSUPPORTED](entry);
        }
    }
    [ONERROR](er, entry) {
        // Cwd has to exist, or else nothing works. That's serious.
        // Other errors are warnings, which raise the error in strict
        // mode, but otherwise continue on.
        if (er.name === 'CwdError') {
            this.emit('error', er);
        }
        else {
            this.warn('TAR_ENTRY_ERROR', er, { entry });
            this[UNPEND]();
            entry.resume();
        }
    }
    [MKDIR](dir, mode, cb) {
        (0, mkdir_js_1.mkdir)((0, normalize_windows_path_js_1.normalizeWindowsPath)(dir), {
            uid: this.uid,
            gid: this.gid,
            processUid: this.processUid,
            processGid: this.processGid,
            umask: this.processUmask,
            preserve: this.preservePaths,
            unlink: this.unlink,
            cache: this.dirCache,
            cwd: this.cwd,
            mode: mode,
        }, cb);
    }
    [DOCHOWN](entry) {
        // in preserve owner mode, chown if the entry doesn't match process
        // in set owner mode, chown if setting doesn't match process
        return (this.forceChown ||
            (this.preserveOwner &&
                ((typeof entry.uid === 'number' &&
                    entry.uid !== this.processUid) ||
                    (typeof entry.gid === 'number' &&
                        entry.gid !== this.processGid))) ||
            (typeof this.uid === 'number' &&
                this.uid !== this.processUid) ||
            (typeof this.gid === 'number' && this.gid !== this.processGid));
    }
    [UID](entry) {
        return uint32(this.uid, entry.uid, this.processUid);
    }
    [GID](entry) {
        return uint32(this.gid, entry.gid, this.processGid);
    }
    [FILE](entry, fullyDone) {
        const mode = typeof entry.mode === 'number' ?
            entry.mode & 0o7777
            : this.fmode;
        const stream = new fsm.WriteStream(String(entry.absolute), {
            // slight lie, but it can be numeric flags
            flags: (0, get_write_flag_js_1.getWriteFlag)(entry.size),
            mode: mode,
            autoClose: false,
        });
        stream.on('error', (er) => {
            if (stream.fd) {
                node_fs_1.default.close(stream.fd, () => { });
            }
            // flush all the data out so that we aren't left hanging
            // if the error wasn't actually fatal.  otherwise the parse
            // is blocked, and we never proceed.
            stream.write = () => true;
            this[ONERROR](er, entry);
            fullyDone();
        });
        let actions = 1;
        const done = (er) => {
            if (er) {
                /* c8 ignore start - we should always have a fd by now */
                if (stream.fd) {
                    node_fs_1.default.close(stream.fd, () => { });
                }
                /* c8 ignore stop */
                this[ONERROR](er, entry);
                fullyDone();
                return;
            }
            if (--actions === 0) {
                if (stream.fd !== undefined) {
                    node_fs_1.default.close(stream.fd, er => {
                        if (er) {
                            this[ONERROR](er, entry);
                        }
                        else {
                            this[UNPEND]();
                        }
                        fullyDone();
                    });
                }
            }
        };
        stream.on('finish', () => {
            // if futimes fails, try utimes
            // if utimes fails, fail with the original error
            // same for fchown/chown
            const abs = String(entry.absolute);
            const fd = stream.fd;
            if (typeof fd === 'number' && entry.mtime && !this.noMtime) {
                actions++;
                const atime = entry.atime || new Date();
                const mtime = entry.mtime;
                node_fs_1.default.futimes(fd, atime, mtime, er => er ?
                    node_fs_1.default.utimes(abs, atime, mtime, er2 => done(er2 && er))
                    : done());
            }
            if (typeof fd === 'number' && this[DOCHOWN](entry)) {
                actions++;
                const uid = this[UID](entry);
                const gid = this[GID](entry);
                if (typeof uid === 'number' && typeof gid === 'number') {
                    node_fs_1.default.fchown(fd, uid, gid, er => er ?
                        node_fs_1.default.chown(abs, uid, gid, er2 => done(er2 && er))
                        : done());
                }
            }
            done();
        });
        const tx = this.transform ? this.transform(entry) || entry : entry;
        if (tx !== entry) {
            tx.on('error', (er) => {
                this[ONERROR](er, entry);
                fullyDone();
            });
            entry.pipe(tx);
        }
        tx.pipe(stream);
    }
    [DIRECTORY](entry, fullyDone) {
        const mode = typeof entry.mode === 'number' ?
            entry.mode & 0o7777
            : this.dmode;
        this[MKDIR](String(entry.absolute), mode, er => {
            if (er) {
                this[ONERROR](er, entry);
                fullyDone();
                return;
            }
            let actions = 1;
            const done = () => {
                if (--actions === 0) {
                    fullyDone();
                    this[UNPEND]();
                    entry.resume();
                }
            };
            if (entry.mtime && !this.noMtime) {
                actions++;
                node_fs_1.default.utimes(String(entry.absolute), entry.atime || new Date(), entry.mtime, done);
            }
            if (this[DOCHOWN](entry)) {
                actions++;
                node_fs_1.default.chown(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)), done);
            }
            done();
        });
    }
    [UNSUPPORTED](entry) {
        entry.unsupported = true;
        this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry });
        entry.resume();
    }
    [SYMLINK](entry, done) {
        this[LINK](entry, String(entry.linkpath), 'symlink', done);
    }
    [HARDLINK](entry, done) {
        const linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(this.cwd, String(entry.linkpath)));
        this[LINK](entry, linkpath, 'link', done);
    }
    [PEND]() {
        this[PENDING]++;
    }
    [UNPEND]() {
        this[PENDING]--;
        this[MAYBECLOSE]();
    }
    [SKIP](entry) {
        this[UNPEND]();
        entry.resume();
    }
    // Check if we can reuse an existing filesystem entry safely and
    // overwrite it, rather than unlinking and recreating
    // Windows doesn't report a useful nlink, so we just never reuse entries
    [ISREUSABLE](entry, st) {
        return (entry.type === 'File' &&
            !this.unlink &&
            st.isFile() &&
            st.nlink <= 1 &&
            !isWindows);
    }
    // check if a thing is there, and if so, try to clobber it
    [CHECKFS](entry) {
        this[PEND]();
        const paths = [entry.path];
        if (entry.linkpath) {
            paths.push(entry.linkpath);
        }
        this.reservations.reserve(paths, done => this[CHECKFS2](entry, done));
    }
    [PRUNECACHE](entry) {
        // if we are not creating a directory, and the path is in the dirCache,
        // then that means we are about to delete the directory we created
        // previously, and it is no longer going to be a directory, and neither
        // is any of its children.
        // If a symbolic link is encountered, all bets are off.  There is no
        // reasonable way to sanitize the cache in such a way we will be able to
        // avoid having filesystem collisions.  If this happens with a non-symlink
        // entry, it'll just fail to unpack, but a symlink to a directory, using an
        // 8.3 shortname or certain unicode attacks, can evade detection and lead
        // to arbitrary writes to anywhere on the system.
        if (entry.type === 'SymbolicLink') {
            dropCache(this.dirCache);
        }
        else if (entry.type !== 'Directory') {
            pruneCache(this.dirCache, String(entry.absolute));
        }
    }
    [CHECKFS2](entry, fullyDone) {
        this[PRUNECACHE](entry);
        const done = (er) => {
            this[PRUNECACHE](entry);
            fullyDone(er);
        };
        const checkCwd = () => {
            this[MKDIR](this.cwd, this.dmode, er => {
                if (er) {
                    this[ONERROR](er, entry);
                    done();
                    return;
                }
                this[CHECKED_CWD] = true;
                start();
            });
        };
        const start = () => {
            if (entry.absolute !== this.cwd) {
                const parent = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.dirname(String(entry.absolute)));
                if (parent !== this.cwd) {
                    return this[MKDIR](parent, this.dmode, er => {
                        if (er) {
                            this[ONERROR](er, entry);
                            done();
                            return;
                        }
                        afterMakeParent();
                    });
                }
            }
            afterMakeParent();
        };
        const afterMakeParent = () => {
            node_fs_1.default.lstat(String(entry.absolute), (lstatEr, st) => {
                if (st &&
                    (this.keep ||
                        /* c8 ignore next */
                        (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
                    this[SKIP](entry);
                    done();
                    return;
                }
                if (lstatEr || this[ISREUSABLE](entry, st)) {
                    return this[MAKEFS](null, entry, done);
                }
                if (st.isDirectory()) {
                    if (entry.type === 'Directory') {
                        const needChmod = this.chmod &&
                            entry.mode &&
                            (st.mode & 0o7777) !== entry.mode;
                        const afterChmod = (er) => this[MAKEFS](er ?? null, entry, done);
                        if (!needChmod) {
                            return afterChmod();
                        }
                        return node_fs_1.default.chmod(String(entry.absolute), Number(entry.mode), afterChmod);
                    }
                    // Not a dir entry, have to remove it.
                    // NB: the only way to end up with an entry that is the cwd
                    // itself, in such a way that == does not detect, is a
                    // tricky windows absolute path with UNC or 8.3 parts (and
                    // preservePaths:true, or else it will have been stripped).
                    // In that case, the user has opted out of path protections
                    // explicitly, so if they blow away the cwd, c'est la vie.
                    if (entry.absolute !== this.cwd) {
                        return node_fs_1.default.rmdir(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done));
                    }
                }
                // not a dir, and not reusable
                // don't remove if the cwd, we want that error
                if (entry.absolute === this.cwd) {
                    return this[MAKEFS](null, entry, done);
                }
                unlinkFile(String(entry.absolute), er => this[MAKEFS](er ?? null, entry, done));
            });
        };
        if (this[CHECKED_CWD]) {
            start();
        }
        else {
            checkCwd();
        }
    }
    [MAKEFS](er, entry, done) {
        if (er) {
            this[ONERROR](er, entry);
            done();
            return;
        }
        switch (entry.type) {
            case 'File':
            case 'OldFile':
            case 'ContiguousFile':
                return this[FILE](entry, done);
            case 'Link':
                return this[HARDLINK](entry, done);
            case 'SymbolicLink':
                return this[SYMLINK](entry, done);
            case 'Directory':
            case 'GNUDumpDir':
                return this[DIRECTORY](entry, done);
        }
    }
    [LINK](entry, linkpath, link, done) {
        // XXX: get the type ('symlink' or 'junction') for windows
        node_fs_1.default[link](linkpath, String(entry.absolute), er => {
            if (er) {
                this[ONERROR](er, entry);
            }
            else {
                this[UNPEND]();
                entry.resume();
            }
            done();
        });
    }
}
exports.Unpack = Unpack;
const callSync = (fn) => {
    try {
        return [null, fn()];
    }
    catch (er) {
        return [er, null];
    }
};
class UnpackSync extends Unpack {
    sync = true;
    [MAKEFS](er, entry) {
        return super[MAKEFS](er, entry, () => { });
    }
    [CHECKFS](entry) {
        this[PRUNECACHE](entry);
        if (!this[CHECKED_CWD]) {
            const er = this[MKDIR](this.cwd, this.dmode);
            if (er) {
                return this[ONERROR](er, entry);
            }
            this[CHECKED_CWD] = true;
        }
        // don't bother to make the parent if the current entry is the cwd,
        // we've already checked it.
        if (entry.absolute !== this.cwd) {
            const parent = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.dirname(String(entry.absolute)));
            if (parent !== this.cwd) {
                const mkParent = this[MKDIR](parent, this.dmode);
                if (mkParent) {
                    return this[ONERROR](mkParent, entry);
                }
            }
        }
        const [lstatEr, st] = callSync(() => node_fs_1.default.lstatSync(String(entry.absolute)));
        if (st &&
            (this.keep ||
                /* c8 ignore next */
                (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
            return this[SKIP](entry);
        }
        if (lstatEr || this[ISREUSABLE](entry, st)) {
            return this[MAKEFS](null, entry);
        }
        if (st.isDirectory()) {
            if (entry.type === 'Directory') {
                const needChmod = this.chmod &&
                    entry.mode &&
                    (st.mode & 0o7777) !== entry.mode;
                const [er] = needChmod ?
                    callSync(() => {
                        node_fs_1.default.chmodSync(String(entry.absolute), Number(entry.mode));
                    })
                    : [];
                return this[MAKEFS](er, entry);
            }
            // not a dir entry, have to remove it
            const [er] = callSync(() => node_fs_1.default.rmdirSync(String(entry.absolute)));
            this[MAKEFS](er, entry);
        }
        // not a dir, and not reusable.
        // don't remove if it's the cwd, since we want that error.
        const [er] = entry.absolute === this.cwd ?
            []
            : callSync(() => unlinkFileSync(String(entry.absolute)));
        this[MAKEFS](er, entry);
    }
    [FILE](entry, done) {
        const mode = typeof entry.mode === 'number' ?
            entry.mode & 0o7777
            : this.fmode;
        const oner = (er) => {
            let closeError;
            try {
                node_fs_1.default.closeSync(fd);
            }
            catch (e) {
                closeError = e;
            }
            if (er || closeError) {
                this[ONERROR](er || closeError, entry);
            }
            done();
        };
        let fd;
        try {
            fd = node_fs_1.default.openSync(String(entry.absolute), (0, get_write_flag_js_1.getWriteFlag)(entry.size), mode);
        }
        catch (er) {
            return oner(er);
        }
        const tx = this.transform ? this.transform(entry) || entry : entry;
        if (tx !== entry) {
            tx.on('error', (er) => this[ONERROR](er, entry));
            entry.pipe(tx);
        }
        tx.on('data', (chunk) => {
            try {
                node_fs_1.default.writeSync(fd, chunk, 0, chunk.length);
            }
            catch (er) {
                oner(er);
            }
        });
        tx.on('end', () => {
            let er = null;
            // try both, falling futimes back to utimes
            // if either fails, handle the first error
            if (entry.mtime && !this.noMtime) {
                const atime = entry.atime || new Date();
                const mtime = entry.mtime;
                try {
                    node_fs_1.default.futimesSync(fd, atime, mtime);
                }
                catch (futimeser) {
                    try {
                        node_fs_1.default.utimesSync(String(entry.absolute), atime, mtime);
                    }
                    catch (utimeser) {
                        er = futimeser;
                    }
                }
            }
            if (this[DOCHOWN](entry)) {
                const uid = this[UID](entry);
                const gid = this[GID](entry);
                try {
                    node_fs_1.default.fchownSync(fd, Number(uid), Number(gid));
                }
                catch (fchowner) {
                    try {
                        node_fs_1.default.chownSync(String(entry.absolute), Number(uid), Number(gid));
                    }
                    catch (chowner) {
                        er = er || fchowner;
                    }
                }
            }
            oner(er);
        });
    }
    [DIRECTORY](entry, done) {
        const mode = typeof entry.mode === 'number' ?
            entry.mode & 0o7777
            : this.dmode;
        const er = this[MKDIR](String(entry.absolute), mode);
        if (er) {
            this[ONERROR](er, entry);
            done();
            return;
        }
        if (entry.mtime && !this.noMtime) {
            try {
                node_fs_1.default.utimesSync(String(entry.absolute), entry.atime || new Date(), entry.mtime);
                /* c8 ignore next */
            }
            catch (er) { }
        }
        if (this[DOCHOWN](entry)) {
            try {
                node_fs_1.default.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)));
            }
            catch (er) { }
        }
        done();
        entry.resume();
    }
    [MKDIR](dir, mode) {
        try {
            return (0, mkdir_js_1.mkdirSync)((0, normalize_windows_path_js_1.normalizeWindowsPath)(dir), {
                uid: this.uid,
                gid: this.gid,
                processUid: this.processUid,
                processGid: this.processGid,
                umask: this.processUmask,
                preserve: this.preservePaths,
                unlink: this.unlink,
                cache: this.dirCache,
                cwd: this.cwd,
                mode: mode,
            });
        }
        catch (er) {
            return er;
        }
    }
    [LINK](entry, linkpath, link, done) {
        const ls = `${link}Sync`;
        try {
            node_fs_1.default[ls](linkpath, String(entry.absolute));
            done();
            entry.resume();
        }
        catch (er) {
            return this[ONERROR](er, entry);
        }
    }
}
exports.UnpackSync = UnpackSync;
//# sourceMappingURL=unpack.js.map"use strict";
// tar -u
Object.defineProperty(exports, "__esModule", { value: true });
exports.update = void 0;
const make_command_js_1 = require("./make-command.js");
const replace_js_1 = require("./replace.js");
// just call tar.r with the filter and mtimeCache
exports.update = (0, make_command_js_1.makeCommand)(replace_js_1.replace.syncFile, replace_js_1.replace.asyncFile, replace_js_1.replace.syncNoFile, replace_js_1.replace.asyncNoFile, (opt, entries = []) => {
    replace_js_1.replace.validate?.(opt, entries);
    mtimeFilter(opt);
});
const mtimeFilter = (opt) => {
    const filter = opt.filter;
    if (!opt.mtimeCache) {
        opt.mtimeCache = new Map();
    }
    opt.filter =
        filter ?
            (path, stat) => filter(path, stat) &&
                !(
                /* c8 ignore start */
                ((opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) >
                    (stat.mtime ?? 0))
                /* c8 ignore stop */
                )
            : (path, stat) => !(
            /* c8 ignore start */
            ((opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) >
                (stat.mtime ?? 0))
            /* c8 ignore stop */
            );
};
//# sourceMappingURL=update.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.warnMethod = void 0;
const warnMethod = (self, code, message, data = {}) => {
    if (self.file) {
        data.file = self.file;
    }
    if (self.cwd) {
        data.cwd = self.cwd;
    }
    data.code =
        (message instanceof Error &&
            message.code) ||
            code;
    data.tarCode = code;
    if (!self.strict && data.recoverable !== false) {
        if (message instanceof Error) {
            data = Object.assign(message, data);
            message = message.message;
        }
        self.emit('warn', code, message, data);
    }
    else if (message instanceof Error) {
        self.emit('error', Object.assign(message, data));
    }
    else {
        self.emit('error', Object.assign(new Error(`${code}: ${message}`), data));
    }
};
exports.warnMethod = warnMethod;
//# sourceMappingURL=warn-method.js.map"use strict";
// When writing files on Windows, translate the characters to their
// 0xf000 higher-encoded versions.
Object.defineProperty(exports, "__esModule", { value: true });
exports.decode = exports.encode = void 0;
const raw = ['|', '<', '>', '?', ':'];
const win = raw.map(char => String.fromCharCode(0xf000 + char.charCodeAt(0)));
const toWin = new Map(raw.map((char, i) => [char, win[i]]));
const toRaw = new Map(win.map((char, i) => [char, raw[i]]));
const encode = (s) => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s);
exports.encode = encode;
const decode = (s) => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s);
exports.decode = decode;
//# sourceMappingURL=winchars.js.map"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WriteEntryTar = exports.WriteEntrySync = exports.WriteEntry = void 0;
const fs_1 = __importDefault(require("fs"));
const minipass_1 = require("minipass");
const path_1 = __importDefault(require("path"));
const header_js_1 = require("./header.js");
const mode_fix_js_1 = require("./mode-fix.js");
const normalize_windows_path_js_1 = require("./normalize-windows-path.js");
const options_js_1 = require("./options.js");
const pax_js_1 = require("./pax.js");
const strip_absolute_path_js_1 = require("./strip-absolute-path.js");
const strip_trailing_slashes_js_1 = require("./strip-trailing-slashes.js");
const warn_method_js_1 = require("./warn-method.js");
const winchars = __importStar(require("./winchars.js"));
const prefixPath = (path, prefix) => {
    if (!prefix) {
        return (0, normalize_windows_path_js_1.normalizeWindowsPath)(path);
    }
    path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(path).replace(/^\.(\/|$)/, '');
    return (0, strip_trailing_slashes_js_1.stripTrailingSlashes)(prefix) + '/' + path;
};
const maxReadSize = 16 * 1024 * 1024;
const PROCESS = Symbol('process');
const FILE = Symbol('file');
const DIRECTORY = Symbol('directory');
const SYMLINK = Symbol('symlink');
const HARDLINK = Symbol('hardlink');
const HEADER = Symbol('header');
const READ = Symbol('read');
const LSTAT = Symbol('lstat');
const ONLSTAT = Symbol('onlstat');
const ONREAD = Symbol('onread');
const ONREADLINK = Symbol('onreadlink');
const OPENFILE = Symbol('openfile');
const ONOPENFILE = Symbol('onopenfile');
const CLOSE = Symbol('close');
const MODE = Symbol('mode');
const AWAITDRAIN = Symbol('awaitDrain');
const ONDRAIN = Symbol('ondrain');
const PREFIX = Symbol('prefix');
class WriteEntry extends minipass_1.Minipass {
    path;
    portable;
    myuid = (process.getuid && process.getuid()) || 0;
    // until node has builtin pwnam functions, this'll have to do
    myuser = process.env.USER || '';
    maxReadSize;
    linkCache;
    statCache;
    preservePaths;
    cwd;
    strict;
    mtime;
    noPax;
    noMtime;
    prefix;
    fd;
    blockLen = 0;
    blockRemain = 0;
    buf;
    pos = 0;
    remain = 0;
    length = 0;
    offset = 0;
    win32;
    absolute;
    header;
    type;
    linkpath;
    stat;
    onWriteEntry;
    #hadError = false;
    constructor(p, opt_ = {}) {
        const opt = (0, options_js_1.dealias)(opt_);
        super();
        this.path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(p);
        // suppress atime, ctime, uid, gid, uname, gname
        this.portable = !!opt.portable;
        this.maxReadSize = opt.maxReadSize || maxReadSize;
        this.linkCache = opt.linkCache || new Map();
        this.statCache = opt.statCache || new Map();
        this.preservePaths = !!opt.preservePaths;
        this.cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.cwd || process.cwd());
        this.strict = !!opt.strict;
        this.noPax = !!opt.noPax;
        this.noMtime = !!opt.noMtime;
        this.mtime = opt.mtime;
        this.prefix =
            opt.prefix ? (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.prefix) : undefined;
        this.onWriteEntry = opt.onWriteEntry;
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        let pathWarn = false;
        if (!this.preservePaths) {
            const [root, stripped] = (0, strip_absolute_path_js_1.stripAbsolutePath)(this.path);
            if (root && typeof stripped === 'string') {
                this.path = stripped;
                pathWarn = root;
            }
        }
        this.win32 = !!opt.win32 || process.platform === 'win32';
        if (this.win32) {
            // force the \ to / normalization, since we might not *actually*
            // be on windows, but want \ to be considered a path separator.
            this.path = winchars.decode(this.path.replace(/\\/g, '/'));
            p = p.replace(/\\/g, '/');
        }
        this.absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(opt.absolute || path_1.default.resolve(this.cwd, p));
        if (this.path === '') {
            this.path = './';
        }
        if (pathWarn) {
            this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {
                entry: this,
                path: pathWarn + this.path,
            });
        }
        const cs = this.statCache.get(this.absolute);
        if (cs) {
            this[ONLSTAT](cs);
        }
        else {
            this[LSTAT]();
        }
    }
    warn(code, message, data = {}) {
        return (0, warn_method_js_1.warnMethod)(this, code, message, data);
    }
    emit(ev, ...data) {
        if (ev === 'error') {
            this.#hadError = true;
        }
        return super.emit(ev, ...data);
    }
    [LSTAT]() {
        fs_1.default.lstat(this.absolute, (er, stat) => {
            if (er) {
                return this.emit('error', er);
            }
            this[ONLSTAT](stat);
        });
    }
    [ONLSTAT](stat) {
        this.statCache.set(this.absolute, stat);
        this.stat = stat;
        if (!stat.isFile()) {
            stat.size = 0;
        }
        this.type = getType(stat);
        this.emit('stat', stat);
        this[PROCESS]();
    }
    [PROCESS]() {
        switch (this.type) {
            case 'File':
                return this[FILE]();
            case 'Directory':
                return this[DIRECTORY]();
            case 'SymbolicLink':
                return this[SYMLINK]();
            // unsupported types are ignored.
            default:
                return this.end();
        }
    }
    [MODE](mode) {
        return (0, mode_fix_js_1.modeFix)(mode, this.type === 'Directory', this.portable);
    }
    [PREFIX](path) {
        return prefixPath(path, this.prefix);
    }
    [HEADER]() {
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('cannot write header before stat');
        }
        /* c8 ignore stop */
        if (this.type === 'Directory' && this.portable) {
            this.noMtime = true;
        }
        this.onWriteEntry?.(this);
        this.header = new header_js_1.Header({
            path: this[PREFIX](this.path),
            // only apply the prefix to hard links.
            linkpath: this.type === 'Link' && this.linkpath !== undefined ?
                this[PREFIX](this.linkpath)
                : this.linkpath,
            // only the permissions and setuid/setgid/sticky bitflags
            // not the higher-order bits that specify file type
            mode: this[MODE](this.stat.mode),
            uid: this.portable ? undefined : this.stat.uid,
            gid: this.portable ? undefined : this.stat.gid,
            size: this.stat.size,
            mtime: this.noMtime ? undefined : this.mtime || this.stat.mtime,
            /* c8 ignore next */
            type: this.type === 'Unsupported' ? undefined : this.type,
            uname: this.portable ? undefined
                : this.stat.uid === this.myuid ? this.myuser
                    : '',
            atime: this.portable ? undefined : this.stat.atime,
            ctime: this.portable ? undefined : this.stat.ctime,
        });
        if (this.header.encode() && !this.noPax) {
            super.write(new pax_js_1.Pax({
                atime: this.portable ? undefined : this.header.atime,
                ctime: this.portable ? undefined : this.header.ctime,
                gid: this.portable ? undefined : this.header.gid,
                mtime: this.noMtime ? undefined : (this.mtime || this.header.mtime),
                path: this[PREFIX](this.path),
                linkpath: this.type === 'Link' && this.linkpath !== undefined ?
                    this[PREFIX](this.linkpath)
                    : this.linkpath,
                size: this.header.size,
                uid: this.portable ? undefined : this.header.uid,
                uname: this.portable ? undefined : this.header.uname,
                dev: this.portable ? undefined : this.stat.dev,
                ino: this.portable ? undefined : this.stat.ino,
                nlink: this.portable ? undefined : this.stat.nlink,
            }).encode());
        }
        const block = this.header?.block;
        /* c8 ignore start */
        if (!block) {
            throw new Error('failed to encode header');
        }
        /* c8 ignore stop */
        super.write(block);
    }
    [DIRECTORY]() {
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('cannot create directory entry without stat');
        }
        /* c8 ignore stop */
        if (this.path.slice(-1) !== '/') {
            this.path += '/';
        }
        this.stat.size = 0;
        this[HEADER]();
        this.end();
    }
    [SYMLINK]() {
        fs_1.default.readlink(this.absolute, (er, linkpath) => {
            if (er) {
                return this.emit('error', er);
            }
            this[ONREADLINK](linkpath);
        });
    }
    [ONREADLINK](linkpath) {
        this.linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(linkpath);
        this[HEADER]();
        this.end();
    }
    [HARDLINK](linkpath) {
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('cannot create link entry without stat');
        }
        /* c8 ignore stop */
        this.type = 'Link';
        this.linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(path_1.default.relative(this.cwd, linkpath));
        this.stat.size = 0;
        this[HEADER]();
        this.end();
    }
    [FILE]() {
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('cannot create file entry without stat');
        }
        /* c8 ignore stop */
        if (this.stat.nlink > 1) {
            const linkKey = `${this.stat.dev}:${this.stat.ino}`;
            const linkpath = this.linkCache.get(linkKey);
            if (linkpath?.indexOf(this.cwd) === 0) {
                return this[HARDLINK](linkpath);
            }
            this.linkCache.set(linkKey, this.absolute);
        }
        this[HEADER]();
        if (this.stat.size === 0) {
            return this.end();
        }
        this[OPENFILE]();
    }
    [OPENFILE]() {
        fs_1.default.open(this.absolute, 'r', (er, fd) => {
            if (er) {
                return this.emit('error', er);
            }
            this[ONOPENFILE](fd);
        });
    }
    [ONOPENFILE](fd) {
        this.fd = fd;
        if (this.#hadError) {
            return this[CLOSE]();
        }
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('should stat before calling onopenfile');
        }
        /* c8 ignore start */
        this.blockLen = 512 * Math.ceil(this.stat.size / 512);
        this.blockRemain = this.blockLen;
        const bufLen = Math.min(this.blockLen, this.maxReadSize);
        this.buf = Buffer.allocUnsafe(bufLen);
        this.offset = 0;
        this.pos = 0;
        this.remain = this.stat.size;
        this.length = this.buf.length;
        this[READ]();
    }
    [READ]() {
        const { fd, buf, offset, length, pos } = this;
        if (fd === undefined || buf === undefined) {
            throw new Error('cannot read file without first opening');
        }
        fs_1.default.read(fd, buf, offset, length, pos, (er, bytesRead) => {
            if (er) {
                // ignoring the error from close(2) is a bad practice, but at
                // this point we already have an error, don't need another one
                return this[CLOSE](() => this.emit('error', er));
            }
            this[ONREAD](bytesRead);
        });
    }
    /* c8 ignore start */
    [CLOSE](cb = () => { }) {
        /* c8 ignore stop */
        if (this.fd !== undefined)
            fs_1.default.close(this.fd, cb);
    }
    [ONREAD](bytesRead) {
        if (bytesRead <= 0 && this.remain > 0) {
            const er = Object.assign(new Error('encountered unexpected EOF'), {
                path: this.absolute,
                syscall: 'read',
                code: 'EOF',
            });
            return this[CLOSE](() => this.emit('error', er));
        }
        if (bytesRead > this.remain) {
            const er = Object.assign(new Error('did not encounter expected EOF'), {
                path: this.absolute,
                syscall: 'read',
                code: 'EOF',
            });
            return this[CLOSE](() => this.emit('error', er));
        }
        /* c8 ignore start */
        if (!this.buf) {
            throw new Error('should have created buffer prior to reading');
        }
        /* c8 ignore stop */
        // null out the rest of the buffer, if we could fit the block padding
        // at the end of this loop, we've incremented bytesRead and this.remain
        // to be incremented up to the blockRemain level, as if we had expected
        // to get a null-padded file, and read it until the end.  then we will
        // decrement both remain and blockRemain by bytesRead, and know that we
        // reached the expected EOF, without any null buffer to append.
        if (bytesRead === this.remain) {
            for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) {
                this.buf[i + this.offset] = 0;
                bytesRead++;
                this.remain++;
            }
        }
        const chunk = this.offset === 0 && bytesRead === this.buf.length ?
            this.buf
            : this.buf.subarray(this.offset, this.offset + bytesRead);
        const flushed = this.write(chunk);
        if (!flushed) {
            this[AWAITDRAIN](() => this[ONDRAIN]());
        }
        else {
            this[ONDRAIN]();
        }
    }
    [AWAITDRAIN](cb) {
        this.once('drain', cb);
    }
    write(chunk, encoding, cb) {
        /* c8 ignore start - just junk to comply with NodeJS.WritableStream */
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8');
        }
        /* c8 ignore stop */
        if (this.blockRemain < chunk.length) {
            const er = Object.assign(new Error('writing more data than expected'), {
                path: this.absolute,
            });
            return this.emit('error', er);
        }
        this.remain -= chunk.length;
        this.blockRemain -= chunk.length;
        this.pos += chunk.length;
        this.offset += chunk.length;
        return super.write(chunk, null, cb);
    }
    [ONDRAIN]() {
        if (!this.remain) {
            if (this.blockRemain) {
                super.write(Buffer.alloc(this.blockRemain));
            }
            return this[CLOSE](er => er ? this.emit('error', er) : this.end());
        }
        /* c8 ignore start */
        if (!this.buf) {
            throw new Error('buffer lost somehow in ONDRAIN');
        }
        /* c8 ignore stop */
        if (this.offset >= this.length) {
            // if we only have a smaller bit left to read, alloc a smaller buffer
            // otherwise, keep it the same length it was before.
            this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length));
            this.offset = 0;
        }
        this.length = this.buf.length - this.offset;
        this[READ]();
    }
}
exports.WriteEntry = WriteEntry;
class WriteEntrySync extends WriteEntry {
    sync = true;
    [LSTAT]() {
        this[ONLSTAT](fs_1.default.lstatSync(this.absolute));
    }
    [SYMLINK]() {
        this[ONREADLINK](fs_1.default.readlinkSync(this.absolute));
    }
    [OPENFILE]() {
        this[ONOPENFILE](fs_1.default.openSync(this.absolute, 'r'));
    }
    [READ]() {
        let threw = true;
        try {
            const { fd, buf, offset, length, pos } = this;
            /* c8 ignore start */
            if (fd === undefined || buf === undefined) {
                throw new Error('fd and buf must be set in READ method');
            }
            /* c8 ignore stop */
            const bytesRead = fs_1.default.readSync(fd, buf, offset, length, pos);
            this[ONREAD](bytesRead);
            threw = false;
        }
        finally {
            // ignoring the error from close(2) is a bad practice, but at
            // this point we already have an error, don't need another one
            if (threw) {
                try {
                    this[CLOSE](() => { });
                }
                catch (er) { }
            }
        }
    }
    [AWAITDRAIN](cb) {
        cb();
    }
    /* c8 ignore start */
    [CLOSE](cb = () => { }) {
        /* c8 ignore stop */
        if (this.fd !== undefined)
            fs_1.default.closeSync(this.fd);
        cb();
    }
}
exports.WriteEntrySync = WriteEntrySync;
class WriteEntryTar extends minipass_1.Minipass {
    blockLen = 0;
    blockRemain = 0;
    buf = 0;
    pos = 0;
    remain = 0;
    length = 0;
    preservePaths;
    portable;
    strict;
    noPax;
    noMtime;
    readEntry;
    type;
    prefix;
    path;
    mode;
    uid;
    gid;
    uname;
    gname;
    header;
    mtime;
    atime;
    ctime;
    linkpath;
    size;
    onWriteEntry;
    warn(code, message, data = {}) {
        return (0, warn_method_js_1.warnMethod)(this, code, message, data);
    }
    constructor(readEntry, opt_ = {}) {
        const opt = (0, options_js_1.dealias)(opt_);
        super();
        this.preservePaths = !!opt.preservePaths;
        this.portable = !!opt.portable;
        this.strict = !!opt.strict;
        this.noPax = !!opt.noPax;
        this.noMtime = !!opt.noMtime;
        this.onWriteEntry = opt.onWriteEntry;
        this.readEntry = readEntry;
        const { type } = readEntry;
        /* c8 ignore start */
        if (type === 'Unsupported') {
            throw new Error('writing entry that should be ignored');
        }
        /* c8 ignore stop */
        this.type = type;
        if (this.type === 'Directory' && this.portable) {
            this.noMtime = true;
        }
        this.prefix = opt.prefix;
        this.path = (0, normalize_windows_path_js_1.normalizeWindowsPath)(readEntry.path);
        this.mode =
            readEntry.mode !== undefined ?
                this[MODE](readEntry.mode)
                : undefined;
        this.uid = this.portable ? undefined : readEntry.uid;
        this.gid = this.portable ? undefined : readEntry.gid;
        this.uname = this.portable ? undefined : readEntry.uname;
        this.gname = this.portable ? undefined : readEntry.gname;
        this.size = readEntry.size;
        this.mtime =
            this.noMtime ? undefined : opt.mtime || readEntry.mtime;
        this.atime = this.portable ? undefined : readEntry.atime;
        this.ctime = this.portable ? undefined : readEntry.ctime;
        this.linkpath =
            readEntry.linkpath !== undefined ?
                (0, normalize_windows_path_js_1.normalizeWindowsPath)(readEntry.linkpath)
                : undefined;
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        let pathWarn = false;
        if (!this.preservePaths) {
            const [root, stripped] = (0, strip_absolute_path_js_1.stripAbsolutePath)(this.path);
            if (root && typeof stripped === 'string') {
                this.path = stripped;
                pathWarn = root;
            }
        }
        this.remain = readEntry.size;
        this.blockRemain = readEntry.startBlockSize;
        this.onWriteEntry?.(this);
        this.header = new header_js_1.Header({
            path: this[PREFIX](this.path),
            linkpath: this.type === 'Link' && this.linkpath !== undefined ?
                this[PREFIX](this.linkpath)
                : this.linkpath,
            // only the permissions and setuid/setgid/sticky bitflags
            // not the higher-order bits that specify file type
            mode: this.mode,
            uid: this.portable ? undefined : this.uid,
            gid: this.portable ? undefined : this.gid,
            size: this.size,
            mtime: this.noMtime ? undefined : this.mtime,
            type: this.type,
            uname: this.portable ? undefined : this.uname,
            atime: this.portable ? undefined : this.atime,
            ctime: this.portable ? undefined : this.ctime,
        });
        if (pathWarn) {
            this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {
                entry: this,
                path: pathWarn + this.path,
            });
        }
        if (this.header.encode() && !this.noPax) {
            super.write(new pax_js_1.Pax({
                atime: this.portable ? undefined : this.atime,
                ctime: this.portable ? undefined : this.ctime,
                gid: this.portable ? undefined : this.gid,
                mtime: this.noMtime ? undefined : this.mtime,
                path: this[PREFIX](this.path),
                linkpath: this.type === 'Link' && this.linkpath !== undefined ?
                    this[PREFIX](this.linkpath)
                    : this.linkpath,
                size: this.size,
                uid: this.portable ? undefined : this.uid,
                uname: this.portable ? undefined : this.uname,
                dev: this.portable ? undefined : this.readEntry.dev,
                ino: this.portable ? undefined : this.readEntry.ino,
                nlink: this.portable ? undefined : this.readEntry.nlink,
            }).encode());
        }
        const b = this.header?.block;
        /* c8 ignore start */
        if (!b)
            throw new Error('failed to encode header');
        /* c8 ignore stop */
        super.write(b);
        readEntry.pipe(this);
    }
    [PREFIX](path) {
        return prefixPath(path, this.prefix);
    }
    [MODE](mode) {
        return (0, mode_fix_js_1.modeFix)(mode, this.type === 'Directory', this.portable);
    }
    write(chunk, encoding, cb) {
        /* c8 ignore start - just junk to comply with NodeJS.WritableStream */
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8');
        }
        /* c8 ignore stop */
        const writeLen = chunk.length;
        if (writeLen > this.blockRemain) {
            throw new Error('writing more to entry than is appropriate');
        }
        this.blockRemain -= writeLen;
        return super.write(chunk, cb);
    }
    end(chunk, encoding, cb) {
        if (this.blockRemain) {
            super.write(Buffer.alloc(this.blockRemain));
        }
        /* c8 ignore start - just junk to comply with NodeJS.WritableStream */
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, encoding ?? 'utf8');
        }
        if (cb)
            this.once('finish', cb);
        chunk ? super.end(chunk, cb) : super.end(cb);
        /* c8 ignore stop */
        return this;
    }
}
exports.WriteEntryTar = WriteEntryTar;
const getType = (stat) => stat.isFile() ? 'File'
    : stat.isDirectory() ? 'Directory'
        : stat.isSymbolicLink() ? 'SymbolicLink'
            : 'Unsupported';
//# sourceMappingURL=write-entry.js.mapimport { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass';
import path from 'node:path';
import { list } from './list.js';
import { makeCommand } from './make-command.js';
import { Pack, PackSync } from './pack.js';
const createFileSync = (opt, files) => {
    const p = new PackSync(opt);
    const stream = new WriteStreamSync(opt.file, {
        mode: opt.mode || 0o666,
    });
    p.pipe(stream);
    addFilesSync(p, files);
};
const createFile = (opt, files) => {
    const p = new Pack(opt);
    const stream = new WriteStream(opt.file, {
        mode: opt.mode || 0o666,
    });
    p.pipe(stream);
    const promise = new Promise((res, rej) => {
        stream.on('error', rej);
        stream.on('close', res);
        p.on('error', rej);
    });
    addFilesAsync(p, files);
    return promise;
};
const addFilesSync = (p, files) => {
    files.forEach(file => {
        if (file.charAt(0) === '@') {
            list({
                file: path.resolve(p.cwd, file.slice(1)),
                sync: true,
                noResume: true,
                onReadEntry: entry => p.add(entry),
            });
        }
        else {
            p.add(file);
        }
    });
    p.end();
};
const addFilesAsync = async (p, files) => {
    for (let i = 0; i < files.length; i++) {
        const file = String(files[i]);
        if (file.charAt(0) === '@') {
            await list({
                file: path.resolve(String(p.cwd), file.slice(1)),
                noResume: true,
                onReadEntry: entry => {
                    p.add(entry);
                },
            });
        }
        else {
            p.add(file);
        }
    }
    p.end();
};
const createSync = (opt, files) => {
    const p = new PackSync(opt);
    addFilesSync(p, files);
    return p;
};
const createAsync = (opt, files) => {
    const p = new Pack(opt);
    addFilesAsync(p, files);
    return p;
};
export const create = makeCommand(createFileSync, createFile, createSync, createAsync, (_opt, files) => {
    if (!files?.length) {
        throw new TypeError('no paths specified to add to archive');
    }
});
//# sourceMappingURL=create.js.mapexport class CwdError extends Error {
    path;
    code;
    syscall = 'chdir';
    constructor(path, code) {
        super(`${code}: Cannot cd into '${path}'`);
        this.path = path;
        this.code = code;
    }
    get name() {
        return 'CwdError';
    }
}
//# sourceMappingURL=cwd-error.js.map// tar -x
import * as fsm from '@isaacs/fs-minipass';
import fs from 'node:fs';
import { filesFilter } from './list.js';
import { makeCommand } from './make-command.js';
import { Unpack, UnpackSync } from './unpack.js';
const extractFileSync = (opt) => {
    const u = new UnpackSync(opt);
    const file = opt.file;
    const stat = fs.statSync(file);
    // This trades a zero-byte read() syscall for a stat
    // However, it will usually result in less memory allocation
    const readSize = opt.maxReadSize || 16 * 1024 * 1024;
    const stream = new fsm.ReadStreamSync(file, {
        readSize: readSize,
        size: stat.size,
    });
    stream.pipe(u);
};
const extractFile = (opt, _) => {
    const u = new Unpack(opt);
    const readSize = opt.maxReadSize || 16 * 1024 * 1024;
    const file = opt.file;
    const p = new Promise((resolve, reject) => {
        u.on('error', reject);
        u.on('close', resolve);
        // This trades a zero-byte read() syscall for a stat
        // However, it will usually result in less memory allocation
        fs.stat(file, (er, stat) => {
            if (er) {
                reject(er);
            }
            else {
                const stream = new fsm.ReadStream(file, {
                    readSize: readSize,
                    size: stat.size,
                });
                stream.on('error', reject);
                stream.pipe(u);
            }
        });
    });
    return p;
};
export const extract = makeCommand(extractFileSync, extractFile, opt => new UnpackSync(opt), opt => new Unpack(opt), (opt, files) => {
    if (files?.length)
        filesFilter(opt, files);
});
//# sourceMappingURL=extract.js.map// Get the appropriate flag to use for creating files
// We use fmap on Windows platforms for files less than
// 512kb.  This is a fairly low limit, but avoids making
// things slower in some cases.  Since most of what this
// library is used for is extracting tarballs of many
// relatively small files in npm packages and the like,
// it can be a big boost on Windows platforms.
import fs from 'fs';
const platform = process.env.__FAKE_PLATFORM__ || process.platform;
const isWindows = platform === 'win32';
/* c8 ignore start */
const { O_CREAT, O_TRUNC, O_WRONLY } = fs.constants;
const UV_FS_O_FILEMAP = Number(process.env.__FAKE_FS_O_FILENAME__) ||
    fs.constants.UV_FS_O_FILEMAP ||
    0;
/* c8 ignore stop */
const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP;
const fMapLimit = 512 * 1024;
const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY;
export const getWriteFlag = !fMapEnabled ?
    () => 'w'
    : (size) => (size < fMapLimit ? fMapFlag : 'w');
//# sourceMappingURL=get-write-flag.js.map// parse a 512-byte header block to a data object, or vice-versa
// encode returns `true` if a pax extended header is needed, because
// the data could not be faithfully encoded in a simple header.
// (Also, check header.needPax to see if it needs a pax header.)
import { posix as pathModule } from 'node:path';
import * as large from './large-numbers.js';
import * as types from './types.js';
export class Header {
    cksumValid = false;
    needPax = false;
    nullBlock = false;
    block;
    path;
    mode;
    uid;
    gid;
    size;
    cksum;
    #type = 'Unsupported';
    linkpath;
    uname;
    gname;
    devmaj = 0;
    devmin = 0;
    atime;
    ctime;
    mtime;
    charset;
    comment;
    constructor(data, off = 0, ex, gex) {
        if (Buffer.isBuffer(data)) {
            this.decode(data, off || 0, ex, gex);
        }
        else if (data) {
            this.#slurp(data);
        }
    }
    decode(buf, off, ex, gex) {
        if (!off) {
            off = 0;
        }
        if (!buf || !(buf.length >= off + 512)) {
            throw new Error('need 512 bytes for header');
        }
        this.path = decString(buf, off, 100);
        this.mode = decNumber(buf, off + 100, 8);
        this.uid = decNumber(buf, off + 108, 8);
        this.gid = decNumber(buf, off + 116, 8);
        this.size = decNumber(buf, off + 124, 12);
        this.mtime = decDate(buf, off + 136, 12);
        this.cksum = decNumber(buf, off + 148, 12);
        // if we have extended or global extended headers, apply them now
        // See https://github.com/npm/node-tar/pull/187
        // Apply global before local, so it overrides
        if (gex)
            this.#slurp(gex, true);
        if (ex)
            this.#slurp(ex);
        // old tar versions marked dirs as a file with a trailing /
        const t = decString(buf, off + 156, 1);
        if (types.isCode(t)) {
            this.#type = t || '0';
        }
        if (this.#type === '0' && this.path.slice(-1) === '/') {
            this.#type = '5';
        }
        // tar implementations sometimes incorrectly put the stat(dir).size
        // as the size in the tarball, even though Directory entries are
        // not able to have any body at all.  In the very rare chance that
        // it actually DOES have a body, we weren't going to do anything with
        // it anyway, and it'll just be a warning about an invalid header.
        if (this.#type === '5') {
            this.size = 0;
        }
        this.linkpath = decString(buf, off + 157, 100);
        if (buf.subarray(off + 257, off + 265).toString() ===
            'ustar\u000000') {
            this.uname = decString(buf, off + 265, 32);
            this.gname = decString(buf, off + 297, 32);
            /* c8 ignore start */
            this.devmaj = decNumber(buf, off + 329, 8) ?? 0;
            this.devmin = decNumber(buf, off + 337, 8) ?? 0;
            /* c8 ignore stop */
            if (buf[off + 475] !== 0) {
                // definitely a prefix, definitely >130 chars.
                const prefix = decString(buf, off + 345, 155);
                this.path = prefix + '/' + this.path;
            }
            else {
                const prefix = decString(buf, off + 345, 130);
                if (prefix) {
                    this.path = prefix + '/' + this.path;
                }
                this.atime = decDate(buf, off + 476, 12);
                this.ctime = decDate(buf, off + 488, 12);
            }
        }
        let sum = 8 * 0x20;
        for (let i = off; i < off + 148; i++) {
            sum += buf[i];
        }
        for (let i = off + 156; i < off + 512; i++) {
            sum += buf[i];
        }
        this.cksumValid = sum === this.cksum;
        if (this.cksum === undefined && sum === 8 * 0x20) {
            this.nullBlock = true;
        }
    }
    #slurp(ex, gex = false) {
        Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => {
            // we slurp in everything except for the path attribute in
            // a global extended header, because that's weird. Also, any
            // null/undefined values are ignored.
            return !(v === null ||
                v === undefined ||
                (k === 'path' && gex) ||
                (k === 'linkpath' && gex) ||
                k === 'global');
        })));
    }
    encode(buf, off = 0) {
        if (!buf) {
            buf = this.block = Buffer.alloc(512);
        }
        if (this.#type === 'Unsupported') {
            this.#type = '0';
        }
        if (!(buf.length >= off + 512)) {
            throw new Error('need 512 bytes for header');
        }
        const prefixSize = this.ctime || this.atime ? 130 : 155;
        const split = splitPrefix(this.path || '', prefixSize);
        const path = split[0];
        const prefix = split[1];
        this.needPax = !!split[2];
        this.needPax = encString(buf, off, 100, path) || this.needPax;
        this.needPax =
            encNumber(buf, off + 100, 8, this.mode) || this.needPax;
        this.needPax =
            encNumber(buf, off + 108, 8, this.uid) || this.needPax;
        this.needPax =
            encNumber(buf, off + 116, 8, this.gid) || this.needPax;
        this.needPax =
            encNumber(buf, off + 124, 12, this.size) || this.needPax;
        this.needPax =
            encDate(buf, off + 136, 12, this.mtime) || this.needPax;
        buf[off + 156] = this.#type.charCodeAt(0);
        this.needPax =
            encString(buf, off + 157, 100, this.linkpath) || this.needPax;
        buf.write('ustar\u000000', off + 257, 8);
        this.needPax =
            encString(buf, off + 265, 32, this.uname) || this.needPax;
        this.needPax =
            encString(buf, off + 297, 32, this.gname) || this.needPax;
        this.needPax =
            encNumber(buf, off + 329, 8, this.devmaj) || this.needPax;
        this.needPax =
            encNumber(buf, off + 337, 8, this.devmin) || this.needPax;
        this.needPax =
            encString(buf, off + 345, prefixSize, prefix) || this.needPax;
        if (buf[off + 475] !== 0) {
            this.needPax =
                encString(buf, off + 345, 155, prefix) || this.needPax;
        }
        else {
            this.needPax =
                encString(buf, off + 345, 130, prefix) || this.needPax;
            this.needPax =
                encDate(buf, off + 476, 12, this.atime) || this.needPax;
            this.needPax =
                encDate(buf, off + 488, 12, this.ctime) || this.needPax;
        }
        let sum = 8 * 0x20;
        for (let i = off; i < off + 148; i++) {
            sum += buf[i];
        }
        for (let i = off + 156; i < off + 512; i++) {
            sum += buf[i];
        }
        this.cksum = sum;
        encNumber(buf, off + 148, 8, this.cksum);
        this.cksumValid = true;
        return this.needPax;
    }
    get type() {
        return (this.#type === 'Unsupported' ?
            this.#type
            : types.name.get(this.#type));
    }
    get typeKey() {
        return this.#type;
    }
    set type(type) {
        const c = String(types.code.get(type));
        if (types.isCode(c) || c === 'Unsupported') {
            this.#type = c;
        }
        else if (types.isCode(type)) {
            this.#type = type;
        }
        else {
            throw new TypeError('invalid entry type: ' + type);
        }
    }
}
const splitPrefix = (p, prefixSize) => {
    const pathSize = 100;
    let pp = p;
    let prefix = '';
    let ret = undefined;
    const root = pathModule.parse(p).root || '.';
    if (Buffer.byteLength(pp) < pathSize) {
        ret = [pp, prefix, false];
    }
    else {
        // first set prefix to the dir, and path to the base
        prefix = pathModule.dirname(pp);
        pp = pathModule.basename(pp);
        do {
            if (Buffer.byteLength(pp) <= pathSize &&
                Buffer.byteLength(prefix) <= prefixSize) {
                // both fit!
                ret = [pp, prefix, false];
            }
            else if (Buffer.byteLength(pp) > pathSize &&
                Buffer.byteLength(prefix) <= prefixSize) {
                // prefix fits in prefix, but path doesn't fit in path
                ret = [pp.slice(0, pathSize - 1), prefix, true];
            }
            else {
                // make path take a bit from prefix
                pp = pathModule.join(pathModule.basename(prefix), pp);
                prefix = pathModule.dirname(prefix);
            }
        } while (prefix !== root && ret === undefined);
        // at this point, found no resolution, just truncate
        if (!ret) {
            ret = [p.slice(0, pathSize - 1), '', true];
        }
    }
    return ret;
};
const decString = (buf, off, size) => buf
    .subarray(off, off + size)
    .toString('utf8')
    .replace(/\0.*/, '');
const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size));
const numToDate = (num) => num === undefined ? undefined : new Date(num * 1000);
const decNumber = (buf, off, size) => Number(buf[off]) & 0x80 ?
    large.parse(buf.subarray(off, off + size))
    : decSmallNumber(buf, off, size);
const nanUndef = (value) => (isNaN(value) ? undefined : value);
const decSmallNumber = (buf, off, size) => nanUndef(parseInt(buf
    .subarray(off, off + size)
    .toString('utf8')
    .replace(/\0.*$/, '')
    .trim(), 8));
// the maximum encodable as a null-terminated octal, by field size
const MAXNUM = {
    12: 0o77777777777,
    8: 0o7777777,
};
const encNumber = (buf, off, size, num) => num === undefined ? false
    : num > MAXNUM[size] || num < 0 ?
        (large.encode(num, buf.subarray(off, off + size)), true)
        : (encSmallNumber(buf, off, size, num), false);
const encSmallNumber = (buf, off, size, num) => buf.write(octalString(num, size), off, size, 'ascii');
const octalString = (num, size) => padOctal(Math.floor(num).toString(8), size);
const padOctal = (str, size) => (str.length === size - 1 ?
    str
    : new Array(size - str.length - 1).join('0') + str + ' ') + '\0';
const encDate = (buf, off, size, date) => date === undefined ? false : (encNumber(buf, off, size, date.getTime() / 1000));
// enough to fill the longest string we've got
const NULLS = new Array(156).join('\0');
// pad with nulls, return true if it's longer or non-ascii
const encString = (buf, off, size, str) => str === undefined ? false : ((buf.write(str + NULLS, off, size, 'utf8'),
    str.length !== Buffer.byteLength(str) || str.length > size));
//# sourceMappingURL=header.js.mapexport * from './create.js';
export { create as c } from './create.js';
export * from './extract.js';
export { extract as x } from './extract.js';
export * from './header.js';
export * from './list.js';
export { list as t } from './list.js';
// classes
export * from './pack.js';
export * from './parse.js';
export * from './pax.js';
export * from './read-entry.js';
export * from './replace.js';
export { replace as r } from './replace.js';
export * as types from './types.js';
export * from './unpack.js';
export * from './update.js';
export { update as u } from './update.js';
export * from './write-entry.js';
//# sourceMappingURL=index.js.map// Tar can encode large and negative numbers using a leading byte of
// 0xff for negative, and 0x80 for positive.
export const encode = (num, buf) => {
    if (!Number.isSafeInteger(num)) {
        // The number is so large that javascript cannot represent it with integer
        // precision.
        throw Error('cannot encode number outside of javascript safe integer range');
    }
    else if (num < 0) {
        encodeNegative(num, buf);
    }
    else {
        encodePositive(num, buf);
    }
    return buf;
};
const encodePositive = (num, buf) => {
    buf[0] = 0x80;
    for (var i = buf.length; i > 1; i--) {
        buf[i - 1] = num & 0xff;
        num = Math.floor(num / 0x100);
    }
};
const encodeNegative = (num, buf) => {
    buf[0] = 0xff;
    var flipped = false;
    num = num * -1;
    for (var i = buf.length; i > 1; i--) {
        var byte = num & 0xff;
        num = Math.floor(num / 0x100);
        if (flipped) {
            buf[i - 1] = onesComp(byte);
        }
        else if (byte === 0) {
            buf[i - 1] = 0;
        }
        else {
            flipped = true;
            buf[i - 1] = twosComp(byte);
        }
    }
};
export const parse = (buf) => {
    const pre = buf[0];
    const value = pre === 0x80 ? pos(buf.subarray(1, buf.length))
        : pre === 0xff ? twos(buf)
            : null;
    if (value === null) {
        throw Error('invalid base256 encoding');
    }
    if (!Number.isSafeInteger(value)) {
        // The number is so large that javascript cannot represent it with integer
        // precision.
        throw Error('parsed number outside of javascript safe integer range');
    }
    return value;
};
const twos = (buf) => {
    var len = buf.length;
    var sum = 0;
    var flipped = false;
    for (var i = len - 1; i > -1; i--) {
        var byte = Number(buf[i]);
        var f;
        if (flipped) {
            f = onesComp(byte);
        }
        else if (byte === 0) {
            f = byte;
        }
        else {
            flipped = true;
            f = twosComp(byte);
        }
        if (f !== 0) {
            sum -= f * Math.pow(256, len - i - 1);
        }
    }
    return sum;
};
const pos = (buf) => {
    var len = buf.length;
    var sum = 0;
    for (var i = len - 1; i > -1; i--) {
        var byte = Number(buf[i]);
        if (byte !== 0) {
            sum += byte * Math.pow(256, len - i - 1);
        }
    }
    return sum;
};
const onesComp = (byte) => (0xff ^ byte) & 0xff;
const twosComp = (byte) => ((0xff ^ byte) + 1) & 0xff;
//# sourceMappingURL=large-numbers.js.map// tar -t
import * as fsm from '@isaacs/fs-minipass';
import fs from 'node:fs';
import { dirname, parse } from 'path';
import { makeCommand } from './make-command.js';
import { Parser } from './parse.js';
import { stripTrailingSlashes } from './strip-trailing-slashes.js';
const onReadEntryFunction = (opt) => {
    const onReadEntry = opt.onReadEntry;
    opt.onReadEntry =
        onReadEntry ?
            e => {
                onReadEntry(e);
                e.resume();
            }
            : e => e.resume();
};
// construct a filter that limits the file entries listed
// include child entries if a dir is included
export const filesFilter = (opt, files) => {
    const map = new Map(files.map(f => [stripTrailingSlashes(f), true]));
    const filter = opt.filter;
    const mapHas = (file, r = '') => {
        const root = r || parse(file).root || '.';
        let ret;
        if (file === root)
            ret = false;
        else {
            const m = map.get(file);
            if (m !== undefined) {
                ret = m;
            }
            else {
                ret = mapHas(dirname(file), root);
            }
        }
        map.set(file, ret);
        return ret;
    };
    opt.filter =
        filter ?
            (file, entry) => filter(file, entry) && mapHas(stripTrailingSlashes(file))
            : file => mapHas(stripTrailingSlashes(file));
};
const listFileSync = (opt) => {
    const p = new Parser(opt);
    const file = opt.file;
    let fd;
    try {
        const stat = fs.statSync(file);
        const readSize = opt.maxReadSize || 16 * 1024 * 1024;
        if (stat.size < readSize) {
            p.end(fs.readFileSync(file));
        }
        else {
            let pos = 0;
            const buf = Buffer.allocUnsafe(readSize);
            fd = fs.openSync(file, 'r');
            while (pos < stat.size) {
                const bytesRead = fs.readSync(fd, buf, 0, readSize, pos);
                pos += bytesRead;
                p.write(buf.subarray(0, bytesRead));
            }
            p.end();
        }
    }
    finally {
        if (typeof fd === 'number') {
            try {
                fs.closeSync(fd);
                /* c8 ignore next */
            }
            catch (er) { }
        }
    }
};
const listFile = (opt, _files) => {
    const parse = new Parser(opt);
    const readSize = opt.maxReadSize || 16 * 1024 * 1024;
    const file = opt.file;
    const p = new Promise((resolve, reject) => {
        parse.on('error', reject);
        parse.on('end', resolve);
        fs.stat(file, (er, stat) => {
            if (er) {
                reject(er);
            }
            else {
                const stream = new fsm.ReadStream(file, {
                    readSize: readSize,
                    size: stat.size,
                });
                stream.on('error', reject);
                stream.pipe(parse);
            }
        });
    });
    return p;
};
export const list = makeCommand(listFileSync, listFile, opt => new Parser(opt), opt => new Parser(opt), (opt, files) => {
    if (files?.length)
        filesFilter(opt, files);
    if (!opt.noResume)
        onReadEntryFunction(opt);
});
//# sourceMappingURL=list.js.mapimport { dealias, isAsyncFile, isAsyncNoFile, isSyncFile, isSyncNoFile, } from './options.js';
export const makeCommand = (syncFile, asyncFile, syncNoFile, asyncNoFile, validate) => {
    return Object.assign((opt_ = [], entries, cb) => {
        if (Array.isArray(opt_)) {
            entries = opt_;
            opt_ = {};
        }
        if (typeof entries === 'function') {
            cb = entries;
            entries = undefined;
        }
        if (!entries) {
            entries = [];
        }
        else {
            entries = Array.from(entries);
        }
        const opt = dealias(opt_);
        validate?.(opt, entries);
        if (isSyncFile(opt)) {
            if (typeof cb === 'function') {
                throw new TypeError('callback not supported for sync tar functions');
            }
            return syncFile(opt, entries);
        }
        else if (isAsyncFile(opt)) {
            const p = asyncFile(opt, entries);
            // weirdness to make TS happy
            const c = cb ? cb : undefined;
            return c ? p.then(() => c(), c) : p;
        }
        else if (isSyncNoFile(opt)) {
            if (typeof cb === 'function') {
                throw new TypeError('callback not supported for sync tar functions');
            }
            return syncNoFile(opt, entries);
        }
        else if (isAsyncNoFile(opt)) {
            if (typeof cb === 'function') {
                throw new TypeError('callback only supported with file option');
            }
            return asyncNoFile(opt, entries);
            /* c8 ignore start */
        }
        else {
            throw new Error('impossible options??');
        }
        /* c8 ignore stop */
    }, {
        syncFile,
        asyncFile,
        syncNoFile,
        asyncNoFile,
        validate,
    });
};
//# sourceMappingURL=make-command.js.mapimport { chownr, chownrSync } from 'chownr';
import fs from 'fs';
import { mkdirp, mkdirpSync } from 'mkdirp';
import path from 'node:path';
import { CwdError } from './cwd-error.js';
import { normalizeWindowsPath } from './normalize-windows-path.js';
import { SymlinkError } from './symlink-error.js';
const cGet = (cache, key) => cache.get(normalizeWindowsPath(key));
const cSet = (cache, key, val) => cache.set(normalizeWindowsPath(key), val);
const checkCwd = (dir, cb) => {
    fs.stat(dir, (er, st) => {
        if (er || !st.isDirectory()) {
            er = new CwdError(dir, er?.code || 'ENOTDIR');
        }
        cb(er);
    });
};
/**
 * Wrapper around mkdirp for tar's needs.
 *
 * The main purpose is to avoid creating directories if we know that
 * they already exist (and track which ones exist for this purpose),
 * and prevent entries from being extracted into symlinked folders,
 * if `preservePaths` is not set.
 */
export const mkdir = (dir, opt, cb) => {
    dir = normalizeWindowsPath(dir);
    // if there's any overlap between mask and mode,
    // then we'll need an explicit chmod
    /* c8 ignore next */
    const umask = opt.umask ?? 0o22;
    const mode = opt.mode | 0o0700;
    const needChmod = (mode & umask) !== 0;
    const uid = opt.uid;
    const gid = opt.gid;
    const doChown = typeof uid === 'number' &&
        typeof gid === 'number' &&
        (uid !== opt.processUid || gid !== opt.processGid);
    const preserve = opt.preserve;
    const unlink = opt.unlink;
    const cache = opt.cache;
    const cwd = normalizeWindowsPath(opt.cwd);
    const done = (er, created) => {
        if (er) {
            cb(er);
        }
        else {
            cSet(cache, dir, true);
            if (created && doChown) {
                chownr(created, uid, gid, er => done(er));
            }
            else if (needChmod) {
                fs.chmod(dir, mode, cb);
            }
            else {
                cb();
            }
        }
    };
    if (cache && cGet(cache, dir) === true) {
        return done();
    }
    if (dir === cwd) {
        return checkCwd(dir, done);
    }
    if (preserve) {
        return mkdirp(dir, { mode }).then(made => done(null, made ?? undefined), // oh, ts
        done);
    }
    const sub = normalizeWindowsPath(path.relative(cwd, dir));
    const parts = sub.split('/');
    mkdir_(cwd, parts, mode, cache, unlink, cwd, undefined, done);
};
const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => {
    if (!parts.length) {
        return cb(null, created);
    }
    const p = parts.shift();
    const part = normalizeWindowsPath(path.resolve(base + '/' + p));
    if (cGet(cache, part)) {
        return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb);
    }
    fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb));
};
const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => (er) => {
    if (er) {
        fs.lstat(part, (statEr, st) => {
            if (statEr) {
                statEr.path =
                    statEr.path && normalizeWindowsPath(statEr.path);
                cb(statEr);
            }
            else if (st.isDirectory()) {
                mkdir_(part, parts, mode, cache, unlink, cwd, created, cb);
            }
            else if (unlink) {
                fs.unlink(part, er => {
                    if (er) {
                        return cb(er);
                    }
                    fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb));
                });
            }
            else if (st.isSymbolicLink()) {
                return cb(new SymlinkError(part, part + '/' + parts.join('/')));
            }
            else {
                cb(er);
            }
        });
    }
    else {
        created = created || part;
        mkdir_(part, parts, mode, cache, unlink, cwd, created, cb);
    }
};
const checkCwdSync = (dir) => {
    let ok = false;
    let code = undefined;
    try {
        ok = fs.statSync(dir).isDirectory();
    }
    catch (er) {
        code = er?.code;
    }
    finally {
        if (!ok) {
            throw new CwdError(dir, code ?? 'ENOTDIR');
        }
    }
};
export const mkdirSync = (dir, opt) => {
    dir = normalizeWindowsPath(dir);
    // if there's any overlap between mask and mode,
    // then we'll need an explicit chmod
    /* c8 ignore next */
    const umask = opt.umask ?? 0o22;
    const mode = opt.mode | 0o700;
    const needChmod = (mode & umask) !== 0;
    const uid = opt.uid;
    const gid = opt.gid;
    const doChown = typeof uid === 'number' &&
        typeof gid === 'number' &&
        (uid !== opt.processUid || gid !== opt.processGid);
    const preserve = opt.preserve;
    const unlink = opt.unlink;
    const cache = opt.cache;
    const cwd = normalizeWindowsPath(opt.cwd);
    const done = (created) => {
        cSet(cache, dir, true);
        if (created && doChown) {
            chownrSync(created, uid, gid);
        }
        if (needChmod) {
            fs.chmodSync(dir, mode);
        }
    };
    if (cache && cGet(cache, dir) === true) {
        return done();
    }
    if (dir === cwd) {
        checkCwdSync(cwd);
        return done();
    }
    if (preserve) {
        return done(mkdirpSync(dir, mode) ?? undefined);
    }
    const sub = normalizeWindowsPath(path.relative(cwd, dir));
    const parts = sub.split('/');
    let created = undefined;
    for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) {
        part = normalizeWindowsPath(path.resolve(part));
        if (cGet(cache, part)) {
            continue;
        }
        try {
            fs.mkdirSync(part, mode);
            created = created || part;
            cSet(cache, part, true);
        }
        catch (er) {
            const st = fs.lstatSync(part);
            if (st.isDirectory()) {
                cSet(cache, part, true);
                continue;
            }
            else if (unlink) {
                fs.unlinkSync(part);
                fs.mkdirSync(part, mode);
                created = created || part;
                cSet(cache, part, true);
                continue;
            }
            else if (st.isSymbolicLink()) {
                return new SymlinkError(part, part + '/' + parts.join('/'));
            }
        }
    }
    return done(created);
};
//# sourceMappingURL=mkdir.js.mapexport const modeFix = (mode, isDir, portable) => {
    mode &= 0o7777;
    // in portable mode, use the minimum reasonable umask
    // if this system creates files with 0o664 by default
    // (as some linux distros do), then we'll write the
    // archive with 0o644 instead.  Also, don't ever create
    // a file that is not readable/writable by the owner.
    if (portable) {
        mode = (mode | 0o600) & ~0o22;
    }
    // if dirs are readable, then they should be listable
    if (isDir) {
        if (mode & 0o400) {
            mode |= 0o100;
        }
        if (mode & 0o40) {
            mode |= 0o10;
        }
        if (mode & 0o4) {
            mode |= 0o1;
        }
    }
    return mode;
};
//# sourceMappingURL=mode-fix.js.map// warning: extremely hot code path.
// This has been meticulously optimized for use
// within npm install on large package trees.
// Do not edit without careful benchmarking.
const normalizeCache = Object.create(null);
const { hasOwnProperty } = Object.prototype;
export const normalizeUnicode = (s) => {
    if (!hasOwnProperty.call(normalizeCache, s)) {
        normalizeCache[s] = s.normalize('NFD');
    }
    return normalizeCache[s];
};
//# sourceMappingURL=normalize-unicode.js.map// on windows, either \ or / are valid directory separators.
// on unix, \ is a valid character in filenames.
// so, on windows, and only on windows, we replace all \ chars with /,
// so that we can use / as our one and only directory separator char.
const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
export const normalizeWindowsPath = platform !== 'win32' ?
    (p) => p
    : (p) => p && p.replace(/\\/g, '/');
//# sourceMappingURL=normalize-windows-path.js.map// turn tar(1) style args like `C` into the more verbose things like `cwd`
const argmap = new Map([
    ['C', 'cwd'],
    ['f', 'file'],
    ['z', 'gzip'],
    ['P', 'preservePaths'],
    ['U', 'unlink'],
    ['strip-components', 'strip'],
    ['stripComponents', 'strip'],
    ['keep-newer', 'newer'],
    ['keepNewer', 'newer'],
    ['keep-newer-files', 'newer'],
    ['keepNewerFiles', 'newer'],
    ['k', 'keep'],
    ['keep-existing', 'keep'],
    ['keepExisting', 'keep'],
    ['m', 'noMtime'],
    ['no-mtime', 'noMtime'],
    ['p', 'preserveOwner'],
    ['L', 'follow'],
    ['h', 'follow'],
    ['onentry', 'onReadEntry'],
]);
export const isSyncFile = (o) => !!o.sync && !!o.file;
export const isAsyncFile = (o) => !o.sync && !!o.file;
export const isSyncNoFile = (o) => !!o.sync && !o.file;
export const isAsyncNoFile = (o) => !o.sync && !o.file;
export const isSync = (o) => !!o.sync;
export const isAsync = (o) => !o.sync;
export const isFile = (o) => !!o.file;
export const isNoFile = (o) => !o.file;
const dealiasKey = (k) => {
    const d = argmap.get(k);
    if (d)
        return d;
    return k;
};
export const dealias = (opt = {}) => {
    if (!opt)
        return {};
    const result = {};
    for (const [key, v] of Object.entries(opt)) {
        // TS doesn't know that aliases are going to always be the same type
        const k = dealiasKey(key);
        result[k] = v;
    }
    // affordance for deprecated noChmod -> chmod
    if (result.chmod === undefined && result.noChmod === false) {
        result.chmod = true;
    }
    delete result.noChmod;
    return result;
};
//# sourceMappingURL=options.js.map// A readable tar stream creator
// Technically, this is a transform stream that you write paths into,
// and tar format comes out of.
// The `add()` method is like `write()` but returns this,
// and end() return `this` as well, so you can
// do `new Pack(opt).add('files').add('dir').end().pipe(output)
// You could also do something like:
// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))
import fs from 'fs';
import { WriteEntry, WriteEntrySync, WriteEntryTar, } from './write-entry.js';
export class PackJob {
    path;
    absolute;
    entry;
    stat;
    readdir;
    pending = false;
    ignore = false;
    piped = false;
    constructor(path, absolute) {
        this.path = path || './';
        this.absolute = absolute;
    }
}
import { Minipass } from 'minipass';
import * as zlib from 'minizlib';
import { Yallist } from 'yallist';
import { ReadEntry } from './read-entry.js';
import { warnMethod, } from './warn-method.js';
const EOF = Buffer.alloc(1024);
const ONSTAT = Symbol('onStat');
const ENDED = Symbol('ended');
const QUEUE = Symbol('queue');
const CURRENT = Symbol('current');
const PROCESS = Symbol('process');
const PROCESSING = Symbol('processing');
const PROCESSJOB = Symbol('processJob');
const JOBS = Symbol('jobs');
const JOBDONE = Symbol('jobDone');
const ADDFSENTRY = Symbol('addFSEntry');
const ADDTARENTRY = Symbol('addTarEntry');
const STAT = Symbol('stat');
const READDIR = Symbol('readdir');
const ONREADDIR = Symbol('onreaddir');
const PIPE = Symbol('pipe');
const ENTRY = Symbol('entry');
const ENTRYOPT = Symbol('entryOpt');
const WRITEENTRYCLASS = Symbol('writeEntryClass');
const WRITE = Symbol('write');
const ONDRAIN = Symbol('ondrain');
import path from 'path';
import { normalizeWindowsPath } from './normalize-windows-path.js';
export class Pack extends Minipass {
    opt;
    cwd;
    maxReadSize;
    preservePaths;
    strict;
    noPax;
    prefix;
    linkCache;
    statCache;
    file;
    portable;
    zip;
    readdirCache;
    noDirRecurse;
    follow;
    noMtime;
    mtime;
    filter;
    jobs;
    [WRITEENTRYCLASS];
    onWriteEntry;
    [QUEUE];
    [JOBS] = 0;
    [PROCESSING] = false;
    [ENDED] = false;
    constructor(opt = {}) {
        //@ts-ignore
        super();
        this.opt = opt;
        this.file = opt.file || '';
        this.cwd = opt.cwd || process.cwd();
        this.maxReadSize = opt.maxReadSize;
        this.preservePaths = !!opt.preservePaths;
        this.strict = !!opt.strict;
        this.noPax = !!opt.noPax;
        this.prefix = normalizeWindowsPath(opt.prefix || '');
        this.linkCache = opt.linkCache || new Map();
        this.statCache = opt.statCache || new Map();
        this.readdirCache = opt.readdirCache || new Map();
        this.onWriteEntry = opt.onWriteEntry;
        this[WRITEENTRYCLASS] = WriteEntry;
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        this.portable = !!opt.portable;
        if (opt.gzip || opt.brotli) {
            if (opt.gzip && opt.brotli) {
                throw new TypeError('gzip and brotli are mutually exclusive');
            }
            if (opt.gzip) {
                if (typeof opt.gzip !== 'object') {
                    opt.gzip = {};
                }
                if (this.portable) {
                    opt.gzip.portable = true;
                }
                this.zip = new zlib.Gzip(opt.gzip);
            }
            if (opt.brotli) {
                if (typeof opt.brotli !== 'object') {
                    opt.brotli = {};
                }
                this.zip = new zlib.BrotliCompress(opt.brotli);
            }
            /* c8 ignore next */
            if (!this.zip)
                throw new Error('impossible');
            const zip = this.zip;
            zip.on('data', chunk => super.write(chunk));
            zip.on('end', () => super.end());
            zip.on('drain', () => this[ONDRAIN]());
            this.on('resume', () => zip.resume());
        }
        else {
            this.on('drain', this[ONDRAIN]);
        }
        this.noDirRecurse = !!opt.noDirRecurse;
        this.follow = !!opt.follow;
        this.noMtime = !!opt.noMtime;
        if (opt.mtime)
            this.mtime = opt.mtime;
        this.filter =
            typeof opt.filter === 'function' ? opt.filter : () => true;
        this[QUEUE] = new Yallist();
        this[JOBS] = 0;
        this.jobs = Number(opt.jobs) || 4;
        this[PROCESSING] = false;
        this[ENDED] = false;
    }
    [WRITE](chunk) {
        return super.write(chunk);
    }
    add(path) {
        this.write(path);
        return this;
    }
    end(path, encoding, cb) {
        /* c8 ignore start */
        if (typeof path === 'function') {
            cb = path;
            path = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (path) {
            this.add(path);
        }
        this[ENDED] = true;
        this[PROCESS]();
        /* c8 ignore next */
        if (cb)
            cb();
        return this;
    }
    write(path) {
        if (this[ENDED]) {
            throw new Error('write after end');
        }
        if (path instanceof ReadEntry) {
            this[ADDTARENTRY](path);
        }
        else {
            this[ADDFSENTRY](path);
        }
        return this.flowing;
    }
    [ADDTARENTRY](p) {
        const absolute = normalizeWindowsPath(path.resolve(this.cwd, p.path));
        // in this case, we don't have to wait for the stat
        if (!this.filter(p.path, p)) {
            p.resume();
        }
        else {
            const job = new PackJob(p.path, absolute);
            job.entry = new WriteEntryTar(p, this[ENTRYOPT](job));
            job.entry.on('end', () => this[JOBDONE](job));
            this[JOBS] += 1;
            this[QUEUE].push(job);
        }
        this[PROCESS]();
    }
    [ADDFSENTRY](p) {
        const absolute = normalizeWindowsPath(path.resolve(this.cwd, p));
        this[QUEUE].push(new PackJob(p, absolute));
        this[PROCESS]();
    }
    [STAT](job) {
        job.pending = true;
        this[JOBS] += 1;
        const stat = this.follow ? 'stat' : 'lstat';
        fs[stat](job.absolute, (er, stat) => {
            job.pending = false;
            this[JOBS] -= 1;
            if (er) {
                this.emit('error', er);
            }
            else {
                this[ONSTAT](job, stat);
            }
        });
    }
    [ONSTAT](job, stat) {
        this.statCache.set(job.absolute, stat);
        job.stat = stat;
        // now we have the stat, we can filter it.
        if (!this.filter(job.path, stat)) {
            job.ignore = true;
        }
        this[PROCESS]();
    }
    [READDIR](job) {
        job.pending = true;
        this[JOBS] += 1;
        fs.readdir(job.absolute, (er, entries) => {
            job.pending = false;
            this[JOBS] -= 1;
            if (er) {
                return this.emit('error', er);
            }
            this[ONREADDIR](job, entries);
        });
    }
    [ONREADDIR](job, entries) {
        this.readdirCache.set(job.absolute, entries);
        job.readdir = entries;
        this[PROCESS]();
    }
    [PROCESS]() {
        if (this[PROCESSING]) {
            return;
        }
        this[PROCESSING] = true;
        for (let w = this[QUEUE].head; !!w && this[JOBS] < this.jobs; w = w.next) {
            this[PROCESSJOB](w.value);
            if (w.value.ignore) {
                const p = w.next;
                this[QUEUE].removeNode(w);
                w.next = p;
            }
        }
        this[PROCESSING] = false;
        if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) {
            if (this.zip) {
                this.zip.end(EOF);
            }
            else {
                super.write(EOF);
                super.end();
            }
        }
    }
    get [CURRENT]() {
        return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value;
    }
    [JOBDONE](_job) {
        this[QUEUE].shift();
        this[JOBS] -= 1;
        this[PROCESS]();
    }
    [PROCESSJOB](job) {
        if (job.pending) {
            return;
        }
        if (job.entry) {
            if (job === this[CURRENT] && !job.piped) {
                this[PIPE](job);
            }
            return;
        }
        if (!job.stat) {
            const sc = this.statCache.get(job.absolute);
            if (sc) {
                this[ONSTAT](job, sc);
            }
            else {
                this[STAT](job);
            }
        }
        if (!job.stat) {
            return;
        }
        // filtered out!
        if (job.ignore) {
            return;
        }
        if (!this.noDirRecurse &&
            job.stat.isDirectory() &&
            !job.readdir) {
            const rc = this.readdirCache.get(job.absolute);
            if (rc) {
                this[ONREADDIR](job, rc);
            }
            else {
                this[READDIR](job);
            }
            if (!job.readdir) {
                return;
            }
        }
        // we know it doesn't have an entry, because that got checked above
        job.entry = this[ENTRY](job);
        if (!job.entry) {
            job.ignore = true;
            return;
        }
        if (job === this[CURRENT] && !job.piped) {
            this[PIPE](job);
        }
    }
    [ENTRYOPT](job) {
        return {
            onwarn: (code, msg, data) => this.warn(code, msg, data),
            noPax: this.noPax,
            cwd: this.cwd,
            absolute: job.absolute,
            preservePaths: this.preservePaths,
            maxReadSize: this.maxReadSize,
            strict: this.strict,
            portable: this.portable,
            linkCache: this.linkCache,
            statCache: this.statCache,
            noMtime: this.noMtime,
            mtime: this.mtime,
            prefix: this.prefix,
            onWriteEntry: this.onWriteEntry,
        };
    }
    [ENTRY](job) {
        this[JOBS] += 1;
        try {
            const e = new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job));
            return e
                .on('end', () => this[JOBDONE](job))
                .on('error', er => this.emit('error', er));
        }
        catch (er) {
            this.emit('error', er);
        }
    }
    [ONDRAIN]() {
        if (this[CURRENT] && this[CURRENT].entry) {
            this[CURRENT].entry.resume();
        }
    }
    // like .pipe() but using super, because our write() is special
    [PIPE](job) {
        job.piped = true;
        if (job.readdir) {
            job.readdir.forEach(entry => {
                const p = job.path;
                const base = p === './' ? '' : p.replace(/\/*$/, '/');
                this[ADDFSENTRY](base + entry);
            });
        }
        const source = job.entry;
        const zip = this.zip;
        /* c8 ignore start */
        if (!source)
            throw new Error('cannot pipe without source');
        /* c8 ignore stop */
        if (zip) {
            source.on('data', chunk => {
                if (!zip.write(chunk)) {
                    source.pause();
                }
            });
        }
        else {
            source.on('data', chunk => {
                if (!super.write(chunk)) {
                    source.pause();
                }
            });
        }
    }
    pause() {
        if (this.zip) {
            this.zip.pause();
        }
        return super.pause();
    }
    warn(code, message, data = {}) {
        warnMethod(this, code, message, data);
    }
}
export class PackSync extends Pack {
    sync = true;
    constructor(opt) {
        super(opt);
        this[WRITEENTRYCLASS] = WriteEntrySync;
    }
    // pause/resume are no-ops in sync streams.
    pause() { }
    resume() { }
    [STAT](job) {
        const stat = this.follow ? 'statSync' : 'lstatSync';
        this[ONSTAT](job, fs[stat](job.absolute));
    }
    [READDIR](job) {
        this[ONREADDIR](job, fs.readdirSync(job.absolute));
    }
    // gotta get it all in this tick
    [PIPE](job) {
        const source = job.entry;
        const zip = this.zip;
        if (job.readdir) {
            job.readdir.forEach(entry => {
                const p = job.path;
                const base = p === './' ? '' : p.replace(/\/*$/, '/');
                this[ADDFSENTRY](base + entry);
            });
        }
        /* c8 ignore start */
        if (!source)
            throw new Error('Cannot pipe without source');
        /* c8 ignore stop */
        if (zip) {
            source.on('data', chunk => {
                zip.write(chunk);
            });
        }
        else {
            source.on('data', chunk => {
                super[WRITE](chunk);
            });
        }
    }
}
//# sourceMappingURL=pack.js.map{
  "type": "module"
}
// this[BUFFER] is the remainder of a chunk if we're waiting for
// the full 512 bytes of a header to come in.  We will Buffer.concat()
// it to the next write(), which is a mem copy, but a small one.
//
// this[QUEUE] is a Yallist of entries that haven't been emitted
// yet this can only get filled up if the user keeps write()ing after
// a write() returns false, or does a write() with more than one entry
//
// We don't buffer chunks, we always parse them and either create an
// entry, or push it into the active entry.  The ReadEntry class knows
// to throw data away if .ignore=true
//
// Shift entry off the buffer when it emits 'end', and emit 'entry' for
// the next one in the list.
//
// At any time, we're pushing body chunks into the entry at WRITEENTRY,
// and waiting for 'end' on the entry at READENTRY
//
// ignored entries get .resume() called on them straight away
import { EventEmitter as EE } from 'events';
import { BrotliDecompress, Unzip } from 'minizlib';
import { Yallist } from 'yallist';
import { Header } from './header.js';
import { Pax } from './pax.js';
import { ReadEntry } from './read-entry.js';
import { warnMethod, } from './warn-method.js';
const maxMetaEntrySize = 1024 * 1024;
const gzipHeader = Buffer.from([0x1f, 0x8b]);
const STATE = Symbol('state');
const WRITEENTRY = Symbol('writeEntry');
const READENTRY = Symbol('readEntry');
const NEXTENTRY = Symbol('nextEntry');
const PROCESSENTRY = Symbol('processEntry');
const EX = Symbol('extendedHeader');
const GEX = Symbol('globalExtendedHeader');
const META = Symbol('meta');
const EMITMETA = Symbol('emitMeta');
const BUFFER = Symbol('buffer');
const QUEUE = Symbol('queue');
const ENDED = Symbol('ended');
const EMITTEDEND = Symbol('emittedEnd');
const EMIT = Symbol('emit');
const UNZIP = Symbol('unzip');
const CONSUMECHUNK = Symbol('consumeChunk');
const CONSUMECHUNKSUB = Symbol('consumeChunkSub');
const CONSUMEBODY = Symbol('consumeBody');
const CONSUMEMETA = Symbol('consumeMeta');
const CONSUMEHEADER = Symbol('consumeHeader');
const CONSUMING = Symbol('consuming');
const BUFFERCONCAT = Symbol('bufferConcat');
const MAYBEEND = Symbol('maybeEnd');
const WRITING = Symbol('writing');
const ABORTED = Symbol('aborted');
const DONE = Symbol('onDone');
const SAW_VALID_ENTRY = Symbol('sawValidEntry');
const SAW_NULL_BLOCK = Symbol('sawNullBlock');
const SAW_EOF = Symbol('sawEOF');
const CLOSESTREAM = Symbol('closeStream');
const noop = () => true;
export class Parser extends EE {
    file;
    strict;
    maxMetaEntrySize;
    filter;
    brotli;
    writable = true;
    readable = false;
    [QUEUE] = new Yallist();
    [BUFFER];
    [READENTRY];
    [WRITEENTRY];
    [STATE] = 'begin';
    [META] = '';
    [EX];
    [GEX];
    [ENDED] = false;
    [UNZIP];
    [ABORTED] = false;
    [SAW_VALID_ENTRY];
    [SAW_NULL_BLOCK] = false;
    [SAW_EOF] = false;
    [WRITING] = false;
    [CONSUMING] = false;
    [EMITTEDEND] = false;
    constructor(opt = {}) {
        super();
        this.file = opt.file || '';
        // these BADARCHIVE errors can't be detected early. listen on DONE.
        this.on(DONE, () => {
            if (this[STATE] === 'begin' ||
                this[SAW_VALID_ENTRY] === false) {
                // either less than 1 block of data, or all entries were invalid.
                // Either way, probably not even a tarball.
                this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format');
            }
        });
        if (opt.ondone) {
            this.on(DONE, opt.ondone);
        }
        else {
            this.on(DONE, () => {
                this.emit('prefinish');
                this.emit('finish');
                this.emit('end');
            });
        }
        this.strict = !!opt.strict;
        this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize;
        this.filter = typeof opt.filter === 'function' ? opt.filter : noop;
        // Unlike gzip, brotli doesn't have any magic bytes to identify it
        // Users need to explicitly tell us they're extracting a brotli file
        // Or we infer from the file extension
        const isTBR = opt.file &&
            (opt.file.endsWith('.tar.br') || opt.file.endsWith('.tbr'));
        // if it's a tbr file it MIGHT be brotli, but we don't know until
        // we look at it and verify it's not a valid tar file.
        this.brotli =
            !opt.gzip && opt.brotli !== undefined ? opt.brotli
                : isTBR ? undefined
                    : false;
        // have to set this so that streams are ok piping into it
        this.on('end', () => this[CLOSESTREAM]());
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        if (typeof opt.onReadEntry === 'function') {
            this.on('entry', opt.onReadEntry);
        }
    }
    warn(code, message, data = {}) {
        warnMethod(this, code, message, data);
    }
    [CONSUMEHEADER](chunk, position) {
        if (this[SAW_VALID_ENTRY] === undefined) {
            this[SAW_VALID_ENTRY] = false;
        }
        let header;
        try {
            header = new Header(chunk, position, this[EX], this[GEX]);
        }
        catch (er) {
            return this.warn('TAR_ENTRY_INVALID', er);
        }
        if (header.nullBlock) {
            if (this[SAW_NULL_BLOCK]) {
                this[SAW_EOF] = true;
                // ending an archive with no entries.  pointless, but legal.
                if (this[STATE] === 'begin') {
                    this[STATE] = 'header';
                }
                this[EMIT]('eof');
            }
            else {
                this[SAW_NULL_BLOCK] = true;
                this[EMIT]('nullBlock');
            }
        }
        else {
            this[SAW_NULL_BLOCK] = false;
            if (!header.cksumValid) {
                this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header });
            }
            else if (!header.path) {
                this.warn('TAR_ENTRY_INVALID', 'path is required', { header });
            }
            else {
                const type = header.type;
                if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) {
                    this.warn('TAR_ENTRY_INVALID', 'linkpath required', {
                        header,
                    });
                }
                else if (!/^(Symbolic)?Link$/.test(type) &&
                    !/^(Global)?ExtendedHeader$/.test(type) &&
                    header.linkpath) {
                    this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {
                        header,
                    });
                }
                else {
                    const entry = (this[WRITEENTRY] = new ReadEntry(header, this[EX], this[GEX]));
                    // we do this for meta & ignored entries as well, because they
                    // are still valid tar, or else we wouldn't know to ignore them
                    if (!this[SAW_VALID_ENTRY]) {
                        if (entry.remain) {
                            // this might be the one!
                            const onend = () => {
                                if (!entry.invalid) {
                                    this[SAW_VALID_ENTRY] = true;
                                }
                            };
                            entry.on('end', onend);
                        }
                        else {
                            this[SAW_VALID_ENTRY] = true;
                        }
                    }
                    if (entry.meta) {
                        if (entry.size > this.maxMetaEntrySize) {
                            entry.ignore = true;
                            this[EMIT]('ignoredEntry', entry);
                            this[STATE] = 'ignore';
                            entry.resume();
                        }
                        else if (entry.size > 0) {
                            this[META] = '';
                            entry.on('data', c => (this[META] += c));
                            this[STATE] = 'meta';
                        }
                    }
                    else {
                        this[EX] = undefined;
                        entry.ignore =
                            entry.ignore || !this.filter(entry.path, entry);
                        if (entry.ignore) {
                            // probably valid, just not something we care about
                            this[EMIT]('ignoredEntry', entry);
                            this[STATE] = entry.remain ? 'ignore' : 'header';
                            entry.resume();
                        }
                        else {
                            if (entry.remain) {
                                this[STATE] = 'body';
                            }
                            else {
                                this[STATE] = 'header';
                                entry.end();
                            }
                            if (!this[READENTRY]) {
                                this[QUEUE].push(entry);
                                this[NEXTENTRY]();
                            }
                            else {
                                this[QUEUE].push(entry);
                            }
                        }
                    }
                }
            }
        }
    }
    [CLOSESTREAM]() {
        queueMicrotask(() => this.emit('close'));
    }
    [PROCESSENTRY](entry) {
        let go = true;
        if (!entry) {
            this[READENTRY] = undefined;
            go = false;
        }
        else if (Array.isArray(entry)) {
            const [ev, ...args] = entry;
            this.emit(ev, ...args);
        }
        else {
            this[READENTRY] = entry;
            this.emit('entry', entry);
            if (!entry.emittedEnd) {
                entry.on('end', () => this[NEXTENTRY]());
                go = false;
            }
        }
        return go;
    }
    [NEXTENTRY]() {
        do { } while (this[PROCESSENTRY](this[QUEUE].shift()));
        if (!this[QUEUE].length) {
            // At this point, there's nothing in the queue, but we may have an
            // entry which is being consumed (readEntry).
            // If we don't, then we definitely can handle more data.
            // If we do, and either it's flowing, or it has never had any data
            // written to it, then it needs more.
            // The only other possibility is that it has returned false from a
            // write() call, so we wait for the next drain to continue.
            const re = this[READENTRY];
            const drainNow = !re || re.flowing || re.size === re.remain;
            if (drainNow) {
                if (!this[WRITING]) {
                    this.emit('drain');
                }
            }
            else {
                re.once('drain', () => this.emit('drain'));
            }
        }
    }
    [CONSUMEBODY](chunk, position) {
        // write up to but no  more than writeEntry.blockRemain
        const entry = this[WRITEENTRY];
        /* c8 ignore start */
        if (!entry) {
            throw new Error('attempt to consume body without entry??');
        }
        const br = entry.blockRemain ?? 0;
        /* c8 ignore stop */
        const c = br >= chunk.length && position === 0 ?
            chunk
            : chunk.subarray(position, position + br);
        entry.write(c);
        if (!entry.blockRemain) {
            this[STATE] = 'header';
            this[WRITEENTRY] = undefined;
            entry.end();
        }
        return c.length;
    }
    [CONSUMEMETA](chunk, position) {
        const entry = this[WRITEENTRY];
        const ret = this[CONSUMEBODY](chunk, position);
        // if we finished, then the entry is reset
        if (!this[WRITEENTRY] && entry) {
            this[EMITMETA](entry);
        }
        return ret;
    }
    [EMIT](ev, data, extra) {
        if (!this[QUEUE].length && !this[READENTRY]) {
            this.emit(ev, data, extra);
        }
        else {
            this[QUEUE].push([ev, data, extra]);
        }
    }
    [EMITMETA](entry) {
        this[EMIT]('meta', this[META]);
        switch (entry.type) {
            case 'ExtendedHeader':
            case 'OldExtendedHeader':
                this[EX] = Pax.parse(this[META], this[EX], false);
                break;
            case 'GlobalExtendedHeader':
                this[GEX] = Pax.parse(this[META], this[GEX], true);
                break;
            case 'NextFileHasLongPath':
            case 'OldGnuLongPath': {
                const ex = this[EX] ?? Object.create(null);
                this[EX] = ex;
                ex.path = this[META].replace(/\0.*/, '');
                break;
            }
            case 'NextFileHasLongLinkpath': {
                const ex = this[EX] || Object.create(null);
                this[EX] = ex;
                ex.linkpath = this[META].replace(/\0.*/, '');
                break;
            }
            /* c8 ignore start */
            default:
                throw new Error('unknown meta: ' + entry.type);
            /* c8 ignore stop */
        }
    }
    abort(error) {
        this[ABORTED] = true;
        this.emit('abort', error);
        // always throws, even in non-strict mode
        this.warn('TAR_ABORT', error, { recoverable: false });
    }
    write(chunk, encoding, cb) {
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, 
            /* c8 ignore next */
            typeof encoding === 'string' ? encoding : 'utf8');
        }
        if (this[ABORTED]) {
            /* c8 ignore next */
            cb?.();
            return false;
        }
        // first write, might be gzipped
        const needSniff = this[UNZIP] === undefined ||
            (this.brotli === undefined && this[UNZIP] === false);
        if (needSniff && chunk) {
            if (this[BUFFER]) {
                chunk = Buffer.concat([this[BUFFER], chunk]);
                this[BUFFER] = undefined;
            }
            if (chunk.length < gzipHeader.length) {
                this[BUFFER] = chunk;
                /* c8 ignore next */
                cb?.();
                return true;
            }
            // look for gzip header
            for (let i = 0; this[UNZIP] === undefined && i < gzipHeader.length; i++) {
                if (chunk[i] !== gzipHeader[i]) {
                    this[UNZIP] = false;
                }
            }
            const maybeBrotli = this.brotli === undefined;
            if (this[UNZIP] === false && maybeBrotli) {
                // read the first header to see if it's a valid tar file. If so,
                // we can safely assume that it's not actually brotli, despite the
                // .tbr or .tar.br file extension.
                // if we ended before getting a full chunk, yes, def brotli
                if (chunk.length < 512) {
                    if (this[ENDED]) {
                        this.brotli = true;
                    }
                    else {
                        this[BUFFER] = chunk;
                        /* c8 ignore next */
                        cb?.();
                        return true;
                    }
                }
                else {
                    // if it's tar, it's pretty reliably not brotli, chances of
                    // that happening are astronomical.
                    try {
                        new Header(chunk.subarray(0, 512));
                        this.brotli = false;
                    }
                    catch (_) {
                        this.brotli = true;
                    }
                }
            }
            if (this[UNZIP] === undefined ||
                (this[UNZIP] === false && this.brotli)) {
                const ended = this[ENDED];
                this[ENDED] = false;
                this[UNZIP] =
                    this[UNZIP] === undefined ?
                        new Unzip({})
                        : new BrotliDecompress({});
                this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk));
                this[UNZIP].on('error', er => this.abort(er));
                this[UNZIP].on('end', () => {
                    this[ENDED] = true;
                    this[CONSUMECHUNK]();
                });
                this[WRITING] = true;
                const ret = !!this[UNZIP][ended ? 'end' : 'write'](chunk);
                this[WRITING] = false;
                cb?.();
                return ret;
            }
        }
        this[WRITING] = true;
        if (this[UNZIP]) {
            this[UNZIP].write(chunk);
        }
        else {
            this[CONSUMECHUNK](chunk);
        }
        this[WRITING] = false;
        // return false if there's a queue, or if the current entry isn't flowing
        const ret = this[QUEUE].length ? false
            : this[READENTRY] ? this[READENTRY].flowing
                : true;
        // if we have no queue, then that means a clogged READENTRY
        if (!ret && !this[QUEUE].length) {
            this[READENTRY]?.once('drain', () => this.emit('drain'));
        }
        /* c8 ignore next */
        cb?.();
        return ret;
    }
    [BUFFERCONCAT](c) {
        if (c && !this[ABORTED]) {
            this[BUFFER] =
                this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c;
        }
    }
    [MAYBEEND]() {
        if (this[ENDED] &&
            !this[EMITTEDEND] &&
            !this[ABORTED] &&
            !this[CONSUMING]) {
            this[EMITTEDEND] = true;
            const entry = this[WRITEENTRY];
            if (entry && entry.blockRemain) {
                // truncated, likely a damaged file
                const have = this[BUFFER] ? this[BUFFER].length : 0;
                this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${entry.blockRemain} more bytes, only ${have} available)`, { entry });
                if (this[BUFFER]) {
                    entry.write(this[BUFFER]);
                }
                entry.end();
            }
            this[EMIT](DONE);
        }
    }
    [CONSUMECHUNK](chunk) {
        if (this[CONSUMING] && chunk) {
            this[BUFFERCONCAT](chunk);
        }
        else if (!chunk && !this[BUFFER]) {
            this[MAYBEEND]();
        }
        else if (chunk) {
            this[CONSUMING] = true;
            if (this[BUFFER]) {
                this[BUFFERCONCAT](chunk);
                const c = this[BUFFER];
                this[BUFFER] = undefined;
                this[CONSUMECHUNKSUB](c);
            }
            else {
                this[CONSUMECHUNKSUB](chunk);
            }
            while (this[BUFFER] &&
                this[BUFFER]?.length >= 512 &&
                !this[ABORTED] &&
                !this[SAW_EOF]) {
                const c = this[BUFFER];
                this[BUFFER] = undefined;
                this[CONSUMECHUNKSUB](c);
            }
            this[CONSUMING] = false;
        }
        if (!this[BUFFER] || this[ENDED]) {
            this[MAYBEEND]();
        }
    }
    [CONSUMECHUNKSUB](chunk) {
        // we know that we are in CONSUMING mode, so anything written goes into
        // the buffer.  Advance the position and put any remainder in the buffer.
        let position = 0;
        const length = chunk.length;
        while (position + 512 <= length &&
            !this[ABORTED] &&
            !this[SAW_EOF]) {
            switch (this[STATE]) {
                case 'begin':
                case 'header':
                    this[CONSUMEHEADER](chunk, position);
                    position += 512;
                    break;
                case 'ignore':
                case 'body':
                    position += this[CONSUMEBODY](chunk, position);
                    break;
                case 'meta':
                    position += this[CONSUMEMETA](chunk, position);
                    break;
                /* c8 ignore start */
                default:
                    throw new Error('invalid state: ' + this[STATE]);
                /* c8 ignore stop */
            }
        }
        if (position < length) {
            if (this[BUFFER]) {
                this[BUFFER] = Buffer.concat([
                    chunk.subarray(position),
                    this[BUFFER],
                ]);
            }
            else {
                this[BUFFER] = chunk.subarray(position);
            }
        }
    }
    end(chunk, encoding, cb) {
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, encoding);
        }
        if (cb)
            this.once('finish', cb);
        if (!this[ABORTED]) {
            if (this[UNZIP]) {
                /* c8 ignore start */
                if (chunk)
                    this[UNZIP].write(chunk);
                /* c8 ignore stop */
                this[UNZIP].end();
            }
            else {
                this[ENDED] = true;
                if (this.brotli === undefined)
                    chunk = chunk || Buffer.alloc(0);
                if (chunk)
                    this.write(chunk);
                this[MAYBEEND]();
            }
        }
        return this;
    }
}
//# sourceMappingURL=parse.js.map// A path exclusive reservation system
// reserve([list, of, paths], fn)
// When the fn is first in line for all its paths, it
// is called with a cb that clears the reservation.
//
// Used by async unpack to avoid clobbering paths in use,
// while still allowing maximal safe parallelization.
import { join } from 'node:path';
import { normalizeUnicode } from './normalize-unicode.js';
import { stripTrailingSlashes } from './strip-trailing-slashes.js';
const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
const isWindows = platform === 'win32';
// return a set of parent dirs for a given path
// '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d']
const getDirs = (path) => {
    const dirs = path
        .split('/')
        .slice(0, -1)
        .reduce((set, path) => {
        const s = set[set.length - 1];
        if (s !== undefined) {
            path = join(s, path);
        }
        set.push(path || '/');
        return set;
    }, []);
    return dirs;
};
export class PathReservations {
    // path => [function or Set]
    // A Set object means a directory reservation
    // A fn is a direct reservation on that path
    #queues = new Map();
    // fn => {paths:[path,...], dirs:[path, ...]}
    #reservations = new Map();
    // functions currently running
    #running = new Set();
    reserve(paths, fn) {
        paths =
            isWindows ?
                ['win32 parallelization disabled']
                : paths.map(p => {
                    // don't need normPath, because we skip this entirely for windows
                    return stripTrailingSlashes(join(normalizeUnicode(p))).toLowerCase();
                });
        const dirs = new Set(paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)));
        this.#reservations.set(fn, { dirs, paths });
        for (const p of paths) {
            const q = this.#queues.get(p);
            if (!q) {
                this.#queues.set(p, [fn]);
            }
            else {
                q.push(fn);
            }
        }
        for (const dir of dirs) {
            const q = this.#queues.get(dir);
            if (!q) {
                this.#queues.set(dir, [new Set([fn])]);
            }
            else {
                const l = q[q.length - 1];
                if (l instanceof Set) {
                    l.add(fn);
                }
                else {
                    q.push(new Set([fn]));
                }
            }
        }
        return this.#run(fn);
    }
    // return the queues for each path the function cares about
    // fn => {paths, dirs}
    #getQueues(fn) {
        const res = this.#reservations.get(fn);
        /* c8 ignore start */
        if (!res) {
            throw new Error('function does not have any path reservations');
        }
        /* c8 ignore stop */
        return {
            paths: res.paths.map((path) => this.#queues.get(path)),
            dirs: [...res.dirs].map(path => this.#queues.get(path)),
        };
    }
    // check if fn is first in line for all its paths, and is
    // included in the first set for all its dir queues
    check(fn) {
        const { paths, dirs } = this.#getQueues(fn);
        return (paths.every(q => q && q[0] === fn) &&
            dirs.every(q => q && q[0] instanceof Set && q[0].has(fn)));
    }
    // run the function if it's first in line and not already running
    #run(fn) {
        if (this.#running.has(fn) || !this.check(fn)) {
            return false;
        }
        this.#running.add(fn);
        fn(() => this.#clear(fn));
        return true;
    }
    #clear(fn) {
        if (!this.#running.has(fn)) {
            return false;
        }
        const res = this.#reservations.get(fn);
        /* c8 ignore start */
        if (!res) {
            throw new Error('invalid reservation');
        }
        /* c8 ignore stop */
        const { paths, dirs } = res;
        const next = new Set();
        for (const path of paths) {
            const q = this.#queues.get(path);
            /* c8 ignore start */
            if (!q || q?.[0] !== fn) {
                continue;
            }
            /* c8 ignore stop */
            const q0 = q[1];
            if (!q0) {
                this.#queues.delete(path);
                continue;
            }
            q.shift();
            if (typeof q0 === 'function') {
                next.add(q0);
            }
            else {
                for (const f of q0) {
                    next.add(f);
                }
            }
        }
        for (const dir of dirs) {
            const q = this.#queues.get(dir);
            const q0 = q?.[0];
            /* c8 ignore next - type safety only */
            if (!q || !(q0 instanceof Set))
                continue;
            if (q0.size === 1 && q.length === 1) {
                this.#queues.delete(dir);
                continue;
            }
            else if (q0.size === 1) {
                q.shift();
                // next one must be a function,
                // or else the Set would've been reused
                const n = q[0];
                if (typeof n === 'function') {
                    next.add(n);
                }
            }
            else {
                q0.delete(fn);
            }
        }
        this.#running.delete(fn);
        next.forEach(fn => this.#run(fn));
        return true;
    }
}
//# sourceMappingURL=path-reservations.js.mapimport { basename } from 'node:path';
import { Header } from './header.js';
export class Pax {
    atime;
    mtime;
    ctime;
    charset;
    comment;
    gid;
    uid;
    gname;
    uname;
    linkpath;
    dev;
    ino;
    nlink;
    path;
    size;
    mode;
    global;
    constructor(obj, global = false) {
        this.atime = obj.atime;
        this.charset = obj.charset;
        this.comment = obj.comment;
        this.ctime = obj.ctime;
        this.dev = obj.dev;
        this.gid = obj.gid;
        this.global = global;
        this.gname = obj.gname;
        this.ino = obj.ino;
        this.linkpath = obj.linkpath;
        this.mtime = obj.mtime;
        this.nlink = obj.nlink;
        this.path = obj.path;
        this.size = obj.size;
        this.uid = obj.uid;
        this.uname = obj.uname;
    }
    encode() {
        const body = this.encodeBody();
        if (body === '') {
            return Buffer.allocUnsafe(0);
        }
        const bodyLen = Buffer.byteLength(body);
        // round up to 512 bytes
        // add 512 for header
        const bufLen = 512 * Math.ceil(1 + bodyLen / 512);
        const buf = Buffer.allocUnsafe(bufLen);
        // 0-fill the header section, it might not hit every field
        for (let i = 0; i < 512; i++) {
            buf[i] = 0;
        }
        new Header({
            // XXX split the path
            // then the path should be PaxHeader + basename, but less than 99,
            // prepend with the dirname
            /* c8 ignore start */
            path: ('PaxHeader/' + basename(this.path ?? '')).slice(0, 99),
            /* c8 ignore stop */
            mode: this.mode || 0o644,
            uid: this.uid,
            gid: this.gid,
            size: bodyLen,
            mtime: this.mtime,
            type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader',
            linkpath: '',
            uname: this.uname || '',
            gname: this.gname || '',
            devmaj: 0,
            devmin: 0,
            atime: this.atime,
            ctime: this.ctime,
        }).encode(buf);
        buf.write(body, 512, bodyLen, 'utf8');
        // null pad after the body
        for (let i = bodyLen + 512; i < buf.length; i++) {
            buf[i] = 0;
        }
        return buf;
    }
    encodeBody() {
        return (this.encodeField('path') +
            this.encodeField('ctime') +
            this.encodeField('atime') +
            this.encodeField('dev') +
            this.encodeField('ino') +
            this.encodeField('nlink') +
            this.encodeField('charset') +
            this.encodeField('comment') +
            this.encodeField('gid') +
            this.encodeField('gname') +
            this.encodeField('linkpath') +
            this.encodeField('mtime') +
            this.encodeField('size') +
            this.encodeField('uid') +
            this.encodeField('uname'));
    }
    encodeField(field) {
        if (this[field] === undefined) {
            return '';
        }
        const r = this[field];
        const v = r instanceof Date ? r.getTime() / 1000 : r;
        const s = ' ' +
            (field === 'dev' || field === 'ino' || field === 'nlink' ?
                'SCHILY.'
                : '') +
            field +
            '=' +
            v +
            '\n';
        const byteLen = Buffer.byteLength(s);
        // the digits includes the length of the digits in ascii base-10
        // so if it's 9 characters, then adding 1 for the 9 makes it 10
        // which makes it 11 chars.
        let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1;
        if (byteLen + digits >= Math.pow(10, digits)) {
            digits += 1;
        }
        const len = digits + byteLen;
        return len + s;
    }
    static parse(str, ex, g = false) {
        return new Pax(merge(parseKV(str), ex), g);
    }
}
const merge = (a, b) => b ? Object.assign({}, b, a) : a;
const parseKV = (str) => str
    .replace(/\n$/, '')
    .split('\n')
    .reduce(parseKVLine, Object.create(null));
const parseKVLine = (set, line) => {
    const n = parseInt(line, 10);
    // XXX Values with \n in them will fail this.
    // Refactor to not be a naive line-by-line parse.
    if (n !== Buffer.byteLength(line) + 1) {
        return set;
    }
    line = line.slice((n + ' ').length);
    const kv = line.split('=');
    const r = kv.shift();
    if (!r) {
        return set;
    }
    const k = r.replace(/^SCHILY\.(dev|ino|nlink)/, '$1');
    const v = kv.join('=');
    set[k] =
        /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ?
            new Date(Number(v) * 1000)
            : /^[0-9]+$/.test(v) ? +v
                : v;
    return set;
};
//# sourceMappingURL=pax.js.mapimport { Minipass } from 'minipass';
import { normalizeWindowsPath } from './normalize-windows-path.js';
export class ReadEntry extends Minipass {
    extended;
    globalExtended;
    header;
    startBlockSize;
    blockRemain;
    remain;
    type;
    meta = false;
    ignore = false;
    path;
    mode;
    uid;
    gid;
    uname;
    gname;
    size = 0;
    mtime;
    atime;
    ctime;
    linkpath;
    dev;
    ino;
    nlink;
    invalid = false;
    absolute;
    unsupported = false;
    constructor(header, ex, gex) {
        super({});
        // read entries always start life paused.  this is to avoid the
        // situation where Minipass's auto-ending empty streams results
        // in an entry ending before we're ready for it.
        this.pause();
        this.extended = ex;
        this.globalExtended = gex;
        this.header = header;
        /* c8 ignore start */
        this.remain = header.size ?? 0;
        /* c8 ignore stop */
        this.startBlockSize = 512 * Math.ceil(this.remain / 512);
        this.blockRemain = this.startBlockSize;
        this.type = header.type;
        switch (this.type) {
            case 'File':
            case 'OldFile':
            case 'Link':
            case 'SymbolicLink':
            case 'CharacterDevice':
            case 'BlockDevice':
            case 'Directory':
            case 'FIFO':
            case 'ContiguousFile':
            case 'GNUDumpDir':
                break;
            case 'NextFileHasLongLinkpath':
            case 'NextFileHasLongPath':
            case 'OldGnuLongPath':
            case 'GlobalExtendedHeader':
            case 'ExtendedHeader':
            case 'OldExtendedHeader':
                this.meta = true;
                break;
            // NOTE: gnutar and bsdtar treat unrecognized types as 'File'
            // it may be worth doing the same, but with a warning.
            default:
                this.ignore = true;
        }
        /* c8 ignore start */
        if (!header.path) {
            throw new Error('no path provided for tar.ReadEntry');
        }
        /* c8 ignore stop */
        this.path = normalizeWindowsPath(header.path);
        this.mode = header.mode;
        if (this.mode) {
            this.mode = this.mode & 0o7777;
        }
        this.uid = header.uid;
        this.gid = header.gid;
        this.uname = header.uname;
        this.gname = header.gname;
        this.size = this.remain;
        this.mtime = header.mtime;
        this.atime = header.atime;
        this.ctime = header.ctime;
        /* c8 ignore start */
        this.linkpath =
            header.linkpath ?
                normalizeWindowsPath(header.linkpath)
                : undefined;
        /* c8 ignore stop */
        this.uname = header.uname;
        this.gname = header.gname;
        if (ex) {
            this.#slurp(ex);
        }
        if (gex) {
            this.#slurp(gex, true);
        }
    }
    write(data) {
        const writeLen = data.length;
        if (writeLen > this.blockRemain) {
            throw new Error('writing more to entry than is appropriate');
        }
        const r = this.remain;
        const br = this.blockRemain;
        this.remain = Math.max(0, r - writeLen);
        this.blockRemain = Math.max(0, br - writeLen);
        if (this.ignore) {
            return true;
        }
        if (r >= writeLen) {
            return super.write(data);
        }
        // r < writeLen
        return super.write(data.subarray(0, r));
    }
    #slurp(ex, gex = false) {
        if (ex.path)
            ex.path = normalizeWindowsPath(ex.path);
        if (ex.linkpath)
            ex.linkpath = normalizeWindowsPath(ex.linkpath);
        Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => {
            // we slurp in everything except for the path attribute in
            // a global extended header, because that's weird. Also, any
            // null/undefined values are ignored.
            return !(v === null ||
                v === undefined ||
                (k === 'path' && gex));
        })));
    }
}
//# sourceMappingURL=read-entry.js.map// tar -r
import { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass';
import fs from 'node:fs';
import path from 'node:path';
import { Header } from './header.js';
import { list } from './list.js';
import { makeCommand } from './make-command.js';
import { isFile, } from './options.js';
import { Pack, PackSync } from './pack.js';
// starting at the head of the file, read a Header
// If the checksum is invalid, that's our position to start writing
// If it is, jump forward by the specified size (round up to 512)
// and try again.
// Write the new Pack stream starting there.
const replaceSync = (opt, files) => {
    const p = new PackSync(opt);
    let threw = true;
    let fd;
    let position;
    try {
        try {
            fd = fs.openSync(opt.file, 'r+');
        }
        catch (er) {
            if (er?.code === 'ENOENT') {
                fd = fs.openSync(opt.file, 'w+');
            }
            else {
                throw er;
            }
        }
        const st = fs.fstatSync(fd);
        const headBuf = Buffer.alloc(512);
        POSITION: for (position = 0; position < st.size; position += 512) {
            for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) {
                bytes = fs.readSync(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos);
                if (position === 0 &&
                    headBuf[0] === 0x1f &&
                    headBuf[1] === 0x8b) {
                    throw new Error('cannot append to compressed archives');
                }
                if (!bytes) {
                    break POSITION;
                }
            }
            const h = new Header(headBuf);
            if (!h.cksumValid) {
                break;
            }
            const entryBlockSize = 512 * Math.ceil((h.size || 0) / 512);
            if (position + entryBlockSize + 512 > st.size) {
                break;
            }
            // the 512 for the header we just parsed will be added as well
            // also jump ahead all the blocks for the body
            position += entryBlockSize;
            if (opt.mtimeCache && h.mtime) {
                opt.mtimeCache.set(String(h.path), h.mtime);
            }
        }
        threw = false;
        streamSync(opt, p, position, fd, files);
    }
    finally {
        if (threw) {
            try {
                fs.closeSync(fd);
            }
            catch (er) { }
        }
    }
};
const streamSync = (opt, p, position, fd, files) => {
    const stream = new WriteStreamSync(opt.file, {
        fd: fd,
        start: position,
    });
    p.pipe(stream);
    addFilesSync(p, files);
};
const replaceAsync = (opt, files) => {
    files = Array.from(files);
    const p = new Pack(opt);
    const getPos = (fd, size, cb_) => {
        const cb = (er, pos) => {
            if (er) {
                fs.close(fd, _ => cb_(er));
            }
            else {
                cb_(null, pos);
            }
        };
        let position = 0;
        if (size === 0) {
            return cb(null, 0);
        }
        let bufPos = 0;
        const headBuf = Buffer.alloc(512);
        const onread = (er, bytes) => {
            if (er || typeof bytes === 'undefined') {
                return cb(er);
            }
            bufPos += bytes;
            if (bufPos < 512 && bytes) {
                return fs.read(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread);
            }
            if (position === 0 &&
                headBuf[0] === 0x1f &&
                headBuf[1] === 0x8b) {
                return cb(new Error('cannot append to compressed archives'));
            }
            // truncated header
            if (bufPos < 512) {
                return cb(null, position);
            }
            const h = new Header(headBuf);
            if (!h.cksumValid) {
                return cb(null, position);
            }
            /* c8 ignore next */
            const entryBlockSize = 512 * Math.ceil((h.size ?? 0) / 512);
            if (position + entryBlockSize + 512 > size) {
                return cb(null, position);
            }
            position += entryBlockSize + 512;
            if (position >= size) {
                return cb(null, position);
            }
            if (opt.mtimeCache && h.mtime) {
                opt.mtimeCache.set(String(h.path), h.mtime);
            }
            bufPos = 0;
            fs.read(fd, headBuf, 0, 512, position, onread);
        };
        fs.read(fd, headBuf, 0, 512, position, onread);
    };
    const promise = new Promise((resolve, reject) => {
        p.on('error', reject);
        let flag = 'r+';
        const onopen = (er, fd) => {
            if (er && er.code === 'ENOENT' && flag === 'r+') {
                flag = 'w+';
                return fs.open(opt.file, flag, onopen);
            }
            if (er || !fd) {
                return reject(er);
            }
            fs.fstat(fd, (er, st) => {
                if (er) {
                    return fs.close(fd, () => reject(er));
                }
                getPos(fd, st.size, (er, position) => {
                    if (er) {
                        return reject(er);
                    }
                    const stream = new WriteStream(opt.file, {
                        fd: fd,
                        start: position,
                    });
                    p.pipe(stream);
                    stream.on('error', reject);
                    stream.on('close', resolve);
                    addFilesAsync(p, files);
                });
            });
        };
        fs.open(opt.file, flag, onopen);
    });
    return promise;
};
const addFilesSync = (p, files) => {
    files.forEach(file => {
        if (file.charAt(0) === '@') {
            list({
                file: path.resolve(p.cwd, file.slice(1)),
                sync: true,
                noResume: true,
                onReadEntry: entry => p.add(entry),
            });
        }
        else {
            p.add(file);
        }
    });
    p.end();
};
const addFilesAsync = async (p, files) => {
    for (let i = 0; i < files.length; i++) {
        const file = String(files[i]);
        if (file.charAt(0) === '@') {
            await list({
                file: path.resolve(String(p.cwd), file.slice(1)),
                noResume: true,
                onReadEntry: entry => p.add(entry),
            });
        }
        else {
            p.add(file);
        }
    }
    p.end();
};
export const replace = makeCommand(replaceSync, replaceAsync, 
/* c8 ignore start */
() => {
    throw new TypeError('file is required');
}, () => {
    throw new TypeError('file is required');
}, 
/* c8 ignore stop */
(opt, entries) => {
    if (!isFile(opt)) {
        throw new TypeError('file is required');
    }
    if (opt.gzip ||
        opt.brotli ||
        opt.file.endsWith('.br') ||
        opt.file.endsWith('.tbr')) {
        throw new TypeError('cannot append to compressed archives');
    }
    if (!entries?.length) {
        throw new TypeError('no paths specified to add/replace');
    }
});
//# sourceMappingURL=replace.js.map// unix absolute paths are also absolute on win32, so we use this for both
import { win32 } from 'node:path';
const { isAbsolute, parse } = win32;
// returns [root, stripped]
// Note that windows will think that //x/y/z/a has a "root" of //x/y, and in
// those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip /
// explicitly if it's the first character.
// drive-specific relative paths on Windows get their root stripped off even
// though they are not absolute, so `c:../foo` becomes ['c:', '../foo']
export const stripAbsolutePath = (path) => {
    let r = '';
    let parsed = parse(path);
    while (isAbsolute(path) || parsed.root) {
        // windows will think that //x/y/z has a "root" of //x/y/
        // but strip the //?/C:/ off of //?/C:/path
        const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ?
            '/'
            : parsed.root;
        path = path.slice(root.length);
        r += root;
        parsed = parse(path);
    }
    return [r, path];
};
//# sourceMappingURL=strip-absolute-path.js.map// warning: extremely hot code path.
// This has been meticulously optimized for use
// within npm install on large package trees.
// Do not edit without careful benchmarking.
export const stripTrailingSlashes = (str) => {
    let i = str.length - 1;
    let slashesStart = -1;
    while (i > -1 && str.charAt(i) === '/') {
        slashesStart = i;
        i--;
    }
    return slashesStart === -1 ? str : str.slice(0, slashesStart);
};
//# sourceMappingURL=strip-trailing-slashes.js.mapexport class SymlinkError extends Error {
    path;
    symlink;
    syscall = 'symlink';
    code = 'TAR_SYMLINK_ERROR';
    constructor(symlink, path) {
        super('TAR_SYMLINK_ERROR: Cannot extract through symbolic link');
        this.symlink = symlink;
        this.path = path;
    }
    get name() {
        return 'SymlinkError';
    }
}
//# sourceMappingURL=symlink-error.js.mapexport const isCode = (c) => name.has(c);
export const isName = (c) => code.has(c);
// map types from key to human-friendly name
export const name = new Map([
    ['0', 'File'],
    // same as File
    ['', 'OldFile'],
    ['1', 'Link'],
    ['2', 'SymbolicLink'],
    // Devices and FIFOs aren't fully supported
    // they are parsed, but skipped when unpacking
    ['3', 'CharacterDevice'],
    ['4', 'BlockDevice'],
    ['5', 'Directory'],
    ['6', 'FIFO'],
    // same as File
    ['7', 'ContiguousFile'],
    // pax headers
    ['g', 'GlobalExtendedHeader'],
    ['x', 'ExtendedHeader'],
    // vendor-specific stuff
    // skip
    ['A', 'SolarisACL'],
    // like 5, but with data, which should be skipped
    ['D', 'GNUDumpDir'],
    // metadata only, skip
    ['I', 'Inode'],
    // data = link path of next file
    ['K', 'NextFileHasLongLinkpath'],
    // data = path of next file
    ['L', 'NextFileHasLongPath'],
    // skip
    ['M', 'ContinuationFile'],
    // like L
    ['N', 'OldGnuLongPath'],
    // skip
    ['S', 'SparseFile'],
    // skip
    ['V', 'TapeVolumeHeader'],
    // like x
    ['X', 'OldExtendedHeader'],
]);
// map the other direction
export const code = new Map(Array.from(name).map(kv => [kv[1], kv[0]]));
//# sourceMappingURL=types.js.map// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet.
// but the path reservations are required to avoid race conditions where
// parallelized unpack ops may mess with one another, due to dependencies
// (like a Link depending on its target) or destructive operations (like
// clobbering an fs object to create one of a different type.)
import * as fsm from '@isaacs/fs-minipass';
import assert from 'node:assert';
import { randomBytes } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { getWriteFlag } from './get-write-flag.js';
import { mkdir, mkdirSync } from './mkdir.js';
import { normalizeUnicode } from './normalize-unicode.js';
import { normalizeWindowsPath } from './normalize-windows-path.js';
import { Parser } from './parse.js';
import { stripAbsolutePath } from './strip-absolute-path.js';
import { stripTrailingSlashes } from './strip-trailing-slashes.js';
import * as wc from './winchars.js';
import { PathReservations } from './path-reservations.js';
const ONENTRY = Symbol('onEntry');
const CHECKFS = Symbol('checkFs');
const CHECKFS2 = Symbol('checkFs2');
const PRUNECACHE = Symbol('pruneCache');
const ISREUSABLE = Symbol('isReusable');
const MAKEFS = Symbol('makeFs');
const FILE = Symbol('file');
const DIRECTORY = Symbol('directory');
const LINK = Symbol('link');
const SYMLINK = Symbol('symlink');
const HARDLINK = Symbol('hardlink');
const UNSUPPORTED = Symbol('unsupported');
const CHECKPATH = Symbol('checkPath');
const MKDIR = Symbol('mkdir');
const ONERROR = Symbol('onError');
const PENDING = Symbol('pending');
const PEND = Symbol('pend');
const UNPEND = Symbol('unpend');
const ENDED = Symbol('ended');
const MAYBECLOSE = Symbol('maybeClose');
const SKIP = Symbol('skip');
const DOCHOWN = Symbol('doChown');
const UID = Symbol('uid');
const GID = Symbol('gid');
const CHECKED_CWD = Symbol('checkedCwd');
const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
const isWindows = platform === 'win32';
const DEFAULT_MAX_DEPTH = 1024;
// Unlinks on Windows are not atomic.
//
// This means that if you have a file entry, followed by another
// file entry with an identical name, and you cannot re-use the file
// (because it's a hardlink, or because unlink:true is set, or it's
// Windows, which does not have useful nlink values), then the unlink
// will be committed to the disk AFTER the new file has been written
// over the old one, deleting the new file.
//
// To work around this, on Windows systems, we rename the file and then
// delete the renamed file.  It's a sloppy kludge, but frankly, I do not
// know of a better way to do this, given windows' non-atomic unlink
// semantics.
//
// See: https://github.com/npm/node-tar/issues/183
/* c8 ignore start */
const unlinkFile = (path, cb) => {
    if (!isWindows) {
        return fs.unlink(path, cb);
    }
    const name = path + '.DELETE.' + randomBytes(16).toString('hex');
    fs.rename(path, name, er => {
        if (er) {
            return cb(er);
        }
        fs.unlink(name, cb);
    });
};
/* c8 ignore stop */
/* c8 ignore start */
const unlinkFileSync = (path) => {
    if (!isWindows) {
        return fs.unlinkSync(path);
    }
    const name = path + '.DELETE.' + randomBytes(16).toString('hex');
    fs.renameSync(path, name);
    fs.unlinkSync(name);
};
/* c8 ignore stop */
// this.gid, entry.gid, this.processUid
const uint32 = (a, b, c) => a !== undefined && a === a >>> 0 ? a
    : b !== undefined && b === b >>> 0 ? b
        : c;
// clear the cache if it's a case-insensitive unicode-squashing match.
// we can't know if the current file system is case-sensitive or supports
// unicode fully, so we check for similarity on the maximally compatible
// representation.  Err on the side of pruning, since all it's doing is
// preventing lstats, and it's not the end of the world if we get a false
// positive.
// Note that on windows, we always drop the entire cache whenever a
// symbolic link is encountered, because 8.3 filenames are impossible
// to reason about, and collisions are hazards rather than just failures.
const cacheKeyNormalize = (path) => stripTrailingSlashes(normalizeWindowsPath(normalizeUnicode(path))).toLowerCase();
// remove all cache entries matching ${abs}/**
const pruneCache = (cache, abs) => {
    abs = cacheKeyNormalize(abs);
    for (const path of cache.keys()) {
        const pnorm = cacheKeyNormalize(path);
        if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) {
            cache.delete(path);
        }
    }
};
const dropCache = (cache) => {
    for (const key of cache.keys()) {
        cache.delete(key);
    }
};
export class Unpack extends Parser {
    [ENDED] = false;
    [CHECKED_CWD] = false;
    [PENDING] = 0;
    reservations = new PathReservations();
    transform;
    writable = true;
    readable = false;
    dirCache;
    uid;
    gid;
    setOwner;
    preserveOwner;
    processGid;
    processUid;
    maxDepth;
    forceChown;
    win32;
    newer;
    keep;
    noMtime;
    preservePaths;
    unlink;
    cwd;
    strip;
    processUmask;
    umask;
    dmode;
    fmode;
    chmod;
    constructor(opt = {}) {
        opt.ondone = () => {
            this[ENDED] = true;
            this[MAYBECLOSE]();
        };
        super(opt);
        this.transform = opt.transform;
        this.dirCache = opt.dirCache || new Map();
        this.chmod = !!opt.chmod;
        if (typeof opt.uid === 'number' || typeof opt.gid === 'number') {
            // need both or neither
            if (typeof opt.uid !== 'number' ||
                typeof opt.gid !== 'number') {
                throw new TypeError('cannot set owner without number uid and gid');
            }
            if (opt.preserveOwner) {
                throw new TypeError('cannot preserve owner in archive and also set owner explicitly');
            }
            this.uid = opt.uid;
            this.gid = opt.gid;
            this.setOwner = true;
        }
        else {
            this.uid = undefined;
            this.gid = undefined;
            this.setOwner = false;
        }
        // default true for root
        if (opt.preserveOwner === undefined &&
            typeof opt.uid !== 'number') {
            this.preserveOwner = !!(process.getuid && process.getuid() === 0);
        }
        else {
            this.preserveOwner = !!opt.preserveOwner;
        }
        this.processUid =
            (this.preserveOwner || this.setOwner) && process.getuid ?
                process.getuid()
                : undefined;
        this.processGid =
            (this.preserveOwner || this.setOwner) && process.getgid ?
                process.getgid()
                : undefined;
        // prevent excessively deep nesting of subfolders
        // set to `Infinity` to remove this restriction
        this.maxDepth =
            typeof opt.maxDepth === 'number' ?
                opt.maxDepth
                : DEFAULT_MAX_DEPTH;
        // mostly just for testing, but useful in some cases.
        // Forcibly trigger a chown on every entry, no matter what
        this.forceChown = opt.forceChown === true;
        // turn > this[ONENTRY](entry));
    }
    // a bad or damaged archive is a warning for Parser, but an error
    // when extracting.  Mark those errors as unrecoverable, because
    // the Unpack contract cannot be met.
    warn(code, msg, data = {}) {
        if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') {
            data.recoverable = false;
        }
        return super.warn(code, msg, data);
    }
    [MAYBECLOSE]() {
        if (this[ENDED] && this[PENDING] === 0) {
            this.emit('prefinish');
            this.emit('finish');
            this.emit('end');
        }
    }
    [CHECKPATH](entry) {
        const p = normalizeWindowsPath(entry.path);
        const parts = p.split('/');
        if (this.strip) {
            if (parts.length < this.strip) {
                return false;
            }
            if (entry.type === 'Link') {
                const linkparts = normalizeWindowsPath(String(entry.linkpath)).split('/');
                if (linkparts.length >= this.strip) {
                    entry.linkpath = linkparts.slice(this.strip).join('/');
                }
                else {
                    return false;
                }
            }
            parts.splice(0, this.strip);
            entry.path = parts.join('/');
        }
        if (isFinite(this.maxDepth) && parts.length > this.maxDepth) {
            this.warn('TAR_ENTRY_ERROR', 'path excessively deep', {
                entry,
                path: p,
                depth: parts.length,
                maxDepth: this.maxDepth,
            });
            return false;
        }
        if (!this.preservePaths) {
            if (parts.includes('..') ||
                /* c8 ignore next */
                (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) {
                this.warn('TAR_ENTRY_ERROR', `path contains '..'`, {
                    entry,
                    path: p,
                });
                return false;
            }
            // strip off the root
            const [root, stripped] = stripAbsolutePath(p);
            if (root) {
                entry.path = String(stripped);
                this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, {
                    entry,
                    path: p,
                });
            }
        }
        if (path.isAbsolute(entry.path)) {
            entry.absolute = normalizeWindowsPath(path.resolve(entry.path));
        }
        else {
            entry.absolute = normalizeWindowsPath(path.resolve(this.cwd, entry.path));
        }
        // if we somehow ended up with a path that escapes the cwd, and we are
        // not in preservePaths mode, then something is fishy!  This should have
        // been prevented above, so ignore this for coverage.
        /* c8 ignore start - defense in depth */
        if (!this.preservePaths &&
            typeof entry.absolute === 'string' &&
            entry.absolute.indexOf(this.cwd + '/') !== 0 &&
            entry.absolute !== this.cwd) {
            this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', {
                entry,
                path: normalizeWindowsPath(entry.path),
                resolvedPath: entry.absolute,
                cwd: this.cwd,
            });
            return false;
        }
        /* c8 ignore stop */
        // an archive can set properties on the extraction directory, but it
        // may not replace the cwd with a different kind of thing entirely.
        if (entry.absolute === this.cwd &&
            entry.type !== 'Directory' &&
            entry.type !== 'GNUDumpDir') {
            return false;
        }
        // only encode : chars that aren't drive letter indicators
        if (this.win32) {
            const { root: aRoot } = path.win32.parse(String(entry.absolute));
            entry.absolute =
                aRoot + wc.encode(String(entry.absolute).slice(aRoot.length));
            const { root: pRoot } = path.win32.parse(entry.path);
            entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length));
        }
        return true;
    }
    [ONENTRY](entry) {
        if (!this[CHECKPATH](entry)) {
            return entry.resume();
        }
        assert.equal(typeof entry.absolute, 'string');
        switch (entry.type) {
            case 'Directory':
            case 'GNUDumpDir':
                if (entry.mode) {
                    entry.mode = entry.mode | 0o700;
                }
            // eslint-disable-next-line no-fallthrough
            case 'File':
            case 'OldFile':
            case 'ContiguousFile':
            case 'Link':
            case 'SymbolicLink':
                return this[CHECKFS](entry);
            case 'CharacterDevice':
            case 'BlockDevice':
            case 'FIFO':
            default:
                return this[UNSUPPORTED](entry);
        }
    }
    [ONERROR](er, entry) {
        // Cwd has to exist, or else nothing works. That's serious.
        // Other errors are warnings, which raise the error in strict
        // mode, but otherwise continue on.
        if (er.name === 'CwdError') {
            this.emit('error', er);
        }
        else {
            this.warn('TAR_ENTRY_ERROR', er, { entry });
            this[UNPEND]();
            entry.resume();
        }
    }
    [MKDIR](dir, mode, cb) {
        mkdir(normalizeWindowsPath(dir), {
            uid: this.uid,
            gid: this.gid,
            processUid: this.processUid,
            processGid: this.processGid,
            umask: this.processUmask,
            preserve: this.preservePaths,
            unlink: this.unlink,
            cache: this.dirCache,
            cwd: this.cwd,
            mode: mode,
        }, cb);
    }
    [DOCHOWN](entry) {
        // in preserve owner mode, chown if the entry doesn't match process
        // in set owner mode, chown if setting doesn't match process
        return (this.forceChown ||
            (this.preserveOwner &&
                ((typeof entry.uid === 'number' &&
                    entry.uid !== this.processUid) ||
                    (typeof entry.gid === 'number' &&
                        entry.gid !== this.processGid))) ||
            (typeof this.uid === 'number' &&
                this.uid !== this.processUid) ||
            (typeof this.gid === 'number' && this.gid !== this.processGid));
    }
    [UID](entry) {
        return uint32(this.uid, entry.uid, this.processUid);
    }
    [GID](entry) {
        return uint32(this.gid, entry.gid, this.processGid);
    }
    [FILE](entry, fullyDone) {
        const mode = typeof entry.mode === 'number' ?
            entry.mode & 0o7777
            : this.fmode;
        const stream = new fsm.WriteStream(String(entry.absolute), {
            // slight lie, but it can be numeric flags
            flags: getWriteFlag(entry.size),
            mode: mode,
            autoClose: false,
        });
        stream.on('error', (er) => {
            if (stream.fd) {
                fs.close(stream.fd, () => { });
            }
            // flush all the data out so that we aren't left hanging
            // if the error wasn't actually fatal.  otherwise the parse
            // is blocked, and we never proceed.
            stream.write = () => true;
            this[ONERROR](er, entry);
            fullyDone();
        });
        let actions = 1;
        const done = (er) => {
            if (er) {
                /* c8 ignore start - we should always have a fd by now */
                if (stream.fd) {
                    fs.close(stream.fd, () => { });
                }
                /* c8 ignore stop */
                this[ONERROR](er, entry);
                fullyDone();
                return;
            }
            if (--actions === 0) {
                if (stream.fd !== undefined) {
                    fs.close(stream.fd, er => {
                        if (er) {
                            this[ONERROR](er, entry);
                        }
                        else {
                            this[UNPEND]();
                        }
                        fullyDone();
                    });
                }
            }
        };
        stream.on('finish', () => {
            // if futimes fails, try utimes
            // if utimes fails, fail with the original error
            // same for fchown/chown
            const abs = String(entry.absolute);
            const fd = stream.fd;
            if (typeof fd === 'number' && entry.mtime && !this.noMtime) {
                actions++;
                const atime = entry.atime || new Date();
                const mtime = entry.mtime;
                fs.futimes(fd, atime, mtime, er => er ?
                    fs.utimes(abs, atime, mtime, er2 => done(er2 && er))
                    : done());
            }
            if (typeof fd === 'number' && this[DOCHOWN](entry)) {
                actions++;
                const uid = this[UID](entry);
                const gid = this[GID](entry);
                if (typeof uid === 'number' && typeof gid === 'number') {
                    fs.fchown(fd, uid, gid, er => er ?
                        fs.chown(abs, uid, gid, er2 => done(er2 && er))
                        : done());
                }
            }
            done();
        });
        const tx = this.transform ? this.transform(entry) || entry : entry;
        if (tx !== entry) {
            tx.on('error', (er) => {
                this[ONERROR](er, entry);
                fullyDone();
            });
            entry.pipe(tx);
        }
        tx.pipe(stream);
    }
    [DIRECTORY](entry, fullyDone) {
        const mode = typeof entry.mode === 'number' ?
            entry.mode & 0o7777
            : this.dmode;
        this[MKDIR](String(entry.absolute), mode, er => {
            if (er) {
                this[ONERROR](er, entry);
                fullyDone();
                return;
            }
            let actions = 1;
            const done = () => {
                if (--actions === 0) {
                    fullyDone();
                    this[UNPEND]();
                    entry.resume();
                }
            };
            if (entry.mtime && !this.noMtime) {
                actions++;
                fs.utimes(String(entry.absolute), entry.atime || new Date(), entry.mtime, done);
            }
            if (this[DOCHOWN](entry)) {
                actions++;
                fs.chown(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)), done);
            }
            done();
        });
    }
    [UNSUPPORTED](entry) {
        entry.unsupported = true;
        this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry });
        entry.resume();
    }
    [SYMLINK](entry, done) {
        this[LINK](entry, String(entry.linkpath), 'symlink', done);
    }
    [HARDLINK](entry, done) {
        const linkpath = normalizeWindowsPath(path.resolve(this.cwd, String(entry.linkpath)));
        this[LINK](entry, linkpath, 'link', done);
    }
    [PEND]() {
        this[PENDING]++;
    }
    [UNPEND]() {
        this[PENDING]--;
        this[MAYBECLOSE]();
    }
    [SKIP](entry) {
        this[UNPEND]();
        entry.resume();
    }
    // Check if we can reuse an existing filesystem entry safely and
    // overwrite it, rather than unlinking and recreating
    // Windows doesn't report a useful nlink, so we just never reuse entries
    [ISREUSABLE](entry, st) {
        return (entry.type === 'File' &&
            !this.unlink &&
            st.isFile() &&
            st.nlink <= 1 &&
            !isWindows);
    }
    // check if a thing is there, and if so, try to clobber it
    [CHECKFS](entry) {
        this[PEND]();
        const paths = [entry.path];
        if (entry.linkpath) {
            paths.push(entry.linkpath);
        }
        this.reservations.reserve(paths, done => this[CHECKFS2](entry, done));
    }
    [PRUNECACHE](entry) {
        // if we are not creating a directory, and the path is in the dirCache,
        // then that means we are about to delete the directory we created
        // previously, and it is no longer going to be a directory, and neither
        // is any of its children.
        // If a symbolic link is encountered, all bets are off.  There is no
        // reasonable way to sanitize the cache in such a way we will be able to
        // avoid having filesystem collisions.  If this happens with a non-symlink
        // entry, it'll just fail to unpack, but a symlink to a directory, using an
        // 8.3 shortname or certain unicode attacks, can evade detection and lead
        // to arbitrary writes to anywhere on the system.
        if (entry.type === 'SymbolicLink') {
            dropCache(this.dirCache);
        }
        else if (entry.type !== 'Directory') {
            pruneCache(this.dirCache, String(entry.absolute));
        }
    }
    [CHECKFS2](entry, fullyDone) {
        this[PRUNECACHE](entry);
        const done = (er) => {
            this[PRUNECACHE](entry);
            fullyDone(er);
        };
        const checkCwd = () => {
            this[MKDIR](this.cwd, this.dmode, er => {
                if (er) {
                    this[ONERROR](er, entry);
                    done();
                    return;
                }
                this[CHECKED_CWD] = true;
                start();
            });
        };
        const start = () => {
            if (entry.absolute !== this.cwd) {
                const parent = normalizeWindowsPath(path.dirname(String(entry.absolute)));
                if (parent !== this.cwd) {
                    return this[MKDIR](parent, this.dmode, er => {
                        if (er) {
                            this[ONERROR](er, entry);
                            done();
                            return;
                        }
                        afterMakeParent();
                    });
                }
            }
            afterMakeParent();
        };
        const afterMakeParent = () => {
            fs.lstat(String(entry.absolute), (lstatEr, st) => {
                if (st &&
                    (this.keep ||
                        /* c8 ignore next */
                        (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
                    this[SKIP](entry);
                    done();
                    return;
                }
                if (lstatEr || this[ISREUSABLE](entry, st)) {
                    return this[MAKEFS](null, entry, done);
                }
                if (st.isDirectory()) {
                    if (entry.type === 'Directory') {
                        const needChmod = this.chmod &&
                            entry.mode &&
                            (st.mode & 0o7777) !== entry.mode;
                        const afterChmod = (er) => this[MAKEFS](er ?? null, entry, done);
                        if (!needChmod) {
                            return afterChmod();
                        }
                        return fs.chmod(String(entry.absolute), Number(entry.mode), afterChmod);
                    }
                    // Not a dir entry, have to remove it.
                    // NB: the only way to end up with an entry that is the cwd
                    // itself, in such a way that == does not detect, is a
                    // tricky windows absolute path with UNC or 8.3 parts (and
                    // preservePaths:true, or else it will have been stripped).
                    // In that case, the user has opted out of path protections
                    // explicitly, so if they blow away the cwd, c'est la vie.
                    if (entry.absolute !== this.cwd) {
                        return fs.rmdir(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done));
                    }
                }
                // not a dir, and not reusable
                // don't remove if the cwd, we want that error
                if (entry.absolute === this.cwd) {
                    return this[MAKEFS](null, entry, done);
                }
                unlinkFile(String(entry.absolute), er => this[MAKEFS](er ?? null, entry, done));
            });
        };
        if (this[CHECKED_CWD]) {
            start();
        }
        else {
            checkCwd();
        }
    }
    [MAKEFS](er, entry, done) {
        if (er) {
            this[ONERROR](er, entry);
            done();
            return;
        }
        switch (entry.type) {
            case 'File':
            case 'OldFile':
            case 'ContiguousFile':
                return this[FILE](entry, done);
            case 'Link':
                return this[HARDLINK](entry, done);
            case 'SymbolicLink':
                return this[SYMLINK](entry, done);
            case 'Directory':
            case 'GNUDumpDir':
                return this[DIRECTORY](entry, done);
        }
    }
    [LINK](entry, linkpath, link, done) {
        // XXX: get the type ('symlink' or 'junction') for windows
        fs[link](linkpath, String(entry.absolute), er => {
            if (er) {
                this[ONERROR](er, entry);
            }
            else {
                this[UNPEND]();
                entry.resume();
            }
            done();
        });
    }
}
const callSync = (fn) => {
    try {
        return [null, fn()];
    }
    catch (er) {
        return [er, null];
    }
};
export class UnpackSync extends Unpack {
    sync = true;
    [MAKEFS](er, entry) {
        return super[MAKEFS](er, entry, () => { });
    }
    [CHECKFS](entry) {
        this[PRUNECACHE](entry);
        if (!this[CHECKED_CWD]) {
            const er = this[MKDIR](this.cwd, this.dmode);
            if (er) {
                return this[ONERROR](er, entry);
            }
            this[CHECKED_CWD] = true;
        }
        // don't bother to make the parent if the current entry is the cwd,
        // we've already checked it.
        if (entry.absolute !== this.cwd) {
            const parent = normalizeWindowsPath(path.dirname(String(entry.absolute)));
            if (parent !== this.cwd) {
                const mkParent = this[MKDIR](parent, this.dmode);
                if (mkParent) {
                    return this[ONERROR](mkParent, entry);
                }
            }
        }
        const [lstatEr, st] = callSync(() => fs.lstatSync(String(entry.absolute)));
        if (st &&
            (this.keep ||
                /* c8 ignore next */
                (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
            return this[SKIP](entry);
        }
        if (lstatEr || this[ISREUSABLE](entry, st)) {
            return this[MAKEFS](null, entry);
        }
        if (st.isDirectory()) {
            if (entry.type === 'Directory') {
                const needChmod = this.chmod &&
                    entry.mode &&
                    (st.mode & 0o7777) !== entry.mode;
                const [er] = needChmod ?
                    callSync(() => {
                        fs.chmodSync(String(entry.absolute), Number(entry.mode));
                    })
                    : [];
                return this[MAKEFS](er, entry);
            }
            // not a dir entry, have to remove it
            const [er] = callSync(() => fs.rmdirSync(String(entry.absolute)));
            this[MAKEFS](er, entry);
        }
        // not a dir, and not reusable.
        // don't remove if it's the cwd, since we want that error.
        const [er] = entry.absolute === this.cwd ?
            []
            : callSync(() => unlinkFileSync(String(entry.absolute)));
        this[MAKEFS](er, entry);
    }
    [FILE](entry, done) {
        const mode = typeof entry.mode === 'number' ?
            entry.mode & 0o7777
            : this.fmode;
        const oner = (er) => {
            let closeError;
            try {
                fs.closeSync(fd);
            }
            catch (e) {
                closeError = e;
            }
            if (er || closeError) {
                this[ONERROR](er || closeError, entry);
            }
            done();
        };
        let fd;
        try {
            fd = fs.openSync(String(entry.absolute), getWriteFlag(entry.size), mode);
        }
        catch (er) {
            return oner(er);
        }
        const tx = this.transform ? this.transform(entry) || entry : entry;
        if (tx !== entry) {
            tx.on('error', (er) => this[ONERROR](er, entry));
            entry.pipe(tx);
        }
        tx.on('data', (chunk) => {
            try {
                fs.writeSync(fd, chunk, 0, chunk.length);
            }
            catch (er) {
                oner(er);
            }
        });
        tx.on('end', () => {
            let er = null;
            // try both, falling futimes back to utimes
            // if either fails, handle the first error
            if (entry.mtime && !this.noMtime) {
                const atime = entry.atime || new Date();
                const mtime = entry.mtime;
                try {
                    fs.futimesSync(fd, atime, mtime);
                }
                catch (futimeser) {
                    try {
                        fs.utimesSync(String(entry.absolute), atime, mtime);
                    }
                    catch (utimeser) {
                        er = futimeser;
                    }
                }
            }
            if (this[DOCHOWN](entry)) {
                const uid = this[UID](entry);
                const gid = this[GID](entry);
                try {
                    fs.fchownSync(fd, Number(uid), Number(gid));
                }
                catch (fchowner) {
                    try {
                        fs.chownSync(String(entry.absolute), Number(uid), Number(gid));
                    }
                    catch (chowner) {
                        er = er || fchowner;
                    }
                }
            }
            oner(er);
        });
    }
    [DIRECTORY](entry, done) {
        const mode = typeof entry.mode === 'number' ?
            entry.mode & 0o7777
            : this.dmode;
        const er = this[MKDIR](String(entry.absolute), mode);
        if (er) {
            this[ONERROR](er, entry);
            done();
            return;
        }
        if (entry.mtime && !this.noMtime) {
            try {
                fs.utimesSync(String(entry.absolute), entry.atime || new Date(), entry.mtime);
                /* c8 ignore next */
            }
            catch (er) { }
        }
        if (this[DOCHOWN](entry)) {
            try {
                fs.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)));
            }
            catch (er) { }
        }
        done();
        entry.resume();
    }
    [MKDIR](dir, mode) {
        try {
            return mkdirSync(normalizeWindowsPath(dir), {
                uid: this.uid,
                gid: this.gid,
                processUid: this.processUid,
                processGid: this.processGid,
                umask: this.processUmask,
                preserve: this.preservePaths,
                unlink: this.unlink,
                cache: this.dirCache,
                cwd: this.cwd,
                mode: mode,
            });
        }
        catch (er) {
            return er;
        }
    }
    [LINK](entry, linkpath, link, done) {
        const ls = `${link}Sync`;
        try {
            fs[ls](linkpath, String(entry.absolute));
            done();
            entry.resume();
        }
        catch (er) {
            return this[ONERROR](er, entry);
        }
    }
}
//# sourceMappingURL=unpack.js.map// tar -u
import { makeCommand } from './make-command.js';
import { replace as r } from './replace.js';
// just call tar.r with the filter and mtimeCache
export const update = makeCommand(r.syncFile, r.asyncFile, r.syncNoFile, r.asyncNoFile, (opt, entries = []) => {
    r.validate?.(opt, entries);
    mtimeFilter(opt);
});
const mtimeFilter = (opt) => {
    const filter = opt.filter;
    if (!opt.mtimeCache) {
        opt.mtimeCache = new Map();
    }
    opt.filter =
        filter ?
            (path, stat) => filter(path, stat) &&
                !(
                /* c8 ignore start */
                ((opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) >
                    (stat.mtime ?? 0))
                /* c8 ignore stop */
                )
            : (path, stat) => !(
            /* c8 ignore start */
            ((opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) >
                (stat.mtime ?? 0))
            /* c8 ignore stop */
            );
};
//# sourceMappingURL=update.js.mapexport const warnMethod = (self, code, message, data = {}) => {
    if (self.file) {
        data.file = self.file;
    }
    if (self.cwd) {
        data.cwd = self.cwd;
    }
    data.code =
        (message instanceof Error &&
            message.code) ||
            code;
    data.tarCode = code;
    if (!self.strict && data.recoverable !== false) {
        if (message instanceof Error) {
            data = Object.assign(message, data);
            message = message.message;
        }
        self.emit('warn', code, message, data);
    }
    else if (message instanceof Error) {
        self.emit('error', Object.assign(message, data));
    }
    else {
        self.emit('error', Object.assign(new Error(`${code}: ${message}`), data));
    }
};
//# sourceMappingURL=warn-method.js.map// When writing files on Windows, translate the characters to their
// 0xf000 higher-encoded versions.
const raw = ['|', '<', '>', '?', ':'];
const win = raw.map(char => String.fromCharCode(0xf000 + char.charCodeAt(0)));
const toWin = new Map(raw.map((char, i) => [char, win[i]]));
const toRaw = new Map(win.map((char, i) => [char, raw[i]]));
export const encode = (s) => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s);
export const decode = (s) => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s);
//# sourceMappingURL=winchars.js.mapimport fs from 'fs';
import { Minipass } from 'minipass';
import path from 'path';
import { Header } from './header.js';
import { modeFix } from './mode-fix.js';
import { normalizeWindowsPath } from './normalize-windows-path.js';
import { dealias, } from './options.js';
import { Pax } from './pax.js';
import { stripAbsolutePath } from './strip-absolute-path.js';
import { stripTrailingSlashes } from './strip-trailing-slashes.js';
import { warnMethod, } from './warn-method.js';
import * as winchars from './winchars.js';
const prefixPath = (path, prefix) => {
    if (!prefix) {
        return normalizeWindowsPath(path);
    }
    path = normalizeWindowsPath(path).replace(/^\.(\/|$)/, '');
    return stripTrailingSlashes(prefix) + '/' + path;
};
const maxReadSize = 16 * 1024 * 1024;
const PROCESS = Symbol('process');
const FILE = Symbol('file');
const DIRECTORY = Symbol('directory');
const SYMLINK = Symbol('symlink');
const HARDLINK = Symbol('hardlink');
const HEADER = Symbol('header');
const READ = Symbol('read');
const LSTAT = Symbol('lstat');
const ONLSTAT = Symbol('onlstat');
const ONREAD = Symbol('onread');
const ONREADLINK = Symbol('onreadlink');
const OPENFILE = Symbol('openfile');
const ONOPENFILE = Symbol('onopenfile');
const CLOSE = Symbol('close');
const MODE = Symbol('mode');
const AWAITDRAIN = Symbol('awaitDrain');
const ONDRAIN = Symbol('ondrain');
const PREFIX = Symbol('prefix');
export class WriteEntry extends Minipass {
    path;
    portable;
    myuid = (process.getuid && process.getuid()) || 0;
    // until node has builtin pwnam functions, this'll have to do
    myuser = process.env.USER || '';
    maxReadSize;
    linkCache;
    statCache;
    preservePaths;
    cwd;
    strict;
    mtime;
    noPax;
    noMtime;
    prefix;
    fd;
    blockLen = 0;
    blockRemain = 0;
    buf;
    pos = 0;
    remain = 0;
    length = 0;
    offset = 0;
    win32;
    absolute;
    header;
    type;
    linkpath;
    stat;
    onWriteEntry;
    #hadError = false;
    constructor(p, opt_ = {}) {
        const opt = dealias(opt_);
        super();
        this.path = normalizeWindowsPath(p);
        // suppress atime, ctime, uid, gid, uname, gname
        this.portable = !!opt.portable;
        this.maxReadSize = opt.maxReadSize || maxReadSize;
        this.linkCache = opt.linkCache || new Map();
        this.statCache = opt.statCache || new Map();
        this.preservePaths = !!opt.preservePaths;
        this.cwd = normalizeWindowsPath(opt.cwd || process.cwd());
        this.strict = !!opt.strict;
        this.noPax = !!opt.noPax;
        this.noMtime = !!opt.noMtime;
        this.mtime = opt.mtime;
        this.prefix =
            opt.prefix ? normalizeWindowsPath(opt.prefix) : undefined;
        this.onWriteEntry = opt.onWriteEntry;
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        let pathWarn = false;
        if (!this.preservePaths) {
            const [root, stripped] = stripAbsolutePath(this.path);
            if (root && typeof stripped === 'string') {
                this.path = stripped;
                pathWarn = root;
            }
        }
        this.win32 = !!opt.win32 || process.platform === 'win32';
        if (this.win32) {
            // force the \ to / normalization, since we might not *actually*
            // be on windows, but want \ to be considered a path separator.
            this.path = winchars.decode(this.path.replace(/\\/g, '/'));
            p = p.replace(/\\/g, '/');
        }
        this.absolute = normalizeWindowsPath(opt.absolute || path.resolve(this.cwd, p));
        if (this.path === '') {
            this.path = './';
        }
        if (pathWarn) {
            this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {
                entry: this,
                path: pathWarn + this.path,
            });
        }
        const cs = this.statCache.get(this.absolute);
        if (cs) {
            this[ONLSTAT](cs);
        }
        else {
            this[LSTAT]();
        }
    }
    warn(code, message, data = {}) {
        return warnMethod(this, code, message, data);
    }
    emit(ev, ...data) {
        if (ev === 'error') {
            this.#hadError = true;
        }
        return super.emit(ev, ...data);
    }
    [LSTAT]() {
        fs.lstat(this.absolute, (er, stat) => {
            if (er) {
                return this.emit('error', er);
            }
            this[ONLSTAT](stat);
        });
    }
    [ONLSTAT](stat) {
        this.statCache.set(this.absolute, stat);
        this.stat = stat;
        if (!stat.isFile()) {
            stat.size = 0;
        }
        this.type = getType(stat);
        this.emit('stat', stat);
        this[PROCESS]();
    }
    [PROCESS]() {
        switch (this.type) {
            case 'File':
                return this[FILE]();
            case 'Directory':
                return this[DIRECTORY]();
            case 'SymbolicLink':
                return this[SYMLINK]();
            // unsupported types are ignored.
            default:
                return this.end();
        }
    }
    [MODE](mode) {
        return modeFix(mode, this.type === 'Directory', this.portable);
    }
    [PREFIX](path) {
        return prefixPath(path, this.prefix);
    }
    [HEADER]() {
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('cannot write header before stat');
        }
        /* c8 ignore stop */
        if (this.type === 'Directory' && this.portable) {
            this.noMtime = true;
        }
        this.onWriteEntry?.(this);
        this.header = new Header({
            path: this[PREFIX](this.path),
            // only apply the prefix to hard links.
            linkpath: this.type === 'Link' && this.linkpath !== undefined ?
                this[PREFIX](this.linkpath)
                : this.linkpath,
            // only the permissions and setuid/setgid/sticky bitflags
            // not the higher-order bits that specify file type
            mode: this[MODE](this.stat.mode),
            uid: this.portable ? undefined : this.stat.uid,
            gid: this.portable ? undefined : this.stat.gid,
            size: this.stat.size,
            mtime: this.noMtime ? undefined : this.mtime || this.stat.mtime,
            /* c8 ignore next */
            type: this.type === 'Unsupported' ? undefined : this.type,
            uname: this.portable ? undefined
                : this.stat.uid === this.myuid ? this.myuser
                    : '',
            atime: this.portable ? undefined : this.stat.atime,
            ctime: this.portable ? undefined : this.stat.ctime,
        });
        if (this.header.encode() && !this.noPax) {
            super.write(new Pax({
                atime: this.portable ? undefined : this.header.atime,
                ctime: this.portable ? undefined : this.header.ctime,
                gid: this.portable ? undefined : this.header.gid,
                mtime: this.noMtime ? undefined : (this.mtime || this.header.mtime),
                path: this[PREFIX](this.path),
                linkpath: this.type === 'Link' && this.linkpath !== undefined ?
                    this[PREFIX](this.linkpath)
                    : this.linkpath,
                size: this.header.size,
                uid: this.portable ? undefined : this.header.uid,
                uname: this.portable ? undefined : this.header.uname,
                dev: this.portable ? undefined : this.stat.dev,
                ino: this.portable ? undefined : this.stat.ino,
                nlink: this.portable ? undefined : this.stat.nlink,
            }).encode());
        }
        const block = this.header?.block;
        /* c8 ignore start */
        if (!block) {
            throw new Error('failed to encode header');
        }
        /* c8 ignore stop */
        super.write(block);
    }
    [DIRECTORY]() {
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('cannot create directory entry without stat');
        }
        /* c8 ignore stop */
        if (this.path.slice(-1) !== '/') {
            this.path += '/';
        }
        this.stat.size = 0;
        this[HEADER]();
        this.end();
    }
    [SYMLINK]() {
        fs.readlink(this.absolute, (er, linkpath) => {
            if (er) {
                return this.emit('error', er);
            }
            this[ONREADLINK](linkpath);
        });
    }
    [ONREADLINK](linkpath) {
        this.linkpath = normalizeWindowsPath(linkpath);
        this[HEADER]();
        this.end();
    }
    [HARDLINK](linkpath) {
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('cannot create link entry without stat');
        }
        /* c8 ignore stop */
        this.type = 'Link';
        this.linkpath = normalizeWindowsPath(path.relative(this.cwd, linkpath));
        this.stat.size = 0;
        this[HEADER]();
        this.end();
    }
    [FILE]() {
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('cannot create file entry without stat');
        }
        /* c8 ignore stop */
        if (this.stat.nlink > 1) {
            const linkKey = `${this.stat.dev}:${this.stat.ino}`;
            const linkpath = this.linkCache.get(linkKey);
            if (linkpath?.indexOf(this.cwd) === 0) {
                return this[HARDLINK](linkpath);
            }
            this.linkCache.set(linkKey, this.absolute);
        }
        this[HEADER]();
        if (this.stat.size === 0) {
            return this.end();
        }
        this[OPENFILE]();
    }
    [OPENFILE]() {
        fs.open(this.absolute, 'r', (er, fd) => {
            if (er) {
                return this.emit('error', er);
            }
            this[ONOPENFILE](fd);
        });
    }
    [ONOPENFILE](fd) {
        this.fd = fd;
        if (this.#hadError) {
            return this[CLOSE]();
        }
        /* c8 ignore start */
        if (!this.stat) {
            throw new Error('should stat before calling onopenfile');
        }
        /* c8 ignore start */
        this.blockLen = 512 * Math.ceil(this.stat.size / 512);
        this.blockRemain = this.blockLen;
        const bufLen = Math.min(this.blockLen, this.maxReadSize);
        this.buf = Buffer.allocUnsafe(bufLen);
        this.offset = 0;
        this.pos = 0;
        this.remain = this.stat.size;
        this.length = this.buf.length;
        this[READ]();
    }
    [READ]() {
        const { fd, buf, offset, length, pos } = this;
        if (fd === undefined || buf === undefined) {
            throw new Error('cannot read file without first opening');
        }
        fs.read(fd, buf, offset, length, pos, (er, bytesRead) => {
            if (er) {
                // ignoring the error from close(2) is a bad practice, but at
                // this point we already have an error, don't need another one
                return this[CLOSE](() => this.emit('error', er));
            }
            this[ONREAD](bytesRead);
        });
    }
    /* c8 ignore start */
    [CLOSE](cb = () => { }) {
        /* c8 ignore stop */
        if (this.fd !== undefined)
            fs.close(this.fd, cb);
    }
    [ONREAD](bytesRead) {
        if (bytesRead <= 0 && this.remain > 0) {
            const er = Object.assign(new Error('encountered unexpected EOF'), {
                path: this.absolute,
                syscall: 'read',
                code: 'EOF',
            });
            return this[CLOSE](() => this.emit('error', er));
        }
        if (bytesRead > this.remain) {
            const er = Object.assign(new Error('did not encounter expected EOF'), {
                path: this.absolute,
                syscall: 'read',
                code: 'EOF',
            });
            return this[CLOSE](() => this.emit('error', er));
        }
        /* c8 ignore start */
        if (!this.buf) {
            throw new Error('should have created buffer prior to reading');
        }
        /* c8 ignore stop */
        // null out the rest of the buffer, if we could fit the block padding
        // at the end of this loop, we've incremented bytesRead and this.remain
        // to be incremented up to the blockRemain level, as if we had expected
        // to get a null-padded file, and read it until the end.  then we will
        // decrement both remain and blockRemain by bytesRead, and know that we
        // reached the expected EOF, without any null buffer to append.
        if (bytesRead === this.remain) {
            for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) {
                this.buf[i + this.offset] = 0;
                bytesRead++;
                this.remain++;
            }
        }
        const chunk = this.offset === 0 && bytesRead === this.buf.length ?
            this.buf
            : this.buf.subarray(this.offset, this.offset + bytesRead);
        const flushed = this.write(chunk);
        if (!flushed) {
            this[AWAITDRAIN](() => this[ONDRAIN]());
        }
        else {
            this[ONDRAIN]();
        }
    }
    [AWAITDRAIN](cb) {
        this.once('drain', cb);
    }
    write(chunk, encoding, cb) {
        /* c8 ignore start - just junk to comply with NodeJS.WritableStream */
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8');
        }
        /* c8 ignore stop */
        if (this.blockRemain < chunk.length) {
            const er = Object.assign(new Error('writing more data than expected'), {
                path: this.absolute,
            });
            return this.emit('error', er);
        }
        this.remain -= chunk.length;
        this.blockRemain -= chunk.length;
        this.pos += chunk.length;
        this.offset += chunk.length;
        return super.write(chunk, null, cb);
    }
    [ONDRAIN]() {
        if (!this.remain) {
            if (this.blockRemain) {
                super.write(Buffer.alloc(this.blockRemain));
            }
            return this[CLOSE](er => er ? this.emit('error', er) : this.end());
        }
        /* c8 ignore start */
        if (!this.buf) {
            throw new Error('buffer lost somehow in ONDRAIN');
        }
        /* c8 ignore stop */
        if (this.offset >= this.length) {
            // if we only have a smaller bit left to read, alloc a smaller buffer
            // otherwise, keep it the same length it was before.
            this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length));
            this.offset = 0;
        }
        this.length = this.buf.length - this.offset;
        this[READ]();
    }
}
export class WriteEntrySync extends WriteEntry {
    sync = true;
    [LSTAT]() {
        this[ONLSTAT](fs.lstatSync(this.absolute));
    }
    [SYMLINK]() {
        this[ONREADLINK](fs.readlinkSync(this.absolute));
    }
    [OPENFILE]() {
        this[ONOPENFILE](fs.openSync(this.absolute, 'r'));
    }
    [READ]() {
        let threw = true;
        try {
            const { fd, buf, offset, length, pos } = this;
            /* c8 ignore start */
            if (fd === undefined || buf === undefined) {
                throw new Error('fd and buf must be set in READ method');
            }
            /* c8 ignore stop */
            const bytesRead = fs.readSync(fd, buf, offset, length, pos);
            this[ONREAD](bytesRead);
            threw = false;
        }
        finally {
            // ignoring the error from close(2) is a bad practice, but at
            // this point we already have an error, don't need another one
            if (threw) {
                try {
                    this[CLOSE](() => { });
                }
                catch (er) { }
            }
        }
    }
    [AWAITDRAIN](cb) {
        cb();
    }
    /* c8 ignore start */
    [CLOSE](cb = () => { }) {
        /* c8 ignore stop */
        if (this.fd !== undefined)
            fs.closeSync(this.fd);
        cb();
    }
}
export class WriteEntryTar extends Minipass {
    blockLen = 0;
    blockRemain = 0;
    buf = 0;
    pos = 0;
    remain = 0;
    length = 0;
    preservePaths;
    portable;
    strict;
    noPax;
    noMtime;
    readEntry;
    type;
    prefix;
    path;
    mode;
    uid;
    gid;
    uname;
    gname;
    header;
    mtime;
    atime;
    ctime;
    linkpath;
    size;
    onWriteEntry;
    warn(code, message, data = {}) {
        return warnMethod(this, code, message, data);
    }
    constructor(readEntry, opt_ = {}) {
        const opt = dealias(opt_);
        super();
        this.preservePaths = !!opt.preservePaths;
        this.portable = !!opt.portable;
        this.strict = !!opt.strict;
        this.noPax = !!opt.noPax;
        this.noMtime = !!opt.noMtime;
        this.onWriteEntry = opt.onWriteEntry;
        this.readEntry = readEntry;
        const { type } = readEntry;
        /* c8 ignore start */
        if (type === 'Unsupported') {
            throw new Error('writing entry that should be ignored');
        }
        /* c8 ignore stop */
        this.type = type;
        if (this.type === 'Directory' && this.portable) {
            this.noMtime = true;
        }
        this.prefix = opt.prefix;
        this.path = normalizeWindowsPath(readEntry.path);
        this.mode =
            readEntry.mode !== undefined ?
                this[MODE](readEntry.mode)
                : undefined;
        this.uid = this.portable ? undefined : readEntry.uid;
        this.gid = this.portable ? undefined : readEntry.gid;
        this.uname = this.portable ? undefined : readEntry.uname;
        this.gname = this.portable ? undefined : readEntry.gname;
        this.size = readEntry.size;
        this.mtime =
            this.noMtime ? undefined : opt.mtime || readEntry.mtime;
        this.atime = this.portable ? undefined : readEntry.atime;
        this.ctime = this.portable ? undefined : readEntry.ctime;
        this.linkpath =
            readEntry.linkpath !== undefined ?
                normalizeWindowsPath(readEntry.linkpath)
                : undefined;
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        let pathWarn = false;
        if (!this.preservePaths) {
            const [root, stripped] = stripAbsolutePath(this.path);
            if (root && typeof stripped === 'string') {
                this.path = stripped;
                pathWarn = root;
            }
        }
        this.remain = readEntry.size;
        this.blockRemain = readEntry.startBlockSize;
        this.onWriteEntry?.(this);
        this.header = new Header({
            path: this[PREFIX](this.path),
            linkpath: this.type === 'Link' && this.linkpath !== undefined ?
                this[PREFIX](this.linkpath)
                : this.linkpath,
            // only the permissions and setuid/setgid/sticky bitflags
            // not the higher-order bits that specify file type
            mode: this.mode,
            uid: this.portable ? undefined : this.uid,
            gid: this.portable ? undefined : this.gid,
            size: this.size,
            mtime: this.noMtime ? undefined : this.mtime,
            type: this.type,
            uname: this.portable ? undefined : this.uname,
            atime: this.portable ? undefined : this.atime,
            ctime: this.portable ? undefined : this.ctime,
        });
        if (pathWarn) {
            this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {
                entry: this,
                path: pathWarn + this.path,
            });
        }
        if (this.header.encode() && !this.noPax) {
            super.write(new Pax({
                atime: this.portable ? undefined : this.atime,
                ctime: this.portable ? undefined : this.ctime,
                gid: this.portable ? undefined : this.gid,
                mtime: this.noMtime ? undefined : this.mtime,
                path: this[PREFIX](this.path),
                linkpath: this.type === 'Link' && this.linkpath !== undefined ?
                    this[PREFIX](this.linkpath)
                    : this.linkpath,
                size: this.size,
                uid: this.portable ? undefined : this.uid,
                uname: this.portable ? undefined : this.uname,
                dev: this.portable ? undefined : this.readEntry.dev,
                ino: this.portable ? undefined : this.readEntry.ino,
                nlink: this.portable ? undefined : this.readEntry.nlink,
            }).encode());
        }
        const b = this.header?.block;
        /* c8 ignore start */
        if (!b)
            throw new Error('failed to encode header');
        /* c8 ignore stop */
        super.write(b);
        readEntry.pipe(this);
    }
    [PREFIX](path) {
        return prefixPath(path, this.prefix);
    }
    [MODE](mode) {
        return modeFix(mode, this.type === 'Directory', this.portable);
    }
    write(chunk, encoding, cb) {
        /* c8 ignore start - just junk to comply with NodeJS.WritableStream */
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8');
        }
        /* c8 ignore stop */
        const writeLen = chunk.length;
        if (writeLen > this.blockRemain) {
            throw new Error('writing more to entry than is appropriate');
        }
        this.blockRemain -= writeLen;
        return super.write(chunk, cb);
    }
    end(chunk, encoding, cb) {
        if (this.blockRemain) {
            super.write(Buffer.alloc(this.blockRemain));
        }
        /* c8 ignore start - just junk to comply with NodeJS.WritableStream */
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        if (typeof chunk === 'string') {
            chunk = Buffer.from(chunk, encoding ?? 'utf8');
        }
        if (cb)
            this.once('finish', cb);
        chunk ? super.end(chunk, cb) : super.end(cb);
        /* c8 ignore stop */
        return this;
    }
}
const getType = (stat) => stat.isFile() ? 'File'
    : stat.isDirectory() ? 'Directory'
        : stat.isSymbolicLink() ? 'SymbolicLink'
            : 'Unsupported';
//# sourceMappingURL=write-entry.js.map{
  "author": "Isaac Z. Schlueter",
  "name": "tar",
  "description": "tar for node",
  "version": "7.4.3",
  "repository": {
    "type": "git",
    "url": "https://github.com/isaacs/node-tar.git"
  },
  "scripts": {
    "genparse": "node scripts/generate-parse-fixtures.js",
    "snap": "tap",
    "test": "tap",
    "pretest": "npm run prepare",
    "presnap": "npm run prepare",
    "prepare": "tshy",
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "format": "prettier --write . --log-level warn",
    "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
  },
  "dependencies": {
    "@isaacs/fs-minipass": "^4.0.0",
    "chownr": "^3.0.0",
    "minipass": "^7.1.2",
    "minizlib": "^3.0.1",
    "mkdirp": "^3.0.1",
    "yallist": "^5.0.0"
  },
  "devDependencies": {
    "chmodr": "^1.2.0",
    "end-of-stream": "^1.4.3",
    "events-to-array": "^2.0.3",
    "mutate-fs": "^2.1.1",
    "nock": "^13.5.4",
    "prettier": "^3.2.5",
    "rimraf": "^5.0.5",
    "tap": "^18.7.2",
    "tshy": "^1.13.1",
    "typedoc": "^0.25.13"
  },
  "license": "ISC",
  "engines": {
    "node": ">=18"
  },
  "files": [
    "dist"
  ],
  "tap": {
    "coverage-map": "map.js",
    "timeout": 0,
    "typecheck": true
  },
  "prettier": {
    "experimentalTernaries": true,
    "semi": false,
    "printWidth": 70,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts",
      "./c": "./src/create.ts",
      "./create": "./src/create.ts",
      "./replace": "./src/create.ts",
      "./r": "./src/create.ts",
      "./list": "./src/list.ts",
      "./t": "./src/list.ts",
      "./update": "./src/update.ts",
      "./u": "./src/update.ts",
      "./extract": "./src/extract.ts",
      "./x": "./src/extract.ts",
      "./pack": "./src/pack.ts",
      "./unpack": "./src/unpack.ts",
      "./parse": "./src/parse.ts",
      "./read-entry": "./src/read-entry.ts",
      "./write-entry": "./src/write-entry.ts",
      "./header": "./src/header.ts",
      "./pax": "./src/pax.ts",
      "./types": "./src/types.ts"
    }
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "source": "./src/index.ts",
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "source": "./src/index.ts",
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    },
    "./c": {
      "import": {
        "source": "./src/create.ts",
        "types": "./dist/esm/create.d.ts",
        "default": "./dist/esm/create.js"
      },
      "require": {
        "source": "./src/create.ts",
        "types": "./dist/commonjs/create.d.ts",
        "default": "./dist/commonjs/create.js"
      }
    },
    "./create": {
      "import": {
        "source": "./src/create.ts",
        "types": "./dist/esm/create.d.ts",
        "default": "./dist/esm/create.js"
      },
      "require": {
        "source": "./src/create.ts",
        "types": "./dist/commonjs/create.d.ts",
        "default": "./dist/commonjs/create.js"
      }
    },
    "./replace": {
      "import": {
        "source": "./src/create.ts",
        "types": "./dist/esm/create.d.ts",
        "default": "./dist/esm/create.js"
      },
      "require": {
        "source": "./src/create.ts",
        "types": "./dist/commonjs/create.d.ts",
        "default": "./dist/commonjs/create.js"
      }
    },
    "./r": {
      "import": {
        "source": "./src/create.ts",
        "types": "./dist/esm/create.d.ts",
        "default": "./dist/esm/create.js"
      },
      "require": {
        "source": "./src/create.ts",
        "types": "./dist/commonjs/create.d.ts",
        "default": "./dist/commonjs/create.js"
      }
    },
    "./list": {
      "import": {
        "source": "./src/list.ts",
        "types": "./dist/esm/list.d.ts",
        "default": "./dist/esm/list.js"
      },
      "require": {
        "source": "./src/list.ts",
        "types": "./dist/commonjs/list.d.ts",
        "default": "./dist/commonjs/list.js"
      }
    },
    "./t": {
      "import": {
        "source": "./src/list.ts",
        "types": "./dist/esm/list.d.ts",
        "default": "./dist/esm/list.js"
      },
      "require": {
        "source": "./src/list.ts",
        "types": "./dist/commonjs/list.d.ts",
        "default": "./dist/commonjs/list.js"
      }
    },
    "./update": {
      "import": {
        "source": "./src/update.ts",
        "types": "./dist/esm/update.d.ts",
        "default": "./dist/esm/update.js"
      },
      "require": {
        "source": "./src/update.ts",
        "types": "./dist/commonjs/update.d.ts",
        "default": "./dist/commonjs/update.js"
      }
    },
    "./u": {
      "import": {
        "source": "./src/update.ts",
        "types": "./dist/esm/update.d.ts",
        "default": "./dist/esm/update.js"
      },
      "require": {
        "source": "./src/update.ts",
        "types": "./dist/commonjs/update.d.ts",
        "default": "./dist/commonjs/update.js"
      }
    },
    "./extract": {
      "import": {
        "source": "./src/extract.ts",
        "types": "./dist/esm/extract.d.ts",
        "default": "./dist/esm/extract.js"
      },
      "require": {
        "source": "./src/extract.ts",
        "types": "./dist/commonjs/extract.d.ts",
        "default": "./dist/commonjs/extract.js"
      }
    },
    "./x": {
      "import": {
        "source": "./src/extract.ts",
        "types": "./dist/esm/extract.d.ts",
        "default": "./dist/esm/extract.js"
      },
      "require": {
        "source": "./src/extract.ts",
        "types": "./dist/commonjs/extract.d.ts",
        "default": "./dist/commonjs/extract.js"
      }
    },
    "./pack": {
      "import": {
        "source": "./src/pack.ts",
        "types": "./dist/esm/pack.d.ts",
        "default": "./dist/esm/pack.js"
      },
      "require": {
        "source": "./src/pack.ts",
        "types": "./dist/commonjs/pack.d.ts",
        "default": "./dist/commonjs/pack.js"
      }
    },
    "./unpack": {
      "import": {
        "source": "./src/unpack.ts",
        "types": "./dist/esm/unpack.d.ts",
        "default": "./dist/esm/unpack.js"
      },
      "require": {
        "source": "./src/unpack.ts",
        "types": "./dist/commonjs/unpack.d.ts",
        "default": "./dist/commonjs/unpack.js"
      }
    },
    "./parse": {
      "import": {
        "source": "./src/parse.ts",
        "types": "./dist/esm/parse.d.ts",
        "default": "./dist/esm/parse.js"
      },
      "require": {
        "source": "./src/parse.ts",
        "types": "./dist/commonjs/parse.d.ts",
        "default": "./dist/commonjs/parse.js"
      }
    },
    "./read-entry": {
      "import": {
        "source": "./src/read-entry.ts",
        "types": "./dist/esm/read-entry.d.ts",
        "default": "./dist/esm/read-entry.js"
      },
      "require": {
        "source": "./src/read-entry.ts",
        "types": "./dist/commonjs/read-entry.d.ts",
        "default": "./dist/commonjs/read-entry.js"
      }
    },
    "./write-entry": {
      "import": {
        "source": "./src/write-entry.ts",
        "types": "./dist/esm/write-entry.d.ts",
        "default": "./dist/esm/write-entry.js"
      },
      "require": {
        "source": "./src/write-entry.ts",
        "types": "./dist/commonjs/write-entry.d.ts",
        "default": "./dist/commonjs/write-entry.js"
      }
    },
    "./header": {
      "import": {
        "source": "./src/header.ts",
        "types": "./dist/esm/header.d.ts",
        "default": "./dist/esm/header.js"
      },
      "require": {
        "source": "./src/header.ts",
        "types": "./dist/commonjs/header.d.ts",
        "default": "./dist/commonjs/header.js"
      }
    },
    "./pax": {
      "import": {
        "source": "./src/pax.ts",
        "types": "./dist/esm/pax.d.ts",
        "default": "./dist/esm/pax.js"
      },
      "require": {
        "source": "./src/pax.ts",
        "types": "./dist/commonjs/pax.d.ts",
        "default": "./dist/commonjs/pax.js"
      }
    },
    "./types": {
      "import": {
        "source": "./src/types.ts",
        "types": "./dist/esm/types.d.ts",
        "default": "./dist/esm/types.js"
      },
      "require": {
        "source": "./src/types.ts",
        "types": "./dist/commonjs/types.d.ts",
        "default": "./dist/commonjs/types.js"
      }
    }
  },
  "type": "module",
  "main": "./dist/commonjs/index.js",
  "types": "./dist/commonjs/index.d.ts"
}
All packages under `src/` are licensed according to the terms in
their respective `LICENSE` or `LICENSE.md` files.

The remainder of this project is licensed under the Blue Oak
Model License, as follows:

-----

# Blue Oak Model License

Version 1.0.0

## Purpose

This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.

## Acceptance

In order to receive this license, you must agree to its
rules.  The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.

## Copyright

Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.

## Notices

You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
.

## Excuse

If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice.  If you do not do so, your license
ends immediately.

## Patent

Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.

## Reliability

No contributor can revoke this license.

## No Liability

***As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim.***
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Node = exports.Yallist = void 0;
class Yallist {
    tail;
    head;
    length = 0;
    static create(list = []) {
        return new Yallist(list);
    }
    constructor(list = []) {
        for (const item of list) {
            this.push(item);
        }
    }
    *[Symbol.iterator]() {
        for (let walker = this.head; walker; walker = walker.next) {
            yield walker.value;
        }
    }
    removeNode(node) {
        if (node.list !== this) {
            throw new Error('removing node which does not belong to this list');
        }
        const next = node.next;
        const prev = node.prev;
        if (next) {
            next.prev = prev;
        }
        if (prev) {
            prev.next = next;
        }
        if (node === this.head) {
            this.head = next;
        }
        if (node === this.tail) {
            this.tail = prev;
        }
        this.length--;
        node.next = undefined;
        node.prev = undefined;
        node.list = undefined;
        return next;
    }
    unshiftNode(node) {
        if (node === this.head) {
            return;
        }
        if (node.list) {
            node.list.removeNode(node);
        }
        const head = this.head;
        node.list = this;
        node.next = head;
        if (head) {
            head.prev = node;
        }
        this.head = node;
        if (!this.tail) {
            this.tail = node;
        }
        this.length++;
    }
    pushNode(node) {
        if (node === this.tail) {
            return;
        }
        if (node.list) {
            node.list.removeNode(node);
        }
        const tail = this.tail;
        node.list = this;
        node.prev = tail;
        if (tail) {
            tail.next = node;
        }
        this.tail = node;
        if (!this.head) {
            this.head = node;
        }
        this.length++;
    }
    push(...args) {
        for (let i = 0, l = args.length; i < l; i++) {
            push(this, args[i]);
        }
        return this.length;
    }
    unshift(...args) {
        for (var i = 0, l = args.length; i < l; i++) {
            unshift(this, args[i]);
        }
        return this.length;
    }
    pop() {
        if (!this.tail) {
            return undefined;
        }
        const res = this.tail.value;
        const t = this.tail;
        this.tail = this.tail.prev;
        if (this.tail) {
            this.tail.next = undefined;
        }
        else {
            this.head = undefined;
        }
        t.list = undefined;
        this.length--;
        return res;
    }
    shift() {
        if (!this.head) {
            return undefined;
        }
        const res = this.head.value;
        const h = this.head;
        this.head = this.head.next;
        if (this.head) {
            this.head.prev = undefined;
        }
        else {
            this.tail = undefined;
        }
        h.list = undefined;
        this.length--;
        return res;
    }
    forEach(fn, thisp) {
        thisp = thisp || this;
        for (let walker = this.head, i = 0; !!walker; i++) {
            fn.call(thisp, walker.value, i, this);
            walker = walker.next;
        }
    }
    forEachReverse(fn, thisp) {
        thisp = thisp || this;
        for (let walker = this.tail, i = this.length - 1; !!walker; i--) {
            fn.call(thisp, walker.value, i, this);
            walker = walker.prev;
        }
    }
    get(n) {
        let i = 0;
        let walker = this.head;
        for (; !!walker && i < n; i++) {
            walker = walker.next;
        }
        if (i === n && !!walker) {
            return walker.value;
        }
    }
    getReverse(n) {
        let i = 0;
        let walker = this.tail;
        for (; !!walker && i < n; i++) {
            // abort out of the list early if we hit a cycle
            walker = walker.prev;
        }
        if (i === n && !!walker) {
            return walker.value;
        }
    }
    map(fn, thisp) {
        thisp = thisp || this;
        const res = new Yallist();
        for (let walker = this.head; !!walker;) {
            res.push(fn.call(thisp, walker.value, this));
            walker = walker.next;
        }
        return res;
    }
    mapReverse(fn, thisp) {
        thisp = thisp || this;
        var res = new Yallist();
        for (let walker = this.tail; !!walker;) {
            res.push(fn.call(thisp, walker.value, this));
            walker = walker.prev;
        }
        return res;
    }
    reduce(fn, initial) {
        let acc;
        let walker = this.head;
        if (arguments.length > 1) {
            acc = initial;
        }
        else if (this.head) {
            walker = this.head.next;
            acc = this.head.value;
        }
        else {
            throw new TypeError('Reduce of empty list with no initial value');
        }
        for (var i = 0; !!walker; i++) {
            acc = fn(acc, walker.value, i);
            walker = walker.next;
        }
        return acc;
    }
    reduceReverse(fn, initial) {
        let acc;
        let walker = this.tail;
        if (arguments.length > 1) {
            acc = initial;
        }
        else if (this.tail) {
            walker = this.tail.prev;
            acc = this.tail.value;
        }
        else {
            throw new TypeError('Reduce of empty list with no initial value');
        }
        for (let i = this.length - 1; !!walker; i--) {
            acc = fn(acc, walker.value, i);
            walker = walker.prev;
        }
        return acc;
    }
    toArray() {
        const arr = new Array(this.length);
        for (let i = 0, walker = this.head; !!walker; i++) {
            arr[i] = walker.value;
            walker = walker.next;
        }
        return arr;
    }
    toArrayReverse() {
        const arr = new Array(this.length);
        for (let i = 0, walker = this.tail; !!walker; i++) {
            arr[i] = walker.value;
            walker = walker.prev;
        }
        return arr;
    }
    slice(from = 0, to = this.length) {
        if (to < 0) {
            to += this.length;
        }
        if (from < 0) {
            from += this.length;
        }
        const ret = new Yallist();
        if (to < from || to < 0) {
            return ret;
        }
        if (from < 0) {
            from = 0;
        }
        if (to > this.length) {
            to = this.length;
        }
        let walker = this.head;
        let i = 0;
        for (i = 0; !!walker && i < from; i++) {
            walker = walker.next;
        }
        for (; !!walker && i < to; i++, walker = walker.next) {
            ret.push(walker.value);
        }
        return ret;
    }
    sliceReverse(from = 0, to = this.length) {
        if (to < 0) {
            to += this.length;
        }
        if (from < 0) {
            from += this.length;
        }
        const ret = new Yallist();
        if (to < from || to < 0) {
            return ret;
        }
        if (from < 0) {
            from = 0;
        }
        if (to > this.length) {
            to = this.length;
        }
        let i = this.length;
        let walker = this.tail;
        for (; !!walker && i > to; i--) {
            walker = walker.prev;
        }
        for (; !!walker && i > from; i--, walker = walker.prev) {
            ret.push(walker.value);
        }
        return ret;
    }
    splice(start, deleteCount = 0, ...nodes) {
        if (start > this.length) {
            start = this.length - 1;
        }
        if (start < 0) {
            start = this.length + start;
        }
        let walker = this.head;
        for (let i = 0; !!walker && i < start; i++) {
            walker = walker.next;
        }
        const ret = [];
        for (let i = 0; !!walker && i < deleteCount; i++) {
            ret.push(walker.value);
            walker = this.removeNode(walker);
        }
        if (!walker) {
            walker = this.tail;
        }
        else if (walker !== this.tail) {
            walker = walker.prev;
        }
        for (const v of nodes) {
            walker = insertAfter(this, walker, v);
        }
        return ret;
    }
    reverse() {
        const head = this.head;
        const tail = this.tail;
        for (let walker = head; !!walker; walker = walker.prev) {
            const p = walker.prev;
            walker.prev = walker.next;
            walker.next = p;
        }
        this.head = tail;
        this.tail = head;
        return this;
    }
}
exports.Yallist = Yallist;
// insertAfter undefined means "make the node the new head of list"
function insertAfter(self, node, value) {
    const prev = node;
    const next = node ? node.next : self.head;
    const inserted = new Node(value, prev, next, self);
    if (inserted.next === undefined) {
        self.tail = inserted;
    }
    if (inserted.prev === undefined) {
        self.head = inserted;
    }
    self.length++;
    return inserted;
}
function push(self, item) {
    self.tail = new Node(item, self.tail, undefined, self);
    if (!self.head) {
        self.head = self.tail;
    }
    self.length++;
}
function unshift(self, item) {
    self.head = new Node(item, undefined, self.head, self);
    if (!self.tail) {
        self.tail = self.head;
    }
    self.length++;
}
class Node {
    list;
    next;
    prev;
    value;
    constructor(value, prev, next, list) {
        this.list = list;
        this.value = value;
        if (prev) {
            prev.next = this;
            this.prev = prev;
        }
        else {
            this.prev = undefined;
        }
        if (next) {
            next.prev = this;
            this.next = next;
        }
        else {
            this.next = undefined;
        }
    }
}
exports.Node = Node;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
export class Yallist {
    tail;
    head;
    length = 0;
    static create(list = []) {
        return new Yallist(list);
    }
    constructor(list = []) {
        for (const item of list) {
            this.push(item);
        }
    }
    *[Symbol.iterator]() {
        for (let walker = this.head; walker; walker = walker.next) {
            yield walker.value;
        }
    }
    removeNode(node) {
        if (node.list !== this) {
            throw new Error('removing node which does not belong to this list');
        }
        const next = node.next;
        const prev = node.prev;
        if (next) {
            next.prev = prev;
        }
        if (prev) {
            prev.next = next;
        }
        if (node === this.head) {
            this.head = next;
        }
        if (node === this.tail) {
            this.tail = prev;
        }
        this.length--;
        node.next = undefined;
        node.prev = undefined;
        node.list = undefined;
        return next;
    }
    unshiftNode(node) {
        if (node === this.head) {
            return;
        }
        if (node.list) {
            node.list.removeNode(node);
        }
        const head = this.head;
        node.list = this;
        node.next = head;
        if (head) {
            head.prev = node;
        }
        this.head = node;
        if (!this.tail) {
            this.tail = node;
        }
        this.length++;
    }
    pushNode(node) {
        if (node === this.tail) {
            return;
        }
        if (node.list) {
            node.list.removeNode(node);
        }
        const tail = this.tail;
        node.list = this;
        node.prev = tail;
        if (tail) {
            tail.next = node;
        }
        this.tail = node;
        if (!this.head) {
            this.head = node;
        }
        this.length++;
    }
    push(...args) {
        for (let i = 0, l = args.length; i < l; i++) {
            push(this, args[i]);
        }
        return this.length;
    }
    unshift(...args) {
        for (var i = 0, l = args.length; i < l; i++) {
            unshift(this, args[i]);
        }
        return this.length;
    }
    pop() {
        if (!this.tail) {
            return undefined;
        }
        const res = this.tail.value;
        const t = this.tail;
        this.tail = this.tail.prev;
        if (this.tail) {
            this.tail.next = undefined;
        }
        else {
            this.head = undefined;
        }
        t.list = undefined;
        this.length--;
        return res;
    }
    shift() {
        if (!this.head) {
            return undefined;
        }
        const res = this.head.value;
        const h = this.head;
        this.head = this.head.next;
        if (this.head) {
            this.head.prev = undefined;
        }
        else {
            this.tail = undefined;
        }
        h.list = undefined;
        this.length--;
        return res;
    }
    forEach(fn, thisp) {
        thisp = thisp || this;
        for (let walker = this.head, i = 0; !!walker; i++) {
            fn.call(thisp, walker.value, i, this);
            walker = walker.next;
        }
    }
    forEachReverse(fn, thisp) {
        thisp = thisp || this;
        for (let walker = this.tail, i = this.length - 1; !!walker; i--) {
            fn.call(thisp, walker.value, i, this);
            walker = walker.prev;
        }
    }
    get(n) {
        let i = 0;
        let walker = this.head;
        for (; !!walker && i < n; i++) {
            walker = walker.next;
        }
        if (i === n && !!walker) {
            return walker.value;
        }
    }
    getReverse(n) {
        let i = 0;
        let walker = this.tail;
        for (; !!walker && i < n; i++) {
            // abort out of the list early if we hit a cycle
            walker = walker.prev;
        }
        if (i === n && !!walker) {
            return walker.value;
        }
    }
    map(fn, thisp) {
        thisp = thisp || this;
        const res = new Yallist();
        for (let walker = this.head; !!walker;) {
            res.push(fn.call(thisp, walker.value, this));
            walker = walker.next;
        }
        return res;
    }
    mapReverse(fn, thisp) {
        thisp = thisp || this;
        var res = new Yallist();
        for (let walker = this.tail; !!walker;) {
            res.push(fn.call(thisp, walker.value, this));
            walker = walker.prev;
        }
        return res;
    }
    reduce(fn, initial) {
        let acc;
        let walker = this.head;
        if (arguments.length > 1) {
            acc = initial;
        }
        else if (this.head) {
            walker = this.head.next;
            acc = this.head.value;
        }
        else {
            throw new TypeError('Reduce of empty list with no initial value');
        }
        for (var i = 0; !!walker; i++) {
            acc = fn(acc, walker.value, i);
            walker = walker.next;
        }
        return acc;
    }
    reduceReverse(fn, initial) {
        let acc;
        let walker = this.tail;
        if (arguments.length > 1) {
            acc = initial;
        }
        else if (this.tail) {
            walker = this.tail.prev;
            acc = this.tail.value;
        }
        else {
            throw new TypeError('Reduce of empty list with no initial value');
        }
        for (let i = this.length - 1; !!walker; i--) {
            acc = fn(acc, walker.value, i);
            walker = walker.prev;
        }
        return acc;
    }
    toArray() {
        const arr = new Array(this.length);
        for (let i = 0, walker = this.head; !!walker; i++) {
            arr[i] = walker.value;
            walker = walker.next;
        }
        return arr;
    }
    toArrayReverse() {
        const arr = new Array(this.length);
        for (let i = 0, walker = this.tail; !!walker; i++) {
            arr[i] = walker.value;
            walker = walker.prev;
        }
        return arr;
    }
    slice(from = 0, to = this.length) {
        if (to < 0) {
            to += this.length;
        }
        if (from < 0) {
            from += this.length;
        }
        const ret = new Yallist();
        if (to < from || to < 0) {
            return ret;
        }
        if (from < 0) {
            from = 0;
        }
        if (to > this.length) {
            to = this.length;
        }
        let walker = this.head;
        let i = 0;
        for (i = 0; !!walker && i < from; i++) {
            walker = walker.next;
        }
        for (; !!walker && i < to; i++, walker = walker.next) {
            ret.push(walker.value);
        }
        return ret;
    }
    sliceReverse(from = 0, to = this.length) {
        if (to < 0) {
            to += this.length;
        }
        if (from < 0) {
            from += this.length;
        }
        const ret = new Yallist();
        if (to < from || to < 0) {
            return ret;
        }
        if (from < 0) {
            from = 0;
        }
        if (to > this.length) {
            to = this.length;
        }
        let i = this.length;
        let walker = this.tail;
        for (; !!walker && i > to; i--) {
            walker = walker.prev;
        }
        for (; !!walker && i > from; i--, walker = walker.prev) {
            ret.push(walker.value);
        }
        return ret;
    }
    splice(start, deleteCount = 0, ...nodes) {
        if (start > this.length) {
            start = this.length - 1;
        }
        if (start < 0) {
            start = this.length + start;
        }
        let walker = this.head;
        for (let i = 0; !!walker && i < start; i++) {
            walker = walker.next;
        }
        const ret = [];
        for (let i = 0; !!walker && i < deleteCount; i++) {
            ret.push(walker.value);
            walker = this.removeNode(walker);
        }
        if (!walker) {
            walker = this.tail;
        }
        else if (walker !== this.tail) {
            walker = walker.prev;
        }
        for (const v of nodes) {
            walker = insertAfter(this, walker, v);
        }
        return ret;
    }
    reverse() {
        const head = this.head;
        const tail = this.tail;
        for (let walker = head; !!walker; walker = walker.prev) {
            const p = walker.prev;
            walker.prev = walker.next;
            walker.next = p;
        }
        this.head = tail;
        this.tail = head;
        return this;
    }
}
// insertAfter undefined means "make the node the new head of list"
function insertAfter(self, node, value) {
    const prev = node;
    const next = node ? node.next : self.head;
    const inserted = new Node(value, prev, next, self);
    if (inserted.next === undefined) {
        self.tail = inserted;
    }
    if (inserted.prev === undefined) {
        self.head = inserted;
    }
    self.length++;
    return inserted;
}
function push(self, item) {
    self.tail = new Node(item, self.tail, undefined, self);
    if (!self.head) {
        self.head = self.tail;
    }
    self.length++;
}
function unshift(self, item) {
    self.head = new Node(item, undefined, self.head, self);
    if (!self.tail) {
        self.tail = self.head;
    }
    self.length++;
}
export class Node {
    list;
    next;
    prev;
    value;
    constructor(value, prev, next, list) {
        this.list = list;
        this.value = value;
        if (prev) {
            prev.next = this;
            this.prev = prev;
        }
        else {
            this.prev = undefined;
        }
        if (next) {
            next.prev = this;
            this.next = next;
        }
        else {
            this.next = undefined;
        }
    }
}
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "name": "yallist",
  "version": "5.0.0",
  "description": "Yet Another Linked List",
  "files": [
    "dist"
  ],
  "devDependencies": {
    "prettier": "^3.2.5",
    "tap": "^18.7.2",
    "tshy": "^1.13.1",
    "typedoc": "^0.25.13"
  },
  "scripts": {
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "presnap": "npm run prepare",
    "test": "tap",
    "snap": "tap",
    "format": "prettier --write . --loglevel warn --ignore-path ../../.prettierignore --cache",
    "typedoc": "typedoc"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/yallist.git"
  },
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "BlueOak-1.0.0",
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "main": "./dist/commonjs/index.js",
  "types": "./dist/commonjs/index.d.ts",
  "type": "module",
  "prettier": {
    "semi": false,
    "printWidth": 70,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "engines": {
    "node": ">=18"
  }
}
{
  "name": "node-gyp",
  "description": "Node.js native addon build tool",
  "license": "MIT",
  "keywords": [
    "native",
    "addon",
    "module",
    "c",
    "c++",
    "bindings",
    "gyp"
  ],
  "version": "11.0.0",
  "installVersion": 11,
  "author": "Nathan Rajlich  (http://tootallnate.net)",
  "repository": {
    "type": "git",
    "url": "git://github.com/nodejs/node-gyp.git"
  },
  "preferGlobal": true,
  "bin": "./bin/node-gyp.js",
  "main": "./lib/node-gyp.js",
  "dependencies": {
    "env-paths": "^2.2.0",
    "exponential-backoff": "^3.1.1",
    "glob": "^10.3.10",
    "graceful-fs": "^4.2.6",
    "make-fetch-happen": "^14.0.3",
    "nopt": "^8.0.0",
    "proc-log": "^5.0.0",
    "semver": "^7.3.5",
    "tar": "^7.4.3",
    "which": "^5.0.0"
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "devDependencies": {
    "bindings": "^1.5.0",
    "cross-env": "^7.0.3",
    "eslint": "^9.16.0",
    "mocha": "^11.0.1",
    "nan": "^2.14.2",
    "neostandard": "^0.11.9",
    "require-inject": "^1.4.4"
  },
  "scripts": {
    "lint": "eslint \"*/*.js\" \"test/**/*.js\" \".github/**/*.js\"",
    "test": "cross-env NODE_GYP_NULL_LOGGER=true mocha --timeout 15000 test/test-download.js test/test-*"
  }
}
{
    "packages": {
        ".": {
            "include-component-in-tag": false,
            "release-type": "node",
            "changelog-sections": [
                { "type": "feat", "section": "Features", "hidden": false },
                { "type": "fix", "section": "Bug Fixes", "hidden": false },
                { "type": "bin", "section": "Core", "hidden": false },
                { "type": "gyp", "section": "Core", "hidden": false },
                { "type": "lib", "section": "Core", "hidden": false },
                { "type": "src", "section": "Core", "hidden": false },
                { "type": "test", "section": "Tests", "hidden": false },
                { "type": "build", "section": "Core", "hidden": false },
                { "type": "clean", "section": "Core", "hidden": false },
                { "type": "configure", "section": "Core", "hidden": false },
                { "type": "install", "section": "Core", "hidden": false },
                { "type": "list", "section": "Core", "hidden": false },
                { "type": "rebuild", "section": "Core", "hidden": false },
                { "type": "remove", "section": "Core", "hidden": false },
                { "type": "deps", "section": "Core", "hidden": false },
                { "type": "python", "section": "Core", "hidden": false },
                { "type": "lin", "section": "Core", "hidden": false },
                { "type": "linux", "section": "Core", "hidden": false },
                { "type": "mac", "section": "Core", "hidden": false },
                { "type": "macos", "section": "Core", "hidden": false },
                { "type": "win", "section": "Core", "hidden": false },
                { "type": "windows", "section": "Core", "hidden": false },
                { "type": "zos", "section": "Core", "hidden": false },
                { "type": "doc", "section": "Doc", "hidden": false },
                { "type": "docs", "section": "Doc", "hidden": false },
                { "type": "readme", "section": "Doc", "hidden": false },
                { "type": "chore", "section": "Miscellaneous", "hidden": false },
                { "type": "refactor", "section": "Miscellaneous", "hidden": false },
                { "type": "ci", "section": "Miscellaneous", "hidden": false },
                { "type": "meta", "section": "Miscellaneous", "hidden": false }
            ]
        }
    }
}
/*
 * When this file is linked to a DLL, it sets up a delay-load hook that
 * intervenes when the DLL is trying to load the host executable
 * dynamically. Instead of trying to locate the .exe file it'll just
 * return a handle to the process image.
 *
 * This allows compiled addons to work when the host executable is renamed.
 */

#ifdef _MSC_VER

#pragma managed(push, off)

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include 

#include 
#include 

static FARPROC WINAPI load_exe_hook(unsigned int event, DelayLoadInfo* info) {
  HMODULE m;
  if (event != dliNotePreLoadLibrary)
    return NULL;

  if (_stricmp(info->szDll, HOST_BINARY) != 0)
    return NULL;

  m = GetModuleHandle(NULL);
  return (FARPROC) m;
}

decltype(__pfnDliNotifyHook2) __pfnDliNotifyHook2 = load_exe_hook;

#pragma managed(pop)

#endif
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
If you want to write an option parser, and have it be good, there are
two ways to do it.  The Right Way, and the Wrong Way.

The Wrong Way is to sit down and write an option parser.  We've all done
that.

The Right Way is to write some complex configurable program with so many
options that you hit the limit of your frustration just trying to
manage them all, and defer it with duct-tape solutions until you see
exactly to the core of the problem, and finally snap and write an
awesome option parser.

If you want to write an option parser, don't write an option parser.
Write a package manager, or a source control system, or a service
restarter, or an operating system.  You probably won't end up with a
good one of those, but if you don't give up, and you are relentless and
diligent enough in your procrastination, you may just end up with a very
nice option parser.

## USAGE

```javascript
// my-program.js
var nopt = require("nopt")
  , Stream = require("stream").Stream
  , path = require("path")
  , knownOpts = { "foo" : [String, null]
                , "bar" : [Stream, Number]
                , "baz" : path
                , "bloo" : [ "big", "medium", "small" ]
                , "flag" : Boolean
                , "pick" : Boolean
                , "many1" : [String, Array]
                , "many2" : [path, Array]
                }
  , shortHands = { "foofoo" : ["--foo", "Mr. Foo"]
                 , "b7" : ["--bar", "7"]
                 , "m" : ["--bloo", "medium"]
                 , "p" : ["--pick"]
                 , "f" : ["--flag"]
                 }
             // everything is optional.
             // knownOpts and shorthands default to {}
             // arg list defaults to process.argv
             // slice defaults to 2
  , parsed = nopt(knownOpts, shortHands, process.argv, 2)
console.log(parsed)
```

This would give you support for any of the following:

```console
$ node my-program.js --foo "blerp" --no-flag
{ "foo" : "blerp", "flag" : false }

$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag
{ bar: 7, foo: "Mr. Hand", flag: true }

$ node my-program.js --foo "blerp" -f -----p
{ foo: "blerp", flag: true, pick: true }

$ node my-program.js -fp --foofoo
{ foo: "Mr. Foo", flag: true, pick: true }

$ node my-program.js --foofoo -- -fp  # -- stops the flag parsing.
{ foo: "Mr. Foo", argv: { remain: ["-fp"] } }

$ node my-program.js --blatzk -fp # unknown opts are ok.
{ blatzk: true, flag: true, pick: true }

$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value
{ blatzk: 1000, flag: true, pick: true }

$ node my-program.js --no-blatzk -fp # unless they start with "no-"
{ blatzk: false, flag: true, pick: true }

$ node my-program.js --baz b/a/z # known paths are resolved.
{ baz: "/Users/isaacs/b/a/z" }

# if Array is one of the types, then it can take many
# values, and will always be an array.  The other types provided
# specify what types are allowed in the list.

$ node my-program.js --many1 5 --many1 null --many1 foo
{ many1: ["5", "null", "foo"] }

$ node my-program.js --many2 foo --many2 bar
{ many2: ["/path/to/foo", "path/to/bar"] }
```

Read the tests at the bottom of `lib/nopt.js` for more examples of
what this puppy can do.

## Types

The following types are supported, and defined on `nopt.typeDefs`

* String: A normal string.  No parsing is done.
* path: A file system path.  Gets resolved against cwd if not absolute.
* url: A url.  If it doesn't parse, it isn't accepted.
* Number: Must be numeric.
* Date: Must parse as a date. If it does, and `Date` is one of the options,
  then it will return a Date object, not a string.
* Boolean: Must be either `true` or `false`.  If an option is a boolean,
  then it does not need a value, and its presence will imply `true` as
  the value.  To negate boolean flags, do `--no-whatever` or `--whatever
  false`
* NaN: Means that the option is strictly not allowed.  Any value will
  fail.
* Stream: An object matching the "Stream" class in node.  Valuable
  for use when validating programmatically.  (npm uses this to let you
  supply any WriteStream on the `outfd` and `logfd` config options.)
* Array: If `Array` is specified as one of the types, then the value
  will be parsed as a list of options.  This means that multiple values
  can be specified, and that the value will always be an array.

If a type is an array of values not on this list, then those are
considered valid values.  For instance, in the example above, the
`--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`,
and any other value will be rejected.

When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be
interpreted as their JavaScript equivalents.

You can also mix types and values, or multiple types, in a list.  For
instance `{ blah: [Number, null] }` would allow a value to be set to
either a Number or null.  When types are ordered, this implies a
preference, and the first type that can be used to properly interpret
the value will be used.

To define a new type, add it to `nopt.typeDefs`.  Each item in that
hash is an object with a `type` member and a `validate` method.  The
`type` member is an object that matches what goes in the type list.  The
`validate` method is a function that gets called with `validate(data,
key, val)`.  Validate methods should assign `data[key]` to the valid
value of `val` if it can be handled properly, or return boolean
`false` if it cannot.

You can also call `nopt.clean(data, types, typeDefs)` to clean up a
config object and remove its invalid properties.

## Error Handling

By default, nopt outputs a warning to standard error when invalid values for
known options are found.  You can change this behavior by assigning a method
to `nopt.invalidHandler`.  This method will be called with
the offending `nopt.invalidHandler(key, val, types)`.

If no `nopt.invalidHandler` is assigned, then it will console.error
its whining.  If it is assigned to boolean `false` then the warning is
suppressed.

## Abbreviations

Yes, they are supported.  If you define options like this:

```javascript
{ "foolhardyelephants" : Boolean
, "pileofmonkeys" : Boolean }
```

Then this will work:

```bash
node program.js --foolhar --pil
node program.js --no-f --pileofmon
# etc.
```

## Shorthands

Shorthands are a hash of shorter option names to a snippet of args that
they expand to.

If multiple one-character shorthands are all combined, and the
combination does not unambiguously match any other option or shorthand,
then they will be broken up into their constituent parts.  For example:

```json
{ "s" : ["--loglevel", "silent"]
, "g" : "--global"
, "f" : "--force"
, "p" : "--parseable"
, "l" : "--long"
}
```

```bash
npm ls -sgflp
# just like doing this:
npm ls --loglevel silent --global --force --long --parseable
```

## The Rest of the args

The config object returned by nopt is given a special member called
`argv`, which is an object with the following fields:

* `remain`: The remaining args after all the parsing has occurred.
* `original`: The args as they originally appeared.
* `cooked`: The args after flags and shorthands are expanded.

## Slicing

Node programs are called with more or less the exact argv as it appears
in C land, after the v8 and node-specific options have been plucked off.
As such, `argv[0]` is always `node` and `argv[1]` is always the
JavaScript program being run.

That's usually not very useful to you.  So they're sliced off by
default.  If you want them, then you can pass in `0` as the last
argument, or any other number that you'd like to slice off the start of
the list.
#!/usr/bin/env node
const nopt = require('../lib/nopt')
const path = require('path')
console.log('parsed', nopt({
  num: Number,
  bool: Boolean,
  help: Boolean,
  list: Array,
  'num-list': [Number, Array],
  'str-list': [String, Array],
  'bool-list': [Boolean, Array],
  str: String,
  clear: Boolean,
  config: Boolean,
  length: Number,
  file: path,
}, {
  s: ['--str', 'astring'],
  b: ['--bool'],
  nb: ['--no-bool'],
  tft: ['--bool-list', '--no-bool-list', '--bool-list', 'true'],
  '?': ['--help'],
  h: ['--help'],
  H: ['--help'],
  n: ['--num', '125'],
  c: ['--config'],
  l: ['--length'],
  f: ['--file'],
}, process.argv, 2))
/* istanbul ignore next */
module.exports = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG
  // eslint-disable-next-line no-console
  ? (...a) => console.error(...a)
  : () => {}
const abbrev = require('abbrev')
const debug = require('./debug')
const defaultTypeDefs = require('./type-defs')

const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k)

const getType = (k, { types, dynamicTypes }) => {
  let hasType = hasOwn(types, k)
  let type = types[k]
  if (!hasType && typeof dynamicTypes === 'function') {
    const matchedType = dynamicTypes(k)
    if (matchedType !== undefined) {
      type = matchedType
      hasType = true
    }
  }
  return [hasType, type]
}

const isTypeDef = (type, def) => def && type === def
const hasTypeDef = (type, def) => def && type.indexOf(def) !== -1
const doesNotHaveTypeDef = (type, def) => def && !hasTypeDef(type, def)

function nopt (args, {
  types,
  shorthands,
  typeDefs,
  invalidHandler,
  typeDefault,
  dynamicTypes,
} = {}) {
  debug(types, shorthands, args, typeDefs)

  const data = {}
  const argv = {
    remain: [],
    cooked: args,
    original: args.slice(0),
  }

  parse(args, data, argv.remain, { typeDefs, types, dynamicTypes, shorthands })

  // now data is full
  clean(data, { types, dynamicTypes, typeDefs, invalidHandler, typeDefault })
  data.argv = argv

  Object.defineProperty(data.argv, 'toString', {
    value: function () {
      return this.original.map(JSON.stringify).join(' ')
    },
    enumerable: false,
  })

  return data
}

function clean (data, {
  types = {},
  typeDefs = {},
  dynamicTypes,
  invalidHandler,
  typeDefault,
} = {}) {
  const StringType = typeDefs.String?.type
  const NumberType = typeDefs.Number?.type
  const ArrayType = typeDefs.Array?.type
  const BooleanType = typeDefs.Boolean?.type
  const DateType = typeDefs.Date?.type

  const hasTypeDefault = typeof typeDefault !== 'undefined'
  if (!hasTypeDefault) {
    typeDefault = [false, true, null]
    if (StringType) {
      typeDefault.push(StringType)
    }
    if (ArrayType) {
      typeDefault.push(ArrayType)
    }
  }

  const remove = {}

  Object.keys(data).forEach((k) => {
    if (k === 'argv') {
      return
    }
    let val = data[k]
    debug('val=%j', val)
    const isArray = Array.isArray(val)
    let [hasType, rawType] = getType(k, { types, dynamicTypes })
    let type = rawType
    if (!isArray) {
      val = [val]
    }
    if (!type) {
      type = typeDefault
    }
    if (isTypeDef(type, ArrayType)) {
      type = typeDefault.concat(ArrayType)
    }
    if (!Array.isArray(type)) {
      type = [type]
    }

    debug('val=%j', val)
    debug('types=', type)
    val = val.map((v) => {
      // if it's an unknown value, then parse false/true/null/numbers/dates
      if (typeof v === 'string') {
        debug('string %j', v)
        v = v.trim()
        if ((v === 'null' && ~type.indexOf(null))
            || (v === 'true' &&
               (~type.indexOf(true) || hasTypeDef(type, BooleanType)))
            || (v === 'false' &&
               (~type.indexOf(false) || hasTypeDef(type, BooleanType)))) {
          v = JSON.parse(v)
          debug('jsonable %j', v)
        } else if (hasTypeDef(type, NumberType) && !isNaN(v)) {
          debug('convert to number', v)
          v = +v
        } else if (hasTypeDef(type, DateType) && !isNaN(Date.parse(v))) {
          debug('convert to date', v)
          v = new Date(v)
        }
      }

      if (!hasType) {
        if (!hasTypeDefault) {
          return v
        }
        // if the default type has been passed in then we want to validate the
        // unknown data key instead of bailing out earlier. we also set the raw
        // type which is passed to the invalid handler so that it can be
        // determined if during validation if it is unknown vs invalid
        rawType = typeDefault
      }

      // allow `--no-blah` to set 'blah' to null if null is allowed
      if (v === false && ~type.indexOf(null) &&
          !(~type.indexOf(false) || hasTypeDef(type, BooleanType))) {
        v = null
      }

      const d = {}
      d[k] = v
      debug('prevalidated val', d, v, rawType)
      if (!validate(d, k, v, rawType, { typeDefs })) {
        if (invalidHandler) {
          invalidHandler(k, v, rawType, data)
        } else if (invalidHandler !== false) {
          debug('invalid: ' + k + '=' + v, rawType)
        }
        return remove
      }
      debug('validated v', d, v, rawType)
      return d[k]
    }).filter((v) => v !== remove)

    // if we allow Array specifically, then an empty array is how we
    // express 'no value here', not null.  Allow it.
    if (!val.length && doesNotHaveTypeDef(type, ArrayType)) {
      debug('VAL HAS NO LENGTH, DELETE IT', val, k, type.indexOf(ArrayType))
      delete data[k]
    } else if (isArray) {
      debug(isArray, data[k], val)
      data[k] = val
    } else {
      data[k] = val[0]
    }

    debug('k=%s val=%j', k, val, data[k])
  })
}

function validate (data, k, val, type, { typeDefs } = {}) {
  const ArrayType = typeDefs?.Array?.type
  // arrays are lists of types.
  if (Array.isArray(type)) {
    for (let i = 0, l = type.length; i < l; i++) {
      if (isTypeDef(type[i], ArrayType)) {
        continue
      }
      if (validate(data, k, val, type[i], { typeDefs })) {
        return true
      }
    }
    delete data[k]
    return false
  }

  // an array of anything?
  if (isTypeDef(type, ArrayType)) {
    return true
  }

  // Original comment:
  // NaN is poisonous.  Means that something is not allowed.
  // New comment: Changing this to an isNaN check breaks a lot of tests.
  // Something is being assumed here that is not actually what happens in
  // practice.  Fixing it is outside the scope of getting linting to pass in
  // this repo. Leaving as-is for now.
  /* eslint-disable-next-line no-self-compare */
  if (type !== type) {
    debug('Poison NaN', k, val, type)
    delete data[k]
    return false
  }

  // explicit list of values
  if (val === type) {
    debug('Explicitly allowed %j', val)
    data[k] = val
    return true
  }

  // now go through the list of typeDefs, validate against each one.
  let ok = false
  const types = Object.keys(typeDefs)
  for (let i = 0, l = types.length; i < l; i++) {
    debug('test type %j %j %j', k, val, types[i])
    const t = typeDefs[types[i]]
    if (t && (
      (type && type.name && t.type && t.type.name) ?
        (type.name === t.type.name) :
        (type === t.type)
    )) {
      const d = {}
      ok = t.validate(d, k, val) !== false
      val = d[k]
      if (ok) {
        data[k] = val
        break
      }
    }
  }
  debug('OK? %j (%j %j %j)', ok, k, val, types[types.length - 1])

  if (!ok) {
    delete data[k]
  }
  return ok
}

function parse (args, data, remain, {
  types = {},
  typeDefs = {},
  shorthands = {},
  dynamicTypes,
} = {}) {
  const StringType = typeDefs.String?.type
  const NumberType = typeDefs.Number?.type
  const ArrayType = typeDefs.Array?.type
  const BooleanType = typeDefs.Boolean?.type

  debug('parse', args, data, remain)

  const abbrevs = abbrev(Object.keys(types))
  debug('abbrevs=%j', abbrevs)
  const shortAbbr = abbrev(Object.keys(shorthands))

  for (let i = 0; i < args.length; i++) {
    let arg = args[i]
    debug('arg', arg)

    if (arg.match(/^-{2,}$/)) {
      // done with keys.
      // the rest are args.
      remain.push.apply(remain, args.slice(i + 1))
      args[i] = '--'
      break
    }
    let hadEq = false
    if (arg.charAt(0) === '-' && arg.length > 1) {
      const at = arg.indexOf('=')
      if (at > -1) {
        hadEq = true
        const v = arg.slice(at + 1)
        arg = arg.slice(0, at)
        args.splice(i, 1, arg, v)
      }

      // see if it's a shorthand
      // if so, splice and back up to re-parse it.
      const shRes = resolveShort(arg, shortAbbr, abbrevs, { shorthands })
      debug('arg=%j shRes=%j', arg, shRes)
      if (shRes) {
        args.splice.apply(args, [i, 1].concat(shRes))
        if (arg !== shRes[0]) {
          i--
          continue
        }
      }
      arg = arg.replace(/^-+/, '')
      let no = null
      while (arg.toLowerCase().indexOf('no-') === 0) {
        no = !no
        arg = arg.slice(3)
      }

      if (abbrevs[arg]) {
        arg = abbrevs[arg]
      }

      let [hasType, argType] = getType(arg, { types, dynamicTypes })
      let isTypeArray = Array.isArray(argType)
      if (isTypeArray && argType.length === 1) {
        isTypeArray = false
        argType = argType[0]
      }

      let isArray = isTypeDef(argType, ArrayType) ||
        isTypeArray && hasTypeDef(argType, ArrayType)

      // allow unknown things to be arrays if specified multiple times.
      if (!hasType && hasOwn(data, arg)) {
        if (!Array.isArray(data[arg])) {
          data[arg] = [data[arg]]
        }
        isArray = true
      }

      let val
      let la = args[i + 1]

      const isBool = typeof no === 'boolean' ||
        isTypeDef(argType, BooleanType) ||
        isTypeArray && hasTypeDef(argType, BooleanType) ||
        (typeof argType === 'undefined' && !hadEq) ||
        (la === 'false' &&
         (argType === null ||
          isTypeArray && ~argType.indexOf(null)))

      if (isBool) {
        // just set and move along
        val = !no
        // however, also support --bool true or --bool false
        if (la === 'true' || la === 'false') {
          val = JSON.parse(la)
          la = null
          if (no) {
            val = !val
          }
          i++
        }

        // also support "foo":[Boolean, "bar"] and "--foo bar"
        if (isTypeArray && la) {
          if (~argType.indexOf(la)) {
            // an explicit type
            val = la
            i++
          } else if (la === 'null' && ~argType.indexOf(null)) {
            // null allowed
            val = null
            i++
          } else if (!la.match(/^-{2,}[^-]/) &&
                      !isNaN(la) &&
                      hasTypeDef(argType, NumberType)) {
            // number
            val = +la
            i++
          } else if (!la.match(/^-[^-]/) && hasTypeDef(argType, StringType)) {
            // string
            val = la
            i++
          }
        }

        if (isArray) {
          (data[arg] = data[arg] || []).push(val)
        } else {
          data[arg] = val
        }

        continue
      }

      if (isTypeDef(argType, StringType)) {
        if (la === undefined) {
          la = ''
        } else if (la.match(/^-{1,2}[^-]+/)) {
          la = ''
          i--
        }
      }

      if (la && la.match(/^-{2,}$/)) {
        la = undefined
        i--
      }

      val = la === undefined ? true : la
      if (isArray) {
        (data[arg] = data[arg] || []).push(val)
      } else {
        data[arg] = val
      }

      i++
      continue
    }
    remain.push(arg)
  }
}

const SINGLES = Symbol('singles')
const singleCharacters = (arg, shorthands) => {
  let singles = shorthands[SINGLES]
  if (!singles) {
    singles = Object.keys(shorthands).filter((s) => s.length === 1).reduce((l, r) => {
      l[r] = true
      return l
    }, {})
    shorthands[SINGLES] = singles
    debug('shorthand singles', singles)
  }
  const chrs = arg.split('').filter((c) => singles[c])
  return chrs.join('') === arg ? chrs : null
}

function resolveShort (arg, ...rest) {
  const { types = {}, shorthands = {} } = rest.length ? rest.pop() : {}
  const shortAbbr = rest[0] ?? abbrev(Object.keys(shorthands))
  const abbrevs = rest[1] ?? abbrev(Object.keys(types))

  // handle single-char shorthands glommed together, like
  // npm ls -glp, but only if there is one dash, and only if
  // all of the chars are single-char shorthands, and it's
  // not a match to some other abbrev.
  arg = arg.replace(/^-+/, '')

  // if it's an exact known option, then don't go any further
  if (abbrevs[arg] === arg) {
    return null
  }

  // if it's an exact known shortopt, same deal
  if (shorthands[arg]) {
    // make it an array, if it's a list of words
    if (shorthands[arg] && !Array.isArray(shorthands[arg])) {
      shorthands[arg] = shorthands[arg].split(/\s+/)
    }

    return shorthands[arg]
  }

  // first check to see if this arg is a set of single-char shorthands
  const chrs = singleCharacters(arg, shorthands)
  if (chrs) {
    return chrs.map((c) => shorthands[c]).reduce((l, r) => l.concat(r), [])
  }

  // if it's an arg abbrev, and not a literal shorthand, then prefer the arg
  if (abbrevs[arg] && !shorthands[arg]) {
    return null
  }

  // if it's an abbr for a shorthand, then use that
  if (shortAbbr[arg]) {
    arg = shortAbbr[arg]
  }

  // make it an array, if it's a list of words
  if (shorthands[arg] && !Array.isArray(shorthands[arg])) {
    shorthands[arg] = shorthands[arg].split(/\s+/)
  }

  return shorthands[arg]
}

module.exports = {
  nopt,
  clean,
  parse,
  validate,
  resolveShort,
  typeDefs: defaultTypeDefs,
}
const lib = require('./nopt-lib')
const defaultTypeDefs = require('./type-defs')

// This is the version of nopt's API that requires setting typeDefs and invalidHandler
// on the required `nopt` object since it is a singleton. To not do a breaking change
// an API that requires all options be passed in is located in `nopt-lib.js` and
// exported here as lib.
// TODO(breaking): make API only work in non-singleton mode

module.exports = exports = nopt
exports.clean = clean
exports.typeDefs = defaultTypeDefs
exports.lib = lib

function nopt (types, shorthands, args = process.argv, slice = 2) {
  return lib.nopt(args.slice(slice), {
    types: types || {},
    shorthands: shorthands || {},
    typeDefs: exports.typeDefs,
    invalidHandler: exports.invalidHandler,
  })
}

function clean (data, types, typeDefs = exports.typeDefs) {
  return lib.clean(data, {
    types: types || {},
    typeDefs,
    invalidHandler: exports.invalidHandler,
  })
}
const url = require('url')
const path = require('path')
const Stream = require('stream').Stream
const os = require('os')
const debug = require('./debug')

function validateString (data, k, val) {
  data[k] = String(val)
}

function validatePath (data, k, val) {
  if (val === true) {
    return false
  }
  if (val === null) {
    return true
  }

  val = String(val)

  const isWin = process.platform === 'win32'
  const homePattern = isWin ? /^~(\/|\\)/ : /^~\//
  const home = os.homedir()

  if (home && val.match(homePattern)) {
    data[k] = path.resolve(home, val.slice(2))
  } else {
    data[k] = path.resolve(val)
  }
  return true
}

function validateNumber (data, k, val) {
  debug('validate Number %j %j %j', k, val, isNaN(val))
  if (isNaN(val)) {
    return false
  }
  data[k] = +val
}

function validateDate (data, k, val) {
  const s = Date.parse(val)
  debug('validate Date %j %j %j', k, val, s)
  if (isNaN(s)) {
    return false
  }
  data[k] = new Date(val)
}

function validateBoolean (data, k, val) {
  if (typeof val === 'string') {
    if (!isNaN(val)) {
      val = !!(+val)
    } else if (val === 'null' || val === 'false') {
      val = false
    } else {
      val = true
    }
  } else {
    val = !!val
  }
  data[k] = val
}

function validateUrl (data, k, val) {
  // Changing this would be a breaking change in the npm cli
  /* eslint-disable-next-line node/no-deprecated-api */
  val = url.parse(String(val))
  if (!val.host) {
    return false
  }
  data[k] = val.href
}

function validateStream (data, k, val) {
  if (!(val instanceof Stream)) {
    return false
  }
  data[k] = val
}

module.exports = {
  String: { type: String, validate: validateString },
  Boolean: { type: Boolean, validate: validateBoolean },
  url: { type: url, validate: validateUrl },
  Number: { type: Number, validate: validateNumber },
  path: { type: path, validate: validatePath },
  Stream: { type: Stream, validate: validateStream },
  Date: { type: Date, validate: validateDate },
  Array: { type: Array },
}
This software is dual-licensed under the ISC and MIT licenses.
You may use this software under EITHER of the following licenses.

----------

The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

----------

Copyright Isaac Z. Schlueter and Contributors
All rights reserved.

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.
module.exports = abbrev

function abbrev (...args) {
  let list = args.length === 1 || Array.isArray(args[0]) ? args[0] : args

  for (let i = 0, l = list.length; i < l; i++) {
    list[i] = typeof list[i] === 'string' ? list[i] : String(list[i])
  }

  // sort them lexicographically, so that they're next to their nearest kin
  list = list.sort(lexSort)

  // walk through each, seeing how much it has in common with the next and previous
  const abbrevs = {}
  let prev = ''
  for (let ii = 0, ll = list.length; ii < ll; ii++) {
    const current = list[ii]
    const next = list[ii + 1] || ''
    let nextMatches = true
    let prevMatches = true
    if (current === next) {
      continue
    }
    let j = 0
    const cl = current.length
    for (; j < cl; j++) {
      const curChar = current.charAt(j)
      nextMatches = nextMatches && curChar === next.charAt(j)
      prevMatches = prevMatches && curChar === prev.charAt(j)
      if (!nextMatches && !prevMatches) {
        j++
        break
      }
    }
    prev = current
    if (j === cl) {
      abbrevs[current] = current
      continue
    }
    for (let a = current.slice(0, j); j <= cl; j++) {
      abbrevs[a] = current
      a += current.charAt(j)
    }
  }
  return abbrevs
}

function lexSort (a, b) {
  return a === b ? 0 : a > b ? 1 : -1
}
{
  "name": "abbrev",
  "version": "2.0.0",
  "description": "Like ruby's abbrev module, but in js",
  "author": "GitHub Inc.",
  "main": "lib/index.js",
  "scripts": {
    "test": "tap",
    "lint": "eslint \"**/*.js\"",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run lint -- --fix",
    "snap": "tap",
    "posttest": "npm run lint"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/npm/abbrev-js.git"
  },
  "license": "ISC",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.8.0",
    "tap": "^16.3.0"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.8.0"
  }
}
{
  "name": "nopt",
  "version": "8.0.0",
  "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.",
  "author": "GitHub Inc.",
  "main": "lib/nopt.js",
  "scripts": {
    "test": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "snap": "tap",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/nopt.git"
  },
  "bin": {
    "nopt": "bin/nopt.js"
  },
  "license": "ISC",
  "dependencies": {
    "abbrev": "^2.0.0"
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.3.0"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "windowsCI": false,
    "version": "4.23.3",
    "publish": true
  }
}
This package contains code originally written by Isaac Z. Schlueter.
Used with permission.

Copyright (c) Meryn Stol ("Author")
All rights reserved.

The BSD License

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. 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.
module.exports = extractDescription

// Extracts description from contents of a readme file in markdown format
function extractDescription (d) {
  if (!d) {
    return
  }
  if (d === 'ERROR: No README data found!') {
    return
  }
  // the first block of text before the first heading
  // that isn't the first line heading
  d = d.trim().split('\n')
  let s = 0
  while (d[s] && d[s].trim().match(/^(#|$)/)) {
    s++
  }
  const l = d.length
  let e = s + 1
  while (e < l && d[e].trim()) {
    e++
  }
  return d.slice(s, e).join(' ').trim()
}
var isValidSemver = require('semver/functions/valid')
var cleanSemver = require('semver/functions/clean')
var validateLicense = require('validate-npm-package-license')
var hostedGitInfo = require('hosted-git-info')
var moduleBuiltin = require('node:module')
var depTypes = ['dependencies', 'devDependencies', 'optionalDependencies']
var extractDescription = require('./extract_description')
var url = require('url')
var typos = require('./typos.json')

var isEmail = str => str.includes('@') && (str.indexOf('@') < str.lastIndexOf('.'))

module.exports = {
  // default warning function
  warn: function () {},

  fixRepositoryField: function (data) {
    if (data.repositories) {
      this.warn('repositories')
      data.repository = data.repositories[0]
    }
    if (!data.repository) {
      return this.warn('missingRepository')
    }
    if (typeof data.repository === 'string') {
      data.repository = {
        type: 'git',
        url: data.repository,
      }
    }
    var r = data.repository.url || ''
    if (r) {
      var hosted = hostedGitInfo.fromUrl(r)
      if (hosted) {
        r = data.repository.url
          = hosted.getDefaultRepresentation() === 'shortcut' ? hosted.https() : hosted.toString()
      }
    }

    if (r.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)) {
      this.warn('brokenGitUrl', r)
    }
  },

  fixTypos: function (data) {
    Object.keys(typos.topLevel).forEach(function (d) {
      if (Object.prototype.hasOwnProperty.call(data, d)) {
        this.warn('typo', d, typos.topLevel[d])
      }
    }, this)
  },

  fixScriptsField: function (data) {
    if (!data.scripts) {
      return
    }
    if (typeof data.scripts !== 'object') {
      this.warn('nonObjectScripts')
      delete data.scripts
      return
    }
    Object.keys(data.scripts).forEach(function (k) {
      if (typeof data.scripts[k] !== 'string') {
        this.warn('nonStringScript')
        delete data.scripts[k]
      } else if (typos.script[k] && !data.scripts[typos.script[k]]) {
        this.warn('typo', k, typos.script[k], 'scripts')
      }
    }, this)
  },

  fixFilesField: function (data) {
    var files = data.files
    if (files && !Array.isArray(files)) {
      this.warn('nonArrayFiles')
      delete data.files
    } else if (data.files) {
      data.files = data.files.filter(function (file) {
        if (!file || typeof file !== 'string') {
          this.warn('invalidFilename', file)
          return false
        } else {
          return true
        }
      }, this)
    }
  },

  fixBinField: function (data) {
    if (!data.bin) {
      return
    }
    if (typeof data.bin === 'string') {
      var b = {}
      var match
      if (match = data.name.match(/^@[^/]+[/](.*)$/)) {
        b[match[1]] = data.bin
      } else {
        b[data.name] = data.bin
      }
      data.bin = b
    }
  },

  fixManField: function (data) {
    if (!data.man) {
      return
    }
    if (typeof data.man === 'string') {
      data.man = [data.man]
    }
  },
  fixBundleDependenciesField: function (data) {
    var bdd = 'bundledDependencies'
    var bd = 'bundleDependencies'
    if (data[bdd] && !data[bd]) {
      data[bd] = data[bdd]
      delete data[bdd]
    }
    if (data[bd] && !Array.isArray(data[bd])) {
      this.warn('nonArrayBundleDependencies')
      delete data[bd]
    } else if (data[bd]) {
      data[bd] = data[bd].filter(function (filtered) {
        if (!filtered || typeof filtered !== 'string') {
          this.warn('nonStringBundleDependency', filtered)
          return false
        } else {
          if (!data.dependencies) {
            data.dependencies = {}
          }
          if (!Object.prototype.hasOwnProperty.call(data.dependencies, filtered)) {
            this.warn('nonDependencyBundleDependency', filtered)
            data.dependencies[filtered] = '*'
          }
          return true
        }
      }, this)
    }
  },

  fixDependencies: function (data) {
    objectifyDeps(data, this.warn)
    addOptionalDepsToDeps(data, this.warn)
    this.fixBundleDependenciesField(data)

    ;['dependencies', 'devDependencies'].forEach(function (deps) {
      if (!(deps in data)) {
        return
      }
      if (!data[deps] || typeof data[deps] !== 'object') {
        this.warn('nonObjectDependencies', deps)
        delete data[deps]
        return
      }
      Object.keys(data[deps]).forEach(function (d) {
        var r = data[deps][d]
        if (typeof r !== 'string') {
          this.warn('nonStringDependency', d, JSON.stringify(r))
          delete data[deps][d]
        }
        var hosted = hostedGitInfo.fromUrl(data[deps][d])
        if (hosted) {
          data[deps][d] = hosted.toString()
        }
      }, this)
    }, this)
  },

  fixModulesField: function (data) {
    if (data.modules) {
      this.warn('deprecatedModules')
      delete data.modules
    }
  },

  fixKeywordsField: function (data) {
    if (typeof data.keywords === 'string') {
      data.keywords = data.keywords.split(/,\s+/)
    }
    if (data.keywords && !Array.isArray(data.keywords)) {
      delete data.keywords
      this.warn('nonArrayKeywords')
    } else if (data.keywords) {
      data.keywords = data.keywords.filter(function (kw) {
        if (typeof kw !== 'string' || !kw) {
          this.warn('nonStringKeyword')
          return false
        } else {
          return true
        }
      }, this)
    }
  },

  fixVersionField: function (data, strict) {
    // allow "loose" semver 1.0 versions in non-strict mode
    // enforce strict semver 2.0 compliance in strict mode
    var loose = !strict
    if (!data.version) {
      data.version = ''
      return true
    }
    if (!isValidSemver(data.version, loose)) {
      throw new Error('Invalid version: "' + data.version + '"')
    }
    data.version = cleanSemver(data.version, loose)
    return true
  },

  fixPeople: function (data) {
    modifyPeople(data, unParsePerson)
    modifyPeople(data, parsePerson)
  },

  fixNameField: function (data, options) {
    if (typeof options === 'boolean') {
      options = { strict: options }
    } else if (typeof options === 'undefined') {
      options = {}
    }
    var strict = options.strict
    if (!data.name && !strict) {
      data.name = ''
      return
    }
    if (typeof data.name !== 'string') {
      throw new Error('name field must be a string.')
    }
    if (!strict) {
      data.name = data.name.trim()
    }
    ensureValidName(data.name, strict, options.allowLegacyCase)
    if (moduleBuiltin.builtinModules.includes(data.name)) {
      this.warn('conflictingName', data.name)
    }
  },

  fixDescriptionField: function (data) {
    if (data.description && typeof data.description !== 'string') {
      this.warn('nonStringDescription')
      delete data.description
    }
    if (data.readme && !data.description) {
      data.description = extractDescription(data.readme)
    }
    if (data.description === undefined) {
      delete data.description
    }
    if (!data.description) {
      this.warn('missingDescription')
    }
  },

  fixReadmeField: function (data) {
    if (!data.readme) {
      this.warn('missingReadme')
      data.readme = 'ERROR: No README data found!'
    }
  },

  fixBugsField: function (data) {
    if (!data.bugs && data.repository && data.repository.url) {
      var hosted = hostedGitInfo.fromUrl(data.repository.url)
      if (hosted && hosted.bugs()) {
        data.bugs = { url: hosted.bugs() }
      }
    } else if (data.bugs) {
      if (typeof data.bugs === 'string') {
        if (isEmail(data.bugs)) {
          data.bugs = { email: data.bugs }
        /* eslint-disable-next-line node/no-deprecated-api */
        } else if (url.parse(data.bugs).protocol) {
          data.bugs = { url: data.bugs }
        } else {
          this.warn('nonEmailUrlBugsString')
        }
      } else {
        bugsTypos(data.bugs, this.warn)
        var oldBugs = data.bugs
        data.bugs = {}
        if (oldBugs.url) {
          /* eslint-disable-next-line node/no-deprecated-api */
          if (typeof (oldBugs.url) === 'string' && url.parse(oldBugs.url).protocol) {
            data.bugs.url = oldBugs.url
          } else {
            this.warn('nonUrlBugsUrlField')
          }
        }
        if (oldBugs.email) {
          if (typeof (oldBugs.email) === 'string' && isEmail(oldBugs.email)) {
            data.bugs.email = oldBugs.email
          } else {
            this.warn('nonEmailBugsEmailField')
          }
        }
      }
      if (!data.bugs.email && !data.bugs.url) {
        delete data.bugs
        this.warn('emptyNormalizedBugs')
      }
    }
  },

  fixHomepageField: function (data) {
    if (!data.homepage && data.repository && data.repository.url) {
      var hosted = hostedGitInfo.fromUrl(data.repository.url)
      if (hosted && hosted.docs()) {
        data.homepage = hosted.docs()
      }
    }
    if (!data.homepage) {
      return
    }

    if (typeof data.homepage !== 'string') {
      this.warn('nonUrlHomepage')
      return delete data.homepage
    }
    /* eslint-disable-next-line node/no-deprecated-api */
    if (!url.parse(data.homepage).protocol) {
      data.homepage = 'http://' + data.homepage
    }
  },

  fixLicenseField: function (data) {
    const license = data.license || data.licence
    if (!license) {
      return this.warn('missingLicense')
    }
    if (
      typeof (license) !== 'string' ||
      license.length < 1 ||
      license.trim() === ''
    ) {
      return this.warn('invalidLicense')
    }
    if (!validateLicense(license).validForNewPackages) {
      return this.warn('invalidLicense')
    }
  },
}

function isValidScopedPackageName (spec) {
  if (spec.charAt(0) !== '@') {
    return false
  }

  var rest = spec.slice(1).split('/')
  if (rest.length !== 2) {
    return false
  }

  return rest[0] && rest[1] &&
    rest[0] === encodeURIComponent(rest[0]) &&
    rest[1] === encodeURIComponent(rest[1])
}

function isCorrectlyEncodedName (spec) {
  return !spec.match(/[/@\s+%:]/) &&
    spec === encodeURIComponent(spec)
}

function ensureValidName (name, strict, allowLegacyCase) {
  if (name.charAt(0) === '.' ||
      !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) ||
      (strict && (!allowLegacyCase) && name !== name.toLowerCase()) ||
      name.toLowerCase() === 'node_modules' ||
      name.toLowerCase() === 'favicon.ico') {
    throw new Error('Invalid name: ' + JSON.stringify(name))
  }
}

function modifyPeople (data, fn) {
  if (data.author) {
    data.author = fn(data.author)
  }['maintainers', 'contributors'].forEach(function (set) {
    if (!Array.isArray(data[set])) {
      return
    }
    data[set] = data[set].map(fn)
  })
  return data
}

function unParsePerson (person) {
  if (typeof person === 'string') {
    return person
  }
  var name = person.name || ''
  var u = person.url || person.web
  var wrappedUrl = u ? (' (' + u + ')') : ''
  var e = person.email || person.mail
  var wrappedEmail = e ? (' <' + e + '>') : ''
  return name + wrappedEmail + wrappedUrl
}

function parsePerson (person) {
  if (typeof person !== 'string') {
    return person
  }
  var matchedName = person.match(/^([^(<]+)/)
  var matchedUrl = person.match(/\(([^()]+)\)/)
  var matchedEmail = person.match(/<([^<>]+)>/)
  var obj = {}
  if (matchedName && matchedName[0].trim()) {
    obj.name = matchedName[0].trim()
  }
  if (matchedEmail) {
    obj.email = matchedEmail[1]
  }
  if (matchedUrl) {
    obj.url = matchedUrl[1]
  }
  return obj
}

function addOptionalDepsToDeps (data) {
  var o = data.optionalDependencies
  if (!o) {
    return
  }
  var d = data.dependencies || {}
  Object.keys(o).forEach(function (k) {
    d[k] = o[k]
  })
  data.dependencies = d
}

function depObjectify (deps, type, warn) {
  if (!deps) {
    return {}
  }
  if (typeof deps === 'string') {
    deps = deps.trim().split(/[\n\r\s\t ,]+/)
  }
  if (!Array.isArray(deps)) {
    return deps
  }
  warn('deprecatedArrayDependencies', type)
  var o = {}
  deps.filter(function (d) {
    return typeof d === 'string'
  }).forEach(function (d) {
    d = d.trim().split(/(:?[@\s><=])/)
    var dn = d.shift()
    var dv = d.join('')
    dv = dv.trim()
    dv = dv.replace(/^@/, '')
    o[dn] = dv
  })
  return o
}

function objectifyDeps (data, warn) {
  depTypes.forEach(function (type) {
    if (!data[type]) {
      return
    }
    data[type] = depObjectify(data[type], type, warn)
  })
}

function bugsTypos (bugs, warn) {
  if (!bugs) {
    return
  }
  Object.keys(bugs).forEach(function (k) {
    if (typos.bugs[k]) {
      warn('typo', k, typos.bugs[k], 'bugs')
      bugs[typos.bugs[k]] = bugs[k]
      delete bugs[k]
    }
  })
}
var util = require('util')
var messages = require('./warning_messages.json')

module.exports = function () {
  var args = Array.prototype.slice.call(arguments, 0)
  var warningName = args.shift()
  if (warningName === 'typo') {
    return makeTypoWarning.apply(null, args)
  } else {
    var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'"
    args.unshift(msgTemplate)
    return util.format.apply(null, args)
  }
}

function makeTypoWarning (providedName, probableName, field) {
  if (field) {
    providedName = field + "['" + providedName + "']"
    probableName = field + "['" + probableName + "']"
  }
  return util.format(messages.typo, providedName, probableName)
}
module.exports = normalize

var fixer = require('./fixer')
normalize.fixer = fixer

var makeWarning = require('./make_warning')

var fieldsToFix = ['name', 'version', 'description', 'repository', 'modules', 'scripts',
  'files', 'bin', 'man', 'bugs', 'keywords', 'readme', 'homepage', 'license']
var otherThingsToFix = ['dependencies', 'people', 'typos']

var thingsToFix = fieldsToFix.map(function (fieldName) {
  return ucFirst(fieldName) + 'Field'
})
// two ways to do this in CoffeeScript on only one line, sub-70 chars:
// thingsToFix = fieldsToFix.map (name) -> ucFirst(name) + "Field"
// thingsToFix = (ucFirst(name) + "Field" for name in fieldsToFix)
thingsToFix = thingsToFix.concat(otherThingsToFix)

function normalize (data, warn, strict) {
  if (warn === true) {
    warn = null
    strict = true
  }
  if (!strict) {
    strict = false
  }
  if (!warn || data.private) {
    warn = function () { /* noop */ }
  }

  if (data.scripts &&
      data.scripts.install === 'node-gyp rebuild' &&
      !data.scripts.preinstall) {
    data.gypfile = true
  }
  fixer.warn = function () {
    warn(makeWarning.apply(null, arguments))
  }
  thingsToFix.forEach(function (thingName) {
    fixer['fix' + ucFirst(thingName)](data, strict)
  })
  data._id = data.name + '@' + data.version
}

function ucFirst (string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}
var util = require('util')

module.exports = function () {
  var args = Array.prototype.slice.call(arguments, 0)
  args.forEach(function (arg) {
    if (!arg) {
      throw new TypeError('Bad arguments.')
    }
  })
  return util.format.apply(null, arguments)
}
{
  "topLevel": {
    "dependancies": "dependencies"
   ,"dependecies": "dependencies"
   ,"depdenencies": "dependencies"
   ,"devEependencies": "devDependencies"
   ,"depends": "dependencies"
   ,"dev-dependencies": "devDependencies"
   ,"devDependences": "devDependencies"
   ,"devDepenencies": "devDependencies"
   ,"devdependencies": "devDependencies"
   ,"repostitory": "repository"
   ,"repo": "repository"
   ,"prefereGlobal": "preferGlobal"
   ,"hompage": "homepage"
   ,"hampage": "homepage"
   ,"autohr": "author"
   ,"autor": "author"
   ,"contributers": "contributors"
   ,"publicationConfig": "publishConfig"
   ,"script": "scripts"
  },
  "bugs": { "web": "url", "name": "url" },
  "script": { "server": "start", "tests": "test" }
}
{
  "repositories": "'repositories' (plural) Not supported. Please pick one as the 'repository' field"
  ,"missingRepository": "No repository field."
  ,"brokenGitUrl": "Probably broken git url: %s"
  ,"nonObjectScripts": "scripts must be an object"
  ,"nonStringScript": "script values must be string commands"
  ,"nonArrayFiles": "Invalid 'files' member"
  ,"invalidFilename": "Invalid filename in 'files' list: %s"
  ,"nonArrayBundleDependencies": "Invalid 'bundleDependencies' list. Must be array of package names"
  ,"nonStringBundleDependency": "Invalid bundleDependencies member: %s"
  ,"nonDependencyBundleDependency": "Non-dependency in bundleDependencies: %s"
  ,"nonObjectDependencies": "%s field must be an object"
  ,"nonStringDependency": "Invalid dependency: %s %s"
  ,"deprecatedArrayDependencies": "specifying %s as array is deprecated"
  ,"deprecatedModules": "modules field is deprecated"
  ,"nonArrayKeywords": "keywords should be an array of strings"
  ,"nonStringKeyword": "keywords should be an array of strings"
  ,"conflictingName": "%s is also the name of a node core module."
  ,"nonStringDescription": "'description' field should be a string"
  ,"missingDescription": "No description"
  ,"missingReadme": "No README data"
  ,"missingLicense": "No license field."
  ,"nonEmailUrlBugsString": "Bug string field must be url, email, or {email,url}"
  ,"nonUrlBugsUrlField": "bugs.url field must be a string url. Deleted."
  ,"nonEmailBugsEmailField": "bugs.email field must be a string email. Deleted."
  ,"emptyNormalizedBugs": "Normalized value of bugs field is an empty object. Deleted."
  ,"nonUrlHomepage": "homepage field must be a string url. Deleted."
  ,"invalidLicense": "license should be a valid SPDX license expression"
  ,"typo": "%s should probably be %s."
}
{
  "name": "normalize-package-data",
  "version": "7.0.0",
  "author": "GitHub Inc.",
  "description": "Normalizes data that can be found in package.json files.",
  "license": "BSD-2-Clause",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/normalize-package-data.git"
  },
  "main": "lib/normalize.js",
  "scripts": {
    "test": "tap",
    "npmclilint": "npmcli-lint",
    "lint": "npm run eslint",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "postsnap": "npm run lintfix --",
    "postlint": "template-oss-check",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "dependencies": {
    "hosted-git-info": "^8.0.0",
    "semver": "^7.3.5",
    "validate-npm-package-license": "^3.0.4"
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.0.1"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": "true"
  },
  "tap": {
    "branches": 86,
    "functions": 92,
    "lines": 86,
    "statements": 86,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  }
}
ISC License

Copyright (c) npm, Inc.

Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS
ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
USE OR PERFORMANCE OF THIS SOFTWARE.
module.exports = (chalk) => {
  const green = s => chalk.green.bold(s)
  const red = s => chalk.red.bold(s)
  const magenta = s => chalk.magenta.bold(s)
  const yellow = s => chalk.yellow.bold(s)
  const white = s => chalk.bold(s)
  const severity = (sev, s) => sev.toLowerCase() === 'moderate' ? yellow(s || sev)
    : sev.toLowerCase() === 'high' ? red(s || sev)
    : sev.toLowerCase() === 'critical' ? magenta(s || sev)
    : white(s || sev)
  const dim = s => chalk.dim(s)

  return {
    dim,
    green,
    red,
    magenta,
    yellow,
    white,
    severity,
  }
}
// return 1 if any vulns in the set are at or above the specified severity
const severities = new Map(Object.entries([
  'info',
  'low',
  'moderate',
  'high',
  'critical',
  'none',
]).map(s => s.reverse()))

module.exports = (data, level) =>
  Object.entries(data.metadata.vulnerabilities)
    .some(([sev, count]) => count > 0 && severities.has(sev) &&
      severities.get(sev) >= severities.get(level)) ? 1 : 0
'use strict'

const reporters = {
  install: require('./reporters/install'),
  detail: require('./reporters/detail'),
  json: require('./reporters/json'),
  quiet: require('./reporters/quiet'),
}

const exitCode = require('./exit-code.js')

module.exports = Object.assign((data, options = {}) => {
  const {
    reporter = 'install',
    chalk,
    unicode = true,
    indent = 2,
  } = options

  // CLI defaults this to `null` so the defaulting method above doesn't work
  const auditLevel = options.auditLevel || 'low'

  if (!data) {
    throw Object.assign(
      new TypeError('ENOAUDITDATA'),
      {
        code: 'ENOAUDITDATA',
        message: 'missing audit data',
      }
    )
  }

  if (typeof data.toJSON === 'function') {
    data = data.toJSON()
  }

  return {
    report: reporters[reporter](data, { chalk, unicode, indent }),
    exitCode: exitCode(data, auditLevel),
  }
}, { reporters })
'use strict'

const colors = require('../colors.js')
const install = require('./install.js')

module.exports = (data, { chalk }) => {
  const summary = install.summary(data, { chalk })
  const none = data.metadata.vulnerabilities.total === 0
  return none ? summary : fullReport(data, { chalk, summary })
}

const fullReport = (data, { chalk, summary }) => {
  const c = colors(chalk)
  const output = [c.white('# npm audit report'), '']

  const printed = new Set()
  for (const [, vuln] of Object.entries(data.vulnerabilities)) {
    // only print starting from the top-level advisories
    if (vuln.via.filter(v => typeof v !== 'string').length !== 0) {
      output.push(printVuln(vuln, c, data.vulnerabilities, printed))
    }
  }

  output.push(summary)

  return output.join('\n')
}

const printVuln = (vuln, c, vulnerabilities, printed, indent = '') => {
  if (printed.has(vuln)) {
    return null
  }

  printed.add(vuln)
  const output = []

  output.push(c.white(vuln.name) + '  ' + vuln.range)

  if (indent === '' && (vuln.severity !== 'low' || vuln.severity === 'info')) {
    output.push(`Severity: ${c.severity(vuln.severity)}`)
  }

  for (const via of vuln.via) {
    if (typeof via === 'string') {
      output.push(`Depends on vulnerable versions of ${c.white(via)}`)
    } else if (indent === '') {
      output.push(`${c.white(via.title)} - ${via.url}`)
    }
  }

  if (indent === '') {
    const { fixAvailable: fa } = vuln
    if (fa === false) {
      output.push(c.red('No fix available'))
    } else if (fa === true) {
      output.push(c.green('fix available') + ' via `npm audit fix`')
    } else {
      /* istanbul ignore else - should be impossible, just being cautious */
      if (typeof fa === 'object' && indent === '') {
        output.push(
          `${c.yellow('fix available')} via \`npm audit fix --force\``,
          `Will install ${fa.name}@${fa.version}` +
          `, which is ${fa.isSemVerMajor ? 'a breaking change' :
            'outside the stated dependency range'}`
        )
      }
    }
  }

  for (const path of vuln.nodes) {
    output.push(c.dim(path))
  }

  for (const effect of vuln.effects) {
    const e = printVuln(vulnerabilities[effect], c, vulnerabilities, printed, '  ')
    if (e) {
      output.push(...e.split('\n'))
    }
  }

  if (indent === '') {
    output.push('')
  }

  return output.map(l => `${indent}${l}`).join('\n')
}
const colors = require('../colors.js')

const calculate = (data, { chalk }) => {
  const c = colors(chalk)
  const output = []
  const { metadata: { vulnerabilities } } = data
  const vulnCount = vulnerabilities.total

  let someFixable = false
  let someForceFixable = false
  let forceFixSemVerMajor = false
  let someUnfixable = false

  if (vulnCount === 0) {
    output.push(`found ${c.green('0')} vulnerabilities`)
  } else {
    for (const [, vuln] of Object.entries(data.vulnerabilities)) {
      const { fixAvailable } = vuln
      someFixable = someFixable || fixAvailable === true
      someUnfixable = someUnfixable || fixAvailable === false
      if (typeof fixAvailable === 'object') {
        someForceFixable = true
        forceFixSemVerMajor = forceFixSemVerMajor || fixAvailable.isSemVerMajor
      }
    }
    const total = vulnerabilities.total
    const sevs = Object.entries(vulnerabilities).filter(([s, count]) => {
      return (s === 'low' || s === 'moderate' || s === 'high' || s === 'critical') &&
        count > 0
    })

    if (sevs.length > 1) {
      const severities = sevs.map(([s, count]) => {
        return `${count} ${c.severity(s)}`
      }).join(', ')
      output.push(`${c.red(total)} vulnerabilities (${severities})`)
    } else {
      const [sev, count] = sevs[0]
      output.push(`${count} ${c.severity(sev)} severity vulnerabilit${count === 1 ? 'y' : 'ies'}`)
    }

    // XXX use a different footer line if some aren't fixable easily.
    // just 'run `npm audit` for details' maybe?

    if (someFixable) {
      output.push('', 'To address ' +
        (someForceFixable || someUnfixable ? 'issues that do not require attention'
        : 'all issues') + ', run:\n  npm audit fix')
    }

    if (someForceFixable) {
      output.push('', 'To address all issues' +
        (someUnfixable ? ' possible' : '') +
        (forceFixSemVerMajor ? ' (including breaking changes)' : '') +
        ', run:\n  npm audit fix --force')
    }

    if (someUnfixable) {
      output.push('',
        'Some issues need review, and may require choosing',
        'a different dependency.')
    }
  }

  const summary = output.join('\n')
  return {
    summary,
    report: vulnCount > 0 ? `${summary}\n\nRun \`npm audit\` for details.`
    : summary,
  }
}

module.exports = Object.assign((data, opt) => calculate(data, opt).report, {
  summary: (data, opt) => calculate(data, opt).summary,
})
module.exports = (data, { indent }) => JSON.stringify(data, null, indent)
module.exports = () => ''
{
  "name": "npm-audit-report",
  "version": "6.0.0",
  "description": "Given a response from the npm security api, render it into a variety of security reports",
  "main": "lib/index.js",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "tap": {
    "check-coverage": true,
    "coverage-map": "map.js",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "keywords": [
    "npm",
    "security",
    "report",
    "audit"
  ],
  "author": "GitHub Inc.",
  "license": "ISC",
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "chalk": "^5.2.0",
    "tap": "^16.0.0"
  },
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-audit-report.git"
  },
  "bugs": {
    "url": "https://github.com/npm/npm-audit-report/issues"
  },
  "homepage": "https://github.com/npm/npm-audit-report#readme",
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  }
}
The ISC License

Copyright (c) npm, Inc. and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'

// walk the tree of deps starting from the top level list of bundled deps
// Any deps at the top level that are depended on by a bundled dep that
// does not have that dep in its own node_modules folder are considered
// bundled deps as well.  This list of names can be passed to npm-packlist
// as the "bundled" argument.  Additionally, packageJsonCache is shared so
// packlist doesn't have to re-read files already consumed in this pass

const fs = require('fs')
const path = require('path')
const EE = require('events').EventEmitter
// we don't care about the package bins, but we share a pj cache
// with other modules that DO care about it, so keep it nice.
const normalizePackageBin = require('npm-normalize-package-bin')

class BundleWalker extends EE {
  constructor (opt) {
    opt = opt || {}
    super(opt)
    this.path = path.resolve(opt.path || process.cwd())

    this.parent = opt.parent || null
    if (this.parent) {
      this.result = this.parent.result
      // only collect results in node_modules folders at the top level
      // since the node_modules in a bundled dep is included always
      if (!this.parent.parent) {
        const base = path.basename(this.path)
        const scope = path.basename(path.dirname(this.path))
        this.result.add(/^@/.test(scope) ? scope + '/' + base : base)
      }
      this.root = this.parent.root
      this.packageJsonCache = this.parent.packageJsonCache
    } else {
      this.result = new Set()
      this.root = this.path
      this.packageJsonCache = opt.packageJsonCache || new Map()
    }

    this.seen = new Set()
    this.didDone = false
    this.children = 0
    this.node_modules = []
    this.package = null
    this.bundle = null
  }

  addListener (ev, fn) {
    return this.on(ev, fn)
  }

  on (ev, fn) {
    const ret = super.on(ev, fn)
    if (ev === 'done' && this.didDone) {
      this.emit('done', this.result)
    }
    return ret
  }

  done () {
    if (!this.didDone) {
      this.didDone = true
      if (!this.parent) {
        const res = Array.from(this.result)
        this.result = res
        this.emit('done', res)
      } else {
        this.emit('done')
      }
    }
  }

  start () {
    const pj = path.resolve(this.path, 'package.json')
    if (this.packageJsonCache.has(pj)) {
      this.onPackage(this.packageJsonCache.get(pj))
    } else {
      this.readPackageJson(pj)
    }
    return this
  }

  readPackageJson (pj) {
    fs.readFile(pj, (er, data) =>
      er ? this.done() : this.onPackageJson(pj, data))
  }

  onPackageJson (pj, data) {
    try {
      this.package = normalizePackageBin(JSON.parse(data + ''))
    } catch (er) {
      return this.done()
    }
    this.packageJsonCache.set(pj, this.package)
    this.onPackage(this.package)
  }

  allDepsBundled (pkg) {
    return Object.keys(pkg.dependencies || {}).concat(
      Object.keys(pkg.optionalDependencies || {}))
  }

  onPackage (pkg) {
    // all deps are bundled if we got here as a child.
    // otherwise, only bundle bundledDeps
    // Get a unique-ified array with a short-lived Set
    const bdRaw = this.parent ? this.allDepsBundled(pkg)
      : pkg.bundleDependencies || pkg.bundledDependencies || []

    const bd = Array.from(new Set(
      Array.isArray(bdRaw) ? bdRaw
      : bdRaw === true ? this.allDepsBundled(pkg)
      : Object.keys(bdRaw)))

    if (!bd.length) {
      return this.done()
    }

    this.bundle = bd
    this.readModules()
  }

  readModules () {
    readdirNodeModules(this.path + '/node_modules', (er, nm) =>
      er ? this.onReaddir([]) : this.onReaddir(nm))
  }

  onReaddir (nm) {
    // keep track of what we have, in case children need it
    this.node_modules = nm

    this.bundle.forEach(dep => this.childDep(dep))
    if (this.children === 0) {
      this.done()
    }
  }

  childDep (dep) {
    if (this.node_modules.indexOf(dep) !== -1) {
      if (!this.seen.has(dep)) {
        this.seen.add(dep)
        this.child(dep)
      }
    } else if (this.parent) {
      this.parent.childDep(dep)
    }
  }

  child (dep) {
    const p = this.path + '/node_modules/' + dep
    this.children += 1
    const child = new BundleWalker({
      path: p,
      parent: this,
    })
    child.on('done', () => {
      if (--this.children === 0) {
        this.done()
      }
    })
    child.start()
  }
}

class BundleWalkerSync extends BundleWalker {
  start () {
    super.start()
    this.done()
    return this
  }

  readPackageJson (pj) {
    try {
      this.onPackageJson(pj, fs.readFileSync(pj))
    } catch {
      // empty catch
    }
    return this
  }

  readModules () {
    try {
      this.onReaddir(readdirNodeModulesSync(this.path + '/node_modules'))
    } catch {
      this.onReaddir([])
    }
  }

  child (dep) {
    new BundleWalkerSync({
      path: this.path + '/node_modules/' + dep,
      parent: this,
    }).start()
  }
}

const readdirNodeModules = (nm, cb) => {
  fs.readdir(nm, (er, set) => {
    if (er) {
      cb(er)
    } else {
      const scopes = set.filter(f => /^@/.test(f))
      if (!scopes.length) {
        cb(null, set)
      } else {
        const unscoped = set.filter(f => !/^@/.test(f))
        let count = scopes.length
        scopes.forEach(scope => {
          fs.readdir(nm + '/' + scope, (readdirEr, pkgs) => {
            if (readdirEr || !pkgs.length) {
              unscoped.push(scope)
            } else {
              unscoped.push.apply(unscoped, pkgs.map(p => scope + '/' + p))
            }
            if (--count === 0) {
              cb(null, unscoped)
            }
          })
        })
      }
    }
  })
}

const readdirNodeModulesSync = nm => {
  const set = fs.readdirSync(nm)
  const unscoped = set.filter(f => !/^@/.test(f))
  const scopes = set.filter(f => /^@/.test(f)).map(scope => {
    try {
      const pkgs = fs.readdirSync(nm + '/' + scope)
      return pkgs.length ? pkgs.map(p => scope + '/' + p) : [scope]
    } catch (er) {
      return [scope]
    }
  }).reduce((a, b) => a.concat(b), [])
  return unscoped.concat(scopes)
}

const walk = (options, callback) => {
  const p = new Promise((resolve, reject) => {
    new BundleWalker(options).on('done', resolve).on('error', reject).start()
  })
  return callback ? p.then(res => callback(null, res), callback) : p
}

const walkSync = options => {
  return new BundleWalkerSync(options).start().result
}

module.exports = walk
walk.sync = walkSync
walk.BundleWalker = BundleWalker
walk.BundleWalkerSync = BundleWalkerSync
{
  "name": "npm-bundled",
  "version": "4.0.0",
  "description": "list things in node_modules that are bundledDependencies, or transitive dependencies thereof",
  "main": "lib/index.js",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-bundled.git"
  },
  "author": "GitHub Inc.",
  "license": "ISC",
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "mutate-fs": "^2.1.1",
    "tap": "^16.3.0"
  },
  "scripts": {
    "test": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "snap": "tap",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "dependencies": {
    "npm-normalize-package-bin": "^4.0.0"
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  }
}
Copyright (c) Robert Kowalski and Isaac Z. Schlueter ("Authors")
All rights reserved.

The BSD License

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. 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 AUTHORS 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 AUTHORS 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.
const process = require('node:process')
const nodeOs = require('node:os')
const fs = require('node:fs')

function isMusl (file) {
  return file.includes('libc.musl-') || file.includes('ld-musl-')
}

function os () {
  return process.platform
}

function cpu () {
  return process.arch
}

const LDD_PATH = '/usr/bin/ldd'
function getFamilyFromFilesystem () {
  try {
    const content = fs.readFileSync(LDD_PATH, 'utf-8')
    if (content.includes('musl')) {
      return 'musl'
    }
    if (content.includes('GNU C Library')) {
      return 'glibc'
    }
    return null
  } catch {
    return undefined
  }
}

function getFamilyFromReport () {
  const originalExclude = process.report.excludeNetwork
  process.report.excludeNetwork = true
  const report = process.report.getReport()
  process.report.excludeNetwork = originalExclude
  if (report.header?.glibcVersionRuntime) {
    family = 'glibc'
  } else if (Array.isArray(report.sharedObjects) && report.sharedObjects.some(isMusl)) {
    family = 'musl'
  } else {
    family = null
  }
  return family
}

let family
function libc (osName) {
  if (osName !== 'linux') {
    return undefined
  }
  if (family === undefined) {
    family = getFamilyFromFilesystem()
    if (family === undefined) {
      family = getFamilyFromReport()
    }
  }
  return family
}

function devEngines (env = {}) {
  const osName = env.os || os()
  return {
    cpu: {
      name: env.cpu || cpu(),
    },
    libc: {
      name: env.libc || libc(osName),
    },
    os: {
      name: osName,
      version: env.osVersion || nodeOs.release(),
    },
    packageManager: {
      name: 'npm',
      version: env.npmVersion,
    },
    runtime: {
      name: 'node',
      version: env.nodeVersion || process.version,
    },
  }
}

module.exports = {
  cpu,
  libc,
  os,
  devEngines,
}
const satisfies = require('semver/functions/satisfies')
const validRange = require('semver/ranges/valid')

const recognizedOnFail = [
  'ignore',
  'warn',
  'error',
  'download',
]

const recognizedProperties = [
  'name',
  'version',
  'onFail',
]

const recognizedEngines = [
  'packageManager',
  'runtime',
  'cpu',
  'libc',
  'os',
]

/** checks a devEngine dependency */
function checkDependency (wanted, current, opts) {
  const { engine } = opts

  if ((typeof wanted !== 'object' || wanted === null) || Array.isArray(wanted)) {
    throw new Error(`Invalid non-object value for "${engine}"`)
  }

  const properties = Object.keys(wanted)

  for (const prop of properties) {
    if (!recognizedProperties.includes(prop)) {
      throw new Error(`Invalid property "${prop}" for "${engine}"`)
    }
  }

  if (!properties.includes('name')) {
    throw new Error(`Missing "name" property for "${engine}"`)
  }

  if (typeof wanted.name !== 'string') {
    throw new Error(`Invalid non-string value for "name" within "${engine}"`)
  }

  if (typeof current.name !== 'string' || current.name === '') {
    throw new Error(`Unable to determine "name" for "${engine}"`)
  }

  if (properties.includes('onFail')) {
    if (typeof wanted.onFail !== 'string') {
      throw new Error(`Invalid non-string value for "onFail" within "${engine}"`)
    }
    if (!recognizedOnFail.includes(wanted.onFail)) {
      throw new Error(`Invalid onFail value "${wanted.onFail}" for "${engine}"`)
    }
  }

  if (wanted.name !== current.name) {
    return new Error(
      `Invalid name "${wanted.name}" does not match "${current.name}" for "${engine}"`
    )
  }

  if (properties.includes('version')) {
    if (typeof wanted.version !== 'string') {
      throw new Error(`Invalid non-string value for "version" within "${engine}"`)
    }
    if (typeof current.version !== 'string' || current.version === '') {
      throw new Error(`Unable to determine "version" for "${engine}" "${wanted.name}"`)
    }
    if (validRange(wanted.version)) {
      if (!satisfies(current.version, wanted.version, opts.semver)) {
        return new Error(
          // eslint-disable-next-line max-len
          `Invalid semver version "${wanted.version}" does not match "${current.version}" for "${engine}"`
        )
      }
    } else if (wanted.version !== current.version) {
      return new Error(
        `Invalid version "${wanted.version}" does not match "${current.version}" for "${engine}"`
      )
    }
  }
}

/** checks devEngines package property and returns array of warnings / errors */
function checkDevEngines (wanted, current = {}, opts = {}) {
  if ((typeof wanted !== 'object' || wanted === null) || Array.isArray(wanted)) {
    throw new Error(`Invalid non-object value for devEngines`)
  }

  const errors = []

  for (const engine of Object.keys(wanted)) {
    if (!recognizedEngines.includes(engine)) {
      throw new Error(`Invalid property "${engine}"`)
    }
    const dependencyAsAuthored = wanted[engine]
    const dependencies = [dependencyAsAuthored].flat()
    const currentEngine = current[engine] || {}

    // this accounts for empty array eg { runtime: [] } and ignores it
    if (dependencies.length === 0) {
      continue
    }

    const depErrors = []
    for (const dep of dependencies) {
      const result = checkDependency(dep, currentEngine, { ...opts, engine })
      if (result) {
        depErrors.push(result)
      }
    }

    const invalid = depErrors.length === dependencies.length

    if (invalid) {
      const lastDependency = dependencies[dependencies.length - 1]
      let onFail = lastDependency.onFail || 'error'
      if (onFail === 'download') {
        onFail = 'error'
      }

      const err = Object.assign(new Error(`Invalid engine "${engine}"`), {
        errors: depErrors,
        engine,
        isWarn: onFail === 'warn',
        isError: onFail === 'error',
        current: currentEngine,
        required: dependencyAsAuthored,
      })

      errors.push(err)
    }
  }
  return errors
}

module.exports = {
  checkDevEngines,
}
const semver = require('semver')
const currentEnv = require('./current-env')
const { checkDevEngines } = require('./dev-engines')

const checkEngine = (target, npmVer, nodeVer, force = false) => {
  const nodev = force ? null : nodeVer
  const eng = target.engines
  const opt = { includePrerelease: true }
  if (!eng) {
    return
  }

  const nodeFail = nodev && eng.node && !semver.satisfies(nodev, eng.node, opt)
  const npmFail = npmVer && eng.npm && !semver.satisfies(npmVer, eng.npm, opt)
  if (nodeFail || npmFail) {
    throw Object.assign(new Error('Unsupported engine'), {
      pkgid: target._id,
      current: { node: nodeVer, npm: npmVer },
      required: eng,
      code: 'EBADENGINE',
    })
  }
}

const checkPlatform = (target, force = false, environment = {}) => {
  if (force) {
    return
  }

  const os = environment.os || currentEnv.os()
  const cpu = environment.cpu || currentEnv.cpu()
  const libc = environment.libc || currentEnv.libc(os)

  const osOk = target.os ? checkList(os, target.os) : true
  const cpuOk = target.cpu ? checkList(cpu, target.cpu) : true
  let libcOk = target.libc ? checkList(libc, target.libc) : true
  if (target.libc && !libc) {
    libcOk = false
  }

  if (!osOk || !cpuOk || !libcOk) {
    throw Object.assign(new Error('Unsupported platform'), {
      pkgid: target._id,
      current: {
        os,
        cpu,
        libc,
      },
      required: {
        os: target.os,
        cpu: target.cpu,
        libc: target.libc,
      },
      code: 'EBADPLATFORM',
    })
  }
}

const checkList = (value, list) => {
  if (typeof list === 'string') {
    list = [list]
  }
  if (list.length === 1 && list[0] === 'any') {
    return true
  }
  // match none of the negated values, and at least one of the
  // non-negated values, if any are present.
  let negated = 0
  let match = false
  for (const entry of list) {
    const negate = entry.charAt(0) === '!'
    const test = negate ? entry.slice(1) : entry
    if (negate) {
      negated++
      if (value === test) {
        return false
      }
    } else {
      match = match || value === test
    }
  }
  return match || negated === list.length
}

module.exports = {
  checkEngine,
  checkPlatform,
  checkDevEngines,
  currentEnv,
}
{
  "name": "npm-install-checks",
  "version": "7.1.1",
  "description": "Check the engines and platform fields in package.json",
  "main": "lib/index.js",
  "dependencies": {
    "semver": "^7.1.1"
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.4",
    "tap": "^16.0.1"
  },
  "scripts": {
    "test": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "snap": "tap",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-install-checks.git"
  },
  "keywords": [
    "npm,",
    "install"
  ],
  "license": "BSD-2-Clause",
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "author": "GitHub Inc.",
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.4",
    "publish": "true"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  }
}
The ISC License

Copyright (c) npm, Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// pass in a manifest with a 'bin' field here, and it'll turn it
// into a properly santized bin object
const { join, basename } = require('path')

const normalize = pkg =>
  !pkg.bin ? removeBin(pkg)
  : typeof pkg.bin === 'string' ? normalizeString(pkg)
  : Array.isArray(pkg.bin) ? normalizeArray(pkg)
  : typeof pkg.bin === 'object' ? normalizeObject(pkg)
  : removeBin(pkg)

const normalizeString = pkg => {
  if (!pkg.name) {
    return removeBin(pkg)
  }
  pkg.bin = { [pkg.name]: pkg.bin }
  return normalizeObject(pkg)
}

const normalizeArray = pkg => {
  pkg.bin = pkg.bin.reduce((acc, k) => {
    acc[basename(k)] = k
    return acc
  }, {})
  return normalizeObject(pkg)
}

const removeBin = pkg => {
  delete pkg.bin
  return pkg
}

const normalizeObject = pkg => {
  const orig = pkg.bin
  const clean = {}
  let hasBins = false
  Object.keys(orig).forEach(binKey => {
    const base = join('/', basename(binKey.replace(/\\|:/g, '/'))).slice(1)

    if (typeof orig[binKey] !== 'string' || !base) {
      return
    }

    const binTarget = join('/', orig[binKey].replace(/\\/g, '/'))
      .replace(/\\/g, '/').slice(1)

    if (!binTarget) {
      return
    }

    clean[base] = binTarget
    hasBins = true
  })

  if (hasBins) {
    pkg.bin = clean
  } else {
    delete pkg.bin
  }

  return pkg
}

module.exports = normalize
{
  "name": "npm-normalize-package-bin",
  "version": "4.0.0",
  "description": "Turn any flavor of allowable package.json bin into a normalized object",
  "main": "lib/index.js",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-normalize-package-bin.git"
  },
  "author": "GitHub Inc.",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.3.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": "true"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  }
}
The ISC License

Copyright (c) npm, Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'
module.exports = npa
module.exports.resolve = resolve
module.exports.toPurl = toPurl
module.exports.Result = Result

const { URL } = require('url')
const HostedGit = require('hosted-git-info')
const semver = require('semver')
const path = global.FAKE_WINDOWS ? require('path').win32 : require('path')
const validatePackageName = require('validate-npm-package-name')
const { homedir } = require('os')
const { log } = require('proc-log')

const isWindows = process.platform === 'win32' || global.FAKE_WINDOWS
const hasSlashes = isWindows ? /\\|[/]/ : /[/]/
const isURL = /^(?:git[+])?[a-z]+:/i
const isGit = /^[^@]+@[^:.]+\.[^:]+:.+$/i
const isFilename = /[.](?:tgz|tar.gz|tar)$/i
const isPortNumber = /:[0-9]+(\/|$)/i

function npa (arg, where) {
  let name
  let spec
  if (typeof arg === 'object') {
    if (arg instanceof Result && (!where || where === arg.where)) {
      return arg
    } else if (arg.name && arg.rawSpec) {
      return npa.resolve(arg.name, arg.rawSpec, where || arg.where)
    } else {
      return npa(arg.raw, where || arg.where)
    }
  }
  const nameEndsAt = arg[0] === '@' ? arg.slice(1).indexOf('@') + 1 : arg.indexOf('@')
  const namePart = nameEndsAt > 0 ? arg.slice(0, nameEndsAt) : arg
  if (isURL.test(arg)) {
    spec = arg
  } else if (isGit.test(arg)) {
    spec = `git+ssh://${arg}`
  } else if (namePart[0] !== '@' && (hasSlashes.test(namePart) || isFilename.test(namePart))) {
    spec = arg
  } else if (nameEndsAt > 0) {
    name = namePart
    spec = arg.slice(nameEndsAt + 1) || '*'
  } else {
    const valid = validatePackageName(arg)
    if (valid.validForOldPackages) {
      name = arg
      spec = '*'
    } else {
      spec = arg
    }
  }
  return resolve(name, spec, where, arg)
}

const isFilespec = isWindows ? /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ : /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/

function resolve (name, spec, where, arg) {
  const res = new Result({
    raw: arg,
    name: name,
    rawSpec: spec,
    fromArgument: arg != null,
  })

  if (name) {
    res.setName(name)
  }

  if (spec && (isFilespec.test(spec) || /^file:/i.test(spec))) {
    return fromFile(res, where)
  } else if (spec && /^npm:/i.test(spec)) {
    return fromAlias(res, where)
  }

  const hosted = HostedGit.fromUrl(spec, {
    noGitPlus: true,
    noCommittish: true,
  })
  if (hosted) {
    return fromHostedGit(res, hosted)
  } else if (spec && isURL.test(spec)) {
    return fromURL(res)
  } else if (spec && (hasSlashes.test(spec) || isFilename.test(spec))) {
    return fromFile(res, where)
  } else {
    return fromRegistry(res)
  }
}

const defaultRegistry = 'https://registry.npmjs.org'

function toPurl (arg, reg = defaultRegistry) {
  const res = npa(arg)

  if (res.type !== 'version') {
    throw invalidPurlType(res.type, res.raw)
  }

  // URI-encode leading @ of scoped packages
  let purl = 'pkg:npm/' + res.name.replace(/^@/, '%40') + '@' + res.rawSpec
  if (reg !== defaultRegistry) {
    purl += '?repository_url=' + reg
  }

  return purl
}

function invalidPackageName (name, valid, raw) {
  // eslint-disable-next-line max-len
  const err = new Error(`Invalid package name "${name}" of package "${raw}": ${valid.errors.join('; ')}.`)
  err.code = 'EINVALIDPACKAGENAME'
  return err
}

function invalidTagName (name, raw) {
  // eslint-disable-next-line max-len
  const err = new Error(`Invalid tag name "${name}" of package "${raw}": Tags may not have any characters that encodeURIComponent encodes.`)
  err.code = 'EINVALIDTAGNAME'
  return err
}

function invalidPurlType (type, raw) {
  // eslint-disable-next-line max-len
  const err = new Error(`Invalid type "${type}" of package "${raw}": Purl can only be generated for "version" types.`)
  err.code = 'EINVALIDPURLTYPE'
  return err
}

function Result (opts) {
  this.type = opts.type
  this.registry = opts.registry
  this.where = opts.where
  if (opts.raw == null) {
    this.raw = opts.name ? opts.name + '@' + opts.rawSpec : opts.rawSpec
  } else {
    this.raw = opts.raw
  }

  this.name = undefined
  this.escapedName = undefined
  this.scope = undefined
  this.rawSpec = opts.rawSpec || ''
  this.saveSpec = opts.saveSpec
  this.fetchSpec = opts.fetchSpec
  if (opts.name) {
    this.setName(opts.name)
  }
  this.gitRange = opts.gitRange
  this.gitCommittish = opts.gitCommittish
  this.gitSubdir = opts.gitSubdir
  this.hosted = opts.hosted
}

Result.prototype.setName = function (name) {
  const valid = validatePackageName(name)
  if (!valid.validForOldPackages) {
    throw invalidPackageName(name, valid, this.raw)
  }

  this.name = name
  this.scope = name[0] === '@' ? name.slice(0, name.indexOf('/')) : undefined
  // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar
  this.escapedName = name.replace('/', '%2f')
  return this
}

Result.prototype.toString = function () {
  const full = []
  if (this.name != null && this.name !== '') {
    full.push(this.name)
  }
  const spec = this.saveSpec || this.fetchSpec || this.rawSpec
  if (spec != null && spec !== '') {
    full.push(spec)
  }
  return full.length ? full.join('@') : this.raw
}

Result.prototype.toJSON = function () {
  const result = Object.assign({}, this)
  delete result.hosted
  return result
}

// sets res.gitCommittish, res.gitRange, and res.gitSubdir
function setGitAttrs (res, committish) {
  if (!committish) {
    res.gitCommittish = null
    return
  }

  // for each :: separated item:
  for (const part of committish.split('::')) {
    // if the item has no : the n it is a commit-ish
    if (!part.includes(':')) {
      if (res.gitRange) {
        throw new Error('cannot override existing semver range with a committish')
      }
      if (res.gitCommittish) {
        throw new Error('cannot override existing committish with a second committish')
      }
      res.gitCommittish = part
      continue
    }
    // split on name:value
    const [name, value] = part.split(':')
    // if name is semver do semver lookup of ref or tag
    if (name === 'semver') {
      if (res.gitCommittish) {
        throw new Error('cannot override existing committish with a semver range')
      }
      if (res.gitRange) {
        throw new Error('cannot override existing semver range with a second semver range')
      }
      res.gitRange = decodeURIComponent(value)
      continue
    }
    if (name === 'path') {
      if (res.gitSubdir) {
        throw new Error('cannot override existing path with a second path')
      }
      res.gitSubdir = `/${value}`
      continue
    }
    log.warn('npm-package-arg', `ignoring unknown key "${name}"`)
  }
}

function fromFile (res, where) {
  if (!where) {
    where = process.cwd()
  }
  res.type = isFilename.test(res.rawSpec) ? 'file' : 'directory'
  res.where = where

  // always put the '/' on where when resolving urls, or else
  // file:foo from /path/to/bar goes to /path/to/foo, when we want
  // it to be /path/to/bar/foo

  let specUrl
  let resolvedUrl
  const prefix = (!/^file:/.test(res.rawSpec) ? 'file:' : '')
  const rawWithPrefix = prefix + res.rawSpec
  let rawNoPrefix = rawWithPrefix.replace(/^file:/, '')
  try {
    resolvedUrl = new URL(rawWithPrefix, `file://${path.resolve(where)}/`)
    specUrl = new URL(rawWithPrefix)
  } catch (originalError) {
    const er = new Error('Invalid file: URL, must comply with RFC 8089')
    throw Object.assign(er, {
      raw: res.rawSpec,
      spec: res,
      where,
      originalError,
    })
  }

  // XXX backwards compatibility lack of compliance with RFC 8089
  if (resolvedUrl.host && resolvedUrl.host !== 'localhost') {
    const rawSpec = res.rawSpec.replace(/^file:\/\//, 'file:///')
    resolvedUrl = new URL(rawSpec, `file://${path.resolve(where)}/`)
    specUrl = new URL(rawSpec)
    rawNoPrefix = rawSpec.replace(/^file:/, '')
  }
  // turn file:/../foo into file:../foo
  // for 1, 2 or 3 leading slashes since we attempted
  // in the previous step to make it a file protocol url with a leading slash
  if (/^\/{1,3}\.\.?(\/|$)/.test(rawNoPrefix)) {
    const rawSpec = res.rawSpec.replace(/^file:\/{1,3}/, 'file:')
    resolvedUrl = new URL(rawSpec, `file://${path.resolve(where)}/`)
    specUrl = new URL(rawSpec)
    rawNoPrefix = rawSpec.replace(/^file:/, '')
  }
  // XXX end RFC 8089 violation backwards compatibility section

  // turn /C:/blah into just C:/blah on windows
  let specPath = decodeURIComponent(specUrl.pathname)
  let resolvedPath = decodeURIComponent(resolvedUrl.pathname)
  if (isWindows) {
    specPath = specPath.replace(/^\/+([a-z]:\/)/i, '$1')
    resolvedPath = resolvedPath.replace(/^\/+([a-z]:\/)/i, '$1')
  }

  // replace ~ with homedir, but keep the ~ in the saveSpec
  // otherwise, make it relative to where param
  if (/^\/~(\/|$)/.test(specPath)) {
    res.saveSpec = `file:${specPath.substr(1)}`
    resolvedPath = path.resolve(homedir(), specPath.substr(3))
  } else if (!path.isAbsolute(rawNoPrefix)) {
    res.saveSpec = `file:${path.relative(where, resolvedPath)}`
  } else {
    res.saveSpec = `file:${path.resolve(resolvedPath)}`
  }

  res.fetchSpec = path.resolve(where, resolvedPath)
  return res
}

function fromHostedGit (res, hosted) {
  res.type = 'git'
  res.hosted = hosted
  res.saveSpec = hosted.toString({ noGitPlus: false, noCommittish: false })
  res.fetchSpec = hosted.getDefaultRepresentation() === 'shortcut' ? null : hosted.toString()
  setGitAttrs(res, hosted.committish)
  return res
}

function unsupportedURLType (protocol, spec) {
  const err = new Error(`Unsupported URL Type "${protocol}": ${spec}`)
  err.code = 'EUNSUPPORTEDPROTOCOL'
  return err
}

function fromURL (res) {
  let rawSpec = res.rawSpec
  res.saveSpec = rawSpec
  if (rawSpec.startsWith('git+ssh:')) {
    // git ssh specifiers are overloaded to also use scp-style git
    // specifiers, so we have to parse those out and treat them special.
    // They are NOT true URIs, so we can't hand them to URL.

    // This regex looks for things that look like:
    // git+ssh://git@my.custom.git.com:username/project.git#deadbeef
    // ...and various combinations. The username in the beginning is *required*.
    const matched = rawSpec.match(/^git\+ssh:\/\/([^:#]+:[^#]+(?:\.git)?)(?:#(.*))?$/i)
    // Filter out all-number "usernames" which are really port numbers
    // They can either be :1234 :1234/ or :1234/path but not :12abc
    if (matched && !matched[1].match(isPortNumber)) {
      res.type = 'git'
      setGitAttrs(res, matched[2])
      res.fetchSpec = matched[1]
      return res
    }
  } else if (rawSpec.startsWith('git+file://')) {
    // URL can't handle windows paths
    rawSpec = rawSpec.replace(/\\/g, '/')
  }
  const parsedUrl = new URL(rawSpec)
  // check the protocol, and then see if it's git or not
  switch (parsedUrl.protocol) {
    case 'git:':
    case 'git+http:':
    case 'git+https:':
    case 'git+rsync:':
    case 'git+ftp:':
    case 'git+file:':
    case 'git+ssh:':
      res.type = 'git'
      setGitAttrs(res, parsedUrl.hash.slice(1))
      if (parsedUrl.protocol === 'git+file:' && /^git\+file:\/\/[a-z]:/i.test(rawSpec)) {
        // URL can't handle drive letters on windows file paths, the host can't contain a :
        res.fetchSpec = `git+file://${parsedUrl.host.toLowerCase()}:${parsedUrl.pathname}`
      } else {
        parsedUrl.hash = ''
        res.fetchSpec = parsedUrl.toString()
      }
      if (res.fetchSpec.startsWith('git+')) {
        res.fetchSpec = res.fetchSpec.slice(4)
      }
      break
    case 'http:':
    case 'https:':
      res.type = 'remote'
      res.fetchSpec = res.saveSpec
      break

    default:
      throw unsupportedURLType(parsedUrl.protocol, rawSpec)
  }

  return res
}

function fromAlias (res, where) {
  const subSpec = npa(res.rawSpec.substr(4), where)
  if (subSpec.type === 'alias') {
    throw new Error('nested aliases not supported')
  }

  if (!subSpec.registry) {
    throw new Error('aliases only work for registry deps')
  }

  if (!subSpec.name) {
    throw new Error('aliases must have a name')
  }

  res.subSpec = subSpec
  res.registry = true
  res.type = 'alias'
  res.saveSpec = null
  res.fetchSpec = null
  return res
}

function fromRegistry (res) {
  res.registry = true
  const spec = res.rawSpec.trim()
  // no save spec for registry components as we save based on the fetched
  // version, not on the argument so this can't compute that.
  res.saveSpec = null
  res.fetchSpec = spec
  const version = semver.valid(spec, true)
  const range = semver.validRange(spec, true)
  if (version) {
    res.type = 'version'
  } else if (range) {
    res.type = 'range'
  } else {
    if (encodeURIComponent(spec) !== spec) {
      throw invalidTagName(spec, res.raw)
    }
    res.type = 'tag'
  }
  return res
}
{
  "name": "npm-package-arg",
  "version": "12.0.1",
  "description": "Parse the things that can be arguments to `npm install`",
  "main": "./lib/npa.js",
  "directories": {
    "test": "test"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "dependencies": {
    "hosted-git-info": "^8.0.0",
    "proc-log": "^5.0.0",
    "semver": "^7.3.5",
    "validate-npm-package-name": "^6.0.0"
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.4",
    "tap": "^16.0.1"
  },
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "npmclilint": "npmcli-lint",
    "lint": "npm run eslint",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "postsnap": "npm run lintfix --",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-package-arg.git"
  },
  "author": "GitHub Inc.",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/npm/npm-package-arg/issues"
  },
  "homepage": "https://github.com/npm/npm-package-arg",
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "tap": {
    "branches": 97,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.4",
    "publish": true
  }
}
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'

const { Walker: IgnoreWalker } = require('ignore-walk')
const { lstatSync: lstat, readFileSync: readFile } = require('fs')
const { basename, dirname, extname, join, relative, resolve, sep } = require('path')

// symbols used to represent synthetic rule sets
const defaultRules = Symbol('npm-packlist.rules.default')
const strictRules = Symbol('npm-packlist.rules.strict')

// There may be others, but :?|<> are handled by node-tar
const nameIsBadForWindows = file => /\*/.test(file)

// these are the default rules that are applied to everything except for non-link bundled deps
const defaults = [
  '.npmignore',
  '.gitignore',
  '**/.git',
  '**/.svn',
  '**/.hg',
  '**/CVS',
  '**/.git/**',
  '**/.svn/**',
  '**/.hg/**',
  '**/CVS/**',
  '/.lock-wscript',
  '/.wafpickle-*',
  '/build/config.gypi',
  'npm-debug.log',
  '**/.npmrc',
  '.*.swp',
  '.DS_Store',
  '**/.DS_Store/**',
  '._*',
  '**/._*/**',
  '*.orig',
  '/archived-packages/**',
]

const strictDefaults = [
  // these are forcibly excluded
  '/.git',
]

const normalizePath = (path) => path.split('\\').join('/')

const readOutOfTreeIgnoreFiles = (root, rel, result = []) => {
  for (const file of ['.npmignore', '.gitignore']) {
    try {
      const ignoreContent = readFile(join(root, file), { encoding: 'utf8' })
      result.push(ignoreContent)
      // break the loop immediately after reading, this allows us to prioritize
      // the .npmignore and discard the .gitignore if one is present
      break
    } catch (err) {
      // we ignore ENOENT errors completely because we don't care if the file doesn't exist
      // but we throw everything else because failing to read a file that does exist is
      // something that the user likely wants to know about
      // istanbul ignore next -- we do not need to test a thrown error
      if (err.code !== 'ENOENT') {
        throw err
      }
    }
  }

  if (!rel) {
    return result
  }

  const firstRel = rel.split(sep, 1)[0]
  const newRoot = join(root, firstRel)
  const newRel = relative(newRoot, join(root, rel))

  return readOutOfTreeIgnoreFiles(newRoot, newRel, result)
}

class PackWalker extends IgnoreWalker {
  constructor (tree, opts) {
    const options = {
      ...opts,
      includeEmpty: false,
      follow: false,
      // we path.resolve() here because ignore-walk doesn't do it and we want full paths
      path: resolve(opts?.path || tree.path).replace(/\\/g, '/'),
      ignoreFiles: opts?.ignoreFiles || [
        defaultRules,
        'package.json',
        '.npmignore',
        '.gitignore',
        strictRules,
      ],
    }

    super(options)
    this.isPackage = options.isPackage
    this.seen = options.seen || new Set()
    this.tree = tree
    this.requiredFiles = options.requiredFiles || []

    const additionalDefaults = []
    if (options.prefix && options.workspaces) {
      const path = normalizePath(options.path)
      const prefix = normalizePath(options.prefix)
      const workspaces = options.workspaces.map((ws) => normalizePath(ws))

      // istanbul ignore else - this does nothing unless we need it to
      if (path !== prefix && workspaces.includes(path)) {
        // if path and prefix are not the same directory, and workspaces has path in it
        // then we know path is a workspace directory. in order to not drop ignore rules
        // from directories between the workspaces root (prefix) and the workspace itself
        // (path) we need to find and read those now
        const relpath = relative(options.prefix, dirname(options.path))
        additionalDefaults.push(...readOutOfTreeIgnoreFiles(options.prefix, relpath))
      } else if (path === prefix) {
        // on the other hand, if the path and prefix are the same, then we ignore workspaces
        // so that we don't pack a workspace as part of the root project. append them as
        // normalized relative paths from the root
        additionalDefaults.push(...workspaces.map((w) => normalizePath(relative(options.path, w))))
      }
    }

    // go ahead and inject the default rules now
    this.injectRules(defaultRules, [...defaults, ...additionalDefaults])

    if (!this.isPackage) {
      // if this instance is not a package, then place some strict default rules, and append
      // known required files for this directory
      this.injectRules(strictRules, [
        ...strictDefaults,
        ...this.requiredFiles.map((file) => `!${file}`),
      ])
    }
  }

  // overridden method: we intercept the reading of the package.json file here so that we can
  // process it into both the package.json file rules as well as the strictRules synthetic rule set
  addIgnoreFile (file, callback) {
    // if we're adding anything other than package.json, then let ignore-walk handle it
    if (file !== 'package.json' || !this.isPackage) {
      return super.addIgnoreFile(file, callback)
    }

    return this.processPackage(callback)
  }

  // overridden method: if we're done, but we're a package, then we also need to evaluate bundles
  // before we actually emit our done event
  emit (ev, data) {
    if (ev !== 'done' || !this.isPackage) {
      return super.emit(ev, data)
    }

    // we intentionally delay the done event while keeping the function sync here
    // eslint-disable-next-line promise/catch-or-return, promise/always-return
    this.gatherBundles().then(() => {
      super.emit('done', this.result)
    })
    return true
  }

  // overridden method: before actually filtering, we make sure that we've removed the rules for
  // files that should no longer take effect due to our order of precedence
  filterEntries () {
    if (this.ignoreRules['package.json']) {
      // package.json means no .npmignore or .gitignore
      this.ignoreRules['.npmignore'] = null
      this.ignoreRules['.gitignore'] = null
    } else if (this.ignoreRules['.npmignore']) {
      // .npmignore means no .gitignore
      this.ignoreRules['.gitignore'] = null
    }

    return super.filterEntries()
  }

  // overridden method: we never want to include anything that isn't a file or directory
  onstat (opts, callback) {
    if (!opts.st.isFile() && !opts.st.isDirectory()) {
      return callback()
    }

    return super.onstat(opts, callback)
  }

  // overridden method: we want to refuse to pack files that are invalid, node-tar protects us from
  // a lot of them but not all
  stat (opts, callback) {
    if (nameIsBadForWindows(opts.entry)) {
      return callback()
    }

    return super.stat(opts, callback)
  }

  // overridden method: this is called to create options for a child walker when we step
  // in to a normal child directory (this will never be a bundle). the default method here
  // copies the root's `ignoreFiles` value, but we don't want to respect package.json for
  // subdirectories, so we override it with a list that intentionally omits package.json
  walkerOpt (entry, opts) {
    let ignoreFiles = null

    // however, if we have a tree, and we have workspaces, and the directory we're about
    // to step into is a workspace, then we _do_ want to respect its package.json
    if (this.tree.workspaces) {
      const workspaceDirs = [...this.tree.workspaces.values()]
        .map((dir) => dir.replace(/\\/g, '/'))

      const entryPath = join(this.path, entry).replace(/\\/g, '/')
      if (workspaceDirs.includes(entryPath)) {
        ignoreFiles = [
          defaultRules,
          'package.json',
          '.npmignore',
          '.gitignore',
          strictRules,
        ]
      }
    } else {
      ignoreFiles = [
        defaultRules,
        '.npmignore',
        '.gitignore',
        strictRules,
      ]
    }

    return {
      ...super.walkerOpt(entry, opts),
      ignoreFiles,
      // we map over our own requiredFiles and pass ones that are within this entry
      requiredFiles: this.requiredFiles
        .map((file) => {
          if (relative(file, entry) === '..') {
            return relative(entry, file).replace(/\\/g, '/')
          }
          return false
        })
        .filter(Boolean),
    }
  }

  // overridden method: we want child walkers to be instances of this class, not ignore-walk
  walker (entry, opts, callback) {
    new PackWalker(this.tree, this.walkerOpt(entry, opts)).on('done', callback).start()
  }

  // overridden method: we use a custom sort method to help compressibility
  sort (a, b) {
    // optimize for compressibility
    // extname, then basename, then locale alphabetically
    // https://twitter.com/isntitvacant/status/1131094910923231232
    const exta = extname(a).toLowerCase()
    const extb = extname(b).toLowerCase()
    const basea = basename(a).toLowerCase()
    const baseb = basename(b).toLowerCase()

    return exta.localeCompare(extb, 'en') ||
      basea.localeCompare(baseb, 'en') ||
      a.localeCompare(b, 'en')
  }

  // convenience method: this joins the given rules with newlines, appends a trailing newline,
  // and calls the internal onReadIgnoreFile method
  injectRules (filename, rules, callback = () => {}) {
    this.onReadIgnoreFile(filename, `${rules.join('\n')}\n`, callback)
  }

  // custom method: this is called by addIgnoreFile when we find a package.json, it uses the
  // arborist tree to pull both default rules and strict rules for the package
  processPackage (callback) {
    const {
      bin,
      browser,
      files,
      main,
    } = this.tree.package

    // rules in these arrays are inverted since they are patterns we want to _not_ ignore
    const ignores = []
    const strict = [
      ...strictDefaults,
      '!/package.json',
      '!/readme{,.*[^~$]}',
      '!/copying{,.*[^~$]}',
      '!/license{,.*[^~$]}',
      '!/licence{,.*[^~$]}',
      '/.git',
      '/node_modules',
      '.npmrc',
      '/package-lock.json',
      '/yarn.lock',
      '/pnpm-lock.yaml',
      '/bun.lockb',
    ]

    // if we have a files array in our package, we need to pull rules from it
    if (files) {
      for (let file of files) {
        // invert the rule because these are things we want to include
        if (file.startsWith('./')) {
          file = file.slice(1)
        }
        if (file.endsWith('/*')) {
          file += '*'
        }
        const inverse = `!${file}`
        try {
          // if an entry in the files array is a specific file, then we need to include it as a
          // strict requirement for this package. if it's a directory or a pattern, it's a default
          // pattern instead. this is ugly, but we have to stat to find out if it's a file
          const stat = lstat(join(this.path, file.replace(/^!+/, '')).replace(/\\/g, '/'))
          // if we have a file and we know that, it's strictly required
          if (stat.isFile()) {
            strict.unshift(inverse)
            this.requiredFiles.push(file.startsWith('/') ? file.slice(1) : file)
          } else if (stat.isDirectory()) {
            // otherwise, it's a default ignore, and since we got here we know it's not a pattern
            // so we include the directory contents
            ignores.push(inverse)
            ignores.push(`${inverse}/**`)
          }
          // if the thing exists, but is neither a file or a directory, we don't want it at all
        } catch (err) {
          // if lstat throws, then we assume we're looking at a pattern and treat it as a default
          ignores.push(inverse)
        }
      }

      // we prepend a '*' to exclude everything, followed by our inverted file rules
      // which now mean to include those
      this.injectRules('package.json', ['*', ...ignores])
    }

    // browser is required
    if (browser) {
      strict.push(`!/${browser}`)
    }

    // main is required
    if (main) {
      strict.push(`!/${main}`)
    }

    // each bin is required
    if (bin) {
      for (const key in bin) {
        strict.push(`!/${bin[key]}`)
      }
    }

    // and now we add all of the strict rules to our synthetic file
    this.injectRules(strictRules, strict, callback)
  }

  // custom method: after we've finished gathering the files for the root package, we call this
  // before emitting the 'done' event in order to gather all of the files for bundled deps
  async gatherBundles () {
    if (this.seen.has(this.tree)) {
      return
    }

    // add this node to our seen tracker
    this.seen.add(this.tree)

    // if we're the project root, then we look at our bundleDependencies, otherwise we got here
    // because we're a bundled dependency of the root, which means we need to include all prod
    // and optional dependencies in the bundle
    let toBundle
    if (this.tree.isProjectRoot) {
      const { bundleDependencies } = this.tree.package
      toBundle = bundleDependencies || []
    } else {
      const { dependencies, optionalDependencies } = this.tree.package
      toBundle = Object.keys(dependencies || {}).concat(Object.keys(optionalDependencies || {}))
    }

    for (const dep of toBundle) {
      const edge = this.tree.edgesOut.get(dep)
      // no edgeOut = missing node, so skip it. we can't pack it if it's not here
      // we also refuse to pack peer dependencies and dev dependencies
      if (!edge || edge.peer || edge.dev) {
        continue
      }

      // get a reference to the node we're bundling
      const node = this.tree.edgesOut.get(dep).to
      // if there's no node, this is most likely an optional dependency that hasn't been
      // installed. just skip it.
      if (!node) {
        continue
      }
      // we use node.path for the path because we want the location the node was linked to,
      // not where it actually lives on disk
      const path = node.path
      // but link nodes don't have edgesOut, so we need to pass in the target of the node
      // in order to make sure we correctly traverse its dependencies
      const tree = node.target

      // and start building options to be passed to the walker for this package
      const walkerOpts = {
        path,
        isPackage: true,
        ignoreFiles: [],
        seen: this.seen, // pass through seen so we can prevent infinite circular loops
      }

      // if our node is a link, we apply defaultRules. we don't do this for regular bundled
      // deps because their .npmignore and .gitignore files are excluded by default and may
      // override defaults
      if (node.isLink) {
        walkerOpts.ignoreFiles.push(defaultRules)
      }

      // _all_ nodes will follow package.json rules from their package root
      walkerOpts.ignoreFiles.push('package.json')

      // only link nodes will obey .npmignore or .gitignore
      if (node.isLink) {
        walkerOpts.ignoreFiles.push('.npmignore')
        walkerOpts.ignoreFiles.push('.gitignore')
      }

      // _all_ nodes follow strict rules
      walkerOpts.ignoreFiles.push(strictRules)

      // create a walker for this dependency and gather its results
      const walker = new PackWalker(tree, walkerOpts)
      const bundled = await new Promise((pResolve, pReject) => {
        walker.on('error', pReject)
        walker.on('done', pResolve)
        walker.start()
      })

      // now we make sure we have our paths correct from the root, and accumulate everything into
      // our own result set to deduplicate
      const relativeFrom = relative(this.root, walker.path)
      for (const file of bundled) {
        this.result.add(join(relativeFrom, file).replace(/\\/g, '/'))
      }
    }
  }
}

const walk = (tree, options, callback) => {
  if (typeof options === 'function') {
    callback = options
    options = {}
  }
  const p = new Promise((pResolve, pReject) => {
    new PackWalker(tree, { ...options, isPackage: true })
      .on('done', pResolve).on('error', pReject).start()
  })
  return callback ? p.then(res => callback(null, res), callback) : p
}

module.exports = walk
walk.Walker = PackWalker
{
  "name": "npm-packlist",
  "version": "10.0.0",
  "description": "Get a list of the files to add from a folder into an npm package",
  "directories": {
    "test": "test"
  },
  "main": "lib/index.js",
  "dependencies": {
    "ignore-walk": "^7.0.0"
  },
  "author": "GitHub Inc.",
  "license": "ISC",
  "files": [
    "bin/",
    "lib/"
  ],
  "devDependencies": {
    "@npmcli/arborist": "^8.0.0",
    "@npmcli/eslint-config": "^5.0.1",
    "@npmcli/template-oss": "4.23.4",
    "mutate-fs": "^2.1.1",
    "tap": "^16.0.1"
  },
  "scripts": {
    "test": "tap",
    "posttest": "npm run lint",
    "snap": "tap",
    "postsnap": "npm run lintfix --",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lint": "npm run eslint",
    "lintfix": "npm run eslint -- --fix",
    "npmclilint": "npmcli-lint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-packlist.git"
  },
  "tap": {
    "test-env": [
      "LC_ALL=sk"
    ],
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ],
    "files": [
      "test/*.js"
    ]
  },
  "engines": {
    "node": "^20.17.0 || >=22.9.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.4",
    "publish": true
  }
}
ISC License

Copyright (c) npm, Inc.

Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS
ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'

const npa = require('npm-package-arg')
const semver = require('semver')
const { checkEngine } = require('npm-install-checks')
const normalizeBin = require('npm-normalize-package-bin')

const engineOk = (manifest, npmVersion, nodeVersion) => {
  try {
    checkEngine(manifest, npmVersion, nodeVersion)
    return true
  } catch (_) {
    return false
  }
}

const isBefore = (verTimes, ver, time) =>
  !verTimes || !verTimes[ver] || Date.parse(verTimes[ver]) <= time

const avoidSemverOpt = { includePrerelease: true, loose: true }
const shouldAvoid = (ver, avoid) =>
  avoid && semver.satisfies(ver, avoid, avoidSemverOpt)

const decorateAvoid = (result, avoid) =>
  result && shouldAvoid(result.version, avoid)
    ? { ...result, _shouldAvoid: true }
    : result

const pickManifest = (packument, wanted, opts) => {
  const {
    defaultTag = 'latest',
    before = null,
    nodeVersion = process.version,
    npmVersion = null,
    includeStaged = false,
    avoid = null,
    avoidStrict = false,
  } = opts

  const { name, time: verTimes } = packument
  const versions = packument.versions || {}

  if (avoidStrict) {
    const looseOpts = {
      ...opts,
      avoidStrict: false,
    }

    const result = pickManifest(packument, wanted, looseOpts)
    if (!result || !result._shouldAvoid) {
      return result
    }

    const caret = pickManifest(packument, `^${result.version}`, looseOpts)
    if (!caret || !caret._shouldAvoid) {
      return {
        ...caret,
        _outsideDependencyRange: true,
        _isSemVerMajor: false,
      }
    }

    const star = pickManifest(packument, '*', looseOpts)
    if (!star || !star._shouldAvoid) {
      return {
        ...star,
        _outsideDependencyRange: true,
        _isSemVerMajor: true,
      }
    }

    throw Object.assign(new Error(`No avoidable versions for ${name}`), {
      code: 'ETARGET',
      name,
      wanted,
      avoid,
      before,
      versions: Object.keys(versions),
    })
  }

  const staged = (includeStaged && packument.stagedVersions &&
    packument.stagedVersions.versions) || {}
  const restricted = (packument.policyRestrictions &&
    packument.policyRestrictions.versions) || {}

  const time = before && verTimes ? +(new Date(before)) : Infinity
  const spec = npa.resolve(name, wanted || defaultTag)
  const type = spec.type
  const distTags = packument['dist-tags'] || {}

  if (type !== 'tag' && type !== 'version' && type !== 'range') {
    throw new Error('Only tag, version, and range are supported')
  }

  // if the type is 'tag', and not just the implicit default, then it must
  // be that exactly, or nothing else will do.
  if (wanted && type === 'tag') {
    const ver = distTags[wanted]
    // if the version in the dist-tags is before the before date, then
    // we use that.  Otherwise, we get the highest precedence version
    // prior to the dist-tag.
    if (isBefore(verTimes, ver, time)) {
      return decorateAvoid(versions[ver] || staged[ver] || restricted[ver], avoid)
    } else {
      return pickManifest(packument, `<=${ver}`, opts)
    }
  }

  // similarly, if a specific version, then only that version will do
  if (wanted && type === 'version') {
    const ver = semver.clean(wanted, { loose: true })
    const mani = versions[ver] || staged[ver] || restricted[ver]
    return isBefore(verTimes, ver, time) ? decorateAvoid(mani, avoid) : null
  }

  // ok, sort based on our heuristics, and pick the best fit
  const range = type === 'range' ? wanted : '*'

  // if the range is *, then we prefer the 'latest' if available
  // but skip this if it should be avoided, in that case we have
  // to try a little harder.
  const defaultVer = distTags[defaultTag]
  if (defaultVer &&
      (range === '*' || semver.satisfies(defaultVer, range, { loose: true })) &&
      !restricted[defaultVer] &&
      !shouldAvoid(defaultVer, avoid)) {
    const mani = versions[defaultVer]
    const ok = mani &&
      isBefore(verTimes, defaultVer, time) &&
      engineOk(mani, npmVersion, nodeVersion) &&
      !mani.deprecated &&
      !staged[defaultVer]
    if (ok) {
      return mani
    }
  }

  // ok, actually have to sort the list and take the winner
  const allEntries = Object.entries(versions)
    .concat(Object.entries(staged))
    .concat(Object.entries(restricted))
    .filter(([ver]) => isBefore(verTimes, ver, time))

  if (!allEntries.length) {
    throw Object.assign(new Error(`No versions available for ${name}`), {
      code: 'ENOVERSIONS',
      name,
      type,
      wanted,
      before,
      versions: Object.keys(versions),
    })
  }

  const sortSemverOpt = { loose: true }
  const entries = allEntries.filter(([ver]) =>
    semver.satisfies(ver, range, { loose: true }))
    .sort((a, b) => {
      const [vera, mania] = a
      const [verb, manib] = b
      const notavoida = !shouldAvoid(vera, avoid)
      const notavoidb = !shouldAvoid(verb, avoid)
      const notrestra = !restricted[vera]
      const notrestrb = !restricted[verb]
      const notstagea = !staged[vera]
      const notstageb = !staged[verb]
      const notdepra = !mania.deprecated
      const notdeprb = !manib.deprecated
      const enginea = engineOk(mania, npmVersion, nodeVersion)
      const engineb = engineOk(manib, npmVersion, nodeVersion)
      // sort by:
      // - not an avoided version
      // - not restricted
      // - not staged
      // - not deprecated and engine ok
      // - engine ok
      // - not deprecated
      // - semver
      return (notavoidb - notavoida) ||
        (notrestrb - notrestra) ||
        (notstageb - notstagea) ||
        ((notdeprb && engineb) - (notdepra && enginea)) ||
        (engineb - enginea) ||
        (notdeprb - notdepra) ||
        semver.rcompare(vera, verb, sortSemverOpt)
    })

  return decorateAvoid(entries[0] && entries[0][1], avoid)
}

module.exports = (packument, wanted, opts = {}) => {
  const mani = pickManifest(packument, wanted, opts)
  const picked = mani && normalizeBin(mani)
  const policyRestrictions = packument.policyRestrictions
  const restricted = (policyRestrictions && policyRestrictions.versions) || {}

  if (picked && !restricted[picked.version]) {
    return picked
  }

  const { before = null, defaultTag = 'latest' } = opts
  const bstr = before ? new Date(before).toLocaleString() : ''
  const { name } = packument
  const pckg = `${name}@${wanted}` +
    (before ? ` with a date before ${bstr}` : '')

  const isForbidden = picked && !!restricted[picked.version]
  const polMsg = isForbidden ? policyRestrictions.message : ''

  const msg = !isForbidden ? `No matching version found for ${pckg}.`
    : `Could not download ${pckg} due to policy violations:\n${polMsg}`

  const code = isForbidden ? 'E403' : 'ETARGET'
  throw Object.assign(new Error(msg), {
    code,
    type: npa.resolve(packument.name, wanted).type,
    wanted,
    versions: Object.keys(packument.versions ?? {}),
    name,
    distTags: packument['dist-tags'],
    defaultTag,
  })
}
{
  "name": "npm-pick-manifest",
  "version": "10.0.0",
  "description": "Resolves a matching manifest from a package metadata document according to standard npm semver resolution rules.",
  "main": "./lib",
  "files": [
    "bin/",
    "lib/"
  ],
  "scripts": {
    "coverage": "tap",
    "lint": "npm run eslint",
    "test": "tap",
    "posttest": "npm run lint",
    "postlint": "template-oss-check",
    "lintfix": "npm run eslint -- --fix",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-pick-manifest.git"
  },
  "keywords": [
    "npm",
    "semver",
    "package manager"
  ],
  "author": "GitHub Inc.",
  "license": "ISC",
  "dependencies": {
    "npm-install-checks": "^7.1.0",
    "npm-normalize-package-bin": "^4.0.0",
    "npm-package-arg": "^12.0.0",
    "semver": "^7.3.5"
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.0.1"
  },
  "tap": {
    "check-coverage": true,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  }
}


ISC License

Copyright npm, Inc.

Permission to use, copy, modify, and/or distribute this
software for any purpose with or without fee is hereby
granted, provided that the above copyright notice and this
permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
USE OR PERFORMANCE OF THIS SOFTWARE.
const { URL } = require('node:url')
const timers = require('node:timers/promises')
const fetch = require('npm-registry-fetch')
const { HttpErrorBase } = require('npm-registry-fetch/lib/errors')
const { log } = require('proc-log')

// try loginWeb, catch the "not supported" message and fall back to couch
const login = async (opener, prompter, opts = {}) => {
  try {
    return await loginWeb(opener, opts)
  } catch (er) {
    if (er instanceof WebLoginNotSupported) {
      log.verbose('web login', 'not supported, trying couch')
      const { username, password } = await prompter(opts.creds)
      return loginCouch(username, password, opts)
    }
    throw er
  }
}

const adduser = async (opener, prompter, opts = {}) => {
  try {
    return await adduserWeb(opener, opts)
  } catch (er) {
    if (er instanceof WebLoginNotSupported) {
      log.verbose('web adduser', 'not supported, trying couch')
      const { username, email, password } = await prompter(opts.creds)
      return adduserCouch(username, email, password, opts)
    }
    throw er
  }
}

const adduserWeb = (opener, opts = {}) => {
  log.verbose('web adduser', 'before first POST')
  return webAuth(opener, opts, { create: true })
}

const loginWeb = (opener, opts = {}) => {
  log.verbose('web login', 'before first POST')
  return webAuth(opener, opts, {})
}

const isValidUrl = u => {
  try {
    return /^https?:$/.test(new URL(u).protocol)
  } catch {
    return false
  }
}

const webAuth = async (opener, opts, body) => {
  try {
    const res = await fetch('/-/v1/login', {
      ...opts,
      method: 'POST',
      body,
    })

    const content = await res.json()
    log.verbose('web auth', 'got response', content)

    const { doneUrl, loginUrl } = content
    if (!isValidUrl(doneUrl) || !isValidUrl(loginUrl)) {
      throw new WebLoginInvalidResponse('POST', res, content)
    }

    return await webAuthOpener(opener, loginUrl, doneUrl, opts)
  } catch (er) {
    if ((er.statusCode >= 400 && er.statusCode <= 499) || er.statusCode === 500) {
      throw new WebLoginNotSupported('POST', {
        status: er.statusCode,
        headers: er.headers,
      }, er.body)
    }
    throw er
  }
}

const webAuthOpener = async (opener, loginUrl, doneUrl, opts) => {
  const abortController = new AbortController()
  const { signal } = abortController
  try {
    log.verbose('web auth', 'opening url pair')
    const [, authResult] = await Promise.all([
      opener(loginUrl, { signal }).catch((err) => {
        if (err.name === 'AbortError') {
          abortController.abort()
          return
        }
        throw err
      }),
      webAuthCheckLogin(doneUrl, { ...opts, cache: false }, { signal }).then((r) => {
        log.verbose('web auth', 'done-check finished')
        abortController.abort()
        return r
      }),
    ])
    return authResult
  } catch (er) {
    abortController.abort()
    throw er
  }
}

const webAuthCheckLogin = async (doneUrl, opts, { signal } = {}) => {
  signal?.throwIfAborted()

  const res = await fetch(doneUrl, opts)
  const content = await res.json()

  if (res.status === 200) {
    if (!content.token) {
      throw new WebLoginInvalidResponse('GET', res, content)
    }
    return content
  }

  if (res.status === 202) {
    const retry = +res.headers.get('retry-after') * 1000
    if (retry > 0) {
      await timers.setTimeout(retry, null, { signal })
    }
    return webAuthCheckLogin(doneUrl, opts, { signal })
  }

  throw new WebLoginInvalidResponse('GET', res, content)
}

const couchEndpoint = (username) => `/-/user/org.couchdb.user:${encodeURIComponent(username)}`

const putCouch = async (path, username, body, opts) => {
  const result = await fetch.json(`${couchEndpoint(username)}${path}`, {
    ...opts,
    method: 'PUT',
    body,
  })
  result.username = username
  return result
}

const adduserCouch = async (username, email, password, opts = {}) => {
  const body = {
    _id: `org.couchdb.user:${username}`,
    name: username,
    password: password,
    email: email,
    type: 'user',
    roles: [],
    date: new Date().toISOString(),
  }

  log.verbose('adduser', 'before first PUT', {
    ...body,
    password: 'XXXXX',
  })

  return putCouch('', username, body, opts)
}

const loginCouch = async (username, password, opts = {}) => {
  const body = {
    _id: `org.couchdb.user:${username}`,
    name: username,
    password: password,
    type: 'user',
    roles: [],
    date: new Date().toISOString(),
  }

  log.verbose('login', 'before first PUT', {
    ...body,
    password: 'XXXXX',
  })

  try {
    return await putCouch('', username, body, opts)
  } catch (err) {
    if (err.code === 'E400') {
      err.message = `There is no user with the username "${username}".`
      throw err
    }

    if (err.code !== 'E409') {
      throw err
    }
  }

  const result = await fetch.json(couchEndpoint(username), {
    ...opts,
    query: { write: true },
  })

  for (const k of Object.keys(result)) {
    if (!body[k] || k === 'roles') {
      body[k] = result[k]
    }
  }

  return putCouch(`/-rev/${body._rev}`, username, body, {
    ...opts,
    forceAuth: {
      username,
      password: Buffer.from(password, 'utf8').toString('base64'),
      otp: opts.otp,
    },
  })
}

const get = (opts = {}) => fetch.json('/-/npm/v1/user', opts)

const set = (profile, opts = {}) => fetch.json('/-/npm/v1/user', {
  ...opts,
  method: 'POST',
  // profile keys can't be empty strings, but they CAN be null
  body: Object.fromEntries(Object.entries(profile).map(([k, v]) => [k, v === '' ? null : v])),
})

const paginate = async (href, opts, items = []) => {
  const result = await fetch.json(href, opts)
  items = items.concat(result.objects)
  if (result.urls.next) {
    return paginate(result.urls.next, opts, items)
  }
  return items
}

const listTokens = (opts = {}) => paginate('/-/npm/v1/tokens', opts)

const removeToken = async (tokenKey, opts = {}) => {
  await fetch(`/-/npm/v1/tokens/token/${tokenKey}`, {
    ...opts,
    method: 'DELETE',
    ignoreBody: true,
  })
  return null
}

const createToken = (password, readonly, cidrs, opts = {}) => fetch.json('/-/npm/v1/tokens', {
  ...opts,
  method: 'POST',
  body: {
    password: password,
    readonly: readonly,
    cidr_whitelist: cidrs,
  },
})

class WebLoginInvalidResponse extends HttpErrorBase {
  constructor (method, res, body) {
    super(method, res, body)
    this.message = 'Invalid response from web login endpoint'
  }
}

class WebLoginNotSupported extends HttpErrorBase {
  constructor (method, res, body) {
    super(method, res, body)
    this.message = 'Web login not supported'
    this.code = 'ENYI'
  }
}

module.exports = {
  adduserCouch,
  loginCouch,
  adduserWeb,
  loginWeb,
  login,
  adduser,
  get,
  set,
  listTokens,
  removeToken,
  createToken,
  webAuthCheckLogin,
  webAuthOpener,
}
{
  "name": "npm-profile",
  "version": "11.0.1",
  "description": "Library for updating an npmjs.com profile",
  "keywords": [],
  "author": "GitHub Inc.",
  "license": "ISC",
  "dependencies": {
    "npm-registry-fetch": "^18.0.0",
    "proc-log": "^5.0.0"
  },
  "main": "./lib/index.js",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-profile.git"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "nock": "^13.2.4",
    "tap": "^16.0.1"
  },
  "scripts": {
    "posttest": "npm run lint",
    "test": "tap",
    "snap": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "lintfix": "npm run eslint -- --fix",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "tap": {
    "check-coverage": true,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  }
}


ISC License

Copyright npm, Inc.

Permission to use, copy, modify, and/or distribute this
software for any purpose with or without fee is hereby
granted, provided that the above copyright notice and this
permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
USE OR PERFORMANCE OF THIS SOFTWARE.
'use strict'
const fs = require('fs')
const npa = require('npm-package-arg')
const { URL } = require('url')

// Find the longest registry key that is used for some kind of auth
// in the options.  Returns the registry key and the auth config.
const regFromURI = (uri, opts) => {
  const parsed = new URL(uri)
  // try to find a config key indicating we have auth for this registry
  // can be one of :_authToken, :_auth, :_password and :username, or
  // :certfile and :keyfile
  // We walk up the "path" until we're left with just //[:],
  // stopping when we reach '//'.
  let regKey = `//${parsed.host}${parsed.pathname}`
  while (regKey.length > '//'.length) {
    const authKey = hasAuth(regKey, opts)
    // got some auth for this URI
    if (authKey) {
      return { regKey, authKey }
    }

    // can be either //host/some/path/:_auth or //host/some/path:_auth
    // walk up by removing EITHER what's after the slash OR the slash itself
    regKey = regKey.replace(/([^/]+|\/)$/, '')
  }
  return { regKey: false, authKey: null }
}

// Not only do we want to know if there is auth, but if we are calling `npm
// logout` we want to know what config value specifically provided it.  This is
// so we can look up where the config came from to delete it (i.e. user vs
// project)
const hasAuth = (regKey, opts) => {
  if (opts[`${regKey}:_authToken`]) {
    return '_authToken'
  }
  if (opts[`${regKey}:_auth`]) {
    return '_auth'
  }
  if (opts[`${regKey}:username`] && opts[`${regKey}:_password`]) {
    // 'password' can be inferred to also be present
    return 'username'
  }
  if (opts[`${regKey}:certfile`] && opts[`${regKey}:keyfile`]) {
    // 'keyfile' can be inferred to also be present
    return 'certfile'
  }
  return false
}

const sameHost = (a, b) => {
  const parsedA = new URL(a)
  const parsedB = new URL(b)
  return parsedA.host === parsedB.host
}

const getRegistry = opts => {
  const { spec } = opts
  const { scope: specScope, subSpec } = spec ? npa(spec) : {}
  const subSpecScope = subSpec && subSpec.scope
  const scope = subSpec ? subSpecScope : specScope
  const scopeReg = scope && opts[`${scope}:registry`]
  return scopeReg || opts.registry
}

const maybeReadFile = file => {
  try {
    return fs.readFileSync(file, 'utf8')
  } catch (er) {
    if (er.code !== 'ENOENT') {
      throw er
    }
    return null
  }
}

const getAuth = (uri, opts = {}) => {
  const { forceAuth } = opts
  if (!uri) {
    throw new Error('URI is required')
  }
  const { regKey, authKey } = regFromURI(uri, forceAuth || opts)

  // we are only allowed to use what's in forceAuth if specified
  if (forceAuth && !regKey) {
    return new Auth({
      // if we force auth we don't want to refer back to anything in config
      regKey: false,
      authKey: null,
      scopeAuthKey: null,
      token: forceAuth._authToken || forceAuth.token,
      username: forceAuth.username,
      password: forceAuth._password || forceAuth.password,
      auth: forceAuth._auth || forceAuth.auth,
      certfile: forceAuth.certfile,
      keyfile: forceAuth.keyfile,
    })
  }

  // no auth for this URI, but might have it for the registry
  if (!regKey) {
    const registry = getRegistry(opts)
    if (registry && uri !== registry && sameHost(uri, registry)) {
      return getAuth(registry, opts)
    } else if (registry !== opts.registry) {
      // If making a tarball request to a different base URI than the
      // registry where we logged in, but the same auth SHOULD be sent
      // to that artifact host, then we track where it was coming in from,
      // and warn the user if we get a 4xx error on it.
      const { regKey: scopeAuthKey, authKey: _authKey } = regFromURI(registry, opts)
      return new Auth({ scopeAuthKey, regKey: scopeAuthKey, authKey: _authKey })
    }
  }

  const {
    [`${regKey}:_authToken`]: token,
    [`${regKey}:username`]: username,
    [`${regKey}:_password`]: password,
    [`${regKey}:_auth`]: auth,
    [`${regKey}:certfile`]: certfile,
    [`${regKey}:keyfile`]: keyfile,
  } = opts

  return new Auth({
    scopeAuthKey: null,
    regKey,
    authKey,
    token,
    auth,
    username,
    password,
    certfile,
    keyfile,
  })
}

class Auth {
  constructor ({
    token,
    auth,
    username,
    password,
    scopeAuthKey,
    certfile,
    keyfile,
    regKey,
    authKey,
  }) {
    // same as regKey but only present for scoped auth. Should have been named scopeRegKey
    this.scopeAuthKey = scopeAuthKey
    // `${regKey}:${authKey}` will get you back to the auth config that gave us auth
    this.regKey = regKey
    this.authKey = authKey
    this.token = null
    this.auth = null
    this.isBasicAuth = false
    this.cert = null
    this.key = null
    if (token) {
      this.token = token
    } else if (auth) {
      this.auth = auth
    } else if (username && password) {
      const p = Buffer.from(password, 'base64').toString('utf8')
      this.auth = Buffer.from(`${username}:${p}`, 'utf8').toString('base64')
      this.isBasicAuth = true
    }
    // mTLS may be used in conjunction with another auth method above
    if (certfile && keyfile) {
      const cert = maybeReadFile(certfile, 'utf-8')
      const key = maybeReadFile(keyfile, 'utf-8')
      if (cert && key) {
        this.cert = cert
        this.key = key
      }
    }
  }
}

module.exports = getAuth
'use strict'

const errors = require('./errors.js')
const { Response } = require('minipass-fetch')
const defaultOpts = require('./default-opts.js')
const { log } = require('proc-log')
const { redact: cleanUrl } = require('@npmcli/redact')

/* eslint-disable-next-line max-len */
const moreInfoUrl = 'https://github.com/npm/cli/wiki/No-auth-for-URI,-but-auth-present-for-scoped-registry'
const checkResponse =
  async ({ method, uri, res, startTime, auth, opts }) => {
    opts = { ...defaultOpts, ...opts }
    if (res.headers.has('npm-notice') && !res.headers.has('x-local-cache')) {
      log.notice('', res.headers.get('npm-notice'))
    }

    if (res.status >= 400) {
      logRequest(method, res, startTime)
      if (auth && auth.scopeAuthKey && !auth.token && !auth.auth) {
      // we didn't have auth for THIS request, but we do have auth for
      // requests to the registry indicated by the spec's scope value.
      // Warn the user.
        log.warn('registry', `No auth for URI, but auth present for scoped registry.

URI: ${uri}
Scoped Registry Key: ${auth.scopeAuthKey}

More info here: ${moreInfoUrl}`)
      }
      return checkErrors(method, res, startTime, opts)
    } else {
      res.body.on('end', () => logRequest(method, res, startTime, opts))
      if (opts.ignoreBody) {
        res.body.resume()
        return new Response(null, res)
      }
      return res
    }
  }
module.exports = checkResponse

function logRequest (method, res, startTime) {
  const elapsedTime = Date.now() - startTime
  const attempt = res.headers.get('x-fetch-attempts')
  const attemptStr = attempt && attempt > 1 ? ` attempt #${attempt}` : ''
  const cacheStatus = res.headers.get('x-local-cache-status')
  const cacheStr = cacheStatus ? ` (cache ${cacheStatus})` : ''
  const urlStr = cleanUrl(res.url)

  // If make-fetch-happen reports a cache hit, then there was no fetch
  if (cacheStatus === 'hit') {
    log.http(
      'cache',
      `${urlStr} ${elapsedTime}ms${attemptStr}${cacheStr}`
    )
  } else {
    log.http(
      'fetch',
      `${method.toUpperCase()} ${res.status} ${urlStr} ${elapsedTime}ms${attemptStr}${cacheStr}`
    )
  }
}

function checkErrors (method, res, startTime, opts) {
  return res.buffer()
    .catch(() => null)
    .then(body => {
      let parsed = body
      try {
        parsed = JSON.parse(body.toString('utf8'))
      } catch {
        // ignore errors
      }
      if (res.status === 401 && res.headers.get('www-authenticate')) {
        const auth = res.headers.get('www-authenticate')
          .split(/,\s*/)
          .map(s => s.toLowerCase())
        if (auth.indexOf('ipaddress') !== -1) {
          throw new errors.HttpErrorAuthIPAddress(
            method, res, parsed, opts.spec
          )
        } else if (auth.indexOf('otp') !== -1) {
          throw new errors.HttpErrorAuthOTP(
            method, res, parsed, opts.spec
          )
        } else {
          throw new errors.HttpErrorAuthUnknown(
            method, res, parsed, opts.spec
          )
        }
      } else if (
        res.status === 401 &&
        body != null &&
        /one-time pass/.test(body.toString('utf8'))
      ) {
        // Heuristic for malformed OTP responses that don't include the
        // www-authenticate header.
        throw new errors.HttpErrorAuthOTP(
          method, res, parsed, opts.spec
        )
      } else {
        throw new errors.HttpErrorGeneral(
          method, res, parsed, opts.spec
        )
      }
    })
}
const pkg = require('../package.json')
module.exports = {
  maxSockets: 12,
  method: 'GET',
  registry: 'https://registry.npmjs.org/',
  timeout: 5 * 60 * 1000, // 5 minutes
  strictSSL: true,
  noProxy: process.env.NOPROXY,
  userAgent: `${pkg.name
    }@${
      pkg.version
    }/node@${
      process.version
    }+${
      process.arch
    } (${
      process.platform
    })`,
}
'use strict'

const { URL } = require('node:url')

function packageName (href) {
  try {
    let basePath = new URL(href).pathname.slice(1)
    if (!basePath.match(/^-/)) {
      basePath = basePath.split('/')
      var index = basePath.indexOf('_rewrite')
      if (index === -1) {
        index = basePath.length - 1
      } else {
        index++
      }
      return decodeURIComponent(basePath[index])
    }
  } catch {
    // this is ok
  }
}

class HttpErrorBase extends Error {
  constructor (method, res, body, spec) {
    super()
    this.name = this.constructor.name
    this.headers = typeof res.headers?.raw === 'function' ? res.headers.raw() : res.headers
    this.statusCode = res.status
    this.code = `E${res.status}`
    this.method = method
    this.uri = res.url
    this.body = body
    this.pkgid = spec ? spec.toString() : packageName(res.url)
    Error.captureStackTrace(this, this.constructor)
  }
}

class HttpErrorGeneral extends HttpErrorBase {
  constructor (method, res, body, spec) {
    super(method, res, body, spec)
    this.message = `${res.status} ${res.statusText} - ${
      this.method.toUpperCase()
    } ${
      this.spec || this.uri
    }${
      (body && body.error) ? ' - ' + body.error : ''
    }`
  }
}

class HttpErrorAuthOTP extends HttpErrorBase {
  constructor (method, res, body, spec) {
    super(method, res, body, spec)
    this.message = 'OTP required for authentication'
    this.code = 'EOTP'
  }
}

class HttpErrorAuthIPAddress extends HttpErrorBase {
  constructor (method, res, body, spec) {
    super(method, res, body, spec)
    this.message = 'Login is not allowed from your IP address'
    this.code = 'EAUTHIP'
  }
}

class HttpErrorAuthUnknown extends HttpErrorBase {
  constructor (method, res, body, spec) {
    super(method, res, body, spec)
    this.message = 'Unable to authenticate, need: ' + res.headers.get('www-authenticate')
  }
}

module.exports = {
  HttpErrorBase,
  HttpErrorGeneral,
  HttpErrorAuthOTP,
  HttpErrorAuthIPAddress,
  HttpErrorAuthUnknown,
}
'use strict'

const { HttpErrorAuthOTP } = require('./errors.js')
const checkResponse = require('./check-response.js')
const getAuth = require('./auth.js')
const fetch = require('make-fetch-happen')
const JSONStream = require('./json-stream')
const npa = require('npm-package-arg')
const qs = require('querystring')
const url = require('url')
const zlib = require('minizlib')
const { Minipass } = require('minipass')

const defaultOpts = require('./default-opts.js')

// WhatWG URL throws if it's not fully resolved
const urlIsValid = u => {
  try {
    return !!new url.URL(u)
  } catch (_) {
    return false
  }
}

module.exports = regFetch
function regFetch (uri, /* istanbul ignore next */ opts_ = {}) {
  const opts = {
    ...defaultOpts,
    ...opts_,
  }

  // if we did not get a fully qualified URI, then we look at the registry
  // config or relevant scope to resolve it.
  const uriValid = urlIsValid(uri)
  let registry = opts.registry || defaultOpts.registry
  if (!uriValid) {
    registry = opts.registry = (
      (opts.spec && pickRegistry(opts.spec, opts)) ||
      opts.registry ||
      registry
    )
    uri = `${
      registry.trim().replace(/\/?$/g, '')
    }/${
      uri.trim().replace(/^\//, '')
    }`
    // asserts that this is now valid
    new url.URL(uri)
  }

  const method = opts.method || 'GET'

  // through that takes into account the scope, the prefix of `uri`, etc
  const startTime = Date.now()
  const auth = getAuth(uri, opts)
  const headers = getHeaders(uri, auth, opts)
  let body = opts.body
  const bodyIsStream = Minipass.isStream(body)
  const bodyIsPromise = body &&
    typeof body === 'object' &&
    typeof body.then === 'function'

  if (
    body && !bodyIsStream && !bodyIsPromise && typeof body !== 'string' && !Buffer.isBuffer(body)
  ) {
    headers['content-type'] = headers['content-type'] || 'application/json'
    body = JSON.stringify(body)
  } else if (body && !headers['content-type']) {
    headers['content-type'] = 'application/octet-stream'
  }

  if (opts.gzip) {
    headers['content-encoding'] = 'gzip'
    if (bodyIsStream) {
      const gz = new zlib.Gzip()
      body.on('error', /* istanbul ignore next: unlikely and hard to test */
        err => gz.emit('error', err))
      body = body.pipe(gz)
    } else if (!bodyIsPromise) {
      body = new zlib.Gzip().end(body).concat()
    }
  }

  const parsed = new url.URL(uri)

  if (opts.query) {
    const q = typeof opts.query === 'string' ? qs.parse(opts.query)
      : opts.query

    Object.keys(q).forEach(key => {
      if (q[key] !== undefined) {
        parsed.searchParams.set(key, q[key])
      }
    })
    uri = url.format(parsed)
  }

  if (parsed.searchParams.get('write') === 'true' && method === 'GET') {
    // do not cache, because this GET is fetching a rev that will be
    // used for a subsequent PUT or DELETE, so we need to conditionally
    // update cache.
    opts.offline = false
    opts.preferOffline = false
    opts.preferOnline = true
  }

  const doFetch = async fetchBody => {
    const p = fetch(uri, {
      agent: opts.agent,
      algorithms: opts.algorithms,
      body: fetchBody,
      cache: getCacheMode(opts),
      cachePath: opts.cache,
      ca: opts.ca,
      cert: auth.cert || opts.cert,
      headers,
      integrity: opts.integrity,
      key: auth.key || opts.key,
      localAddress: opts.localAddress,
      maxSockets: opts.maxSockets,
      memoize: opts.memoize,
      method: method,
      noProxy: opts.noProxy,
      proxy: opts.httpsProxy || opts.proxy,
      retry: opts.retry ? opts.retry : {
        retries: opts.fetchRetries,
        factor: opts.fetchRetryFactor,
        minTimeout: opts.fetchRetryMintimeout,
        maxTimeout: opts.fetchRetryMaxtimeout,
      },
      strictSSL: opts.strictSSL,
      timeout: opts.timeout || 30 * 1000,
    }).then(res => checkResponse({
      method,
      uri,
      res,
      registry,
      startTime,
      auth,
      opts,
    }))

    if (typeof opts.otpPrompt === 'function') {
      return p.catch(async er => {
        if (er instanceof HttpErrorAuthOTP) {
          let otp
          // if otp fails to complete, we fail with that failure
          try {
            otp = await opts.otpPrompt()
          } catch (_) {
            // ignore this error
          }
          // if no otp provided, or otpPrompt errored, throw the original HTTP error
          if (!otp) {
            throw er
          }
          return regFetch(uri, { ...opts, otp })
        }
        throw er
      })
    } else {
      return p
    }
  }

  return Promise.resolve(body).then(doFetch)
}

module.exports.getAuth = getAuth

module.exports.json = fetchJSON
function fetchJSON (uri, opts) {
  return regFetch(uri, opts).then(res => res.json())
}

module.exports.json.stream = fetchJSONStream
function fetchJSONStream (uri, jsonPath,
  /* istanbul ignore next */ opts_ = {}) {
  const opts = { ...defaultOpts, ...opts_ }
  const parser = JSONStream.parse(jsonPath, opts.mapJSON)
  regFetch(uri, opts).then(res =>
    res.body.on('error',
      /* istanbul ignore next: unlikely and difficult to test */
      er => parser.emit('error', er)).pipe(parser)
  ).catch(er => parser.emit('error', er))
  return parser
}

module.exports.pickRegistry = pickRegistry
function pickRegistry (spec, opts = {}) {
  spec = npa(spec)
  let registry = spec.scope &&
    opts[spec.scope.replace(/^@?/, '@') + ':registry']

  if (!registry && opts.scope) {
    registry = opts[opts.scope.replace(/^@?/, '@') + ':registry']
  }

  if (!registry) {
    registry = opts.registry || defaultOpts.registry
  }

  return registry
}

function getCacheMode (opts) {
  return opts.offline ? 'only-if-cached'
    : opts.preferOffline ? 'force-cache'
    : opts.preferOnline ? 'no-cache'
    : 'default'
}

function getHeaders (uri, auth, opts) {
  const headers = Object.assign({
    'user-agent': opts.userAgent,
  }, opts.headers || {})

  if (opts.authType) {
    headers['npm-auth-type'] = opts.authType
  }

  if (opts.scope) {
    headers['npm-scope'] = opts.scope
  }

  if (opts.npmSession) {
    headers['npm-session'] = opts.npmSession
  }

  if (opts.npmCommand) {
    headers['npm-command'] = opts.npmCommand
  }

  // If a tarball is hosted on a different place than the manifest, only send
  // credentials on `alwaysAuth`
  if (auth.token) {
    headers.authorization = `Bearer ${auth.token}`
  } else if (auth.auth) {
    headers.authorization = `Basic ${auth.auth}`
  }

  if (opts.otp) {
    headers['npm-otp'] = opts.otp
  }

  return headers
}
const Parser = require('jsonparse')
const { Minipass } = require('minipass')

class JSONStreamError extends Error {
  constructor (err, caller) {
    super(err.message)
    Error.captureStackTrace(this, caller || this.constructor)
  }

  get name () {
    return 'JSONStreamError'
  }
}

const check = (x, y) =>
  typeof x === 'string' ? String(y) === x
  : x && typeof x.test === 'function' ? x.test(y)
  : typeof x === 'boolean' || typeof x === 'object' ? x
  : typeof x === 'function' ? x(y)
  : false

class JSONStream extends Minipass {
  #count = 0
  #ending = false
  #footer = null
  #header = null
  #map = null
  #onTokenOriginal
  #parser
  #path = null
  #root = null

  constructor (opts) {
    super({
      ...opts,
      objectMode: true,
    })

    const parser = this.#parser = new Parser()
    parser.onValue = value => this.#onValue(value)
    this.#onTokenOriginal = parser.onToken
    parser.onToken = (token, value) => this.#onToken(token, value)
    parser.onError = er => this.#onError(er)

    this.#path = typeof opts.path === 'string'
      ? opts.path.split('.').map(e =>
        e === '$*' ? { emitKey: true }
        : e === '*' ? true
        : e === '' ? { recurse: true }
        : e)
      : Array.isArray(opts.path) && opts.path.length ? opts.path
      : null

    if (typeof opts.map === 'function') {
      this.#map = opts.map
    }
  }

  #setHeaderFooter (key, value) {
    // header has not been emitted yet
    if (this.#header !== false) {
      this.#header = this.#header || {}
      this.#header[key] = value
    }

    // footer has not been emitted yet but header has
    if (this.#footer !== false && this.#header === false) {
      this.#footer = this.#footer || {}
      this.#footer[key] = value
    }
  }

  #onError (er) {
    // error will always happen during a write() call.
    const caller = this.#ending ? this.end : this.write
    this.#ending = false
    return this.emit('error', new JSONStreamError(er, caller))
  }

  #onToken (token, value) {
    const parser = this.#parser
    this.#onTokenOriginal.call(this.#parser, token, value)
    if (parser.stack.length === 0) {
      if (this.#root) {
        const root = this.#root
        if (!this.#path) {
          super.write(root)
        }
        this.#root = null
        this.#count = 0
      }
    }
  }

  #onValue (value) {
    const parser = this.#parser
    // the LAST onValue encountered is the root object.
    // just overwrite it each time.
    this.#root = value

    if (!this.#path) {
      return
    }

    let i = 0 // iterates on path
    let j = 0 // iterates on stack
    let emitKey = false
    while (i < this.#path.length) {
      const key = this.#path[i]
      j++

      if (key && !key.recurse) {
        const c = (j === parser.stack.length) ? parser : parser.stack[j]
        if (!c) {
          return
        }
        if (!check(key, c.key)) {
          this.#setHeaderFooter(c.key, value)
          return
        }
        emitKey = !!key.emitKey
        i++
      } else {
        i++
        if (i >= this.#path.length) {
          return
        }
        const nextKey = this.#path[i]
        if (!nextKey) {
          return
        }
        while (true) {
          const c = (j === parser.stack.length) ? parser : parser.stack[j]
          if (!c) {
            return
          }
          if (check(nextKey, c.key)) {
            i++
            if (!Object.isFrozen(parser.stack[j])) {
              parser.stack[j].value = null
            }
            break
          } else {
            this.#setHeaderFooter(c.key, value)
          }
          j++
        }
      }
    }

    // emit header
    if (this.#header) {
      const header = this.#header
      this.#header = false
      this.emit('header', header)
    }
    if (j !== parser.stack.length) {
      return
    }

    this.#count++
    const actualPath = parser.stack.slice(1)
      .map(e => e.key).concat([parser.key])
    if (value !== null && value !== undefined) {
      const data = this.#map ? this.#map(value, actualPath) : value
      if (data !== null && data !== undefined) {
        const emit = emitKey ? { value: data } : data
        if (emitKey) {
          emit.key = parser.key
        }
        super.write(emit)
      }
    }

    if (parser.value) {
      delete parser.value[parser.key]
    }

    for (const k of parser.stack) {
      k.value = null
    }
  }

  write (chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding)
    } else if (!Buffer.isBuffer(chunk)) {
      return this.emit('error', new TypeError(
        'Can only parse JSON from string or buffer input'))
    }
    this.#parser.write(chunk)
    return this.flowing
  }

  end (chunk, encoding) {
    this.#ending = true
    if (chunk) {
      this.write(chunk, encoding)
    }

    const h = this.#header
    this.#header = null
    const f = this.#footer
    this.#footer = null
    if (h) {
      this.emit('header', h)
    }
    if (f) {
      this.emit('footer', f)
    }
    return super.end()
  }

  static get JSONStreamError () {
    return JSONStreamError
  }

  static parse (path, map) {
    return new JSONStream({ path, map })
  }
}

module.exports = JSONStream
Minizlib was created by Isaac Z. Schlueter.
It is a derivative work of the Node.js project.

"""
Copyright (c) 2017-2023 Isaac Z. Schlueter and Contributors
Copyright (c) 2017-2023 Node.js contributors. All rights reserved.
Copyright (c) 2017-2023 Joyent, Inc. and other Node contributors. All rights reserved.

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.
"""
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.constants = void 0;
// Update with any zlib constants that are added or changed in the future.
// Node v6 didn't export this, so we just hard code the version and rely
// on all the other hard-coded values from zlib v4736.  When node v6
// support drops, we can just export the realZlibConstants object.
const zlib_1 = __importDefault(require("zlib"));
/* c8 ignore start */
const realZlibConstants = zlib_1.default.constants || { ZLIB_VERNUM: 4736 };
/* c8 ignore stop */
exports.constants = Object.freeze(Object.assign(Object.create(null), {
    Z_NO_FLUSH: 0,
    Z_PARTIAL_FLUSH: 1,
    Z_SYNC_FLUSH: 2,
    Z_FULL_FLUSH: 3,
    Z_FINISH: 4,
    Z_BLOCK: 5,
    Z_OK: 0,
    Z_STREAM_END: 1,
    Z_NEED_DICT: 2,
    Z_ERRNO: -1,
    Z_STREAM_ERROR: -2,
    Z_DATA_ERROR: -3,
    Z_MEM_ERROR: -4,
    Z_BUF_ERROR: -5,
    Z_VERSION_ERROR: -6,
    Z_NO_COMPRESSION: 0,
    Z_BEST_SPEED: 1,
    Z_BEST_COMPRESSION: 9,
    Z_DEFAULT_COMPRESSION: -1,
    Z_FILTERED: 1,
    Z_HUFFMAN_ONLY: 2,
    Z_RLE: 3,
    Z_FIXED: 4,
    Z_DEFAULT_STRATEGY: 0,
    DEFLATE: 1,
    INFLATE: 2,
    GZIP: 3,
    GUNZIP: 4,
    DEFLATERAW: 5,
    INFLATERAW: 6,
    UNZIP: 7,
    BROTLI_DECODE: 8,
    BROTLI_ENCODE: 9,
    Z_MIN_WINDOWBITS: 8,
    Z_MAX_WINDOWBITS: 15,
    Z_DEFAULT_WINDOWBITS: 15,
    Z_MIN_CHUNK: 64,
    Z_MAX_CHUNK: Infinity,
    Z_DEFAULT_CHUNK: 16384,
    Z_MIN_MEMLEVEL: 1,
    Z_MAX_MEMLEVEL: 9,
    Z_DEFAULT_MEMLEVEL: 8,
    Z_MIN_LEVEL: -1,
    Z_MAX_LEVEL: 9,
    Z_DEFAULT_LEVEL: -1,
    BROTLI_OPERATION_PROCESS: 0,
    BROTLI_OPERATION_FLUSH: 1,
    BROTLI_OPERATION_FINISH: 2,
    BROTLI_OPERATION_EMIT_METADATA: 3,
    BROTLI_MODE_GENERIC: 0,
    BROTLI_MODE_TEXT: 1,
    BROTLI_MODE_FONT: 2,
    BROTLI_DEFAULT_MODE: 0,
    BROTLI_MIN_QUALITY: 0,
    BROTLI_MAX_QUALITY: 11,
    BROTLI_DEFAULT_QUALITY: 11,
    BROTLI_MIN_WINDOW_BITS: 10,
    BROTLI_MAX_WINDOW_BITS: 24,
    BROTLI_LARGE_MAX_WINDOW_BITS: 30,
    BROTLI_DEFAULT_WINDOW: 22,
    BROTLI_MIN_INPUT_BLOCK_BITS: 16,
    BROTLI_MAX_INPUT_BLOCK_BITS: 24,
    BROTLI_PARAM_MODE: 0,
    BROTLI_PARAM_QUALITY: 1,
    BROTLI_PARAM_LGWIN: 2,
    BROTLI_PARAM_LGBLOCK: 3,
    BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
    BROTLI_PARAM_SIZE_HINT: 5,
    BROTLI_PARAM_LARGE_WINDOW: 6,
    BROTLI_PARAM_NPOSTFIX: 7,
    BROTLI_PARAM_NDIRECT: 8,
    BROTLI_DECODER_RESULT_ERROR: 0,
    BROTLI_DECODER_RESULT_SUCCESS: 1,
    BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
    BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
    BROTLI_DECODER_NO_ERROR: 0,
    BROTLI_DECODER_SUCCESS: 1,
    BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
    BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
    BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
    BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
    BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
    BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
    BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
    BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
    BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
    BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
    BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
    BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
    BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
    BROTLI_DECODER_ERROR_UNREACHABLE: -31,
}, realZlibConstants));
//# sourceMappingURL=constants.js.map"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrotliDecompress = exports.BrotliCompress = exports.Brotli = exports.Unzip = exports.InflateRaw = exports.DeflateRaw = exports.Gunzip = exports.Gzip = exports.Inflate = exports.Deflate = exports.Zlib = exports.ZlibError = exports.constants = void 0;
const assert_1 = __importDefault(require("assert"));
const buffer_1 = require("buffer");
const minipass_1 = require("minipass");
const zlib_1 = __importDefault(require("zlib"));
const constants_js_1 = require("./constants.js");
var constants_js_2 = require("./constants.js");
Object.defineProperty(exports, "constants", { enumerable: true, get: function () { return constants_js_2.constants; } });
const OriginalBufferConcat = buffer_1.Buffer.concat;
const _superWrite = Symbol('_superWrite');
class ZlibError extends Error {
    code;
    errno;
    constructor(err) {
        super('zlib: ' + err.message);
        this.code = err.code;
        this.errno = err.errno;
        /* c8 ignore next */
        if (!this.code)
            this.code = 'ZLIB_ERROR';
        this.message = 'zlib: ' + err.message;
        Error.captureStackTrace(this, this.constructor);
    }
    get name() {
        return 'ZlibError';
    }
}
exports.ZlibError = ZlibError;
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
const _flushFlag = Symbol('flushFlag');
class ZlibBase extends minipass_1.Minipass {
    #sawError = false;
    #ended = false;
    #flushFlag;
    #finishFlushFlag;
    #fullFlushFlag;
    #handle;
    #onError;
    get sawError() {
        return this.#sawError;
    }
    get handle() {
        return this.#handle;
    }
    /* c8 ignore start */
    get flushFlag() {
        return this.#flushFlag;
    }
    /* c8 ignore stop */
    constructor(opts, mode) {
        if (!opts || typeof opts !== 'object')
            throw new TypeError('invalid options for ZlibBase constructor');
        //@ts-ignore
        super(opts);
        /* c8 ignore start */
        this.#flushFlag = opts.flush ?? 0;
        this.#finishFlushFlag = opts.finishFlush ?? 0;
        this.#fullFlushFlag = opts.fullFlushFlag ?? 0;
        /* c8 ignore stop */
        // this will throw if any options are invalid for the class selected
        try {
            // @types/node doesn't know that it exports the classes, but they're there
            //@ts-ignore
            this.#handle = new zlib_1.default[mode](opts);
        }
        catch (er) {
            // make sure that all errors get decorated properly
            throw new ZlibError(er);
        }
        this.#onError = err => {
            // no sense raising multiple errors, since we abort on the first one.
            if (this.#sawError)
                return;
            this.#sawError = true;
            // there is no way to cleanly recover.
            // continuing only obscures problems.
            this.close();
            this.emit('error', err);
        };
        this.#handle?.on('error', er => this.#onError(new ZlibError(er)));
        this.once('end', () => this.close);
    }
    close() {
        if (this.#handle) {
            this.#handle.close();
            this.#handle = undefined;
            this.emit('close');
        }
    }
    reset() {
        if (!this.#sawError) {
            (0, assert_1.default)(this.#handle, 'zlib binding closed');
            //@ts-ignore
            return this.#handle.reset?.();
        }
    }
    flush(flushFlag) {
        if (this.ended)
            return;
        if (typeof flushFlag !== 'number')
            flushFlag = this.#fullFlushFlag;
        this.write(Object.assign(buffer_1.Buffer.alloc(0), { [_flushFlag]: flushFlag }));
    }
    end(chunk, encoding, cb) {
        /* c8 ignore start */
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (chunk) {
            if (encoding)
                this.write(chunk, encoding);
            else
                this.write(chunk);
        }
        this.flush(this.#finishFlushFlag);
        this.#ended = true;
        return super.end(cb);
    }
    get ended() {
        return this.#ended;
    }
    // overridden in the gzip classes to do portable writes
    [_superWrite](data) {
        return super.write(data);
    }
    write(chunk, encoding, cb) {
        // process the chunk using the sync process
        // then super.write() all the outputted chunks
        if (typeof encoding === 'function')
            (cb = encoding), (encoding = 'utf8');
        if (typeof chunk === 'string')
            chunk = buffer_1.Buffer.from(chunk, encoding);
        if (this.#sawError)
            return;
        (0, assert_1.default)(this.#handle, 'zlib binding closed');
        // _processChunk tries to .close() the native handle after it's done, so we
        // intercept that by temporarily making it a no-op.
        // diving into the node:zlib internals a bit here
        const nativeHandle = this.#handle
            ._handle;
        const originalNativeClose = nativeHandle.close;
        nativeHandle.close = () => { };
        const originalClose = this.#handle.close;
        this.#handle.close = () => { };
        // It also calls `Buffer.concat()` at the end, which may be convenient
        // for some, but which we are not interested in as it slows us down.
        buffer_1.Buffer.concat = args => args;
        let result = undefined;
        try {
            const flushFlag = typeof chunk[_flushFlag] === 'number'
                ? chunk[_flushFlag]
                : this.#flushFlag;
            result = this.#handle._processChunk(chunk, flushFlag);
            // if we don't throw, reset it back how it was
            buffer_1.Buffer.concat = OriginalBufferConcat;
        }
        catch (err) {
            // or if we do, put Buffer.concat() back before we emit error
            // Error events call into user code, which may call Buffer.concat()
            buffer_1.Buffer.concat = OriginalBufferConcat;
            this.#onError(new ZlibError(err));
        }
        finally {
            if (this.#handle) {
                // Core zlib resets `_handle` to null after attempting to close the
                // native handle. Our no-op handler prevented actual closure, but we
                // need to restore the `._handle` property.
                ;
                this.#handle._handle =
                    nativeHandle;
                nativeHandle.close = originalNativeClose;
                this.#handle.close = originalClose;
                // `_processChunk()` adds an 'error' listener. If we don't remove it
                // after each call, these handlers start piling up.
                this.#handle.removeAllListeners('error');
                // make sure OUR error listener is still attached tho
            }
        }
        if (this.#handle)
            this.#handle.on('error', er => this.#onError(new ZlibError(er)));
        let writeReturn;
        if (result) {
            if (Array.isArray(result) && result.length > 0) {
                const r = result[0];
                // The first buffer is always `handle._outBuffer`, which would be
                // re-used for later invocations; so, we always have to copy that one.
                writeReturn = this[_superWrite](buffer_1.Buffer.from(r));
                for (let i = 1; i < result.length; i++) {
                    writeReturn = this[_superWrite](result[i]);
                }
            }
            else {
                // either a single Buffer or an empty array
                writeReturn = this[_superWrite](buffer_1.Buffer.from(result));
            }
        }
        if (cb)
            cb();
        return writeReturn;
    }
}
class Zlib extends ZlibBase {
    #level;
    #strategy;
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants_js_1.constants.Z_NO_FLUSH;
        opts.finishFlush = opts.finishFlush || constants_js_1.constants.Z_FINISH;
        opts.fullFlushFlag = constants_js_1.constants.Z_FULL_FLUSH;
        super(opts, mode);
        this.#level = opts.level;
        this.#strategy = opts.strategy;
    }
    params(level, strategy) {
        if (this.sawError)
            return;
        if (!this.handle)
            throw new Error('cannot switch params when binding is closed');
        // no way to test this without also not supporting params at all
        /* c8 ignore start */
        if (!this.handle.params)
            throw new Error('not supported in this implementation');
        /* c8 ignore stop */
        if (this.#level !== level || this.#strategy !== strategy) {
            this.flush(constants_js_1.constants.Z_SYNC_FLUSH);
            (0, assert_1.default)(this.handle, 'zlib binding closed');
            // .params() calls .flush(), but the latter is always async in the
            // core zlib. We override .flush() temporarily to intercept that and
            // flush synchronously.
            const origFlush = this.handle.flush;
            this.handle.flush = (flushFlag, cb) => {
                /* c8 ignore start */
                if (typeof flushFlag === 'function') {
                    cb = flushFlag;
                    flushFlag = this.flushFlag;
                }
                /* c8 ignore stop */
                this.flush(flushFlag);
                cb?.();
            };
            try {
                ;
                this.handle.params(level, strategy);
            }
            finally {
                this.handle.flush = origFlush;
            }
            /* c8 ignore start */
            if (this.handle) {
                this.#level = level;
                this.#strategy = strategy;
            }
            /* c8 ignore stop */
        }
    }
}
exports.Zlib = Zlib;
// minimal 2-byte header
class Deflate extends Zlib {
    constructor(opts) {
        super(opts, 'Deflate');
    }
}
exports.Deflate = Deflate;
class Inflate extends Zlib {
    constructor(opts) {
        super(opts, 'Inflate');
    }
}
exports.Inflate = Inflate;
class Gzip extends Zlib {
    #portable;
    constructor(opts) {
        super(opts, 'Gzip');
        this.#portable = opts && !!opts.portable;
    }
    [_superWrite](data) {
        if (!this.#portable)
            return super[_superWrite](data);
        // we'll always get the header emitted in one first chunk
        // overwrite the OS indicator byte with 0xFF
        this.#portable = false;
        data[9] = 255;
        return super[_superWrite](data);
    }
}
exports.Gzip = Gzip;
class Gunzip extends Zlib {
    constructor(opts) {
        super(opts, 'Gunzip');
    }
}
exports.Gunzip = Gunzip;
// raw - no header
class DeflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'DeflateRaw');
    }
}
exports.DeflateRaw = DeflateRaw;
class InflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'InflateRaw');
    }
}
exports.InflateRaw = InflateRaw;
// auto-detect header.
class Unzip extends Zlib {
    constructor(opts) {
        super(opts, 'Unzip');
    }
}
exports.Unzip = Unzip;
class Brotli extends ZlibBase {
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants_js_1.constants.BROTLI_OPERATION_PROCESS;
        opts.finishFlush =
            opts.finishFlush || constants_js_1.constants.BROTLI_OPERATION_FINISH;
        opts.fullFlushFlag = constants_js_1.constants.BROTLI_OPERATION_FLUSH;
        super(opts, mode);
    }
}
exports.Brotli = Brotli;
class BrotliCompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliCompress');
    }
}
exports.BrotliCompress = BrotliCompress;
class BrotliDecompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliDecompress');
    }
}
exports.BrotliDecompress = BrotliDecompress;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
// Update with any zlib constants that are added or changed in the future.
// Node v6 didn't export this, so we just hard code the version and rely
// on all the other hard-coded values from zlib v4736.  When node v6
// support drops, we can just export the realZlibConstants object.
import realZlib from 'zlib';
/* c8 ignore start */
const realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 };
/* c8 ignore stop */
export const constants = Object.freeze(Object.assign(Object.create(null), {
    Z_NO_FLUSH: 0,
    Z_PARTIAL_FLUSH: 1,
    Z_SYNC_FLUSH: 2,
    Z_FULL_FLUSH: 3,
    Z_FINISH: 4,
    Z_BLOCK: 5,
    Z_OK: 0,
    Z_STREAM_END: 1,
    Z_NEED_DICT: 2,
    Z_ERRNO: -1,
    Z_STREAM_ERROR: -2,
    Z_DATA_ERROR: -3,
    Z_MEM_ERROR: -4,
    Z_BUF_ERROR: -5,
    Z_VERSION_ERROR: -6,
    Z_NO_COMPRESSION: 0,
    Z_BEST_SPEED: 1,
    Z_BEST_COMPRESSION: 9,
    Z_DEFAULT_COMPRESSION: -1,
    Z_FILTERED: 1,
    Z_HUFFMAN_ONLY: 2,
    Z_RLE: 3,
    Z_FIXED: 4,
    Z_DEFAULT_STRATEGY: 0,
    DEFLATE: 1,
    INFLATE: 2,
    GZIP: 3,
    GUNZIP: 4,
    DEFLATERAW: 5,
    INFLATERAW: 6,
    UNZIP: 7,
    BROTLI_DECODE: 8,
    BROTLI_ENCODE: 9,
    Z_MIN_WINDOWBITS: 8,
    Z_MAX_WINDOWBITS: 15,
    Z_DEFAULT_WINDOWBITS: 15,
    Z_MIN_CHUNK: 64,
    Z_MAX_CHUNK: Infinity,
    Z_DEFAULT_CHUNK: 16384,
    Z_MIN_MEMLEVEL: 1,
    Z_MAX_MEMLEVEL: 9,
    Z_DEFAULT_MEMLEVEL: 8,
    Z_MIN_LEVEL: -1,
    Z_MAX_LEVEL: 9,
    Z_DEFAULT_LEVEL: -1,
    BROTLI_OPERATION_PROCESS: 0,
    BROTLI_OPERATION_FLUSH: 1,
    BROTLI_OPERATION_FINISH: 2,
    BROTLI_OPERATION_EMIT_METADATA: 3,
    BROTLI_MODE_GENERIC: 0,
    BROTLI_MODE_TEXT: 1,
    BROTLI_MODE_FONT: 2,
    BROTLI_DEFAULT_MODE: 0,
    BROTLI_MIN_QUALITY: 0,
    BROTLI_MAX_QUALITY: 11,
    BROTLI_DEFAULT_QUALITY: 11,
    BROTLI_MIN_WINDOW_BITS: 10,
    BROTLI_MAX_WINDOW_BITS: 24,
    BROTLI_LARGE_MAX_WINDOW_BITS: 30,
    BROTLI_DEFAULT_WINDOW: 22,
    BROTLI_MIN_INPUT_BLOCK_BITS: 16,
    BROTLI_MAX_INPUT_BLOCK_BITS: 24,
    BROTLI_PARAM_MODE: 0,
    BROTLI_PARAM_QUALITY: 1,
    BROTLI_PARAM_LGWIN: 2,
    BROTLI_PARAM_LGBLOCK: 3,
    BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
    BROTLI_PARAM_SIZE_HINT: 5,
    BROTLI_PARAM_LARGE_WINDOW: 6,
    BROTLI_PARAM_NPOSTFIX: 7,
    BROTLI_PARAM_NDIRECT: 8,
    BROTLI_DECODER_RESULT_ERROR: 0,
    BROTLI_DECODER_RESULT_SUCCESS: 1,
    BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
    BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
    BROTLI_DECODER_NO_ERROR: 0,
    BROTLI_DECODER_SUCCESS: 1,
    BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
    BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
    BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
    BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
    BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
    BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
    BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
    BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
    BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
    BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
    BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
    BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
    BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
    BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
    BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
    BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
    BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
    BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
    BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
    BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
    BROTLI_DECODER_ERROR_UNREACHABLE: -31,
}, realZlibConstants));
//# sourceMappingURL=constants.js.mapimport assert from 'assert';
import { Buffer } from 'buffer';
import { Minipass } from 'minipass';
import realZlib from 'zlib';
import { constants } from './constants.js';
export { constants } from './constants.js';
const OriginalBufferConcat = Buffer.concat;
const _superWrite = Symbol('_superWrite');
export class ZlibError extends Error {
    code;
    errno;
    constructor(err) {
        super('zlib: ' + err.message);
        this.code = err.code;
        this.errno = err.errno;
        /* c8 ignore next */
        if (!this.code)
            this.code = 'ZLIB_ERROR';
        this.message = 'zlib: ' + err.message;
        Error.captureStackTrace(this, this.constructor);
    }
    get name() {
        return 'ZlibError';
    }
}
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
const _flushFlag = Symbol('flushFlag');
class ZlibBase extends Minipass {
    #sawError = false;
    #ended = false;
    #flushFlag;
    #finishFlushFlag;
    #fullFlushFlag;
    #handle;
    #onError;
    get sawError() {
        return this.#sawError;
    }
    get handle() {
        return this.#handle;
    }
    /* c8 ignore start */
    get flushFlag() {
        return this.#flushFlag;
    }
    /* c8 ignore stop */
    constructor(opts, mode) {
        if (!opts || typeof opts !== 'object')
            throw new TypeError('invalid options for ZlibBase constructor');
        //@ts-ignore
        super(opts);
        /* c8 ignore start */
        this.#flushFlag = opts.flush ?? 0;
        this.#finishFlushFlag = opts.finishFlush ?? 0;
        this.#fullFlushFlag = opts.fullFlushFlag ?? 0;
        /* c8 ignore stop */
        // this will throw if any options are invalid for the class selected
        try {
            // @types/node doesn't know that it exports the classes, but they're there
            //@ts-ignore
            this.#handle = new realZlib[mode](opts);
        }
        catch (er) {
            // make sure that all errors get decorated properly
            throw new ZlibError(er);
        }
        this.#onError = err => {
            // no sense raising multiple errors, since we abort on the first one.
            if (this.#sawError)
                return;
            this.#sawError = true;
            // there is no way to cleanly recover.
            // continuing only obscures problems.
            this.close();
            this.emit('error', err);
        };
        this.#handle?.on('error', er => this.#onError(new ZlibError(er)));
        this.once('end', () => this.close);
    }
    close() {
        if (this.#handle) {
            this.#handle.close();
            this.#handle = undefined;
            this.emit('close');
        }
    }
    reset() {
        if (!this.#sawError) {
            assert(this.#handle, 'zlib binding closed');
            //@ts-ignore
            return this.#handle.reset?.();
        }
    }
    flush(flushFlag) {
        if (this.ended)
            return;
        if (typeof flushFlag !== 'number')
            flushFlag = this.#fullFlushFlag;
        this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }));
    }
    end(chunk, encoding, cb) {
        /* c8 ignore start */
        if (typeof chunk === 'function') {
            cb = chunk;
            encoding = undefined;
            chunk = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (chunk) {
            if (encoding)
                this.write(chunk, encoding);
            else
                this.write(chunk);
        }
        this.flush(this.#finishFlushFlag);
        this.#ended = true;
        return super.end(cb);
    }
    get ended() {
        return this.#ended;
    }
    // overridden in the gzip classes to do portable writes
    [_superWrite](data) {
        return super.write(data);
    }
    write(chunk, encoding, cb) {
        // process the chunk using the sync process
        // then super.write() all the outputted chunks
        if (typeof encoding === 'function')
            (cb = encoding), (encoding = 'utf8');
        if (typeof chunk === 'string')
            chunk = Buffer.from(chunk, encoding);
        if (this.#sawError)
            return;
        assert(this.#handle, 'zlib binding closed');
        // _processChunk tries to .close() the native handle after it's done, so we
        // intercept that by temporarily making it a no-op.
        // diving into the node:zlib internals a bit here
        const nativeHandle = this.#handle
            ._handle;
        const originalNativeClose = nativeHandle.close;
        nativeHandle.close = () => { };
        const originalClose = this.#handle.close;
        this.#handle.close = () => { };
        // It also calls `Buffer.concat()` at the end, which may be convenient
        // for some, but which we are not interested in as it slows us down.
        Buffer.concat = args => args;
        let result = undefined;
        try {
            const flushFlag = typeof chunk[_flushFlag] === 'number'
                ? chunk[_flushFlag]
                : this.#flushFlag;
            result = this.#handle._processChunk(chunk, flushFlag);
            // if we don't throw, reset it back how it was
            Buffer.concat = OriginalBufferConcat;
        }
        catch (err) {
            // or if we do, put Buffer.concat() back before we emit error
            // Error events call into user code, which may call Buffer.concat()
            Buffer.concat = OriginalBufferConcat;
            this.#onError(new ZlibError(err));
        }
        finally {
            if (this.#handle) {
                // Core zlib resets `_handle` to null after attempting to close the
                // native handle. Our no-op handler prevented actual closure, but we
                // need to restore the `._handle` property.
                ;
                this.#handle._handle =
                    nativeHandle;
                nativeHandle.close = originalNativeClose;
                this.#handle.close = originalClose;
                // `_processChunk()` adds an 'error' listener. If we don't remove it
                // after each call, these handlers start piling up.
                this.#handle.removeAllListeners('error');
                // make sure OUR error listener is still attached tho
            }
        }
        if (this.#handle)
            this.#handle.on('error', er => this.#onError(new ZlibError(er)));
        let writeReturn;
        if (result) {
            if (Array.isArray(result) && result.length > 0) {
                const r = result[0];
                // The first buffer is always `handle._outBuffer`, which would be
                // re-used for later invocations; so, we always have to copy that one.
                writeReturn = this[_superWrite](Buffer.from(r));
                for (let i = 1; i < result.length; i++) {
                    writeReturn = this[_superWrite](result[i]);
                }
            }
            else {
                // either a single Buffer or an empty array
                writeReturn = this[_superWrite](Buffer.from(result));
            }
        }
        if (cb)
            cb();
        return writeReturn;
    }
}
export class Zlib extends ZlibBase {
    #level;
    #strategy;
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.Z_NO_FLUSH;
        opts.finishFlush = opts.finishFlush || constants.Z_FINISH;
        opts.fullFlushFlag = constants.Z_FULL_FLUSH;
        super(opts, mode);
        this.#level = opts.level;
        this.#strategy = opts.strategy;
    }
    params(level, strategy) {
        if (this.sawError)
            return;
        if (!this.handle)
            throw new Error('cannot switch params when binding is closed');
        // no way to test this without also not supporting params at all
        /* c8 ignore start */
        if (!this.handle.params)
            throw new Error('not supported in this implementation');
        /* c8 ignore stop */
        if (this.#level !== level || this.#strategy !== strategy) {
            this.flush(constants.Z_SYNC_FLUSH);
            assert(this.handle, 'zlib binding closed');
            // .params() calls .flush(), but the latter is always async in the
            // core zlib. We override .flush() temporarily to intercept that and
            // flush synchronously.
            const origFlush = this.handle.flush;
            this.handle.flush = (flushFlag, cb) => {
                /* c8 ignore start */
                if (typeof flushFlag === 'function') {
                    cb = flushFlag;
                    flushFlag = this.flushFlag;
                }
                /* c8 ignore stop */
                this.flush(flushFlag);
                cb?.();
            };
            try {
                ;
                this.handle.params(level, strategy);
            }
            finally {
                this.handle.flush = origFlush;
            }
            /* c8 ignore start */
            if (this.handle) {
                this.#level = level;
                this.#strategy = strategy;
            }
            /* c8 ignore stop */
        }
    }
}
// minimal 2-byte header
export class Deflate extends Zlib {
    constructor(opts) {
        super(opts, 'Deflate');
    }
}
export class Inflate extends Zlib {
    constructor(opts) {
        super(opts, 'Inflate');
    }
}
export class Gzip extends Zlib {
    #portable;
    constructor(opts) {
        super(opts, 'Gzip');
        this.#portable = opts && !!opts.portable;
    }
    [_superWrite](data) {
        if (!this.#portable)
            return super[_superWrite](data);
        // we'll always get the header emitted in one first chunk
        // overwrite the OS indicator byte with 0xFF
        this.#portable = false;
        data[9] = 255;
        return super[_superWrite](data);
    }
}
export class Gunzip extends Zlib {
    constructor(opts) {
        super(opts, 'Gunzip');
    }
}
// raw - no header
export class DeflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'DeflateRaw');
    }
}
export class InflateRaw extends Zlib {
    constructor(opts) {
        super(opts, 'InflateRaw');
    }
}
// auto-detect header.
export class Unzip extends Zlib {
    constructor(opts) {
        super(opts, 'Unzip');
    }
}
export class Brotli extends ZlibBase {
    constructor(opts, mode) {
        opts = opts || {};
        opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS;
        opts.finishFlush =
            opts.finishFlush || constants.BROTLI_OPERATION_FINISH;
        opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH;
        super(opts, mode);
    }
}
export class BrotliCompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliCompress');
    }
}
export class BrotliDecompress extends Brotli {
    constructor(opts) {
        super(opts, 'BrotliDecompress');
    }
}
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "name": "minizlib",
  "version": "3.0.1",
  "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.",
  "main": "./dist/commonjs/index.js",
  "dependencies": {
    "minipass": "^7.0.4",
    "rimraf": "^5.0.5"
  },
  "scripts": {
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "format": "prettier --write . --loglevel warn",
    "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/minizlib.git"
  },
  "keywords": [
    "zlib",
    "gzip",
    "gunzip",
    "deflate",
    "inflate",
    "compression",
    "zip",
    "unzip"
  ],
  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
  "license": "MIT",
  "devDependencies": {
    "@types/node": "^20.11.29",
    "mkdirp": "^3.0.1",
    "tap": "^18.7.1",
    "tshy": "^1.12.0",
    "typedoc": "^0.25.12"
  },
  "files": [
    "dist"
  ],
  "engines": {
    "node": ">= 18"
  },
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "types": "./dist/commonjs/index.d.ts",
  "type": "module",
  "prettier": {
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  }
}
{
  "name": "npm-registry-fetch",
  "version": "18.0.2",
  "description": "Fetch-based http client for use with npm registry APIs",
  "main": "lib",
  "files": [
    "bin/",
    "lib/"
  ],
  "scripts": {
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lint": "npm run eslint",
    "lintfix": "npm run eslint -- --fix",
    "test": "tap",
    "posttest": "npm run lint",
    "npmclilint": "npmcli-lint",
    "postsnap": "npm run lintfix --",
    "postlint": "template-oss-check",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-registry-fetch.git"
  },
  "keywords": [
    "npm",
    "registry",
    "fetch"
  ],
  "author": "GitHub Inc.",
  "license": "ISC",
  "dependencies": {
    "@npmcli/redact": "^3.0.0",
    "jsonparse": "^1.3.1",
    "make-fetch-happen": "^14.0.0",
    "minipass": "^7.0.2",
    "minipass-fetch": "^4.0.0",
    "minizlib": "^3.0.1",
    "npm-package-arg": "^12.0.0",
    "proc-log": "^5.0.0"
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.4",
    "cacache": "^19.0.1",
    "nock": "^13.2.4",
    "require-inject": "^1.4.4",
    "ssri": "^12.0.0",
    "tap": "^16.0.1"
  },
  "tap": {
    "check-coverage": true,
    "test-ignore": "test[\\\\/](util|cache)[\\\\/]",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.4",
    "publish": "true"
  }
}
Copyright (c) Robert Kowalski
All rights reserved.

The BSD License

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. 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 AUTHOR 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 AUTHOR 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.exports.email = email
exports.pw = pw
exports.username = username
var requirements = exports.requirements = {
  username: {
    length: 'Name length must be less than or equal to 214 characters long',
    lowerCase: 'Name must be lowercase',
    urlSafe: 'Name may not contain non-url-safe chars',
    dot: 'Name may not start with "."',
    illegal: 'Name may not contain illegal character',
  },
  password: {},
  email: {
    length: 'Email length must be less then or equal to 254 characters long',
    valid: 'Email must be an email address',
  },
}

var illegalCharacterRe = new RegExp('([' + [
  "'",
].join() + '])')

function username (un) {
  if (un !== un.toLowerCase()) {
    return new Error(requirements.username.lowerCase)
  }

  if (un !== encodeURIComponent(un)) {
    return new Error(requirements.username.urlSafe)
  }

  if (un.charAt(0) === '.') {
    return new Error(requirements.username.dot)
  }

  if (un.length > 214) {
    return new Error(requirements.username.length)
  }

  var illegal = un.match(illegalCharacterRe)
  if (illegal) {
    return new Error(requirements.username.illegal + ' "' + illegal[0] + '"')
  }

  return null
}

function email (em) {
  if (em.length > 254) {
    return new Error(requirements.email.length)
  }
  if (!em.match(/^[^@]+@.+\..+$/)) {
    return new Error(requirements.email.valid)
  }

  return null
}

function pw () {
  return null
}
{
  "name": "npm-user-validate",
  "version": "3.0.0",
  "description": "User validations for npm",
  "main": "lib/index.js",
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.3.2"
  },
  "scripts": {
    "test": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "snap": "tap",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-user-validate.git"
  },
  "keywords": [
    "npm",
    "validation",
    "registry"
  ],
  "author": "GitHub Inc.",
  "license": "BSD-2-Clause",
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  }
}
export default async function pMap(
	iterable,
	mapper,
	{
		concurrency = Number.POSITIVE_INFINITY,
		stopOnError = true,
		signal,
	} = {},
) {
	return new Promise((resolve_, reject_) => {
		if (iterable[Symbol.iterator] === undefined && iterable[Symbol.asyncIterator] === undefined) {
			throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
		}

		if (typeof mapper !== 'function') {
			throw new TypeError('Mapper function is required');
		}

		if (!((Number.isSafeInteger(concurrency) && concurrency >= 1) || concurrency === Number.POSITIVE_INFINITY)) {
			throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
		}

		const result = [];
		const errors = [];
		const skippedIndexesMap = new Map();
		let isRejected = false;
		let isResolved = false;
		let isIterableDone = false;
		let resolvingCount = 0;
		let currentIndex = 0;
		const iterator = iterable[Symbol.iterator] === undefined ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();

		const signalListener = () => {
			reject(signal.reason);
		};

		const cleanup = () => {
			signal?.removeEventListener('abort', signalListener);
		};

		const resolve = value => {
			resolve_(value);
			cleanup();
		};

		const reject = reason => {
			isRejected = true;
			isResolved = true;
			reject_(reason);
			cleanup();
		};

		if (signal) {
			if (signal.aborted) {
				reject(signal.reason);
			}

			signal.addEventListener('abort', signalListener, {once: true});
		}

		const next = async () => {
			if (isResolved) {
				return;
			}

			const nextItem = await iterator.next();

			const index = currentIndex;
			currentIndex++;

			// Note: `iterator.next()` can be called many times in parallel.
			// This can cause multiple calls to this `next()` function to
			// receive a `nextItem` with `done === true`.
			// The shutdown logic that rejects/resolves must be protected
			// so it runs only one time as the `skippedIndex` logic is
			// non-idempotent.
			if (nextItem.done) {
				isIterableDone = true;

				if (resolvingCount === 0 && !isResolved) {
					if (!stopOnError && errors.length > 0) {
						reject(new AggregateError(errors)); // eslint-disable-line unicorn/error-message
						return;
					}

					isResolved = true;

					if (skippedIndexesMap.size === 0) {
						resolve(result);
						return;
					}

					const pureResult = [];

					// Support multiple `pMapSkip`'s.
					for (const [index, value] of result.entries()) {
						if (skippedIndexesMap.get(index) === pMapSkip) {
							continue;
						}

						pureResult.push(value);
					}

					resolve(pureResult);
				}

				return;
			}

			resolvingCount++;

			// Intentionally detached
			(async () => {
				try {
					const element = await nextItem.value;

					if (isResolved) {
						return;
					}

					const value = await mapper(element, index);

					// Use Map to stage the index of the element.
					if (value === pMapSkip) {
						skippedIndexesMap.set(index, value);
					}

					result[index] = value;

					resolvingCount--;
					await next();
				} catch (error) {
					if (stopOnError) {
						reject(error);
					} else {
						errors.push(error);
						resolvingCount--;

						// In that case we can't really continue regardless of `stopOnError` state
						// since an iterable is likely to continue throwing after it throws once.
						// If we continue calling `next()` indefinitely we will likely end up
						// in an infinite loop of failed iteration.
						try {
							await next();
						} catch (error) {
							reject(error);
						}
					}
				}
			})();
		};

		// Create the concurrent runners in a detached (non-awaited)
		// promise. We need this so we can await the `next()` calls
		// to stop creating runners before hitting the concurrency limit
		// if the iterable has already been marked as done.
		// NOTE: We *must* do this for async iterators otherwise we'll spin up
		// infinite `next()` calls by default and never start the event loop.
		(async () => {
			for (let index = 0; index < concurrency; index++) {
				try {
					// eslint-disable-next-line no-await-in-loop
					await next();
				} catch (error) {
					reject(error);
					break;
				}

				if (isIterableDone || isRejected) {
					break;
				}
			}
		})();
	});
}

export function pMapIterable(
	iterable,
	mapper,
	{
		concurrency = Number.POSITIVE_INFINITY,
		backpressure = concurrency,
	} = {},
) {
	if (iterable[Symbol.iterator] === undefined && iterable[Symbol.asyncIterator] === undefined) {
		throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
	}

	if (typeof mapper !== 'function') {
		throw new TypeError('Mapper function is required');
	}

	if (!((Number.isSafeInteger(concurrency) && concurrency >= 1) || concurrency === Number.POSITIVE_INFINITY)) {
		throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
	}

	if (!((Number.isSafeInteger(backpressure) && backpressure >= concurrency) || backpressure === Number.POSITIVE_INFINITY)) {
		throw new TypeError(`Expected \`backpressure\` to be an integer from \`concurrency\` (${concurrency}) and up or \`Infinity\`, got \`${backpressure}\` (${typeof backpressure})`);
	}

	return {
		async * [Symbol.asyncIterator]() {
			const iterator = iterable[Symbol.asyncIterator] === undefined ? iterable[Symbol.iterator]() : iterable[Symbol.asyncIterator]();

			const promises = [];
			let runningMappersCount = 0;
			let isDone = false;
			let index = 0;

			function trySpawn() {
				if (isDone || !(runningMappersCount < concurrency && promises.length < backpressure)) {
					return;
				}

				const promise = (async () => {
					const {done, value} = await iterator.next();

					if (done) {
						return {done: true};
					}

					runningMappersCount++;

					// Spawn if still below concurrency and backpressure limit
					trySpawn();

					try {
						const returnValue = await mapper(await value, index++);

						runningMappersCount--;

						if (returnValue === pMapSkip) {
							const index = promises.indexOf(promise);

							if (index > 0) {
								promises.splice(index, 1);
							}
						}

						// Spawn if still below backpressure limit and just dropped below concurrency limit
						trySpawn();

						return {done: false, value: returnValue};
					} catch (error) {
						isDone = true;
						return {error};
					}
				})();

				promises.push(promise);
			}

			trySpawn();

			while (promises.length > 0) {
				const {error, done, value} = await promises[0]; // eslint-disable-line no-await-in-loop

				promises.shift();

				if (error) {
					throw error;
				}

				if (done) {
					return;
				}

				// Spawn if just dropped below backpressure limit and below the concurrency limit
				trySpawn();

				if (value === pMapSkip) {
					continue;
				}

				yield value;
			}
		},
	};
}

export const pMapSkip = Symbol('skip');
MIT License

Copyright (c) Sindre Sorhus  (https://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.
{
	"name": "p-map",
	"version": "7.0.3",
	"description": "Map over promises concurrently",
	"license": "MIT",
	"repository": "sindresorhus/p-map",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"type": "module",
	"exports": {
		"types": "./index.d.ts",
		"default": "./index.js"
	},
	"sideEffects": false,
	"engines": {
		"node": ">=18"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"promise",
		"map",
		"resolved",
		"wait",
		"collection",
		"iterable",
		"iterator",
		"race",
		"fulfilled",
		"async",
		"await",
		"promises",
		"concurrently",
		"concurrency",
		"parallel",
		"bluebird"
	],
	"devDependencies": {
		"ava": "^5.2.0",
		"chalk": "^5.3.0",
		"delay": "^6.0.0",
		"in-range": "^3.0.0",
		"random-int": "^3.0.0",
		"time-span": "^5.1.0",
		"tsd": "^0.29.0",
		"xo": "^0.56.0"
	}
}
All packages under `src/` are licensed according to the terms in
their respective `LICENSE` or `LICENSE.md` files.

The remainder of this project is licensed under the Blue Oak
Model License, as follows:

-----

# Blue Oak Model License

Version 1.0.0

## Purpose

This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.

## Acceptance

In order to receive this license, you must agree to its
rules.  The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.

## Copyright

Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.

## Notices

You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
.

## Excuse

If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice.  If you do not do so, your license
ends immediately.

## Patent

Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.

## Reliability

No contributor can revoke this license.

## No Liability

***As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim.***
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadPackageJson = exports.findPackageJson = void 0;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const node_url_1 = require("node:url");
const NM = `${node_path_1.sep}node_modules${node_path_1.sep}`;
const STORE = `.store${node_path_1.sep}`;
const PKG = `${node_path_1.sep}package${node_path_1.sep}`;
const DIST = `${node_path_1.sep}dist${node_path_1.sep}`;
/**
 * Find the package.json file, either from a TypeScript file somewhere not
 * in a 'dist' folder, or a built and/or installed 'dist' folder.
 *
 * Note: this *only* works if you build your code into `'./dist'`, and that the
 * source path does not also contain `'dist'`! If you don't build into
 * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will
 * not work properly!
 *
 * The default `pathFromSrc` option assumes that the calling code lives one
 * folder below the root of the package. Otherwise, it must be specified.
 *
 * Example:
 *
 * ```ts
 * // src/index.ts
 * import { findPackageJson } from 'package-json-from-dist'
 *
 * const pj = findPackageJson(import.meta.url)
 * console.log(`package.json found at ${pj}`)
 * ```
 *
 * If the caller is deeper within the project source, then you must provide
 * the appropriate fallback path:
 *
 * ```ts
 * // src/components/something.ts
 * import { findPackageJson } from 'package-json-from-dist'
 *
 * const pj = findPackageJson(import.meta.url, '../../package.json')
 * console.log(`package.json found at ${pj}`)
 * ```
 *
 * When running from CommmonJS, use `__filename` instead of `import.meta.url`
 *
 * ```ts
 * // src/index.cts
 * import { findPackageJson } from 'package-json-from-dist'
 *
 * const pj = findPackageJson(__filename)
 * console.log(`package.json found at ${pj}`)
 * ```
 */
const findPackageJson = (from, pathFromSrc = '../package.json') => {
    const f = typeof from === 'object' || from.startsWith('file://') ?
        (0, node_url_1.fileURLToPath)(from)
        : from;
    const __dirname = (0, node_path_1.dirname)(f);
    const nms = __dirname.lastIndexOf(NM);
    if (nms !== -1) {
        // inside of node_modules. find the dist directly under package name.
        const nm = __dirname.substring(0, nms + NM.length);
        const pkgDir = __dirname.substring(nms + NM.length);
        // affordance for yarn berry, which puts package contents in
        // '.../node_modules/.store/${id}-${hash}/package/...'
        if (pkgDir.startsWith(STORE)) {
            const pkg = pkgDir.indexOf(PKG, STORE.length);
            if (pkg) {
                return (0, node_path_1.resolve)(nm, pkgDir.substring(0, pkg + PKG.length), 'package.json');
            }
        }
        const pkgName = pkgDir.startsWith('@') ?
            pkgDir.split(node_path_1.sep, 2).join(node_path_1.sep)
            : String(pkgDir.split(node_path_1.sep)[0]);
        return (0, node_path_1.resolve)(nm, pkgName, 'package.json');
    }
    else {
        // see if we are in a dist folder.
        const d = __dirname.lastIndexOf(DIST);
        if (d !== -1) {
            return (0, node_path_1.resolve)(__dirname.substring(0, d), 'package.json');
        }
        else {
            return (0, node_path_1.resolve)(__dirname, pathFromSrc);
        }
    }
};
exports.findPackageJson = findPackageJson;
/**
 * Load the package.json file, either from a TypeScript file somewhere not
 * in a 'dist' folder, or a built and/or installed 'dist' folder.
 *
 * Note: this *only* works if you build your code into `'./dist'`, and that the
 * source path does not also contain `'dist'`! If you don't build into
 * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will
 * not work properly!
 *
 * The default `pathFromSrc` option assumes that the calling code lives one
 * folder below the root of the package. Otherwise, it must be specified.
 *
 * Example:
 *
 * ```ts
 * // src/index.ts
 * import { loadPackageJson } from 'package-json-from-dist'
 *
 * const pj = loadPackageJson(import.meta.url)
 * console.log(`Hello from ${pj.name}@${pj.version}`)
 * ```
 *
 * If the caller is deeper within the project source, then you must provide
 * the appropriate fallback path:
 *
 * ```ts
 * // src/components/something.ts
 * import { loadPackageJson } from 'package-json-from-dist'
 *
 * const pj = loadPackageJson(import.meta.url, '../../package.json')
 * console.log(`Hello from ${pj.name}@${pj.version}`)
 * ```
 *
 * When running from CommmonJS, use `__filename` instead of `import.meta.url`
 *
 * ```ts
 * // src/index.cts
 * import { loadPackageJson } from 'package-json-from-dist'
 *
 * const pj = loadPackageJson(__filename)
 * console.log(`Hello from ${pj.name}@${pj.version}`)
 * ```
 */
const loadPackageJson = (from, pathFromSrc = '../package.json') => JSON.parse((0, node_fs_1.readFileSync)((0, exports.findPackageJson)(from, pathFromSrc), 'utf8'));
exports.loadPackageJson = loadPackageJson;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
import { readFileSync } from 'node:fs';
import { dirname, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
const NM = `${sep}node_modules${sep}`;
const STORE = `.store${sep}`;
const PKG = `${sep}package${sep}`;
const DIST = `${sep}dist${sep}`;
/**
 * Find the package.json file, either from a TypeScript file somewhere not
 * in a 'dist' folder, or a built and/or installed 'dist' folder.
 *
 * Note: this *only* works if you build your code into `'./dist'`, and that the
 * source path does not also contain `'dist'`! If you don't build into
 * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will
 * not work properly!
 *
 * The default `pathFromSrc` option assumes that the calling code lives one
 * folder below the root of the package. Otherwise, it must be specified.
 *
 * Example:
 *
 * ```ts
 * // src/index.ts
 * import { findPackageJson } from 'package-json-from-dist'
 *
 * const pj = findPackageJson(import.meta.url)
 * console.log(`package.json found at ${pj}`)
 * ```
 *
 * If the caller is deeper within the project source, then you must provide
 * the appropriate fallback path:
 *
 * ```ts
 * // src/components/something.ts
 * import { findPackageJson } from 'package-json-from-dist'
 *
 * const pj = findPackageJson(import.meta.url, '../../package.json')
 * console.log(`package.json found at ${pj}`)
 * ```
 *
 * When running from CommmonJS, use `__filename` instead of `import.meta.url`
 *
 * ```ts
 * // src/index.cts
 * import { findPackageJson } from 'package-json-from-dist'
 *
 * const pj = findPackageJson(__filename)
 * console.log(`package.json found at ${pj}`)
 * ```
 */
export const findPackageJson = (from, pathFromSrc = '../package.json') => {
    const f = typeof from === 'object' || from.startsWith('file://') ?
        fileURLToPath(from)
        : from;
    const __dirname = dirname(f);
    const nms = __dirname.lastIndexOf(NM);
    if (nms !== -1) {
        // inside of node_modules. find the dist directly under package name.
        const nm = __dirname.substring(0, nms + NM.length);
        const pkgDir = __dirname.substring(nms + NM.length);
        // affordance for yarn berry, which puts package contents in
        // '.../node_modules/.store/${id}-${hash}/package/...'
        if (pkgDir.startsWith(STORE)) {
            const pkg = pkgDir.indexOf(PKG, STORE.length);
            if (pkg) {
                return resolve(nm, pkgDir.substring(0, pkg + PKG.length), 'package.json');
            }
        }
        const pkgName = pkgDir.startsWith('@') ?
            pkgDir.split(sep, 2).join(sep)
            : String(pkgDir.split(sep)[0]);
        return resolve(nm, pkgName, 'package.json');
    }
    else {
        // see if we are in a dist folder.
        const d = __dirname.lastIndexOf(DIST);
        if (d !== -1) {
            return resolve(__dirname.substring(0, d), 'package.json');
        }
        else {
            return resolve(__dirname, pathFromSrc);
        }
    }
};
/**
 * Load the package.json file, either from a TypeScript file somewhere not
 * in a 'dist' folder, or a built and/or installed 'dist' folder.
 *
 * Note: this *only* works if you build your code into `'./dist'`, and that the
 * source path does not also contain `'dist'`! If you don't build into
 * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will
 * not work properly!
 *
 * The default `pathFromSrc` option assumes that the calling code lives one
 * folder below the root of the package. Otherwise, it must be specified.
 *
 * Example:
 *
 * ```ts
 * // src/index.ts
 * import { loadPackageJson } from 'package-json-from-dist'
 *
 * const pj = loadPackageJson(import.meta.url)
 * console.log(`Hello from ${pj.name}@${pj.version}`)
 * ```
 *
 * If the caller is deeper within the project source, then you must provide
 * the appropriate fallback path:
 *
 * ```ts
 * // src/components/something.ts
 * import { loadPackageJson } from 'package-json-from-dist'
 *
 * const pj = loadPackageJson(import.meta.url, '../../package.json')
 * console.log(`Hello from ${pj.name}@${pj.version}`)
 * ```
 *
 * When running from CommmonJS, use `__filename` instead of `import.meta.url`
 *
 * ```ts
 * // src/index.cts
 * import { loadPackageJson } from 'package-json-from-dist'
 *
 * const pj = loadPackageJson(__filename)
 * console.log(`Hello from ${pj.name}@${pj.version}`)
 * ```
 */
export const loadPackageJson = (from, pathFromSrc = '../package.json') => JSON.parse(readFileSync(findPackageJson(from, pathFromSrc), 'utf8'));
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "name": "package-json-from-dist",
  "version": "1.0.1",
  "description": "Load the local package.json from either src or dist folder",
  "main": "./dist/commonjs/index.js",
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "presnap": "npm run prepare",
    "test": "tap",
    "snap": "tap",
    "format": "prettier --write . --log-level warn",
    "typedoc": "typedoc"
  },
  "author": "Isaac Z. Schlueter  (https://izs.me)",
  "license": "BlueOak-1.0.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/package-json-from-dist.git"
  },
  "devDependencies": {
    "@types/node": "^20.12.12",
    "prettier": "^3.2.5",
    "tap": "^18.5.3",
    "typedoc": "^0.24.8",
    "typescript": "^5.1.6",
    "tshy": "^1.14.0"
  },
  "prettier": {
    "semi": false,
    "printWidth": 70,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf",
    "experimentalTernaries": true
  },
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "types": "./dist/commonjs/index.d.ts",
  "type": "module"
}
The ISC License

Copyright (c) Isaac Z. Schlueter, Kat Marchán, npm, Inc., and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# pacote

Fetches package manifests and tarballs from the npm registry.

## USAGE

```js
const pacote = require('pacote')

// get a package manifest
pacote.manifest('foo@1.x').then(manifest => console.log('got it', manifest))

// extract a package into a folder
pacote.extract('github:npm/cli', 'some/path', options)
  .then(({from, resolved, integrity}) => {
    console.log('extracted!', from, resolved, integrity)
  })

pacote.tarball('https://server.com/package.tgz').then(data => {
  console.log('got ' + data.length + ' bytes of tarball data')
})
```

`pacote` works with any kind of package specifier that npm can install.  If
you can pass it to the npm CLI, you can pass it to pacote.  (In fact, that's
exactly what the npm CLI does.)

Anything that you can do with one kind of package, you can do with another.

Data that isn't relevant (like a packument for a tarball) will be
simulated.

`prepare` scripts will be run when generating tarballs from `git` and
`directory` locations, to simulate what _would_ be published to the
registry, so that you get a working package instead of just raw source
code that might need to be transpiled.

## CLI

This module exports a command line interface that can do most of what is
described below.  Run `pacote -h` to learn more.

```
Pacote - The JavaScript Package Handler, v10.1.1

Usage:

  pacote resolve 
    Resolve a specifier and output the fully resolved target
    Returns integrity and from if '--long' flag is set.

  pacote manifest 
    Fetch a manifest and print to stdout

  pacote packument 
    Fetch a full packument and print to stdout

  pacote tarball  []
    Fetch a package tarball and save to 
    If  is missing or '-', the tarball will be streamed to stdout.

  pacote extract  
    Extract a package to the destination folder.

Configuration values all match the names of configs passed to npm, or
options passed to Pacote.  Additional flags for this executable:

  --long     Print an object from 'resolve', including integrity and spec.
  --json     Print result objects as JSON rather than node's default.
             (This is the default if stdout is not a TTY.)
  --help -h  Print this helpful text.

For example '--cache=/path/to/folder' will use that folder as the cache.
```

## API

The `spec` refers to any kind of package specifier that npm can install.
If you can pass it to the npm CLI, you can pass it to pacote.  (In fact,
that's exactly what the npm CLI does.)

See below for valid `opts` values.

* `pacote.resolve(spec, opts)` Resolve a specifier like `foo@latest` or
  `github:user/project` all the way to a tarball url, tarball file, or git
  repo with commit hash.

* `pacote.extract(spec, dest, opts)` Extract a package's tarball into a
  destination folder.  Returns a promise that resolves to the
  `{from,resolved,integrity}` of the extracted package.

* `pacote.manifest(spec, opts)` Fetch (or simulate) a package's manifest
  (basically, the `package.json` file, plus a bit of metadata).
  See below for more on manifests and packuments.  Returns a Promise that
  resolves to the manifest object.

* `pacote.packument(spec, opts)` Fetch (or simulate) a package's packument
  (basically, the top-level package document listing all the manifests that
  the registry returns).  See below for more on manifests and packuments.
  Returns a Promise that resolves to the packument object.

* `pacote.tarball(spec, opts)`  Get a package tarball data as a buffer in
  memory.  Returns a Promise that resolves to the tarball data Buffer, with
  `from`, `resolved`, and `integrity` fields attached.

* `pacote.tarball.file(spec, dest, opts)`  Save a package tarball data to
  a file on disk.  Returns a Promise that resolves to
  `{from,integrity,resolved}` of the fetched tarball.

* `pacote.tarball.stream(spec, streamHandler, opts)`  Fetch a tarball and
  make the stream available to the `streamHandler` function.

    This is mostly an internal function, but it is exposed because it does
    provide some functionality that may be difficult to achieve otherwise.

    The `streamHandler` function MUST return a Promise that resolves when
    the stream (and all associated work) is ended, or rejects if the stream
    has an error.

    The `streamHandler` function MAY be called multiple times, as Pacote
    retries requests in some scenarios, such as cache corruption or
    retriable network failures.

### Options

Options are passed to
[`npm-registry-fetch`](http://npm.im/npm-registry-fetch) and
[`cacache`](http://npm.im/cacache), so in addition to these, anything for
those modules can be given to pacote as well.

Options object is cloned, and mutated along the way to add integrity,
resolved, and other properties, as they are determined.

* `cache` Where to store cache entries and temp files.  Passed to
  [`cacache`](http://npm.im/cacache).  Defaults to the same cache directory
  that npm will use by default, based on platform and environment.
* `where` Base folder for resolving relative `file:` dependencies.
* `resolved` Shortcut for looking up resolved values.  Should be specified
  if known.
* `integrity` Expected integrity of fetched package tarball.  If specified,
  tarballs with mismatched integrity values will raise an `EINTEGRITY`
  error.
* `umask` Permission mode mask for extracted files and directories.
  Defaults to `0o22`.  See "Extracted File Modes" below.
* `fmode` Minimum permission mode for extracted files.  Defaults to
  `0o666`.  See "Extracted File Modes" below.
* `dmode` Minimum permission mode for extracted directories.  Defaults to
  `0o777`.  See "Extracted File Modes" below.
* `preferOnline` Prefer to revalidate cache entries, even when it would not
  be strictly necessary.  Default `false`.
* `before` When picking a manifest from a packument, only consider
  packages published before the specified date.  Default `null`.
* `defaultTag` The default `dist-tag` to use when choosing a manifest from a
  packument.  Defaults to `latest`.
* `registry` The npm registry to use by default.  Defaults to
  `https://registry.npmjs.org/`.
* `fullMetadata` Fetch the full metadata from the registry for packuments,
  including information not strictly required for installation (author,
  description, etc.)  Defaults to `true` when `before` is set, since the
  version publish time is part of the extended packument metadata.
* `fullReadJson` Use the slower `read-package-json` package insted of
  `read-package-json-fast` in order to include extra fields like "readme" in
  the manifest. Defaults to `false`.
* `packumentCache` For registry packuments only, you may provide a `Map`
  object which will be used to cache packument requests between pacote
  calls.  This allows you to easily avoid hitting the registry multiple
  times (even just to validate the cache) for a given packument, since it
  is unlikely to change in the span of a single command.
* `verifySignatures` A boolean that will make pacote verify the
    integrity signature of a manifest, if present.  There must be a
    configured `_keys` entry in the config that is scoped to the
    registry the manifest is being fetched from.
* `verifyAttestations` A boolean that will make pacote verify Sigstore
    attestations, if present. There must be a configured `_keys` entry in the
    config that is scoped to the registry the manifest is being fetched from.
* `tufCache` Where to store metadata/target files when retrieving the package
  attestation key material via TUF. Defaults to the same cache directory that
  npm will use by default, based on platform and environment.

### Advanced API

Each different type of fetcher is exposed for more advanced usage such as
using helper methods from this classes:

* `DirFetcher`
* `FileFetcher`
* `GitFetcher`
* `RegistryFetcher`
* `RemoteFetcher`

## Extracted File Modes

Files are extracted with a mode matching the following formula:

```
( (tarball entry mode value) | (minimum mode option) ) ~ (umask)
```

This is in order to prevent unreadable files or unlistable directories from
cluttering a project's `node_modules` folder, even if the package tarball
specifies that the file should be inaccessible.

It also prevents files from being group- or world-writable without explicit
opt-in by the user, because all file and directory modes are masked against
the `umask` value.

So, a file which is `0o771` in the tarball, using the default `fmode` of
`0o666` and `umask` of `0o22`, will result in a file mode of `0o755`:

```
(0o771 | 0o666) => 0o777
(0o777 ~ 0o22) => 0o755
```

In almost every case, the defaults are appropriate.  To respect exactly
what is in the package tarball (even if this makes an unusable system), set
both `dmode` and `fmode` options to `0`.  Otherwise, the `umask` config
should be used in most cases where file mode modifications are required,
and this functions more or less the same as the `umask` value in most Unix
systems.

## Extracted File Ownership

When running as `root` on Unix systems, all extracted files and folders
will have their owning `uid` and `gid` values set to match the ownership
of the containing folder.

This prevents `root`-owned files showing up in a project's `node_modules`
folder when a user runs `sudo npm install`.

## Manifests

A `manifest` is similar to a `package.json` file.  However, it has a few
pieces of extra metadata, and sometimes lacks metadata that is inessential
to package installation.

In addition to the common `package.json` fields, manifests include:

* `manifest._resolved` The tarball url or file path where the package
  artifact can be found.
* `manifest._from` A normalized form of the spec passed in as an argument.
* `manifest._integrity` The integrity value for the package artifact.
* `manifest._id` The canonical spec of this package version: name@version.
* `manifest.dist` Registry manifests (those included in a packument) have a
  `dist` object.  Only `tarball` is required, though at least one of
  `shasum` or `integrity` is almost always present.

    * `tarball` The url to the associated package artifact.  (Copied by
      Pacote to `manifest._resolved`.)
    * `integrity` The integrity SRI string for the artifact.  This may not
      be present for older packages on the npm registry.  (Copied by Pacote
      to `manifest._integrity`.)
    * `shasum` Legacy integrity value.  Hexadecimal-encoded sha1 hash.
      (Converted to an SRI string and copied by Pacote to
      `manifest._integrity` when `dist.integrity` is not present.)
    * `fileCount` Number of files in the tarball.
    * `unpackedSize` Size on disk of the package when unpacked.
    * `signatures` Signatures of the shasum.  Includes the keyid that
        correlates to a [`key from the npm
        registry`](https://registry.npmjs.org/-/npm/v1/keys)

## Packuments

A packument is the top-level package document that lists the set of
manifests for available versions for a package.

When a packument is fetched with `accept:
application/vnd.npm.install-v1+json` in the HTTP headers, only the most
minimum necessary metadata is returned.  Additional metadata is returned
when fetched with only `accept: application/json`.

For Pacote's purposes, the following fields are relevant:

* `versions` An object where each key is a version, and each value is the
  manifest for that version.
* `dist-tags` An object mapping dist-tags to version numbers.  This is how
  `foo@latest` gets turned into `foo@1.2.3`.
* `time` In the full packument, an object mapping version numbers to
  publication times, for the `opts.before` functionality.

Pacote adds the following field, regardless of the accept header:

* `_contentLength` The size of the packument.
#!/usr/bin/env node

const run = conf => {
  const pacote = require('../')
  switch (conf._[0]) {
    case 'resolve':
    case 'manifest':
    case 'packument':
      if (conf._[0] === 'resolve' && conf.long) {
        return pacote.manifest(conf._[1], conf).then(mani => ({
          resolved: mani._resolved,
          integrity: mani._integrity,
          from: mani._from,
        }))
      }
      return pacote[conf._[0]](conf._[1], conf)

    case 'tarball':
      if (!conf._[2] || conf._[2] === '-') {
        return pacote.tarball.stream(conf._[1], stream => {
          stream.pipe(
            conf.testStdout ||
            /* istanbul ignore next */
            process.stdout
          )
          // make sure it resolves something falsey
          return stream.promise().then(() => {
            return false
          })
        }, conf)
      } else {
        return pacote.tarball.file(conf._[1], conf._[2], conf)
      }

    case 'extract':
      return pacote.extract(conf._[1], conf._[2], conf)

    default: /* istanbul ignore next */ {
      throw new Error(`bad command: ${conf._[0]}`)
    }
  }
}

const version = require('../package.json').version
const usage = () =>
`Pacote - The JavaScript Package Handler, v${version}

Usage:

  pacote resolve 
    Resolve a specifier and output the fully resolved target
    Returns integrity and from if '--long' flag is set.

  pacote manifest 
    Fetch a manifest and print to stdout

  pacote packument 
    Fetch a full packument and print to stdout

  pacote tarball  []
    Fetch a package tarball and save to 
    If  is missing or '-', the tarball will be streamed to stdout.

  pacote extract  
    Extract a package to the destination folder.

Configuration values all match the names of configs passed to npm, or
options passed to Pacote.  Additional flags for this executable:

  --long     Print an object from 'resolve', including integrity and spec.
  --json     Print result objects as JSON rather than node's default.
             (This is the default if stdout is not a TTY.)
  --help -h  Print this helpful text.

For example '--cache=/path/to/folder' will use that folder as the cache.
`

const shouldJSON = (conf, result) =>
  conf.json ||
  !process.stdout.isTTY &&
  conf.json === undefined &&
  result &&
  typeof result === 'object'

const pretty = (conf, result) =>
  shouldJSON(conf, result) ? JSON.stringify(result, 0, 2) : result

let addedLogListener = false
const main = args => {
  const conf = parse(args)
  if (conf.help || conf.h) {
    return console.log(usage())
  }

  if (!addedLogListener) {
    process.on('log', console.error)
    addedLogListener = true
  }

  try {
    return run(conf)
      .then(result => result && console.log(pretty(conf, result)))
      .catch(er => {
        console.error(er)
        process.exit(1)
      })
  } catch (er) {
    console.error(er.message)
    console.error(usage())
  }
}

const parseArg = arg => {
  const split = arg.slice(2).split('=')
  const k = split.shift()
  const v = split.join('=')
  const no = /^no-/.test(k) && !v
  const key = (no ? k.slice(3) : k)
    .replace(/^tag$/, 'defaultTag')
    .replace(/-([a-z])/g, (_, c) => c.toUpperCase())
  const value = v ? v.replace(/^~/, process.env.HOME) : !no
  return { key, value }
}

const parse = args => {
  const conf = {
    _: [],
    cache: process.env.HOME + '/.npm/_cacache',
  }
  let dashdash = false
  args.forEach(arg => {
    if (dashdash) {
      conf._.push(arg)
    } else if (arg === '--') {
      dashdash = true
    } else if (arg === '-h') {
      conf.help = true
    } else if (/^--/.test(arg)) {
      const { key, value } = parseArg(arg)
      conf[key] = value
    } else {
      conf._.push(arg)
    }
  })
  return conf
}

if (module === require.main) {
  main(process.argv.slice(2))
} else {
  module.exports = {
    main,
    run,
    usage,
    parseArg,
    parse,
  }
}
const { resolve } = require('node:path')
const packlist = require('npm-packlist')
const runScript = require('@npmcli/run-script')
const tar = require('tar')
const { Minipass } = require('minipass')
const Fetcher = require('./fetcher.js')
const FileFetcher = require('./file.js')
const _ = require('./util/protected.js')
const tarCreateOptions = require('./util/tar-create-options.js')

class DirFetcher extends Fetcher {
  constructor (spec, opts) {
    super(spec, opts)
    // just the fully resolved filename
    this.resolved = this.spec.fetchSpec

    this.tree = opts.tree || null
    this.Arborist = opts.Arborist || null
  }

  // exposes tarCreateOptions as public API
  static tarCreateOptions (manifest) {
    return tarCreateOptions(manifest)
  }

  get types () {
    return ['directory']
  }

  #prepareDir () {
    return this.manifest().then(mani => {
      if (!mani.scripts || !mani.scripts.prepare) {
        return
      }
      if (this.opts.ignoreScripts) {
        return
      }

      // we *only* run prepare.
      // pre/post-pack is run by the npm CLI for publish and pack,
      // but this function is *also* run when installing git deps
      const stdio = this.opts.foregroundScripts ? 'inherit' : 'pipe'

      return runScript({
        // this || undefined is because runScript will be unhappy with the default null value
        scriptShell: this.opts.scriptShell || undefined,
        pkg: mani,
        event: 'prepare',
        path: this.resolved,
        stdio,
        env: {
          npm_package_resolved: this.resolved,
          npm_package_integrity: this.integrity,
          npm_package_json: resolve(this.resolved, 'package.json'),
        },
      })
    })
  }

  [_.tarballFromResolved] () {
    if (!this.tree && !this.Arborist) {
      throw new Error('DirFetcher requires either a tree or an Arborist constructor to pack')
    }

    const stream = new Minipass()
    stream.resolved = this.resolved
    stream.integrity = this.integrity

    const { prefix, workspaces } = this.opts

    // run the prepare script, get the list of files, and tar it up
    // pipe to the stream, and proxy errors the chain.
    this.#prepareDir()
      .then(async () => {
        if (!this.tree) {
          const arb = new this.Arborist({ path: this.resolved })
          this.tree = await arb.loadActual()
        }
        return packlist(this.tree, { path: this.resolved, prefix, workspaces })
      })
      .then(files => tar.c(tarCreateOptions(this.package), files)
        .on('error', er => stream.emit('error', er)).pipe(stream))
      .catch(er => stream.emit('error', er))
    return stream
  }

  manifest () {
    if (this.package) {
      return Promise.resolve(this.package)
    }

    return this[_.readPackageJson](this.resolved)
      .then(mani => this.package = {
        ...mani,
        _integrity: this.integrity && String(this.integrity),
        _resolved: this.resolved,
        _from: this.from,
      })
  }

  packument () {
    return FileFetcher.prototype.packument.apply(this)
  }
}
module.exports = DirFetcher
// This is the base class that the other fetcher types in lib
// all descend from.
// It handles the unpacking and retry logic that is shared among
// all of the other Fetcher types.

const { basename, dirname } = require('node:path')
const { rm, mkdir } = require('node:fs/promises')
const PackageJson = require('@npmcli/package-json')
const cacache = require('cacache')
const fsm = require('fs-minipass')
const getContents = require('@npmcli/installed-package-contents')
const npa = require('npm-package-arg')
const retry = require('promise-retry')
const ssri = require('ssri')
const tar = require('tar')
const { Minipass } = require('minipass')
const { log } = require('proc-log')
const _ = require('./util/protected.js')
const cacheDir = require('./util/cache-dir.js')
const isPackageBin = require('./util/is-package-bin.js')
const removeTrailingSlashes = require('./util/trailing-slashes.js')

// Pacote is only concerned with the package.json contents
const packageJsonPrepare = (p) => PackageJson.prepare(p).then(pkg => pkg.content)
const packageJsonNormalize = (p) => PackageJson.normalize(p).then(pkg => pkg.content)

class FetcherBase {
  constructor (spec, opts) {
    if (!opts || typeof opts !== 'object') {
      throw new TypeError('options object is required')
    }
    this.spec = npa(spec, opts.where)

    this.allowGitIgnore = !!opts.allowGitIgnore

    // a bit redundant because presumably the caller already knows this,
    // but it makes it easier to not have to keep track of the requested
    // spec when we're dispatching thousands of these at once, and normalizing
    // is nice.  saveSpec is preferred if set, because it turns stuff like
    // x/y#committish into github:x/y#committish.  use name@rawSpec for
    // registry deps so that we turn xyz and xyz@ -> xyz@
    this.from = this.spec.registry
      ? `${this.spec.name}@${this.spec.rawSpec}` : this.spec.saveSpec

    this.#assertType()
    // clone the opts object so that others aren't upset when we mutate it
    // by adding/modifying the integrity value.
    this.opts = { ...opts }

    this.cache = opts.cache || cacheDir().cacache
    this.tufCache = opts.tufCache || cacheDir().tufcache
    this.resolved = opts.resolved || null

    // default to caching/verifying with sha512, that's what we usually have
    // need to change this default, or start overriding it, when sha512
    // is no longer strong enough.
    this.defaultIntegrityAlgorithm = opts.defaultIntegrityAlgorithm || 'sha512'

    if (typeof opts.integrity === 'string') {
      this.opts.integrity = ssri.parse(opts.integrity)
    }

    this.package = null
    this.type = this.constructor.name
    this.fmode = opts.fmode || 0o666
    this.dmode = opts.dmode || 0o777
    // we don't need a default umask, because we don't chmod files coming
    // out of package tarballs.  they're forced to have a mode that is
    // valid, regardless of what's in the tarball entry, and then we let
    // the process's umask setting do its job.  but if configured, we do
    // respect it.
    this.umask = opts.umask || 0

    this.preferOnline = !!opts.preferOnline
    this.preferOffline = !!opts.preferOffline
    this.offline = !!opts.offline

    this.before = opts.before
    this.fullMetadata = this.before ? true : !!opts.fullMetadata
    this.fullReadJson = !!opts.fullReadJson
    this[_.readPackageJson] = this.fullReadJson
      ? packageJsonPrepare
      : packageJsonNormalize

    // rrh is a registry hostname or 'never' or 'always'
    // defaults to registry.npmjs.org
    this.replaceRegistryHost = (!opts.replaceRegistryHost || opts.replaceRegistryHost === 'npmjs') ?
      'registry.npmjs.org' : opts.replaceRegistryHost

    this.defaultTag = opts.defaultTag || 'latest'
    this.registry = removeTrailingSlashes(opts.registry || 'https://registry.npmjs.org')

    // command to run 'prepare' scripts on directories and git dirs
    // To use pacote with yarn, for example, set npmBin to 'yarn'
    // and npmCliConfig with yarn's equivalents.
    this.npmBin = opts.npmBin || 'npm'

    // command to install deps for preparing
    this.npmInstallCmd = opts.npmInstallCmd || ['install', '--force']

    // XXX fill more of this in based on what we know from this.opts
    // we explicitly DO NOT fill in --tag, though, since we are often
    // going to be packing in the context of a publish, which may set
    // a dist-tag, but certainly wants to keep defaulting to latest.
    this.npmCliConfig = opts.npmCliConfig || [
      `--cache=${dirname(this.cache)}`,
      `--prefer-offline=${!!this.preferOffline}`,
      `--prefer-online=${!!this.preferOnline}`,
      `--offline=${!!this.offline}`,
      ...(this.before ? [`--before=${this.before.toISOString()}`] : []),
      '--no-progress',
      '--no-save',
      '--no-audit',
      // override any omit settings from the environment
      '--include=dev',
      '--include=peer',
      '--include=optional',
      // we need the actual things, not just the lockfile
      '--no-package-lock-only',
      '--no-dry-run',
    ]
  }

  get integrity () {
    return this.opts.integrity || null
  }

  set integrity (i) {
    if (!i) {
      return
    }

    i = ssri.parse(i)
    const current = this.opts.integrity

    // do not ever update an existing hash value, but do
    // merge in NEW algos and hashes that we don't already have.
    if (current) {
      current.merge(i)
    } else {
      this.opts.integrity = i
    }
  }

  get notImplementedError () {
    return new Error('not implemented in this fetcher type: ' + this.type)
  }

  // override in child classes
  // Returns a Promise that resolves to this.resolved string value
  resolve () {
    return this.resolved ? Promise.resolve(this.resolved)
      : Promise.reject(this.notImplementedError)
  }

  packument () {
    return Promise.reject(this.notImplementedError)
  }

  // override in child class
  // returns a manifest containing:
  // - name
  // - version
  // - _resolved
  // - _integrity
  // - plus whatever else was in there (corgi, full metadata, or pj file)
  manifest () {
    return Promise.reject(this.notImplementedError)
  }

  // private, should be overridden.
  // Note that they should *not* calculate or check integrity or cache,
  // but *just*  return the raw tarball data stream.
  [_.tarballFromResolved] () {
    throw this.notImplementedError
  }

  // public, should not be overridden
  tarball () {
    return this.tarballStream(stream => stream.concat().then(data => {
      data.integrity = this.integrity && String(this.integrity)
      data.resolved = this.resolved
      data.from = this.from
      return data
    }))
  }

  // private
  // Note: cacache will raise a EINTEGRITY error if the integrity doesn't match
  #tarballFromCache () {
    const startTime = Date.now()
    const stream = cacache.get.stream.byDigest(this.cache, this.integrity, this.opts)
    const elapsedTime = Date.now() - startTime
    // cache is good, so log it as a hit in particular since there was no fetch logged
    log.http(
      'cache',
      `${this.spec} ${elapsedTime}ms (cache hit)`
    )
    return stream
  }

  get [_.cacheFetches] () {
    return true
  }

  #istream (stream) {
    // if not caching this, just return it
    if (!this.opts.cache || !this[_.cacheFetches]) {
      // instead of creating a new integrity stream, we only piggyback on the
      // provided stream's events
      if (stream.hasIntegrityEmitter) {
        stream.on('integrity', i => this.integrity = i)
        return stream
      }

      const istream = ssri.integrityStream(this.opts)
      istream.on('integrity', i => this.integrity = i)
      stream.on('error', err => istream.emit('error', err))
      return stream.pipe(istream)
    }

    // we have to return a stream that gets ALL the data, and proxies errors,
    // but then pipe from the original tarball stream into the cache as well.
    // To do this without losing any data, and since the cacache put stream
    // is not a passthrough, we have to pipe from the original stream into
    // the cache AFTER we pipe into the middleStream.  Since the cache stream
    // has an asynchronous flush to write its contents to disk, we need to
    // defer the middleStream end until the cache stream ends.
    const middleStream = new Minipass()
    stream.on('error', err => middleStream.emit('error', err))
    stream.pipe(middleStream, { end: false })
    const cstream = cacache.put.stream(
      this.opts.cache,
      `pacote:tarball:${this.from}`,
      this.opts
    )
    cstream.on('integrity', i => this.integrity = i)
    cstream.on('error', err => stream.emit('error', err))
    stream.pipe(cstream)

    // eslint-disable-next-line promise/catch-or-return
    cstream.promise().catch(() => {}).then(() => middleStream.end())
    return middleStream
  }

  pickIntegrityAlgorithm () {
    return this.integrity ? this.integrity.pickAlgorithm(this.opts)
      : this.defaultIntegrityAlgorithm
  }

  // TODO: check error class, once those are rolled out to our deps
  isDataCorruptionError (er) {
    return er.code === 'EINTEGRITY' || er.code === 'Z_DATA_ERROR'
  }

  // override the types getter
  get types () {
    return false
  }

  #assertType () {
    if (this.types && !this.types.includes(this.spec.type)) {
      throw new TypeError(`Wrong spec type (${
        this.spec.type
      }) for ${
        this.constructor.name
      }. Supported types: ${this.types.join(', ')}`)
    }
  }

  // We allow ENOENTs from cacache, but not anywhere else.
  // An ENOENT trying to read a tgz file, for example, is Right Out.
  isRetriableError (er) {
    // TODO: check error class, once those are rolled out to our deps
    return this.isDataCorruptionError(er) ||
      er.code === 'ENOENT' ||
      er.code === 'EISDIR'
  }

  // Mostly internal, but has some uses
  // Pass in a function which returns a promise
  // Function will be called 1 or more times with streams that may fail.
  // Retries:
  // Function MUST handle errors on the stream by rejecting the promise,
  // so that retry logic can pick it up and either retry or fail whatever
  // promise it was making (ie, failing extraction, etc.)
  //
  // The return value of this method is a Promise that resolves the same
  // as whatever the streamHandler resolves to.
  //
  // This should never be overridden by child classes, but it is public.
  tarballStream (streamHandler) {
    // Only short-circuit via cache if we have everything else we'll need,
    // and the user has not expressed a preference for checking online.

    const fromCache = (
      !this.preferOnline &&
      this.integrity &&
      this.resolved
    ) ? streamHandler(this.#tarballFromCache()).catch(er => {
        if (this.isDataCorruptionError(er)) {
          log.warn('tarball', `cached data for ${
          this.spec
        } (${this.integrity}) seems to be corrupted. Refreshing cache.`)
          return this.cleanupCached().then(() => {
            throw er
          })
        } else {
          throw er
        }
      }) : null

    const fromResolved = er => {
      if (er) {
        if (!this.isRetriableError(er)) {
          throw er
        }
        log.silly('tarball', `no local data for ${
          this.spec
        }. Extracting by manifest.`)
      }
      return this.resolve().then(() => retry(tryAgain =>
        streamHandler(this.#istream(this[_.tarballFromResolved]()))
          .catch(streamErr => {
          // Most likely data integrity.  A cache ENOENT error is unlikely
          // here, since we're definitely not reading from the cache, but it
          // IS possible that the fetch subsystem accessed the cache, and the
          // entry got blown away or something.  Try one more time to be sure.
            if (this.isRetriableError(streamErr)) {
              log.warn('tarball', `tarball data for ${
              this.spec
            } (${this.integrity}) seems to be corrupted. Trying again.`)
              return this.cleanupCached().then(() => tryAgain(streamErr))
            }
            throw streamErr
          }), { retries: 1, minTimeout: 0, maxTimeout: 0 }))
    }

    return fromCache ? fromCache.catch(fromResolved) : fromResolved()
  }

  cleanupCached () {
    return cacache.rm.content(this.cache, this.integrity, this.opts)
  }

  #empty (path) {
    return getContents({ path, depth: 1 }).then(contents => Promise.all(
      contents.map(entry => rm(entry, { recursive: true, force: true }))))
  }

  async #mkdir (dest) {
    await this.#empty(dest)
    return await mkdir(dest, { recursive: true })
  }

  // extraction is always the same.  the only difference is where
  // the tarball comes from.
  async extract (dest) {
    await this.#mkdir(dest)
    return this.tarballStream((tarball) => this.#extract(dest, tarball))
  }

  #toFile (dest) {
    return this.tarballStream(str => new Promise((res, rej) => {
      const writer = new fsm.WriteStream(dest)
      str.on('error', er => writer.emit('error', er))
      writer.on('error', er => rej(er))
      writer.on('close', () => res({
        integrity: this.integrity && String(this.integrity),
        resolved: this.resolved,
        from: this.from,
      }))
      str.pipe(writer)
    }))
  }

  // don't use this.#mkdir because we don't want to rimraf anything
  async tarballFile (dest) {
    const dir = dirname(dest)
    await mkdir(dir, { recursive: true })
    return this.#toFile(dest)
  }

  #extract (dest, tarball) {
    const extractor = tar.x(this.#tarxOptions({ cwd: dest }))
    const p = new Promise((resolve, reject) => {
      extractor.on('end', () => {
        resolve({
          resolved: this.resolved,
          integrity: this.integrity && String(this.integrity),
          from: this.from,
        })
      })

      extractor.on('error', er => {
        log.warn('tar', er.message)
        log.silly('tar', er)
        reject(er)
      })

      tarball.on('error', er => reject(er))
    })

    tarball.pipe(extractor)
    return p
  }

  // always ensure that entries are at least as permissive as our configured
  // dmode/fmode, but never more permissive than the umask allows.
  #entryMode (path, mode, type) {
    const m = /Directory|GNUDumpDir/.test(type) ? this.dmode
      : /File$/.test(type) ? this.fmode
      : /* istanbul ignore next - should never happen in a pkg */ 0

    // make sure package bins are executable
    const exe = isPackageBin(this.package, path) ? 0o111 : 0
    // always ensure that files are read/writable by the owner
    return ((mode | m) & ~this.umask) | exe | 0o600
  }

  #tarxOptions ({ cwd }) {
    const sawIgnores = new Set()
    return {
      cwd,
      noChmod: true,
      noMtime: true,
      filter: (name, entry) => {
        if (/Link$/.test(entry.type)) {
          return false
        }
        entry.mode = this.#entryMode(entry.path, entry.mode, entry.type)
        // this replicates the npm pack behavior where .gitignore files
        // are treated like .npmignore files, but only if a .npmignore
        // file is not present.
        if (/File$/.test(entry.type)) {
          const base = basename(entry.path)
          if (base === '.npmignore') {
            sawIgnores.add(entry.path)
          } else if (base === '.gitignore' && !this.allowGitIgnore) {
            // rename, but only if there's not already a .npmignore
            const ni = entry.path.replace(/\.gitignore$/, '.npmignore')
            if (sawIgnores.has(ni)) {
              return false
            }
            entry.path = ni
          }
          return true
        }
      },
      strip: 1,
      onwarn: /* istanbul ignore next - we can trust that tar logs */
      (code, msg, data) => {
        log.warn('tar', code, msg)
        log.silly('tar', code, msg, data)
      },
      umask: this.umask,
      // always ignore ownership info from tarball metadata
      preserveOwner: false,
    }
  }
}

module.exports = FetcherBase

// Child classes
const GitFetcher = require('./git.js')
const RegistryFetcher = require('./registry.js')
const FileFetcher = require('./file.js')
const DirFetcher = require('./dir.js')
const RemoteFetcher = require('./remote.js')

// Get an appropriate fetcher object from a spec and options
FetcherBase.get = (rawSpec, opts = {}) => {
  const spec = npa(rawSpec, opts.where)
  switch (spec.type) {
    case 'git':
      return new GitFetcher(spec, opts)

    case 'remote':
      return new RemoteFetcher(spec, opts)

    case 'version':
    case 'range':
    case 'tag':
    case 'alias':
      return new RegistryFetcher(spec.subSpec || spec, opts)

    case 'file':
      return new FileFetcher(spec, opts)

    case 'directory':
      return new DirFetcher(spec, opts)

    default:
      throw new TypeError('Unknown spec type: ' + spec.type)
  }
}
const { resolve } = require('node:path')
const { stat, chmod } = require('node:fs/promises')
const cacache = require('cacache')
const fsm = require('fs-minipass')
const Fetcher = require('./fetcher.js')
const _ = require('./util/protected.js')

class FileFetcher extends Fetcher {
  constructor (spec, opts) {
    super(spec, opts)
    // just the fully resolved filename
    this.resolved = this.spec.fetchSpec
  }

  get types () {
    return ['file']
  }

  manifest () {
    if (this.package) {
      return Promise.resolve(this.package)
    }

    // have to unpack the tarball for this.
    return cacache.tmp.withTmp(this.cache, this.opts, dir =>
      this.extract(dir)
        .then(() => this[_.readPackageJson](dir))
        .then(mani => this.package = {
          ...mani,
          _integrity: this.integrity && String(this.integrity),
          _resolved: this.resolved,
          _from: this.from,
        }))
  }

  #exeBins (pkg, dest) {
    if (!pkg.bin) {
      return Promise.resolve()
    }

    return Promise.all(Object.keys(pkg.bin).map(async k => {
      const script = resolve(dest, pkg.bin[k])
      // Best effort.  Ignore errors here, the only result is that
      // a bin script is not executable.  But if it's missing or
      // something, we just leave it for a later stage to trip over
      // when we can provide a more useful contextual error.
      try {
        const st = await stat(script)
        const mode = st.mode | 0o111
        if (mode === st.mode) {
          return
        }
        await chmod(script, mode)
      } catch {
        // Ignore errors here
      }
    }))
  }

  extract (dest) {
    // if we've already loaded the manifest, then the super got it.
    // but if not, read the unpacked manifest and chmod properly.
    return super.extract(dest)
      .then(result => this.package ? result
      : this[_.readPackageJson](dest).then(pkg =>
        this.#exeBins(pkg, dest)).then(() => result))
  }

  [_.tarballFromResolved] () {
    // create a read stream and return it
    return new fsm.ReadStream(this.resolved)
  }

  packument () {
    // simulate based on manifest
    return this.manifest().then(mani => ({
      name: mani.name,
      'dist-tags': {
        [this.defaultTag]: mani.version,
      },
      versions: {
        [mani.version]: {
          ...mani,
          dist: {
            tarball: `file:${this.resolved}`,
            integrity: this.integrity && String(this.integrity),
          },
        },
      },
    }))
  }
}

module.exports = FileFetcher
const cacache = require('cacache')
const git = require('@npmcli/git')
const npa = require('npm-package-arg')
const pickManifest = require('npm-pick-manifest')
const { Minipass } = require('minipass')
const { log } = require('proc-log')
const DirFetcher = require('./dir.js')
const Fetcher = require('./fetcher.js')
const FileFetcher = require('./file.js')
const RemoteFetcher = require('./remote.js')
const _ = require('./util/protected.js')
const addGitSha = require('./util/add-git-sha.js')
const npm = require('./util/npm.js')

const hashre = /^[a-f0-9]{40}$/

// get the repository url.
// prefer https if there's auth, since ssh will drop that.
// otherwise, prefer ssh if available (more secure).
// We have to add the git+ back because npa suppresses it.
const repoUrl = (h, opts) =>
  h.sshurl && !(h.https && h.auth) && addGitPlus(h.sshurl(opts)) ||
  h.https && addGitPlus(h.https(opts))

// add git+ to the url, but only one time.
const addGitPlus = url => url && `git+${url}`.replace(/^(git\+)+/, 'git+')

class GitFetcher extends Fetcher {
  constructor (spec, opts) {
    super(spec, opts)

    // we never want to compare integrity for git dependencies: npm/rfcs#525
    if (this.opts.integrity) {
      delete this.opts.integrity
      log.warn(`skipping integrity check for git dependency ${this.spec.fetchSpec}`)
    }

    this.resolvedRef = null
    if (this.spec.hosted) {
      this.from = this.spec.hosted.shortcut({ noCommittish: false })
    }

    // shortcut: avoid full clone when we can go straight to the tgz
    // if we have the full sha and it's a hosted git platform
    if (this.spec.gitCommittish && hashre.test(this.spec.gitCommittish)) {
      this.resolvedSha = this.spec.gitCommittish
      // use hosted.tarball() when we shell to RemoteFetcher later
      this.resolved = this.spec.hosted
        ? repoUrl(this.spec.hosted, { noCommittish: false })
        : this.spec.rawSpec
    } else {
      this.resolvedSha = ''
    }

    this.Arborist = opts.Arborist || null
  }

  // just exposed to make it easier to test all the combinations
  static repoUrl (hosted, opts) {
    return repoUrl(hosted, opts)
  }

  get types () {
    return ['git']
  }

  resolve () {
    // likely a hosted git repo with a sha, so get the tarball url
    // but in general, no reason to resolve() more than necessary!
    if (this.resolved) {
      return super.resolve()
    }

    // fetch the git repo and then look at the current hash
    const h = this.spec.hosted
    // try to use ssh, fall back to git.
    return h
      ? this.#resolvedFromHosted(h)
      : this.#resolvedFromRepo(this.spec.fetchSpec)
  }

  // first try https, since that's faster and passphrase-less for
  // public repos, and supports private repos when auth is provided.
  // Fall back to SSH to support private repos
  // NB: we always store the https url in resolved field if auth
  // is present, otherwise ssh if the hosted type provides it
  #resolvedFromHosted (hosted) {
    return this.#resolvedFromRepo(hosted.https && hosted.https()).catch(er => {
      // Throw early since we know pathspec errors will fail again if retried
      if (er instanceof git.errors.GitPathspecError) {
        throw er
      }
      const ssh = hosted.sshurl && hosted.sshurl()
      // no fallthrough if we can't fall through or have https auth
      if (!ssh || hosted.auth) {
        throw er
      }
      return this.#resolvedFromRepo(ssh)
    })
  }

  #resolvedFromRepo (gitRemote) {
    // XXX make this a custom error class
    if (!gitRemote) {
      return Promise.reject(new Error(`No git url for ${this.spec}`))
    }
    const gitRange = this.spec.gitRange
    const name = this.spec.name
    return git.revs(gitRemote, this.opts).then(remoteRefs => {
      return gitRange ? pickManifest({
        versions: remoteRefs.versions,
        'dist-tags': remoteRefs['dist-tags'],
        name,
      }, gitRange, this.opts)
        : this.spec.gitCommittish ?
          remoteRefs.refs[this.spec.gitCommittish] ||
          remoteRefs.refs[remoteRefs.shas[this.spec.gitCommittish]]
          : remoteRefs.refs.HEAD // no git committish, get default head
    }).then(revDoc => {
      // the committish provided isn't in the rev list
      // things like HEAD~3 or @yesterday can land here.
      if (!revDoc || !revDoc.sha) {
        return this.#resolvedFromClone()
      }

      this.resolvedRef = revDoc
      this.resolvedSha = revDoc.sha
      this.#addGitSha(revDoc.sha)
      return this.resolved
    })
  }

  #setResolvedWithSha (withSha) {
    // we haven't cloned, so a tgz download is still faster
    // of course, if it's not a known host, we can't do that.
    this.resolved = !this.spec.hosted ? withSha
      : repoUrl(npa(withSha).hosted, { noCommittish: false })
  }

  // when we get the git sha, we affix it to our spec to build up
  // either a git url with a hash, or a tarball download URL
  #addGitSha (sha) {
    this.#setResolvedWithSha(addGitSha(this.spec, sha))
  }

  #resolvedFromClone () {
    // do a full or shallow clone, then look at the HEAD
    // kind of wasteful, but no other option, really
    return this.#clone(() => this.resolved)
  }

  #prepareDir (dir) {
    return this[_.readPackageJson](dir).then(mani => {
      // no need if we aren't going to do any preparation.
      const scripts = mani.scripts
      if (!mani.workspaces && (!scripts || !(
        scripts.postinstall ||
          scripts.build ||
          scripts.preinstall ||
          scripts.install ||
          scripts.prepack ||
          scripts.prepare))) {
        return
      }

      // to avoid cases where we have an cycle of git deps that depend
      // on one another, we only ever do preparation for one instance
      // of a given git dep along the chain of installations.
      // Note that this does mean that a dependency MAY in theory end up
      // trying to run its prepare script using a dependency that has not
      // been properly prepared itself, but that edge case is smaller
      // and less hazardous than a fork bomb of npm and git commands.
      const noPrepare = !process.env._PACOTE_NO_PREPARE_ ? []
        : process.env._PACOTE_NO_PREPARE_.split('\n')
      if (noPrepare.includes(this.resolved)) {
        log.info('prepare', 'skip prepare, already seen', this.resolved)
        return
      }
      noPrepare.push(this.resolved)

      // the DirFetcher will do its own preparation to run the prepare scripts
      // All we have to do is put the deps in place so that it can succeed.
      return npm(
        this.npmBin,
        [].concat(this.npmInstallCmd).concat(this.npmCliConfig),
        dir,
        { ...process.env, _PACOTE_NO_PREPARE_: noPrepare.join('\n') },
        { message: 'git dep preparation failed' }
      )
    })
  }

  [_.tarballFromResolved] () {
    const stream = new Minipass()
    stream.resolved = this.resolved
    stream.from = this.from

    // check it out and then shell out to the DirFetcher tarball packer
    this.#clone(dir => this.#prepareDir(dir)
      .then(() => new Promise((res, rej) => {
        if (!this.Arborist) {
          throw new Error('GitFetcher requires an Arborist constructor to pack a tarball')
        }
        const df = new DirFetcher(`file:${dir}`, {
          ...this.opts,
          Arborist: this.Arborist,
          resolved: null,
          integrity: null,
        })
        const dirStream = df[_.tarballFromResolved]()
        dirStream.on('error', rej)
        dirStream.on('end', res)
        dirStream.pipe(stream)
      }))).catch(
      /* istanbul ignore next: very unlikely and hard to test */
      er => stream.emit('error', er)
    )
    return stream
  }

  // clone a git repo into a temp folder (or fetch and unpack if possible)
  // handler accepts a directory, and returns a promise that resolves
  // when we're done with it, at which point, cacache deletes it
  //
  // TODO: after cloning, create a tarball of the folder, and add to the cache
  // with cacache.put.stream(), using a key that's deterministic based on the
  // spec and repo, so that we don't ever clone the same thing multiple times.
  #clone (handler, tarballOk = true) {
    const o = { tmpPrefix: 'git-clone' }
    const ref = this.resolvedSha || this.spec.gitCommittish
    const h = this.spec.hosted
    const resolved = this.resolved

    // can be set manually to false to fall back to actual git clone
    tarballOk = tarballOk &&
      h && resolved === repoUrl(h, { noCommittish: false }) && h.tarball

    return cacache.tmp.withTmp(this.cache, o, async tmp => {
      // if we're resolved, and have a tarball url, shell out to RemoteFetcher
      if (tarballOk) {
        const nameat = this.spec.name ? `${this.spec.name}@` : ''
        return new RemoteFetcher(h.tarball({ noCommittish: false }), {
          ...this.opts,
          allowGitIgnore: true,
          pkgid: `git:${nameat}${this.resolved}`,
          resolved: this.resolved,
          integrity: null, // it'll always be different, if we have one
        }).extract(tmp).then(() => handler(tmp), er => {
          // fall back to ssh download if tarball fails
          if (er.constructor.name.match(/^Http/)) {
            return this.#clone(handler, false)
          } else {
            throw er
          }
        })
      }

      const sha = await (
        h ? this.#cloneHosted(ref, tmp)
        : this.#cloneRepo(this.spec.fetchSpec, ref, tmp)
      )
      this.resolvedSha = sha
      if (!this.resolved) {
        await this.#addGitSha(sha)
      }
      return handler(tmp)
    })
  }

  // first try https, since that's faster and passphrase-less for
  // public repos, and supports private repos when auth is provided.
  // Fall back to SSH to support private repos
  // NB: we always store the https url in resolved field if auth
  // is present, otherwise ssh if the hosted type provides it
  #cloneHosted (ref, tmp) {
    const hosted = this.spec.hosted
    return this.#cloneRepo(hosted.https({ noCommittish: true }), ref, tmp)
      .catch(er => {
        // Throw early since we know pathspec errors will fail again if retried
        if (er instanceof git.errors.GitPathspecError) {
          throw er
        }
        const ssh = hosted.sshurl && hosted.sshurl({ noCommittish: true })
        // no fallthrough if we can't fall through or have https auth
        if (!ssh || hosted.auth) {
          throw er
        }
        return this.#cloneRepo(ssh, ref, tmp)
      })
  }

  #cloneRepo (repo, ref, tmp) {
    const { opts, spec } = this
    return git.clone(repo, ref, tmp, { ...opts, spec })
  }

  manifest () {
    if (this.package) {
      return Promise.resolve(this.package)
    }

    return this.spec.hosted && this.resolved
      ? FileFetcher.prototype.manifest.apply(this)
      : this.#clone(dir =>
        this[_.readPackageJson](dir)
          .then(mani => this.package = {
            ...mani,
            _resolved: this.resolved,
            _from: this.from,
          }))
  }

  packument () {
    return FileFetcher.prototype.packument.apply(this)
  }
}
module.exports = GitFetcher
const { get } = require('./fetcher.js')
const GitFetcher = require('./git.js')
const RegistryFetcher = require('./registry.js')
const FileFetcher = require('./file.js')
const DirFetcher = require('./dir.js')
const RemoteFetcher = require('./remote.js')

const tarball = (spec, opts) => get(spec, opts).tarball()
tarball.stream = (spec, handler, opts) => get(spec, opts).tarballStream(handler)
tarball.file = (spec, dest, opts) => get(spec, opts).tarballFile(dest)

module.exports = {
  GitFetcher,
  RegistryFetcher,
  FileFetcher,
  DirFetcher,
  RemoteFetcher,
  resolve: (spec, opts) => get(spec, opts).resolve(),
  extract: (spec, dest, opts) => get(spec, opts).extract(dest),
  manifest: (spec, opts) => get(spec, opts).manifest(),
  packument: (spec, opts) => get(spec, opts).packument(),
  tarball,
}
const crypto = require('node:crypto')
const PackageJson = require('@npmcli/package-json')
const pickManifest = require('npm-pick-manifest')
const ssri = require('ssri')
const npa = require('npm-package-arg')
const sigstore = require('sigstore')
const fetch = require('npm-registry-fetch')
const Fetcher = require('./fetcher.js')
const RemoteFetcher = require('./remote.js')
const pacoteVersion = require('../package.json').version
const removeTrailingSlashes = require('./util/trailing-slashes.js')
const _ = require('./util/protected.js')

// Corgis are cute. ðŸ•ðŸ¶
const corgiDoc = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*'
const fullDoc = 'application/json'

// Some really old packages have no time field in their packument so we need a
// cutoff date.
const MISSING_TIME_CUTOFF = '2015-01-01T00:00:00.000Z'

class RegistryFetcher extends Fetcher {
  #cacheKey
  constructor (spec, opts) {
    super(spec, opts)

    // you usually don't want to fetch the same packument multiple times in
    // the span of a given script or command, no matter how many pacote calls
    // are made, so this lets us avoid doing that.  It's only relevant for
    // registry fetchers, because other types simulate their packument from
    // the manifest, which they memoize on this.package, so it's very cheap
    // already.
    this.packumentCache = this.opts.packumentCache || null

    this.registry = fetch.pickRegistry(spec, opts)
    this.packumentUrl = `${removeTrailingSlashes(this.registry)}/${this.spec.escapedName}`
    this.#cacheKey = `${this.fullMetadata ? 'full' : 'corgi'}:${this.packumentUrl}`

    const parsed = new URL(this.registry)
    const regKey = `//${parsed.host}${parsed.pathname}`
    // unlike the nerf-darted auth keys, this one does *not* allow a mismatch
    // of trailing slashes.  It must match exactly.
    if (this.opts[`${regKey}:_keys`]) {
      this.registryKeys = this.opts[`${regKey}:_keys`]
    }

    // XXX pacote <=9 has some logic to ignore opts.resolved if
    // the resolved URL doesn't go to the same registry.
    // Consider reproducing that here, to throw away this.resolved
    // in that case.
  }

  async resolve () {
    // fetching the manifest sets resolved and (if present) integrity
    await this.manifest()
    if (!this.resolved) {
      throw Object.assign(
        new Error('Invalid package manifest: no `dist.tarball` field'),
        { package: this.spec.toString() }
      )
    }
    return this.resolved
  }

  #headers () {
    return {
      // npm will override UA, but ensure that we always send *something*
      'user-agent': this.opts.userAgent ||
        `pacote/${pacoteVersion} node/${process.version}`,
      ...(this.opts.headers || {}),
      'pacote-version': pacoteVersion,
      'pacote-req-type': 'packument',
      'pacote-pkg-id': `registry:${this.spec.name}`,
      accept: this.fullMetadata ? fullDoc : corgiDoc,
    }
  }

  async packument () {
    // note this might be either an in-flight promise for a request,
    // or the actual packument, but we never want to make more than
    // one request at a time for the same thing regardless.
    if (this.packumentCache?.has(this.#cacheKey)) {
      return this.packumentCache.get(this.#cacheKey)
    }

    // npm-registry-fetch the packument
    // set the appropriate header for corgis if fullMetadata isn't set
    // return the res.json() promise
    try {
      const res = await fetch(this.packumentUrl, {
        ...this.opts,
        headers: this.#headers(),
        spec: this.spec,

        // never check integrity for packuments themselves
        integrity: null,
      })
      const packument = await res.json()
      const contentLength = res.headers.get('content-length')
      if (contentLength) {
        packument._contentLength = Number(contentLength)
      }
      this.packumentCache?.set(this.#cacheKey, packument)
      return packument
    } catch (err) {
      this.packumentCache?.delete(this.#cacheKey)
      if (err.code !== 'E404' || this.fullMetadata) {
        throw err
      }
      // possible that corgis are not supported by this registry
      this.fullMetadata = true
      return this.packument()
    }
  }

  async manifest () {
    if (this.package) {
      return this.package
    }

    // When verifying signatures, we need to fetch the full/uncompressed
    // packument to get publish time as this is not included in the
    // corgi/compressed packument.
    if (this.opts.verifySignatures) {
      this.fullMetadata = true
    }

    const packument = await this.packument()
    const steps = PackageJson.normalizeSteps.filter(s => s !== '_attributes')
    const mani = await new PackageJson().fromContent(pickManifest(packument, this.spec.fetchSpec, {
      ...this.opts,
      defaultTag: this.defaultTag,
      before: this.before,
    })).normalize({ steps }).then(p => p.content)

    /* XXX add ETARGET and E403 revalidation of cached packuments here */

    // add _time from packument if fetched with fullMetadata
    const time = packument.time?.[mani.version]
    if (time) {
      mani._time = time
    }

    // add _resolved and _integrity from dist object
    const { dist } = mani
    if (dist) {
      this.resolved = mani._resolved = dist.tarball
      mani._from = this.from
      const distIntegrity = dist.integrity ? ssri.parse(dist.integrity)
        : dist.shasum ? ssri.fromHex(dist.shasum, 'sha1', { ...this.opts })
        : null
      if (distIntegrity) {
        if (this.integrity && !this.integrity.match(distIntegrity)) {
          // only bork if they have algos in common.
          // otherwise we end up breaking if we have saved a sha512
          // previously for the tarball, but the manifest only
          // provides a sha1, which is possible for older publishes.
          // Otherwise, this is almost certainly a case of holding it
          // wrong, and will result in weird or insecure behavior
          // later on when building package tree.
          for (const algo of Object.keys(this.integrity)) {
            if (distIntegrity[algo]) {
              throw Object.assign(new Error(
                `Integrity checksum failed when using ${algo}: ` +
                `wanted ${this.integrity} but got ${distIntegrity}.`
              ), { code: 'EINTEGRITY' })
            }
          }
        }
        // made it this far, the integrity is worthwhile.  accept it.
        // the setter here will take care of merging it into what we already
        // had.
        this.integrity = distIntegrity
      }
    }
    if (this.integrity) {
      mani._integrity = String(this.integrity)
      if (dist.signatures) {
        if (this.opts.verifySignatures) {
          // validate and throw on error, then set _signatures
          const message = `${mani._id}:${mani._integrity}`
          for (const signature of dist.signatures) {
            const publicKey = this.registryKeys &&
              this.registryKeys.filter(key => (key.keyid === signature.keyid))[0]
            if (!publicKey) {
              throw Object.assign(new Error(
                  `${mani._id} has a registry signature with keyid: ${signature.keyid} ` +
                  'but no corresponding public key can be found'
              ), { code: 'EMISSINGSIGNATUREKEY' })
            }

            const publishedTime = Date.parse(mani._time || MISSING_TIME_CUTOFF)
            const validPublicKey = !publicKey.expires ||
              publishedTime < Date.parse(publicKey.expires)
            if (!validPublicKey) {
              throw Object.assign(new Error(
                  `${mani._id} has a registry signature with keyid: ${signature.keyid} ` +
                  `but the corresponding public key has expired ${publicKey.expires}`
              ), { code: 'EEXPIREDSIGNATUREKEY' })
            }
            const verifier = crypto.createVerify('SHA256')
            verifier.write(message)
            verifier.end()
            const valid = verifier.verify(
              publicKey.pemkey,
              signature.sig,
              'base64'
            )
            if (!valid) {
              throw Object.assign(new Error(
                  `${mani._id} has an invalid registry signature with ` +
                  `keyid: ${publicKey.keyid} and signature: ${signature.sig}`
              ), {
                code: 'EINTEGRITYSIGNATURE',
                keyid: publicKey.keyid,
                signature: signature.sig,
                resolved: mani._resolved,
                integrity: mani._integrity,
              })
            }
          }
          mani._signatures = dist.signatures
        } else {
          mani._signatures = dist.signatures
        }
      }

      if (dist.attestations) {
        if (this.opts.verifyAttestations) {
          // Always fetch attestations from the current registry host
          const attestationsPath = new URL(dist.attestations.url).pathname
          const attestationsUrl = removeTrailingSlashes(this.registry) + attestationsPath
          const res = await fetch(attestationsUrl, {
            ...this.opts,
            // disable integrity check for attestations json payload, we check the
            // integrity in the verification steps below
            integrity: null,
          })
          const { attestations } = await res.json()
          const bundles = attestations.map(({ predicateType, bundle }) => {
            const statement = JSON.parse(
              Buffer.from(bundle.dsseEnvelope.payload, 'base64').toString('utf8')
            )
            const keyid = bundle.dsseEnvelope.signatures[0].keyid
            const signature = bundle.dsseEnvelope.signatures[0].sig

            return {
              predicateType,
              bundle,
              statement,
              keyid,
              signature,
            }
          })

          const attestationKeyIds = bundles.map((b) => b.keyid).filter((k) => !!k)
          const attestationRegistryKeys = (this.registryKeys || [])
            .filter(key => attestationKeyIds.includes(key.keyid))
          if (!attestationRegistryKeys.length) {
            throw Object.assign(new Error(
              `${mani._id} has attestations but no corresponding public key(s) can be found`
            ), { code: 'EMISSINGSIGNATUREKEY' })
          }

          for (const { predicateType, bundle, keyid, signature, statement } of bundles) {
            const publicKey = attestationRegistryKeys.find(key => key.keyid === keyid)
            // Publish attestations have a keyid set and a valid public key must be found
            if (keyid) {
              if (!publicKey) {
                throw Object.assign(new Error(
                  `${mani._id} has attestations with keyid: ${keyid} ` +
                  'but no corresponding public key can be found'
                ), { code: 'EMISSINGSIGNATUREKEY' })
              }

              const integratedTime = new Date(
                Number(
                  bundle.verificationMaterial.tlogEntries[0].integratedTime
                ) * 1000
              )
              const validPublicKey = !publicKey.expires ||
                (integratedTime < Date.parse(publicKey.expires))
              if (!validPublicKey) {
                throw Object.assign(new Error(
                  `${mani._id} has attestations with keyid: ${keyid} ` +
                  `but the corresponding public key has expired ${publicKey.expires}`
                ), { code: 'EEXPIREDSIGNATUREKEY' })
              }
            }

            const subject = {
              name: statement.subject[0].name,
              sha512: statement.subject[0].digest.sha512,
            }

            // Only type 'version' can be turned into a PURL
            const purl = this.spec.type === 'version' ? npa.toPurl(this.spec) : this.spec
            // Verify the statement subject matches the package, version
            if (subject.name !== purl) {
              throw Object.assign(new Error(
                `${mani._id} package name and version (PURL): ${purl} ` +
                `doesn't match what was signed: ${subject.name}`
              ), { code: 'EATTESTATIONSUBJECT' })
            }

            // Verify the statement subject matches the tarball integrity
            const integrityHexDigest = ssri.parse(this.integrity).hexDigest()
            if (subject.sha512 !== integrityHexDigest) {
              throw Object.assign(new Error(
                `${mani._id} package integrity (hex digest): ` +
                `${integrityHexDigest} ` +
                `doesn't match what was signed: ${subject.sha512}`
              ), { code: 'EATTESTATIONSUBJECT' })
            }

            try {
              // Provenance attestations are signed with a signing certificate
              // (including the key) so we don't need to return a public key.
              //
              // Publish attestations are signed with a keyid so we need to
              // specify a public key from the keys endpoint: `registry-host.tld/-/npm/v1/keys`
              const options = {
                tufCachePath: this.tufCache,
                tufForceCache: true,
                keySelector: publicKey ? () => publicKey.pemkey : undefined,
              }
              await sigstore.verify(bundle, options)
            } catch (e) {
              throw Object.assign(new Error(
                `${mani._id} failed to verify attestation: ${e.message}`
              ), {
                code: 'EATTESTATIONVERIFY',
                predicateType,
                keyid,
                signature,
                resolved: mani._resolved,
                integrity: mani._integrity,
              })
            }
          }
          mani._attestations = dist.attestations
        } else {
          mani._attestations = dist.attestations
        }
      }
    }

    this.package = mani
    return this.package
  }

  [_.tarballFromResolved] () {
    // we use a RemoteFetcher to get the actual tarball stream
    return new RemoteFetcher(this.resolved, {
      ...this.opts,
      resolved: this.resolved,
      pkgid: `registry:${this.spec.name}@${this.resolved}`,
    })[_.tarballFromResolved]()
  }

  get types () {
    return [
      'tag',
      'version',
      'range',
    ]
  }
}
module.exports = RegistryFetcher
const fetch = require('npm-registry-fetch')
const { Minipass } = require('minipass')
const Fetcher = require('./fetcher.js')
const FileFetcher = require('./file.js')
const _ = require('./util/protected.js')
const pacoteVersion = require('../package.json').version

class RemoteFetcher extends Fetcher {
  constructor (spec, opts) {
    super(spec, opts)
    this.resolved = this.spec.fetchSpec
    const resolvedURL = new URL(this.resolved)
    if (this.replaceRegistryHost !== 'never'
      && (this.replaceRegistryHost === 'always'
      || this.replaceRegistryHost === resolvedURL.host)) {
      this.resolved = new URL(resolvedURL.pathname, this.registry).href
    }

    // nam is a fermented pork sausage that is good to eat
    const nameat = this.spec.name ? `${this.spec.name}@` : ''
    this.pkgid = opts.pkgid ? opts.pkgid : `remote:${nameat}${this.resolved}`
  }

  // Don't need to cache tarball fetches in pacote, because make-fetch-happen
  // will write into cacache anyway.
  get [_.cacheFetches] () {
    return false
  }

  [_.tarballFromResolved] () {
    const stream = new Minipass()
    stream.hasIntegrityEmitter = true

    const fetchOpts = {
      ...this.opts,
      headers: this.#headers(),
      spec: this.spec,
      integrity: this.integrity,
      algorithms: [this.pickIntegrityAlgorithm()],
    }

    // eslint-disable-next-line promise/always-return
    fetch(this.resolved, fetchOpts).then(res => {
      res.body.on('error',
        /* istanbul ignore next - exceedingly rare and hard to simulate */
        er => stream.emit('error', er)
      )

      res.body.on('integrity', i => {
        this.integrity = i
        stream.emit('integrity', i)
      })

      res.body.pipe(stream)
    }).catch(er => stream.emit('error', er))

    return stream
  }

  #headers () {
    return {
      // npm will override this, but ensure that we always send *something*
      'user-agent': this.opts.userAgent ||
        `pacote/${pacoteVersion} node/${process.version}`,
      ...(this.opts.headers || {}),
      'pacote-version': pacoteVersion,
      'pacote-req-type': 'tarball',
      'pacote-pkg-id': this.pkgid,
      ...(this.integrity ? { 'pacote-integrity': String(this.integrity) }
      : {}),
      ...(this.opts.headers || {}),
    }
  }

  get types () {
    return ['remote']
  }

  // getting a packument and/or manifest is the same as with a file: spec.
  // unpack the tarball stream, and then read from the package.json file.
  packument () {
    return FileFetcher.prototype.packument.apply(this)
  }

  manifest () {
    return FileFetcher.prototype.manifest.apply(this)
  }
}
module.exports = RemoteFetcher
// add a sha to a git remote url spec
const addGitSha = (spec, sha) => {
  if (spec.hosted) {
    const h = spec.hosted
    const opt = { noCommittish: true }
    const base = h.https && h.auth ? h.https(opt) : h.shortcut(opt)

    return `${base}#${sha}`
  } else {
    // don't use new URL for this, because it doesn't handle scp urls
    return spec.rawSpec.replace(/#.*$/, '') + `#${sha}`
  }
}

module.exports = addGitSha
const { resolve } = require('node:path')
const { tmpdir, homedir } = require('node:os')

module.exports = (fakePlatform = false) => {
  const temp = tmpdir()
  const uidOrPid = process.getuid ? process.getuid() : process.pid
  const home = homedir() || resolve(temp, 'npm-' + uidOrPid)
  const platform = fakePlatform || process.platform
  const cacheExtra = platform === 'win32' ? 'npm-cache' : '.npm'
  const cacheRoot = (platform === 'win32' && process.env.LOCALAPPDATA) || home
  return {
    cacache: resolve(cacheRoot, cacheExtra, '_cacache'),
    tufcache: resolve(cacheRoot, cacheExtra, '_tuf'),
  }
}
// Function to determine whether a path is in the package.bin set.
// Used to prevent issues when people publish a package from a
// windows machine, and then install with --no-bin-links.
//
// Note: this is not possible in remote or file fetchers, since
// we don't have the manifest until AFTER we've unpacked.  But the
// main use case is registry fetching with git a distant second,
// so that's an acceptable edge case to not handle.

const binObj = (name, bin) =>
  typeof bin === 'string' ? { [name]: bin } : bin

const hasBin = (pkg, path) => {
  const bin = binObj(pkg.name, pkg.bin)
  const p = path.replace(/^[^\\/]*\//, '')
  for (const kv of Object.entries(bin)) {
    if (kv[1] === p) {
      return true
    }
  }
  return false
}

module.exports = (pkg, path) =>
  pkg && pkg.bin ? hasBin(pkg, path) : false
// run an npm command
const spawn = require('@npmcli/promise-spawn')

module.exports = (npmBin, npmCommand, cwd, env, extra) => {
  const isJS = npmBin.endsWith('.js')
  const cmd = isJS ? process.execPath : npmBin
  const args = (isJS ? [npmBin] : []).concat(npmCommand)
  // when installing to run the `prepare` script for a git dep, we need
  // to ensure that we don't run into a cycle of checking out packages
  // in temp directories.  this lets us link previously-seen repos that
  // are also being prepared.

  return spawn(cmd, args, { cwd, env }, extra)
}
module.exports = {
  cacheFetches: Symbol.for('pacote.Fetcher._cacheFetches'),
  readPackageJson: Symbol.for('package.Fetcher._readPackageJson'),
  tarballFromResolved: Symbol.for('pacote.Fetcher._tarballFromResolved'),
}
const isPackageBin = require('./is-package-bin.js')

const tarCreateOptions = manifest => ({
  cwd: manifest._resolved,
  prefix: 'package/',
  portable: true,
  gzip: {
    // forcing the level to 9 seems to avoid some
    // platform specific optimizations that cause
    // integrity mismatch errors due to differing
    // end results after compression
    level: 9,
  },

  // ensure that package bins are always executable
  // Note that npm-packlist is already filtering out
  // anything that is not a regular file, ignored by
  // .npmignore or package.json "files", etc.
  filter: (path, stat) => {
    if (isPackageBin(manifest, path)) {
      stat.mode |= 0o111
    }
    return true
  },

  // Provide a specific date in the 1980s for the benefit of zip,
  // which is confounded by files dated at the Unix epoch 0.
  mtime: new Date('1985-10-26T08:15:00.000Z'),
})

module.exports = tarCreateOptions
const removeTrailingSlashes = (input) => {
  // in order to avoid regexp redos detection
  let output = input
  while (output.endsWith('/')) {
    output = output.slice(0, -1)
  }
  return output
}

module.exports = removeTrailingSlashes
{
  "name": "pacote",
  "version": "21.0.0",
  "description": "JavaScript package downloader",
  "author": "GitHub Inc.",
  "bin": {
    "pacote": "bin/index.js"
  },
  "license": "ISC",
  "main": "lib/index.js",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "tap": {
    "timeout": 300,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "devDependencies": {
    "@npmcli/arborist": "^8.0.0",
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.4",
    "hosted-git-info": "^8.0.0",
    "mutate-fs": "^2.1.1",
    "nock": "^13.2.4",
    "npm-registry-mock": "^1.3.2",
    "rimraf": "^6.0.1",
    "tap": "^16.0.1"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "keywords": [
    "packages",
    "npm",
    "git"
  ],
  "dependencies": {
    "@npmcli/git": "^6.0.0",
    "@npmcli/installed-package-contents": "^3.0.0",
    "@npmcli/package-json": "^6.0.0",
    "@npmcli/promise-spawn": "^8.0.0",
    "@npmcli/run-script": "^9.0.0",
    "cacache": "^19.0.0",
    "fs-minipass": "^3.0.0",
    "minipass": "^7.0.2",
    "npm-package-arg": "^12.0.0",
    "npm-packlist": "^10.0.0",
    "npm-pick-manifest": "^10.0.0",
    "npm-registry-fetch": "^18.0.0",
    "proc-log": "^5.0.0",
    "promise-retry": "^2.0.1",
    "sigstore": "^3.0.0",
    "ssri": "^12.0.0",
    "tar": "^6.1.11"
  },
  "engines": {
    "node": "^20.17.0 || >=22.9.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/pacote.git"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.4",
    "windowsCI": false,
    "publish": "true"
  }
}


ISC License

Copyright npm, Inc.

Permission to use, copy, modify, and/or distribute this
software for any purpose with or without fee is hereby
granted, provided that the above copyright notice and this
permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
USE OR PERFORMANCE OF THIS SOFTWARE.
const parseJSON = require('json-parse-even-better-errors')
const { diff } = require('just-diff')
const { diffApply } = require('just-diff-apply')

const globalObjectProperties = Object.getOwnPropertyNames(Object.prototype)

const stripBOM = content => {
  content = content.toString()
  // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  // because the buffer-to-string conversion in `fs.readFileSync()`
  // translates it to FEFF, the UTF-16 BOM.
  if (content.charCodeAt(0) === 0xFEFF) {
    content = content.slice(1)
  }
  return content
}

const PARENT_RE = /\|{7,}/g
const OURS_RE = /<{7,}/g
const THEIRS_RE = /={7,}/g
const END_RE = />{7,}/g

const isDiff = str =>
  str.match(OURS_RE) && str.match(THEIRS_RE) && str.match(END_RE)

const parseConflictJSON = (str, reviver, prefer) => {
  prefer = prefer || 'ours'
  if (prefer !== 'theirs' && prefer !== 'ours') {
    throw new TypeError('prefer param must be "ours" or "theirs" if set')
  }

  str = stripBOM(str)

  if (!isDiff(str)) {
    return parseJSON(str)
  }

  const pieces = str.split(/[\n\r]+/g).reduce((acc, line) => {
    if (line.match(PARENT_RE)) {
      acc.state = 'parent'
    } else if (line.match(OURS_RE)) {
      acc.state = 'ours'
    } else if (line.match(THEIRS_RE)) {
      acc.state = 'theirs'
    } else if (line.match(END_RE)) {
      acc.state = 'top'
    } else {
      if (acc.state === 'top' || acc.state === 'ours') {
        acc.ours += line
      }
      if (acc.state === 'top' || acc.state === 'theirs') {
        acc.theirs += line
      }
      if (acc.state === 'top' || acc.state === 'parent') {
        acc.parent += line
      }
    }
    return acc
  }, {
    state: 'top',
    ours: '',
    theirs: '',
    parent: '',
  })

  // this will throw if either piece is not valid JSON, that's intended
  const parent = parseJSON(pieces.parent, reviver)
  const ours = parseJSON(pieces.ours, reviver)
  const theirs = parseJSON(pieces.theirs, reviver)

  return prefer === 'ours'
    ? resolve(parent, ours, theirs)
    : resolve(parent, theirs, ours)
}

const isObj = obj => obj && typeof obj === 'object'

const copyPath = (to, from, path, i) => {
  const p = path[i]
  if (isObj(to[p]) && isObj(from[p]) &&
      Array.isArray(to[p]) === Array.isArray(from[p])) {
    return copyPath(to[p], from[p], path, i + 1)
  }
  to[p] = from[p]
}

// get the diff from parent->ours and applying our changes on top of theirs.
// If they turned an object into a non-object, then put it back.
const resolve = (parent, ours, theirs) => {
  const dours = diff(parent, ours)
  for (let i = 0; i < dours.length; i++) {
    if (globalObjectProperties.find(prop => dours[i].path.includes(prop))) {
      continue
    }
    try {
      diffApply(theirs, [dours[i]])
    } catch (e) {
      copyPath(theirs, ours, dours[i].path, 0)
    }
  }
  return theirs
}

module.exports = Object.assign(parseConflictJSON, { isDiff })
{
  "name": "parse-conflict-json",
  "version": "4.0.0",
  "description": "Parse a JSON string that has git merge conflicts, resolving if possible",
  "author": "GitHub Inc.",
  "license": "ISC",
  "main": "lib",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "tap": {
    "check-coverage": true,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.0.1"
  },
  "dependencies": {
    "json-parse-even-better-errors": "^4.0.0",
    "just-diff": "^6.0.0",
    "just-diff-apply": "^5.2.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/parse-conflict-json.git"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  }
}
'use strict';

const pathKey = (options = {}) => {
	const environment = options.env || process.env;
	const platform = options.platform || process.platform;

	if (platform !== 'win32') {
		return 'PATH';
	}

	return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
};

module.exports = pathKey;
// TODO: Remove this for the next major release
module.exports.default = pathKey;
MIT License

Copyright (c) Sindre Sorhus  (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.
{
	"name": "path-key",
	"version": "3.1.1",
	"description": "Get the PATH environment variable key cross-platform",
	"license": "MIT",
	"repository": "sindresorhus/path-key",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=8"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"path",
		"key",
		"environment",
		"env",
		"variable",
		"var",
		"get",
		"cross-platform",
		"windows"
	],
	"devDependencies": {
		"@types/node": "^11.13.0",
		"ava": "^1.4.1",
		"tsd": "^0.7.2",
		"xo": "^0.24.0"
	}
}
# Blue Oak Model License

Version 1.0.0

## Purpose

This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.

## Acceptance

In order to receive this license, you must agree to its
rules.  The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.

## Copyright

Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.

## Notices

You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
.

## Excuse

If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice.  If you do not do so, your license
ends immediately.

## Patent

Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.

## Reliability

No contributor can revoke this license.

## No Liability

***As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim.***
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PathScurry = exports.Path = exports.PathScurryDarwin = exports.PathScurryPosix = exports.PathScurryWin32 = exports.PathScurryBase = exports.PathPosix = exports.PathWin32 = exports.PathBase = exports.ChildrenCache = exports.ResolveCache = void 0;
const lru_cache_1 = require("lru-cache");
const node_path_1 = require("node:path");
const node_url_1 = require("node:url");
const fs_1 = require("fs");
const actualFS = __importStar(require("node:fs"));
const realpathSync = fs_1.realpathSync.native;
// TODO: test perf of fs/promises realpath vs realpathCB,
// since the promises one uses realpath.native
const promises_1 = require("node:fs/promises");
const minipass_1 = require("minipass");
const defaultFS = {
    lstatSync: fs_1.lstatSync,
    readdir: fs_1.readdir,
    readdirSync: fs_1.readdirSync,
    readlinkSync: fs_1.readlinkSync,
    realpathSync,
    promises: {
        lstat: promises_1.lstat,
        readdir: promises_1.readdir,
        readlink: promises_1.readlink,
        realpath: promises_1.realpath,
    },
};
// if they just gave us require('fs') then use our default
const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ?
    defaultFS
    : {
        ...defaultFS,
        ...fsOption,
        promises: {
            ...defaultFS.promises,
            ...(fsOption.promises || {}),
        },
    };
// turn something like //?/c:/ into c:\
const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\');
// windows paths are separated by either / or \
const eitherSep = /[\\\/]/;
const UNKNOWN = 0; // may not even exist, for all we know
const IFIFO = 0b0001;
const IFCHR = 0b0010;
const IFDIR = 0b0100;
const IFBLK = 0b0110;
const IFREG = 0b1000;
const IFLNK = 0b1010;
const IFSOCK = 0b1100;
const IFMT = 0b1111;
// mask to unset low 4 bits
const IFMT_UNKNOWN = ~IFMT;
// set after successfully calling readdir() and getting entries.
const READDIR_CALLED = 0b0000_0001_0000;
// set after a successful lstat()
const LSTAT_CALLED = 0b0000_0010_0000;
// set if an entry (or one of its parents) is definitely not a dir
const ENOTDIR = 0b0000_0100_0000;
// set if an entry (or one of its parents) does not exist
// (can also be set on lstat errors like EACCES or ENAMETOOLONG)
const ENOENT = 0b0000_1000_0000;
// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK
// set if we fail to readlink
const ENOREADLINK = 0b0001_0000_0000;
// set if we know realpath() will fail
const ENOREALPATH = 0b0010_0000_0000;
const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
const TYPEMASK = 0b0011_1111_1111;
const entToType = (s) => s.isFile() ? IFREG
    : s.isDirectory() ? IFDIR
        : s.isSymbolicLink() ? IFLNK
            : s.isCharacterDevice() ? IFCHR
                : s.isBlockDevice() ? IFBLK
                    : s.isSocket() ? IFSOCK
                        : s.isFIFO() ? IFIFO
                            : UNKNOWN;
// normalize unicode path names
const normalizeCache = new Map();
const normalize = (s) => {
    const c = normalizeCache.get(s);
    if (c)
        return c;
    const n = s.normalize('NFKD');
    normalizeCache.set(s, n);
    return n;
};
const normalizeNocaseCache = new Map();
const normalizeNocase = (s) => {
    const c = normalizeNocaseCache.get(s);
    if (c)
        return c;
    const n = normalize(s.toLowerCase());
    normalizeNocaseCache.set(s, n);
    return n;
};
/**
 * An LRUCache for storing resolved path strings or Path objects.
 * @internal
 */
class ResolveCache extends lru_cache_1.LRUCache {
    constructor() {
        super({ max: 256 });
    }
}
exports.ResolveCache = ResolveCache;
// In order to prevent blowing out the js heap by allocating hundreds of
// thousands of Path entries when walking extremely large trees, the "children"
// in this tree are represented by storing an array of Path entries in an
// LRUCache, indexed by the parent.  At any time, Path.children() may return an
// empty array, indicating that it doesn't know about any of its children, and
// thus has to rebuild that cache.  This is fine, it just means that we don't
// benefit as much from having the cached entries, but huge directory walks
// don't blow out the stack, and smaller ones are still as fast as possible.
//
//It does impose some complexity when building up the readdir data, because we
//need to pass a reference to the children array that we started with.
/**
 * an LRUCache for storing child entries.
 * @internal
 */
class ChildrenCache extends lru_cache_1.LRUCache {
    constructor(maxSize = 16 * 1024) {
        super({
            maxSize,
            // parent + children
            sizeCalculation: a => a.length + 1,
        });
    }
}
exports.ChildrenCache = ChildrenCache;
const setAsCwd = Symbol('PathScurry setAsCwd');
/**
 * Path objects are sort of like a super-powered
 * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}
 *
 * Each one represents a single filesystem entry on disk, which may or may not
 * exist. It includes methods for reading various types of information via
 * lstat, readlink, and readdir, and caches all information to the greatest
 * degree possible.
 *
 * Note that fs operations that would normally throw will instead return an
 * "empty" value. This is in order to prevent excessive overhead from error
 * stack traces.
 */
class PathBase {
    /**
     * the basename of this path
     *
     * **Important**: *always* test the path name against any test string
     * usingthe {@link isNamed} method, and not by directly comparing this
     * string. Otherwise, unicode path strings that the system sees as identical
     * will not be properly treated as the same path, leading to incorrect
     * behavior and possible security issues.
     */
    name;
    /**
     * the Path entry corresponding to the path root.
     *
     * @internal
     */
    root;
    /**
     * All roots found within the current PathScurry family
     *
     * @internal
     */
    roots;
    /**
     * a reference to the parent path, or undefined in the case of root entries
     *
     * @internal
     */
    parent;
    /**
     * boolean indicating whether paths are compared case-insensitively
     * @internal
     */
    nocase;
    /**
     * boolean indicating that this path is the current working directory
     * of the PathScurry collection that contains it.
     */
    isCWD = false;
    // potential default fs override
    #fs;
    // Stats fields
    #dev;
    get dev() {
        return this.#dev;
    }
    #mode;
    get mode() {
        return this.#mode;
    }
    #nlink;
    get nlink() {
        return this.#nlink;
    }
    #uid;
    get uid() {
        return this.#uid;
    }
    #gid;
    get gid() {
        return this.#gid;
    }
    #rdev;
    get rdev() {
        return this.#rdev;
    }
    #blksize;
    get blksize() {
        return this.#blksize;
    }
    #ino;
    get ino() {
        return this.#ino;
    }
    #size;
    get size() {
        return this.#size;
    }
    #blocks;
    get blocks() {
        return this.#blocks;
    }
    #atimeMs;
    get atimeMs() {
        return this.#atimeMs;
    }
    #mtimeMs;
    get mtimeMs() {
        return this.#mtimeMs;
    }
    #ctimeMs;
    get ctimeMs() {
        return this.#ctimeMs;
    }
    #birthtimeMs;
    get birthtimeMs() {
        return this.#birthtimeMs;
    }
    #atime;
    get atime() {
        return this.#atime;
    }
    #mtime;
    get mtime() {
        return this.#mtime;
    }
    #ctime;
    get ctime() {
        return this.#ctime;
    }
    #birthtime;
    get birthtime() {
        return this.#birthtime;
    }
    #matchName;
    #depth;
    #fullpath;
    #fullpathPosix;
    #relative;
    #relativePosix;
    #type;
    #children;
    #linkTarget;
    #realpath;
    /**
     * This property is for compatibility with the Dirent class as of
     * Node v20, where Dirent['parentPath'] refers to the path of the
     * directory that was passed to readdir. For root entries, it's the path
     * to the entry itself.
     */
    get parentPath() {
        return (this.parent || this).fullpath();
    }
    /**
     * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
     * this property refers to the *parent* path, not the path object itself.
     */
    get path() {
        return this.parentPath;
    }
    /**
     * Do not create new Path objects directly.  They should always be accessed
     * via the PathScurry class or other methods on the Path class.
     *
     * @internal
     */
    constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
        this.name = name;
        this.#matchName = nocase ? normalizeNocase(name) : normalize(name);
        this.#type = type & TYPEMASK;
        this.nocase = nocase;
        this.roots = roots;
        this.root = root || this;
        this.#children = children;
        this.#fullpath = opts.fullpath;
        this.#relative = opts.relative;
        this.#relativePosix = opts.relativePosix;
        this.parent = opts.parent;
        if (this.parent) {
            this.#fs = this.parent.#fs;
        }
        else {
            this.#fs = fsFromOption(opts.fs);
        }
    }
    /**
     * Returns the depth of the Path object from its root.
     *
     * For example, a path at `/foo/bar` would have a depth of 2.
     */
    depth() {
        if (this.#depth !== undefined)
            return this.#depth;
        if (!this.parent)
            return (this.#depth = 0);
        return (this.#depth = this.parent.depth() + 1);
    }
    /**
     * @internal
     */
    childrenCache() {
        return this.#children;
    }
    /**
     * Get the Path object referenced by the string path, resolved from this Path
     */
    resolve(path) {
        if (!path) {
            return this;
        }
        const rootPath = this.getRootString(path);
        const dir = path.substring(rootPath.length);
        const dirParts = dir.split(this.splitSep);
        const result = rootPath ?
            this.getRoot(rootPath).#resolveParts(dirParts)
            : this.#resolveParts(dirParts);
        return result;
    }
    #resolveParts(dirParts) {
        let p = this;
        for (const part of dirParts) {
            p = p.child(part);
        }
        return p;
    }
    /**
     * Returns the cached children Path objects, if still available.  If they
     * have fallen out of the cache, then returns an empty array, and resets the
     * READDIR_CALLED bit, so that future calls to readdir() will require an fs
     * lookup.
     *
     * @internal
     */
    children() {
        const cached = this.#children.get(this);
        if (cached) {
            return cached;
        }
        const children = Object.assign([], { provisional: 0 });
        this.#children.set(this, children);
        this.#type &= ~READDIR_CALLED;
        return children;
    }
    /**
     * Resolves a path portion and returns or creates the child Path.
     *
     * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
     * `'..'`.
     *
     * This should not be called directly.  If `pathPart` contains any path
     * separators, it will lead to unsafe undefined behavior.
     *
     * Use `Path.resolve()` instead.
     *
     * @internal
     */
    child(pathPart, opts) {
        if (pathPart === '' || pathPart === '.') {
            return this;
        }
        if (pathPart === '..') {
            return this.parent || this;
        }
        // find the child
        const children = this.children();
        const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart);
        for (const p of children) {
            if (p.#matchName === name) {
                return p;
            }
        }
        // didn't find it, create provisional child, since it might not
        // actually exist.  If we know the parent isn't a dir, then
        // in fact it CAN'T exist.
        const s = this.parent ? this.sep : '';
        const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : undefined;
        const pchild = this.newChild(pathPart, UNKNOWN, {
            ...opts,
            parent: this,
            fullpath,
        });
        if (!this.canReaddir()) {
            pchild.#type |= ENOENT;
        }
        // don't have to update provisional, because if we have real children,
        // then provisional is set to children.length, otherwise a lower number
        children.push(pchild);
        return pchild;
    }
    /**
     * The relative path from the cwd. If it does not share an ancestor with
     * the cwd, then this ends up being equivalent to the fullpath()
     */
    relative() {
        if (this.isCWD)
            return '';
        if (this.#relative !== undefined) {
            return this.#relative;
        }
        const name = this.name;
        const p = this.parent;
        if (!p) {
            return (this.#relative = this.name);
        }
        const pv = p.relative();
        return pv + (!pv || !p.parent ? '' : this.sep) + name;
    }
    /**
     * The relative path from the cwd, using / as the path separator.
     * If it does not share an ancestor with
     * the cwd, then this ends up being equivalent to the fullpathPosix()
     * On posix systems, this is identical to relative().
     */
    relativePosix() {
        if (this.sep === '/')
            return this.relative();
        if (this.isCWD)
            return '';
        if (this.#relativePosix !== undefined)
            return this.#relativePosix;
        const name = this.name;
        const p = this.parent;
        if (!p) {
            return (this.#relativePosix = this.fullpathPosix());
        }
        const pv = p.relativePosix();
        return pv + (!pv || !p.parent ? '' : '/') + name;
    }
    /**
     * The fully resolved path string for this Path entry
     */
    fullpath() {
        if (this.#fullpath !== undefined) {
            return this.#fullpath;
        }
        const name = this.name;
        const p = this.parent;
        if (!p) {
            return (this.#fullpath = this.name);
        }
        const pv = p.fullpath();
        const fp = pv + (!p.parent ? '' : this.sep) + name;
        return (this.#fullpath = fp);
    }
    /**
     * On platforms other than windows, this is identical to fullpath.
     *
     * On windows, this is overridden to return the forward-slash form of the
     * full UNC path.
     */
    fullpathPosix() {
        if (this.#fullpathPosix !== undefined)
            return this.#fullpathPosix;
        if (this.sep === '/')
            return (this.#fullpathPosix = this.fullpath());
        if (!this.parent) {
            const p = this.fullpath().replace(/\\/g, '/');
            if (/^[a-z]:\//i.test(p)) {
                return (this.#fullpathPosix = `//?/${p}`);
            }
            else {
                return (this.#fullpathPosix = p);
            }
        }
        const p = this.parent;
        const pfpp = p.fullpathPosix();
        const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name;
        return (this.#fullpathPosix = fpp);
    }
    /**
     * Is the Path of an unknown type?
     *
     * Note that we might know *something* about it if there has been a previous
     * filesystem operation, for example that it does not exist, or is not a
     * link, or whether it has child entries.
     */
    isUnknown() {
        return (this.#type & IFMT) === UNKNOWN;
    }
    isType(type) {
        return this[`is${type}`]();
    }
    getType() {
        return (this.isUnknown() ? 'Unknown'
            : this.isDirectory() ? 'Directory'
                : this.isFile() ? 'File'
                    : this.isSymbolicLink() ? 'SymbolicLink'
                        : this.isFIFO() ? 'FIFO'
                            : this.isCharacterDevice() ? 'CharacterDevice'
                                : this.isBlockDevice() ? 'BlockDevice'
                                    : /* c8 ignore start */ this.isSocket() ? 'Socket'
                                        : 'Unknown');
        /* c8 ignore stop */
    }
    /**
     * Is the Path a regular file?
     */
    isFile() {
        return (this.#type & IFMT) === IFREG;
    }
    /**
     * Is the Path a directory?
     */
    isDirectory() {
        return (this.#type & IFMT) === IFDIR;
    }
    /**
     * Is the path a character device?
     */
    isCharacterDevice() {
        return (this.#type & IFMT) === IFCHR;
    }
    /**
     * Is the path a block device?
     */
    isBlockDevice() {
        return (this.#type & IFMT) === IFBLK;
    }
    /**
     * Is the path a FIFO pipe?
     */
    isFIFO() {
        return (this.#type & IFMT) === IFIFO;
    }
    /**
     * Is the path a socket?
     */
    isSocket() {
        return (this.#type & IFMT) === IFSOCK;
    }
    /**
     * Is the path a symbolic link?
     */
    isSymbolicLink() {
        return (this.#type & IFLNK) === IFLNK;
    }
    /**
     * Return the entry if it has been subject of a successful lstat, or
     * undefined otherwise.
     *
     * Does not read the filesystem, so an undefined result *could* simply
     * mean that we haven't called lstat on it.
     */
    lstatCached() {
        return this.#type & LSTAT_CALLED ? this : undefined;
    }
    /**
     * Return the cached link target if the entry has been the subject of a
     * successful readlink, or undefined otherwise.
     *
     * Does not read the filesystem, so an undefined result *could* just mean we
     * don't have any cached data. Only use it if you are very sure that a
     * readlink() has been called at some point.
     */
    readlinkCached() {
        return this.#linkTarget;
    }
    /**
     * Returns the cached realpath target if the entry has been the subject
     * of a successful realpath, or undefined otherwise.
     *
     * Does not read the filesystem, so an undefined result *could* just mean we
     * don't have any cached data. Only use it if you are very sure that a
     * realpath() has been called at some point.
     */
    realpathCached() {
        return this.#realpath;
    }
    /**
     * Returns the cached child Path entries array if the entry has been the
     * subject of a successful readdir(), or [] otherwise.
     *
     * Does not read the filesystem, so an empty array *could* just mean we
     * don't have any cached data. Only use it if you are very sure that a
     * readdir() has been called recently enough to still be valid.
     */
    readdirCached() {
        const children = this.children();
        return children.slice(0, children.provisional);
    }
    /**
     * Return true if it's worth trying to readlink.  Ie, we don't (yet) have
     * any indication that readlink will definitely fail.
     *
     * Returns false if the path is known to not be a symlink, if a previous
     * readlink failed, or if the entry does not exist.
     */
    canReadlink() {
        if (this.#linkTarget)
            return true;
        if (!this.parent)
            return false;
        // cases where it cannot possibly succeed
        const ifmt = this.#type & IFMT;
        return !((ifmt !== UNKNOWN && ifmt !== IFLNK) ||
            this.#type & ENOREADLINK ||
            this.#type & ENOENT);
    }
    /**
     * Return true if readdir has previously been successfully called on this
     * path, indicating that cachedReaddir() is likely valid.
     */
    calledReaddir() {
        return !!(this.#type & READDIR_CALLED);
    }
    /**
     * Returns true if the path is known to not exist. That is, a previous lstat
     * or readdir failed to verify its existence when that would have been
     * expected, or a parent entry was marked either enoent or enotdir.
     */
    isENOENT() {
        return !!(this.#type & ENOENT);
    }
    /**
     * Return true if the path is a match for the given path name.  This handles
     * case sensitivity and unicode normalization.
     *
     * Note: even on case-sensitive systems, it is **not** safe to test the
     * equality of the `.name` property to determine whether a given pathname
     * matches, due to unicode normalization mismatches.
     *
     * Always use this method instead of testing the `path.name` property
     * directly.
     */
    isNamed(n) {
        return !this.nocase ?
            this.#matchName === normalize(n)
            : this.#matchName === normalizeNocase(n);
    }
    /**
     * Return the Path object corresponding to the target of a symbolic link.
     *
     * If the Path is not a symbolic link, or if the readlink call fails for any
     * reason, `undefined` is returned.
     *
     * Result is cached, and thus may be outdated if the filesystem is mutated.
     */
    async readlink() {
        const target = this.#linkTarget;
        if (target) {
            return target;
        }
        if (!this.canReadlink()) {
            return undefined;
        }
        /* c8 ignore start */
        // already covered by the canReadlink test, here for ts grumples
        if (!this.parent) {
            return undefined;
        }
        /* c8 ignore stop */
        try {
            const read = await this.#fs.promises.readlink(this.fullpath());
            const linkTarget = (await this.parent.realpath())?.resolve(read);
            if (linkTarget) {
                return (this.#linkTarget = linkTarget);
            }
        }
        catch (er) {
            this.#readlinkFail(er.code);
            return undefined;
        }
    }
    /**
     * Synchronous {@link PathBase.readlink}
     */
    readlinkSync() {
        const target = this.#linkTarget;
        if (target) {
            return target;
        }
        if (!this.canReadlink()) {
            return undefined;
        }
        /* c8 ignore start */
        // already covered by the canReadlink test, here for ts grumples
        if (!this.parent) {
            return undefined;
        }
        /* c8 ignore stop */
        try {
            const read = this.#fs.readlinkSync(this.fullpath());
            const linkTarget = this.parent.realpathSync()?.resolve(read);
            if (linkTarget) {
                return (this.#linkTarget = linkTarget);
            }
        }
        catch (er) {
            this.#readlinkFail(er.code);
            return undefined;
        }
    }
    #readdirSuccess(children) {
        // succeeded, mark readdir called bit
        this.#type |= READDIR_CALLED;
        // mark all remaining provisional children as ENOENT
        for (let p = children.provisional; p < children.length; p++) {
            const c = children[p];
            if (c)
                c.#markENOENT();
        }
    }
    #markENOENT() {
        // mark as UNKNOWN and ENOENT
        if (this.#type & ENOENT)
            return;
        this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN;
        this.#markChildrenENOENT();
    }
    #markChildrenENOENT() {
        // all children are provisional and do not exist
        const children = this.children();
        children.provisional = 0;
        for (const p of children) {
            p.#markENOENT();
        }
    }
    #markENOREALPATH() {
        this.#type |= ENOREALPATH;
        this.#markENOTDIR();
    }
    // save the information when we know the entry is not a dir
    #markENOTDIR() {
        // entry is not a directory, so any children can't exist.
        // this *should* be impossible, since any children created
        // after it's been marked ENOTDIR should be marked ENOENT,
        // so it won't even get to this point.
        /* c8 ignore start */
        if (this.#type & ENOTDIR)
            return;
        /* c8 ignore stop */
        let t = this.#type;
        // this could happen if we stat a dir, then delete it,
        // then try to read it or one of its children.
        if ((t & IFMT) === IFDIR)
            t &= IFMT_UNKNOWN;
        this.#type = t | ENOTDIR;
        this.#markChildrenENOENT();
    }
    #readdirFail(code = '') {
        // markENOTDIR and markENOENT also set provisional=0
        if (code === 'ENOTDIR' || code === 'EPERM') {
            this.#markENOTDIR();
        }
        else if (code === 'ENOENT') {
            this.#markENOENT();
        }
        else {
            this.children().provisional = 0;
        }
    }
    #lstatFail(code = '') {
        // Windows just raises ENOENT in this case, disable for win CI
        /* c8 ignore start */
        if (code === 'ENOTDIR') {
            // already know it has a parent by this point
            const p = this.parent;
            p.#markENOTDIR();
        }
        else if (code === 'ENOENT') {
            /* c8 ignore stop */
            this.#markENOENT();
        }
    }
    #readlinkFail(code = '') {
        let ter = this.#type;
        ter |= ENOREADLINK;
        if (code === 'ENOENT')
            ter |= ENOENT;
        // windows gets a weird error when you try to readlink a file
        if (code === 'EINVAL' || code === 'UNKNOWN') {
            // exists, but not a symlink, we don't know WHAT it is, so remove
            // all IFMT bits.
            ter &= IFMT_UNKNOWN;
        }
        this.#type = ter;
        // windows just gets ENOENT in this case.  We do cover the case,
        // just disabled because it's impossible on Windows CI
        /* c8 ignore start */
        if (code === 'ENOTDIR' && this.parent) {
            this.parent.#markENOTDIR();
        }
        /* c8 ignore stop */
    }
    #readdirAddChild(e, c) {
        return (this.#readdirMaybePromoteChild(e, c) ||
            this.#readdirAddNewChild(e, c));
    }
    #readdirAddNewChild(e, c) {
        // alloc new entry at head, so it's never provisional
        const type = entToType(e);
        const child = this.newChild(e.name, type, { parent: this });
        const ifmt = child.#type & IFMT;
        if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
            child.#type |= ENOTDIR;
        }
        c.unshift(child);
        c.provisional++;
        return child;
    }
    #readdirMaybePromoteChild(e, c) {
        for (let p = c.provisional; p < c.length; p++) {
            const pchild = c[p];
            const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name);
            if (name !== pchild.#matchName) {
                continue;
            }
            return this.#readdirPromoteChild(e, pchild, p, c);
        }
    }
    #readdirPromoteChild(e, p, index, c) {
        const v = p.name;
        // retain any other flags, but set ifmt from dirent
        p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e);
        // case sensitivity fixing when we learn the true name.
        if (v !== e.name)
            p.name = e.name;
        // just advance provisional index (potentially off the list),
        // otherwise we have to splice/pop it out and re-insert at head
        if (index !== c.provisional) {
            if (index === c.length - 1)
                c.pop();
            else
                c.splice(index, 1);
            c.unshift(p);
        }
        c.provisional++;
        return p;
    }
    /**
     * Call lstat() on this Path, and update all known information that can be
     * determined.
     *
     * Note that unlike `fs.lstat()`, the returned value does not contain some
     * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
     * information is required, you will need to call `fs.lstat` yourself.
     *
     * If the Path refers to a nonexistent file, or if the lstat call fails for
     * any reason, `undefined` is returned.  Otherwise the updated Path object is
     * returned.
     *
     * Results are cached, and thus may be out of date if the filesystem is
     * mutated.
     */
    async lstat() {
        if ((this.#type & ENOENT) === 0) {
            try {
                this.#applyStat(await this.#fs.promises.lstat(this.fullpath()));
                return this;
            }
            catch (er) {
                this.#lstatFail(er.code);
            }
        }
    }
    /**
     * synchronous {@link PathBase.lstat}
     */
    lstatSync() {
        if ((this.#type & ENOENT) === 0) {
            try {
                this.#applyStat(this.#fs.lstatSync(this.fullpath()));
                return this;
            }
            catch (er) {
                this.#lstatFail(er.code);
            }
        }
    }
    #applyStat(st) {
        const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st;
        this.#atime = atime;
        this.#atimeMs = atimeMs;
        this.#birthtime = birthtime;
        this.#birthtimeMs = birthtimeMs;
        this.#blksize = blksize;
        this.#blocks = blocks;
        this.#ctime = ctime;
        this.#ctimeMs = ctimeMs;
        this.#dev = dev;
        this.#gid = gid;
        this.#ino = ino;
        this.#mode = mode;
        this.#mtime = mtime;
        this.#mtimeMs = mtimeMs;
        this.#nlink = nlink;
        this.#rdev = rdev;
        this.#size = size;
        this.#uid = uid;
        const ifmt = entToType(st);
        // retain any other flags, but set the ifmt
        this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED;
        if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
            this.#type |= ENOTDIR;
        }
    }
    #onReaddirCB = [];
    #readdirCBInFlight = false;
    #callOnReaddirCB(children) {
        this.#readdirCBInFlight = false;
        const cbs = this.#onReaddirCB.slice();
        this.#onReaddirCB.length = 0;
        cbs.forEach(cb => cb(null, children));
    }
    /**
     * Standard node-style callback interface to get list of directory entries.
     *
     * If the Path cannot or does not contain any children, then an empty array
     * is returned.
     *
     * Results are cached, and thus may be out of date if the filesystem is
     * mutated.
     *
     * @param cb The callback called with (er, entries).  Note that the `er`
     * param is somewhat extraneous, as all readdir() errors are handled and
     * simply result in an empty set of entries being returned.
     * @param allowZalgo Boolean indicating that immediately known results should
     * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
     * zalgo at your peril, the dark pony lord is devious and unforgiving.
     */
    readdirCB(cb, allowZalgo = false) {
        if (!this.canReaddir()) {
            if (allowZalgo)
                cb(null, []);
            else
                queueMicrotask(() => cb(null, []));
            return;
        }
        const children = this.children();
        if (this.calledReaddir()) {
            const c = children.slice(0, children.provisional);
            if (allowZalgo)
                cb(null, c);
            else
                queueMicrotask(() => cb(null, c));
            return;
        }
        // don't have to worry about zalgo at this point.
        this.#onReaddirCB.push(cb);
        if (this.#readdirCBInFlight) {
            return;
        }
        this.#readdirCBInFlight = true;
        // else read the directory, fill up children
        // de-provisionalize any provisional children.
        const fullpath = this.fullpath();
        this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {
            if (er) {
                this.#readdirFail(er.code);
                children.provisional = 0;
            }
            else {
                // if we didn't get an error, we always get entries.
                //@ts-ignore
                for (const e of entries) {
                    this.#readdirAddChild(e, children);
                }
                this.#readdirSuccess(children);
            }
            this.#callOnReaddirCB(children.slice(0, children.provisional));
            return;
        });
    }
    #asyncReaddirInFlight;
    /**
     * Return an array of known child entries.
     *
     * If the Path cannot or does not contain any children, then an empty array
     * is returned.
     *
     * Results are cached, and thus may be out of date if the filesystem is
     * mutated.
     */
    async readdir() {
        if (!this.canReaddir()) {
            return [];
        }
        const children = this.children();
        if (this.calledReaddir()) {
            return children.slice(0, children.provisional);
        }
        // else read the directory, fill up children
        // de-provisionalize any provisional children.
        const fullpath = this.fullpath();
        if (this.#asyncReaddirInFlight) {
            await this.#asyncReaddirInFlight;
        }
        else {
            /* c8 ignore start */
            let resolve = () => { };
            /* c8 ignore stop */
            this.#asyncReaddirInFlight = new Promise(res => (resolve = res));
            try {
                for (const e of await this.#fs.promises.readdir(fullpath, {
                    withFileTypes: true,
                })) {
                    this.#readdirAddChild(e, children);
                }
                this.#readdirSuccess(children);
            }
            catch (er) {
                this.#readdirFail(er.code);
                children.provisional = 0;
            }
            this.#asyncReaddirInFlight = undefined;
            resolve();
        }
        return children.slice(0, children.provisional);
    }
    /**
     * synchronous {@link PathBase.readdir}
     */
    readdirSync() {
        if (!this.canReaddir()) {
            return [];
        }
        const children = this.children();
        if (this.calledReaddir()) {
            return children.slice(0, children.provisional);
        }
        // else read the directory, fill up children
        // de-provisionalize any provisional children.
        const fullpath = this.fullpath();
        try {
            for (const e of this.#fs.readdirSync(fullpath, {
                withFileTypes: true,
            })) {
                this.#readdirAddChild(e, children);
            }
            this.#readdirSuccess(children);
        }
        catch (er) {
            this.#readdirFail(er.code);
            children.provisional = 0;
        }
        return children.slice(0, children.provisional);
    }
    canReaddir() {
        if (this.#type & ENOCHILD)
            return false;
        const ifmt = IFMT & this.#type;
        // we always set ENOTDIR when setting IFMT, so should be impossible
        /* c8 ignore start */
        if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
            return false;
        }
        /* c8 ignore stop */
        return true;
    }
    shouldWalk(dirs, walkFilter) {
        return ((this.#type & IFDIR) === IFDIR &&
            !(this.#type & ENOCHILD) &&
            !dirs.has(this) &&
            (!walkFilter || walkFilter(this)));
    }
    /**
     * Return the Path object corresponding to path as resolved
     * by realpath(3).
     *
     * If the realpath call fails for any reason, `undefined` is returned.
     *
     * Result is cached, and thus may be outdated if the filesystem is mutated.
     * On success, returns a Path object.
     */
    async realpath() {
        if (this.#realpath)
            return this.#realpath;
        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
            return undefined;
        try {
            const rp = await this.#fs.promises.realpath(this.fullpath());
            return (this.#realpath = this.resolve(rp));
        }
        catch (_) {
            this.#markENOREALPATH();
        }
    }
    /**
     * Synchronous {@link realpath}
     */
    realpathSync() {
        if (this.#realpath)
            return this.#realpath;
        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
            return undefined;
        try {
            const rp = this.#fs.realpathSync(this.fullpath());
            return (this.#realpath = this.resolve(rp));
        }
        catch (_) {
            this.#markENOREALPATH();
        }
    }
    /**
     * Internal method to mark this Path object as the scurry cwd,
     * called by {@link PathScurry#chdir}
     *
     * @internal
     */
    [setAsCwd](oldCwd) {
        if (oldCwd === this)
            return;
        oldCwd.isCWD = false;
        this.isCWD = true;
        const changed = new Set([]);
        let rp = [];
        let p = this;
        while (p && p.parent) {
            changed.add(p);
            p.#relative = rp.join(this.sep);
            p.#relativePosix = rp.join('/');
            p = p.parent;
            rp.push('..');
        }
        // now un-memoize parents of old cwd
        p = oldCwd;
        while (p && p.parent && !changed.has(p)) {
            p.#relative = undefined;
            p.#relativePosix = undefined;
            p = p.parent;
        }
    }
}
exports.PathBase = PathBase;
/**
 * Path class used on win32 systems
 *
 * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'`
 * as the path separator for parsing paths.
 */
class PathWin32 extends PathBase {
    /**
     * Separator for generating path strings.
     */
    sep = '\\';
    /**
     * Separator for parsing path strings.
     */
    splitSep = eitherSep;
    /**
     * Do not create new Path objects directly.  They should always be accessed
     * via the PathScurry class or other methods on the Path class.
     *
     * @internal
     */
    constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
        super(name, type, root, roots, nocase, children, opts);
    }
    /**
     * @internal
     */
    newChild(name, type = UNKNOWN, opts = {}) {
        return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
    }
    /**
     * @internal
     */
    getRootString(path) {
        return node_path_1.win32.parse(path).root;
    }
    /**
     * @internal
     */
    getRoot(rootPath) {
        rootPath = uncToDrive(rootPath.toUpperCase());
        if (rootPath === this.root.name) {
            return this.root;
        }
        // ok, not that one, check if it matches another we know about
        for (const [compare, root] of Object.entries(this.roots)) {
            if (this.sameRoot(rootPath, compare)) {
                return (this.roots[rootPath] = root);
            }
        }
        // otherwise, have to create a new one.
        return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root);
    }
    /**
     * @internal
     */
    sameRoot(rootPath, compare = this.root.name) {
        // windows can (rarely) have case-sensitive filesystem, but
        // UNC and drive letters are always case-insensitive, and canonically
        // represented uppercase.
        rootPath = rootPath
            .toUpperCase()
            .replace(/\//g, '\\')
            .replace(uncDriveRegexp, '$1\\');
        return rootPath === compare;
    }
}
exports.PathWin32 = PathWin32;
/**
 * Path class used on all posix systems.
 *
 * Uses `'/'` as the path separator.
 */
class PathPosix extends PathBase {
    /**
     * separator for parsing path strings
     */
    splitSep = '/';
    /**
     * separator for generating path strings
     */
    sep = '/';
    /**
     * Do not create new Path objects directly.  They should always be accessed
     * via the PathScurry class or other methods on the Path class.
     *
     * @internal
     */
    constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
        super(name, type, root, roots, nocase, children, opts);
    }
    /**
     * @internal
     */
    getRootString(path) {
        return path.startsWith('/') ? '/' : '';
    }
    /**
     * @internal
     */
    getRoot(_rootPath) {
        return this.root;
    }
    /**
     * @internal
     */
    newChild(name, type = UNKNOWN, opts = {}) {
        return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
    }
}
exports.PathPosix = PathPosix;
/**
 * The base class for all PathScurry classes, providing the interface for path
 * resolution and filesystem operations.
 *
 * Typically, you should *not* instantiate this class directly, but rather one
 * of the platform-specific classes, or the exported {@link PathScurry} which
 * defaults to the current platform.
 */
class PathScurryBase {
    /**
     * The root Path entry for the current working directory of this Scurry
     */
    root;
    /**
     * The string path for the root of this Scurry's current working directory
     */
    rootPath;
    /**
     * A collection of all roots encountered, referenced by rootPath
     */
    roots;
    /**
     * The Path entry corresponding to this PathScurry's current working directory.
     */
    cwd;
    #resolveCache;
    #resolvePosixCache;
    #children;
    /**
     * Perform path comparisons case-insensitively.
     *
     * Defaults true on Darwin and Windows systems, false elsewhere.
     */
    nocase;
    #fs;
    /**
     * This class should not be instantiated directly.
     *
     * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
     *
     * @internal
     */
    constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) {
        this.#fs = fsFromOption(fs);
        if (cwd instanceof URL || cwd.startsWith('file://')) {
            cwd = (0, node_url_1.fileURLToPath)(cwd);
        }
        // resolve and split root, and then add to the store.
        // this is the only time we call path.resolve()
        const cwdPath = pathImpl.resolve(cwd);
        this.roots = Object.create(null);
        this.rootPath = this.parseRootPath(cwdPath);
        this.#resolveCache = new ResolveCache();
        this.#resolvePosixCache = new ResolveCache();
        this.#children = new ChildrenCache(childrenCacheSize);
        const split = cwdPath.substring(this.rootPath.length).split(sep);
        // resolve('/') leaves '', splits to [''], we don't want that.
        if (split.length === 1 && !split[0]) {
            split.pop();
        }
        /* c8 ignore start */
        if (nocase === undefined) {
            throw new TypeError('must provide nocase setting to PathScurryBase ctor');
        }
        /* c8 ignore stop */
        this.nocase = nocase;
        this.root = this.newRoot(this.#fs);
        this.roots[this.rootPath] = this.root;
        let prev = this.root;
        let len = split.length - 1;
        const joinSep = pathImpl.sep;
        let abs = this.rootPath;
        let sawFirst = false;
        for (const part of split) {
            const l = len--;
            prev = prev.child(part, {
                relative: new Array(l).fill('..').join(joinSep),
                relativePosix: new Array(l).fill('..').join('/'),
                fullpath: (abs += (sawFirst ? '' : joinSep) + part),
            });
            sawFirst = true;
        }
        this.cwd = prev;
    }
    /**
     * Get the depth of a provided path, string, or the cwd
     */
    depth(path = this.cwd) {
        if (typeof path === 'string') {
            path = this.cwd.resolve(path);
        }
        return path.depth();
    }
    /**
     * Return the cache of child entries.  Exposed so subclasses can create
     * child Path objects in a platform-specific way.
     *
     * @internal
     */
    childrenCache() {
        return this.#children;
    }
    /**
     * Resolve one or more path strings to a resolved string
     *
     * Same interface as require('path').resolve.
     *
     * Much faster than path.resolve() when called multiple times for the same
     * path, because the resolved Path objects are cached.  Much slower
     * otherwise.
     */
    resolve(...paths) {
        // first figure out the minimum number of paths we have to test
        // we always start at cwd, but any absolutes will bump the start
        let r = '';
        for (let i = paths.length - 1; i >= 0; i--) {
            const p = paths[i];
            if (!p || p === '.')
                continue;
            r = r ? `${p}/${r}` : p;
            if (this.isAbsolute(p)) {
                break;
            }
        }
        const cached = this.#resolveCache.get(r);
        if (cached !== undefined) {
            return cached;
        }
        const result = this.cwd.resolve(r).fullpath();
        this.#resolveCache.set(r, result);
        return result;
    }
    /**
     * Resolve one or more path strings to a resolved string, returning
     * the posix path.  Identical to .resolve() on posix systems, but on
     * windows will return a forward-slash separated UNC path.
     *
     * Same interface as require('path').resolve.
     *
     * Much faster than path.resolve() when called multiple times for the same
     * path, because the resolved Path objects are cached.  Much slower
     * otherwise.
     */
    resolvePosix(...paths) {
        // first figure out the minimum number of paths we have to test
        // we always start at cwd, but any absolutes will bump the start
        let r = '';
        for (let i = paths.length - 1; i >= 0; i--) {
            const p = paths[i];
            if (!p || p === '.')
                continue;
            r = r ? `${p}/${r}` : p;
            if (this.isAbsolute(p)) {
                break;
            }
        }
        const cached = this.#resolvePosixCache.get(r);
        if (cached !== undefined) {
            return cached;
        }
        const result = this.cwd.resolve(r).fullpathPosix();
        this.#resolvePosixCache.set(r, result);
        return result;
    }
    /**
     * find the relative path from the cwd to the supplied path string or entry
     */
    relative(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.relative();
    }
    /**
     * find the relative path from the cwd to the supplied path string or
     * entry, using / as the path delimiter, even on Windows.
     */
    relativePosix(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.relativePosix();
    }
    /**
     * Return the basename for the provided string or Path object
     */
    basename(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.name;
    }
    /**
     * Return the dirname for the provided string or Path object
     */
    dirname(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return (entry.parent || entry).fullpath();
    }
    async readdir(entry = this.cwd, opts = {
        withFileTypes: true,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes } = opts;
        if (!entry.canReaddir()) {
            return [];
        }
        else {
            const p = await entry.readdir();
            return withFileTypes ? p : p.map(e => e.name);
        }
    }
    readdirSync(entry = this.cwd, opts = {
        withFileTypes: true,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true } = opts;
        if (!entry.canReaddir()) {
            return [];
        }
        else if (withFileTypes) {
            return entry.readdirSync();
        }
        else {
            return entry.readdirSync().map(e => e.name);
        }
    }
    /**
     * Call lstat() on the string or Path object, and update all known
     * information that can be determined.
     *
     * Note that unlike `fs.lstat()`, the returned value does not contain some
     * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
     * information is required, you will need to call `fs.lstat` yourself.
     *
     * If the Path refers to a nonexistent file, or if the lstat call fails for
     * any reason, `undefined` is returned.  Otherwise the updated Path object is
     * returned.
     *
     * Results are cached, and thus may be out of date if the filesystem is
     * mutated.
     */
    async lstat(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.lstat();
    }
    /**
     * synchronous {@link PathScurryBase.lstat}
     */
    lstatSync(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.lstatSync();
    }
    async readlink(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            withFileTypes = entry.withFileTypes;
            entry = this.cwd;
        }
        const e = await entry.readlink();
        return withFileTypes ? e : e?.fullpath();
    }
    readlinkSync(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            withFileTypes = entry.withFileTypes;
            entry = this.cwd;
        }
        const e = entry.readlinkSync();
        return withFileTypes ? e : e?.fullpath();
    }
    async realpath(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            withFileTypes = entry.withFileTypes;
            entry = this.cwd;
        }
        const e = await entry.realpath();
        return withFileTypes ? e : e?.fullpath();
    }
    realpathSync(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            withFileTypes = entry.withFileTypes;
            entry = this.cwd;
        }
        const e = entry.realpathSync();
        return withFileTypes ? e : e?.fullpath();
    }
    async walk(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        const results = [];
        if (!filter || filter(entry)) {
            results.push(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = new Set();
        const walk = (dir, cb) => {
            dirs.add(dir);
            dir.readdirCB((er, entries) => {
                /* c8 ignore start */
                if (er) {
                    return cb(er);
                }
                /* c8 ignore stop */
                let len = entries.length;
                if (!len)
                    return cb();
                const next = () => {
                    if (--len === 0) {
                        cb();
                    }
                };
                for (const e of entries) {
                    if (!filter || filter(e)) {
                        results.push(withFileTypes ? e : e.fullpath());
                    }
                    if (follow && e.isSymbolicLink()) {
                        e.realpath()
                            .then(r => (r?.isUnknown() ? r.lstat() : r))
                            .then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next());
                    }
                    else {
                        if (e.shouldWalk(dirs, walkFilter)) {
                            walk(e, next);
                        }
                        else {
                            next();
                        }
                    }
                }
            }, true); // zalgooooooo
        };
        const start = entry;
        return new Promise((res, rej) => {
            walk(start, er => {
                /* c8 ignore start */
                if (er)
                    return rej(er);
                /* c8 ignore stop */
                res(results);
            });
        });
    }
    walkSync(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        const results = [];
        if (!filter || filter(entry)) {
            results.push(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = new Set([entry]);
        for (const dir of dirs) {
            const entries = dir.readdirSync();
            for (const e of entries) {
                if (!filter || filter(e)) {
                    results.push(withFileTypes ? e : e.fullpath());
                }
                let r = e;
                if (e.isSymbolicLink()) {
                    if (!(follow && (r = e.realpathSync())))
                        continue;
                    if (r.isUnknown())
                        r.lstatSync();
                }
                if (r.shouldWalk(dirs, walkFilter)) {
                    dirs.add(r);
                }
            }
        }
        return results;
    }
    /**
     * Support for `for await`
     *
     * Alias for {@link PathScurryBase.iterate}
     *
     * Note: As of Node 19, this is very slow, compared to other methods of
     * walking.  Consider using {@link PathScurryBase.stream} if memory overhead
     * and backpressure are concerns, or {@link PathScurryBase.walk} if not.
     */
    [Symbol.asyncIterator]() {
        return this.iterate();
    }
    iterate(entry = this.cwd, options = {}) {
        // iterating async over the stream is significantly more performant,
        // especially in the warm-cache scenario, because it buffers up directory
        // entries in the background instead of waiting for a yield for each one.
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            options = entry;
            entry = this.cwd;
        }
        return this.stream(entry, options)[Symbol.asyncIterator]();
    }
    /**
     * Iterating over a PathScurry performs a synchronous walk.
     *
     * Alias for {@link PathScurryBase.iterateSync}
     */
    [Symbol.iterator]() {
        return this.iterateSync();
    }
    *iterateSync(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        if (!filter || filter(entry)) {
            yield withFileTypes ? entry : entry.fullpath();
        }
        const dirs = new Set([entry]);
        for (const dir of dirs) {
            const entries = dir.readdirSync();
            for (const e of entries) {
                if (!filter || filter(e)) {
                    yield withFileTypes ? e : e.fullpath();
                }
                let r = e;
                if (e.isSymbolicLink()) {
                    if (!(follow && (r = e.realpathSync())))
                        continue;
                    if (r.isUnknown())
                        r.lstatSync();
                }
                if (r.shouldWalk(dirs, walkFilter)) {
                    dirs.add(r);
                }
            }
        }
    }
    stream(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        const results = new minipass_1.Minipass({ objectMode: true });
        if (!filter || filter(entry)) {
            results.write(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = new Set();
        const queue = [entry];
        let processing = 0;
        const process = () => {
            let paused = false;
            while (!paused) {
                const dir = queue.shift();
                if (!dir) {
                    if (processing === 0)
                        results.end();
                    return;
                }
                processing++;
                dirs.add(dir);
                const onReaddir = (er, entries, didRealpaths = false) => {
                    /* c8 ignore start */
                    if (er)
                        return results.emit('error', er);
                    /* c8 ignore stop */
                    if (follow && !didRealpaths) {
                        const promises = [];
                        for (const e of entries) {
                            if (e.isSymbolicLink()) {
                                promises.push(e
                                    .realpath()
                                    .then((r) => r?.isUnknown() ? r.lstat() : r));
                            }
                        }
                        if (promises.length) {
                            Promise.all(promises).then(() => onReaddir(null, entries, true));
                            return;
                        }
                    }
                    for (const e of entries) {
                        if (e && (!filter || filter(e))) {
                            if (!results.write(withFileTypes ? e : e.fullpath())) {
                                paused = true;
                            }
                        }
                    }
                    processing--;
                    for (const e of entries) {
                        const r = e.realpathCached() || e;
                        if (r.shouldWalk(dirs, walkFilter)) {
                            queue.push(r);
                        }
                    }
                    if (paused && !results.flowing) {
                        results.once('drain', process);
                    }
                    else if (!sync) {
                        process();
                    }
                };
                // zalgo containment
                let sync = true;
                dir.readdirCB(onReaddir, true);
                sync = false;
            }
        };
        process();
        return results;
    }
    streamSync(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        const results = new minipass_1.Minipass({ objectMode: true });
        const dirs = new Set();
        if (!filter || filter(entry)) {
            results.write(withFileTypes ? entry : entry.fullpath());
        }
        const queue = [entry];
        let processing = 0;
        const process = () => {
            let paused = false;
            while (!paused) {
                const dir = queue.shift();
                if (!dir) {
                    if (processing === 0)
                        results.end();
                    return;
                }
                processing++;
                dirs.add(dir);
                const entries = dir.readdirSync();
                for (const e of entries) {
                    if (!filter || filter(e)) {
                        if (!results.write(withFileTypes ? e : e.fullpath())) {
                            paused = true;
                        }
                    }
                }
                processing--;
                for (const e of entries) {
                    let r = e;
                    if (e.isSymbolicLink()) {
                        if (!(follow && (r = e.realpathSync())))
                            continue;
                        if (r.isUnknown())
                            r.lstatSync();
                    }
                    if (r.shouldWalk(dirs, walkFilter)) {
                        queue.push(r);
                    }
                }
            }
            if (paused && !results.flowing)
                results.once('drain', process);
        };
        process();
        return results;
    }
    chdir(path = this.cwd) {
        const oldCwd = this.cwd;
        this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path;
        this.cwd[setAsCwd](oldCwd);
    }
}
exports.PathScurryBase = PathScurryBase;
/**
 * Windows implementation of {@link PathScurryBase}
 *
 * Defaults to case insensitve, uses `'\\'` to generate path strings.  Uses
 * {@link PathWin32} for Path objects.
 */
class PathScurryWin32 extends PathScurryBase {
    /**
     * separator for generating path strings
     */
    sep = '\\';
    constructor(cwd = process.cwd(), opts = {}) {
        const { nocase = true } = opts;
        super(cwd, node_path_1.win32, '\\', { ...opts, nocase });
        this.nocase = nocase;
        for (let p = this.cwd; p; p = p.parent) {
            p.nocase = this.nocase;
        }
    }
    /**
     * @internal
     */
    parseRootPath(dir) {
        // if the path starts with a single separator, it's not a UNC, and we'll
        // just get separator as the root, and driveFromUNC will return \
        // In that case, mount \ on the root from the cwd.
        return node_path_1.win32.parse(dir).root.toUpperCase();
    }
    /**
     * @internal
     */
    newRoot(fs) {
        return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs });
    }
    /**
     * Return true if the provided path string is an absolute path
     */
    isAbsolute(p) {
        return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p));
    }
}
exports.PathScurryWin32 = PathScurryWin32;
/**
 * {@link PathScurryBase} implementation for all posix systems other than Darwin.
 *
 * Defaults to case-sensitive matching, uses `'/'` to generate path strings.
 *
 * Uses {@link PathPosix} for Path objects.
 */
class PathScurryPosix extends PathScurryBase {
    /**
     * separator for generating path strings
     */
    sep = '/';
    constructor(cwd = process.cwd(), opts = {}) {
        const { nocase = false } = opts;
        super(cwd, node_path_1.posix, '/', { ...opts, nocase });
        this.nocase = nocase;
    }
    /**
     * @internal
     */
    parseRootPath(_dir) {
        return '/';
    }
    /**
     * @internal
     */
    newRoot(fs) {
        return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs });
    }
    /**
     * Return true if the provided path string is an absolute path
     */
    isAbsolute(p) {
        return p.startsWith('/');
    }
}
exports.PathScurryPosix = PathScurryPosix;
/**
 * {@link PathScurryBase} implementation for Darwin (macOS) systems.
 *
 * Defaults to case-insensitive matching, uses `'/'` for generating path
 * strings.
 *
 * Uses {@link PathPosix} for Path objects.
 */
class PathScurryDarwin extends PathScurryPosix {
    constructor(cwd = process.cwd(), opts = {}) {
        const { nocase = true } = opts;
        super(cwd, { ...opts, nocase });
    }
}
exports.PathScurryDarwin = PathScurryDarwin;
/**
 * Default {@link PathBase} implementation for the current platform.
 *
 * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.
 */
exports.Path = process.platform === 'win32' ? PathWin32 : PathPosix;
/**
 * Default {@link PathScurryBase} implementation for the current platform.
 *
 * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on
 * Darwin (macOS) systems, {@link PathScurryPosix} on all others.
 */
exports.PathScurry = process.platform === 'win32' ? PathScurryWin32
    : process.platform === 'darwin' ? PathScurryDarwin
        : PathScurryPosix;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
import { LRUCache } from 'lru-cache';
import { posix, win32 } from 'node:path';
import { fileURLToPath } from 'node:url';
import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps, } from 'fs';
import * as actualFS from 'node:fs';
const realpathSync = rps.native;
// TODO: test perf of fs/promises realpath vs realpathCB,
// since the promises one uses realpath.native
import { lstat, readdir, readlink, realpath } from 'node:fs/promises';
import { Minipass } from 'minipass';
const defaultFS = {
    lstatSync,
    readdir: readdirCB,
    readdirSync,
    readlinkSync,
    realpathSync,
    promises: {
        lstat,
        readdir,
        readlink,
        realpath,
    },
};
// if they just gave us require('fs') then use our default
const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ?
    defaultFS
    : {
        ...defaultFS,
        ...fsOption,
        promises: {
            ...defaultFS.promises,
            ...(fsOption.promises || {}),
        },
    };
// turn something like //?/c:/ into c:\
const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\');
// windows paths are separated by either / or \
const eitherSep = /[\\\/]/;
const UNKNOWN = 0; // may not even exist, for all we know
const IFIFO = 0b0001;
const IFCHR = 0b0010;
const IFDIR = 0b0100;
const IFBLK = 0b0110;
const IFREG = 0b1000;
const IFLNK = 0b1010;
const IFSOCK = 0b1100;
const IFMT = 0b1111;
// mask to unset low 4 bits
const IFMT_UNKNOWN = ~IFMT;
// set after successfully calling readdir() and getting entries.
const READDIR_CALLED = 0b0000_0001_0000;
// set after a successful lstat()
const LSTAT_CALLED = 0b0000_0010_0000;
// set if an entry (or one of its parents) is definitely not a dir
const ENOTDIR = 0b0000_0100_0000;
// set if an entry (or one of its parents) does not exist
// (can also be set on lstat errors like EACCES or ENAMETOOLONG)
const ENOENT = 0b0000_1000_0000;
// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK
// set if we fail to readlink
const ENOREADLINK = 0b0001_0000_0000;
// set if we know realpath() will fail
const ENOREALPATH = 0b0010_0000_0000;
const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
const TYPEMASK = 0b0011_1111_1111;
const entToType = (s) => s.isFile() ? IFREG
    : s.isDirectory() ? IFDIR
        : s.isSymbolicLink() ? IFLNK
            : s.isCharacterDevice() ? IFCHR
                : s.isBlockDevice() ? IFBLK
                    : s.isSocket() ? IFSOCK
                        : s.isFIFO() ? IFIFO
                            : UNKNOWN;
// normalize unicode path names
const normalizeCache = new Map();
const normalize = (s) => {
    const c = normalizeCache.get(s);
    if (c)
        return c;
    const n = s.normalize('NFKD');
    normalizeCache.set(s, n);
    return n;
};
const normalizeNocaseCache = new Map();
const normalizeNocase = (s) => {
    const c = normalizeNocaseCache.get(s);
    if (c)
        return c;
    const n = normalize(s.toLowerCase());
    normalizeNocaseCache.set(s, n);
    return n;
};
/**
 * An LRUCache for storing resolved path strings or Path objects.
 * @internal
 */
export class ResolveCache extends LRUCache {
    constructor() {
        super({ max: 256 });
    }
}
// In order to prevent blowing out the js heap by allocating hundreds of
// thousands of Path entries when walking extremely large trees, the "children"
// in this tree are represented by storing an array of Path entries in an
// LRUCache, indexed by the parent.  At any time, Path.children() may return an
// empty array, indicating that it doesn't know about any of its children, and
// thus has to rebuild that cache.  This is fine, it just means that we don't
// benefit as much from having the cached entries, but huge directory walks
// don't blow out the stack, and smaller ones are still as fast as possible.
//
//It does impose some complexity when building up the readdir data, because we
//need to pass a reference to the children array that we started with.
/**
 * an LRUCache for storing child entries.
 * @internal
 */
export class ChildrenCache extends LRUCache {
    constructor(maxSize = 16 * 1024) {
        super({
            maxSize,
            // parent + children
            sizeCalculation: a => a.length + 1,
        });
    }
}
const setAsCwd = Symbol('PathScurry setAsCwd');
/**
 * Path objects are sort of like a super-powered
 * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}
 *
 * Each one represents a single filesystem entry on disk, which may or may not
 * exist. It includes methods for reading various types of information via
 * lstat, readlink, and readdir, and caches all information to the greatest
 * degree possible.
 *
 * Note that fs operations that would normally throw will instead return an
 * "empty" value. This is in order to prevent excessive overhead from error
 * stack traces.
 */
export class PathBase {
    /**
     * the basename of this path
     *
     * **Important**: *always* test the path name against any test string
     * usingthe {@link isNamed} method, and not by directly comparing this
     * string. Otherwise, unicode path strings that the system sees as identical
     * will not be properly treated as the same path, leading to incorrect
     * behavior and possible security issues.
     */
    name;
    /**
     * the Path entry corresponding to the path root.
     *
     * @internal
     */
    root;
    /**
     * All roots found within the current PathScurry family
     *
     * @internal
     */
    roots;
    /**
     * a reference to the parent path, or undefined in the case of root entries
     *
     * @internal
     */
    parent;
    /**
     * boolean indicating whether paths are compared case-insensitively
     * @internal
     */
    nocase;
    /**
     * boolean indicating that this path is the current working directory
     * of the PathScurry collection that contains it.
     */
    isCWD = false;
    // potential default fs override
    #fs;
    // Stats fields
    #dev;
    get dev() {
        return this.#dev;
    }
    #mode;
    get mode() {
        return this.#mode;
    }
    #nlink;
    get nlink() {
        return this.#nlink;
    }
    #uid;
    get uid() {
        return this.#uid;
    }
    #gid;
    get gid() {
        return this.#gid;
    }
    #rdev;
    get rdev() {
        return this.#rdev;
    }
    #blksize;
    get blksize() {
        return this.#blksize;
    }
    #ino;
    get ino() {
        return this.#ino;
    }
    #size;
    get size() {
        return this.#size;
    }
    #blocks;
    get blocks() {
        return this.#blocks;
    }
    #atimeMs;
    get atimeMs() {
        return this.#atimeMs;
    }
    #mtimeMs;
    get mtimeMs() {
        return this.#mtimeMs;
    }
    #ctimeMs;
    get ctimeMs() {
        return this.#ctimeMs;
    }
    #birthtimeMs;
    get birthtimeMs() {
        return this.#birthtimeMs;
    }
    #atime;
    get atime() {
        return this.#atime;
    }
    #mtime;
    get mtime() {
        return this.#mtime;
    }
    #ctime;
    get ctime() {
        return this.#ctime;
    }
    #birthtime;
    get birthtime() {
        return this.#birthtime;
    }
    #matchName;
    #depth;
    #fullpath;
    #fullpathPosix;
    #relative;
    #relativePosix;
    #type;
    #children;
    #linkTarget;
    #realpath;
    /**
     * This property is for compatibility with the Dirent class as of
     * Node v20, where Dirent['parentPath'] refers to the path of the
     * directory that was passed to readdir. For root entries, it's the path
     * to the entry itself.
     */
    get parentPath() {
        return (this.parent || this).fullpath();
    }
    /**
     * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
     * this property refers to the *parent* path, not the path object itself.
     */
    get path() {
        return this.parentPath;
    }
    /**
     * Do not create new Path objects directly.  They should always be accessed
     * via the PathScurry class or other methods on the Path class.
     *
     * @internal
     */
    constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
        this.name = name;
        this.#matchName = nocase ? normalizeNocase(name) : normalize(name);
        this.#type = type & TYPEMASK;
        this.nocase = nocase;
        this.roots = roots;
        this.root = root || this;
        this.#children = children;
        this.#fullpath = opts.fullpath;
        this.#relative = opts.relative;
        this.#relativePosix = opts.relativePosix;
        this.parent = opts.parent;
        if (this.parent) {
            this.#fs = this.parent.#fs;
        }
        else {
            this.#fs = fsFromOption(opts.fs);
        }
    }
    /**
     * Returns the depth of the Path object from its root.
     *
     * For example, a path at `/foo/bar` would have a depth of 2.
     */
    depth() {
        if (this.#depth !== undefined)
            return this.#depth;
        if (!this.parent)
            return (this.#depth = 0);
        return (this.#depth = this.parent.depth() + 1);
    }
    /**
     * @internal
     */
    childrenCache() {
        return this.#children;
    }
    /**
     * Get the Path object referenced by the string path, resolved from this Path
     */
    resolve(path) {
        if (!path) {
            return this;
        }
        const rootPath = this.getRootString(path);
        const dir = path.substring(rootPath.length);
        const dirParts = dir.split(this.splitSep);
        const result = rootPath ?
            this.getRoot(rootPath).#resolveParts(dirParts)
            : this.#resolveParts(dirParts);
        return result;
    }
    #resolveParts(dirParts) {
        let p = this;
        for (const part of dirParts) {
            p = p.child(part);
        }
        return p;
    }
    /**
     * Returns the cached children Path objects, if still available.  If they
     * have fallen out of the cache, then returns an empty array, and resets the
     * READDIR_CALLED bit, so that future calls to readdir() will require an fs
     * lookup.
     *
     * @internal
     */
    children() {
        const cached = this.#children.get(this);
        if (cached) {
            return cached;
        }
        const children = Object.assign([], { provisional: 0 });
        this.#children.set(this, children);
        this.#type &= ~READDIR_CALLED;
        return children;
    }
    /**
     * Resolves a path portion and returns or creates the child Path.
     *
     * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
     * `'..'`.
     *
     * This should not be called directly.  If `pathPart` contains any path
     * separators, it will lead to unsafe undefined behavior.
     *
     * Use `Path.resolve()` instead.
     *
     * @internal
     */
    child(pathPart, opts) {
        if (pathPart === '' || pathPart === '.') {
            return this;
        }
        if (pathPart === '..') {
            return this.parent || this;
        }
        // find the child
        const children = this.children();
        const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart);
        for (const p of children) {
            if (p.#matchName === name) {
                return p;
            }
        }
        // didn't find it, create provisional child, since it might not
        // actually exist.  If we know the parent isn't a dir, then
        // in fact it CAN'T exist.
        const s = this.parent ? this.sep : '';
        const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : undefined;
        const pchild = this.newChild(pathPart, UNKNOWN, {
            ...opts,
            parent: this,
            fullpath,
        });
        if (!this.canReaddir()) {
            pchild.#type |= ENOENT;
        }
        // don't have to update provisional, because if we have real children,
        // then provisional is set to children.length, otherwise a lower number
        children.push(pchild);
        return pchild;
    }
    /**
     * The relative path from the cwd. If it does not share an ancestor with
     * the cwd, then this ends up being equivalent to the fullpath()
     */
    relative() {
        if (this.isCWD)
            return '';
        if (this.#relative !== undefined) {
            return this.#relative;
        }
        const name = this.name;
        const p = this.parent;
        if (!p) {
            return (this.#relative = this.name);
        }
        const pv = p.relative();
        return pv + (!pv || !p.parent ? '' : this.sep) + name;
    }
    /**
     * The relative path from the cwd, using / as the path separator.
     * If it does not share an ancestor with
     * the cwd, then this ends up being equivalent to the fullpathPosix()
     * On posix systems, this is identical to relative().
     */
    relativePosix() {
        if (this.sep === '/')
            return this.relative();
        if (this.isCWD)
            return '';
        if (this.#relativePosix !== undefined)
            return this.#relativePosix;
        const name = this.name;
        const p = this.parent;
        if (!p) {
            return (this.#relativePosix = this.fullpathPosix());
        }
        const pv = p.relativePosix();
        return pv + (!pv || !p.parent ? '' : '/') + name;
    }
    /**
     * The fully resolved path string for this Path entry
     */
    fullpath() {
        if (this.#fullpath !== undefined) {
            return this.#fullpath;
        }
        const name = this.name;
        const p = this.parent;
        if (!p) {
            return (this.#fullpath = this.name);
        }
        const pv = p.fullpath();
        const fp = pv + (!p.parent ? '' : this.sep) + name;
        return (this.#fullpath = fp);
    }
    /**
     * On platforms other than windows, this is identical to fullpath.
     *
     * On windows, this is overridden to return the forward-slash form of the
     * full UNC path.
     */
    fullpathPosix() {
        if (this.#fullpathPosix !== undefined)
            return this.#fullpathPosix;
        if (this.sep === '/')
            return (this.#fullpathPosix = this.fullpath());
        if (!this.parent) {
            const p = this.fullpath().replace(/\\/g, '/');
            if (/^[a-z]:\//i.test(p)) {
                return (this.#fullpathPosix = `//?/${p}`);
            }
            else {
                return (this.#fullpathPosix = p);
            }
        }
        const p = this.parent;
        const pfpp = p.fullpathPosix();
        const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name;
        return (this.#fullpathPosix = fpp);
    }
    /**
     * Is the Path of an unknown type?
     *
     * Note that we might know *something* about it if there has been a previous
     * filesystem operation, for example that it does not exist, or is not a
     * link, or whether it has child entries.
     */
    isUnknown() {
        return (this.#type & IFMT) === UNKNOWN;
    }
    isType(type) {
        return this[`is${type}`]();
    }
    getType() {
        return (this.isUnknown() ? 'Unknown'
            : this.isDirectory() ? 'Directory'
                : this.isFile() ? 'File'
                    : this.isSymbolicLink() ? 'SymbolicLink'
                        : this.isFIFO() ? 'FIFO'
                            : this.isCharacterDevice() ? 'CharacterDevice'
                                : this.isBlockDevice() ? 'BlockDevice'
                                    : /* c8 ignore start */ this.isSocket() ? 'Socket'
                                        : 'Unknown');
        /* c8 ignore stop */
    }
    /**
     * Is the Path a regular file?
     */
    isFile() {
        return (this.#type & IFMT) === IFREG;
    }
    /**
     * Is the Path a directory?
     */
    isDirectory() {
        return (this.#type & IFMT) === IFDIR;
    }
    /**
     * Is the path a character device?
     */
    isCharacterDevice() {
        return (this.#type & IFMT) === IFCHR;
    }
    /**
     * Is the path a block device?
     */
    isBlockDevice() {
        return (this.#type & IFMT) === IFBLK;
    }
    /**
     * Is the path a FIFO pipe?
     */
    isFIFO() {
        return (this.#type & IFMT) === IFIFO;
    }
    /**
     * Is the path a socket?
     */
    isSocket() {
        return (this.#type & IFMT) === IFSOCK;
    }
    /**
     * Is the path a symbolic link?
     */
    isSymbolicLink() {
        return (this.#type & IFLNK) === IFLNK;
    }
    /**
     * Return the entry if it has been subject of a successful lstat, or
     * undefined otherwise.
     *
     * Does not read the filesystem, so an undefined result *could* simply
     * mean that we haven't called lstat on it.
     */
    lstatCached() {
        return this.#type & LSTAT_CALLED ? this : undefined;
    }
    /**
     * Return the cached link target if the entry has been the subject of a
     * successful readlink, or undefined otherwise.
     *
     * Does not read the filesystem, so an undefined result *could* just mean we
     * don't have any cached data. Only use it if you are very sure that a
     * readlink() has been called at some point.
     */
    readlinkCached() {
        return this.#linkTarget;
    }
    /**
     * Returns the cached realpath target if the entry has been the subject
     * of a successful realpath, or undefined otherwise.
     *
     * Does not read the filesystem, so an undefined result *could* just mean we
     * don't have any cached data. Only use it if you are very sure that a
     * realpath() has been called at some point.
     */
    realpathCached() {
        return this.#realpath;
    }
    /**
     * Returns the cached child Path entries array if the entry has been the
     * subject of a successful readdir(), or [] otherwise.
     *
     * Does not read the filesystem, so an empty array *could* just mean we
     * don't have any cached data. Only use it if you are very sure that a
     * readdir() has been called recently enough to still be valid.
     */
    readdirCached() {
        const children = this.children();
        return children.slice(0, children.provisional);
    }
    /**
     * Return true if it's worth trying to readlink.  Ie, we don't (yet) have
     * any indication that readlink will definitely fail.
     *
     * Returns false if the path is known to not be a symlink, if a previous
     * readlink failed, or if the entry does not exist.
     */
    canReadlink() {
        if (this.#linkTarget)
            return true;
        if (!this.parent)
            return false;
        // cases where it cannot possibly succeed
        const ifmt = this.#type & IFMT;
        return !((ifmt !== UNKNOWN && ifmt !== IFLNK) ||
            this.#type & ENOREADLINK ||
            this.#type & ENOENT);
    }
    /**
     * Return true if readdir has previously been successfully called on this
     * path, indicating that cachedReaddir() is likely valid.
     */
    calledReaddir() {
        return !!(this.#type & READDIR_CALLED);
    }
    /**
     * Returns true if the path is known to not exist. That is, a previous lstat
     * or readdir failed to verify its existence when that would have been
     * expected, or a parent entry was marked either enoent or enotdir.
     */
    isENOENT() {
        return !!(this.#type & ENOENT);
    }
    /**
     * Return true if the path is a match for the given path name.  This handles
     * case sensitivity and unicode normalization.
     *
     * Note: even on case-sensitive systems, it is **not** safe to test the
     * equality of the `.name` property to determine whether a given pathname
     * matches, due to unicode normalization mismatches.
     *
     * Always use this method instead of testing the `path.name` property
     * directly.
     */
    isNamed(n) {
        return !this.nocase ?
            this.#matchName === normalize(n)
            : this.#matchName === normalizeNocase(n);
    }
    /**
     * Return the Path object corresponding to the target of a symbolic link.
     *
     * If the Path is not a symbolic link, or if the readlink call fails for any
     * reason, `undefined` is returned.
     *
     * Result is cached, and thus may be outdated if the filesystem is mutated.
     */
    async readlink() {
        const target = this.#linkTarget;
        if (target) {
            return target;
        }
        if (!this.canReadlink()) {
            return undefined;
        }
        /* c8 ignore start */
        // already covered by the canReadlink test, here for ts grumples
        if (!this.parent) {
            return undefined;
        }
        /* c8 ignore stop */
        try {
            const read = await this.#fs.promises.readlink(this.fullpath());
            const linkTarget = (await this.parent.realpath())?.resolve(read);
            if (linkTarget) {
                return (this.#linkTarget = linkTarget);
            }
        }
        catch (er) {
            this.#readlinkFail(er.code);
            return undefined;
        }
    }
    /**
     * Synchronous {@link PathBase.readlink}
     */
    readlinkSync() {
        const target = this.#linkTarget;
        if (target) {
            return target;
        }
        if (!this.canReadlink()) {
            return undefined;
        }
        /* c8 ignore start */
        // already covered by the canReadlink test, here for ts grumples
        if (!this.parent) {
            return undefined;
        }
        /* c8 ignore stop */
        try {
            const read = this.#fs.readlinkSync(this.fullpath());
            const linkTarget = this.parent.realpathSync()?.resolve(read);
            if (linkTarget) {
                return (this.#linkTarget = linkTarget);
            }
        }
        catch (er) {
            this.#readlinkFail(er.code);
            return undefined;
        }
    }
    #readdirSuccess(children) {
        // succeeded, mark readdir called bit
        this.#type |= READDIR_CALLED;
        // mark all remaining provisional children as ENOENT
        for (let p = children.provisional; p < children.length; p++) {
            const c = children[p];
            if (c)
                c.#markENOENT();
        }
    }
    #markENOENT() {
        // mark as UNKNOWN and ENOENT
        if (this.#type & ENOENT)
            return;
        this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN;
        this.#markChildrenENOENT();
    }
    #markChildrenENOENT() {
        // all children are provisional and do not exist
        const children = this.children();
        children.provisional = 0;
        for (const p of children) {
            p.#markENOENT();
        }
    }
    #markENOREALPATH() {
        this.#type |= ENOREALPATH;
        this.#markENOTDIR();
    }
    // save the information when we know the entry is not a dir
    #markENOTDIR() {
        // entry is not a directory, so any children can't exist.
        // this *should* be impossible, since any children created
        // after it's been marked ENOTDIR should be marked ENOENT,
        // so it won't even get to this point.
        /* c8 ignore start */
        if (this.#type & ENOTDIR)
            return;
        /* c8 ignore stop */
        let t = this.#type;
        // this could happen if we stat a dir, then delete it,
        // then try to read it or one of its children.
        if ((t & IFMT) === IFDIR)
            t &= IFMT_UNKNOWN;
        this.#type = t | ENOTDIR;
        this.#markChildrenENOENT();
    }
    #readdirFail(code = '') {
        // markENOTDIR and markENOENT also set provisional=0
        if (code === 'ENOTDIR' || code === 'EPERM') {
            this.#markENOTDIR();
        }
        else if (code === 'ENOENT') {
            this.#markENOENT();
        }
        else {
            this.children().provisional = 0;
        }
    }
    #lstatFail(code = '') {
        // Windows just raises ENOENT in this case, disable for win CI
        /* c8 ignore start */
        if (code === 'ENOTDIR') {
            // already know it has a parent by this point
            const p = this.parent;
            p.#markENOTDIR();
        }
        else if (code === 'ENOENT') {
            /* c8 ignore stop */
            this.#markENOENT();
        }
    }
    #readlinkFail(code = '') {
        let ter = this.#type;
        ter |= ENOREADLINK;
        if (code === 'ENOENT')
            ter |= ENOENT;
        // windows gets a weird error when you try to readlink a file
        if (code === 'EINVAL' || code === 'UNKNOWN') {
            // exists, but not a symlink, we don't know WHAT it is, so remove
            // all IFMT bits.
            ter &= IFMT_UNKNOWN;
        }
        this.#type = ter;
        // windows just gets ENOENT in this case.  We do cover the case,
        // just disabled because it's impossible on Windows CI
        /* c8 ignore start */
        if (code === 'ENOTDIR' && this.parent) {
            this.parent.#markENOTDIR();
        }
        /* c8 ignore stop */
    }
    #readdirAddChild(e, c) {
        return (this.#readdirMaybePromoteChild(e, c) ||
            this.#readdirAddNewChild(e, c));
    }
    #readdirAddNewChild(e, c) {
        // alloc new entry at head, so it's never provisional
        const type = entToType(e);
        const child = this.newChild(e.name, type, { parent: this });
        const ifmt = child.#type & IFMT;
        if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
            child.#type |= ENOTDIR;
        }
        c.unshift(child);
        c.provisional++;
        return child;
    }
    #readdirMaybePromoteChild(e, c) {
        for (let p = c.provisional; p < c.length; p++) {
            const pchild = c[p];
            const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name);
            if (name !== pchild.#matchName) {
                continue;
            }
            return this.#readdirPromoteChild(e, pchild, p, c);
        }
    }
    #readdirPromoteChild(e, p, index, c) {
        const v = p.name;
        // retain any other flags, but set ifmt from dirent
        p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e);
        // case sensitivity fixing when we learn the true name.
        if (v !== e.name)
            p.name = e.name;
        // just advance provisional index (potentially off the list),
        // otherwise we have to splice/pop it out and re-insert at head
        if (index !== c.provisional) {
            if (index === c.length - 1)
                c.pop();
            else
                c.splice(index, 1);
            c.unshift(p);
        }
        c.provisional++;
        return p;
    }
    /**
     * Call lstat() on this Path, and update all known information that can be
     * determined.
     *
     * Note that unlike `fs.lstat()`, the returned value does not contain some
     * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
     * information is required, you will need to call `fs.lstat` yourself.
     *
     * If the Path refers to a nonexistent file, or if the lstat call fails for
     * any reason, `undefined` is returned.  Otherwise the updated Path object is
     * returned.
     *
     * Results are cached, and thus may be out of date if the filesystem is
     * mutated.
     */
    async lstat() {
        if ((this.#type & ENOENT) === 0) {
            try {
                this.#applyStat(await this.#fs.promises.lstat(this.fullpath()));
                return this;
            }
            catch (er) {
                this.#lstatFail(er.code);
            }
        }
    }
    /**
     * synchronous {@link PathBase.lstat}
     */
    lstatSync() {
        if ((this.#type & ENOENT) === 0) {
            try {
                this.#applyStat(this.#fs.lstatSync(this.fullpath()));
                return this;
            }
            catch (er) {
                this.#lstatFail(er.code);
            }
        }
    }
    #applyStat(st) {
        const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st;
        this.#atime = atime;
        this.#atimeMs = atimeMs;
        this.#birthtime = birthtime;
        this.#birthtimeMs = birthtimeMs;
        this.#blksize = blksize;
        this.#blocks = blocks;
        this.#ctime = ctime;
        this.#ctimeMs = ctimeMs;
        this.#dev = dev;
        this.#gid = gid;
        this.#ino = ino;
        this.#mode = mode;
        this.#mtime = mtime;
        this.#mtimeMs = mtimeMs;
        this.#nlink = nlink;
        this.#rdev = rdev;
        this.#size = size;
        this.#uid = uid;
        const ifmt = entToType(st);
        // retain any other flags, but set the ifmt
        this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED;
        if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
            this.#type |= ENOTDIR;
        }
    }
    #onReaddirCB = [];
    #readdirCBInFlight = false;
    #callOnReaddirCB(children) {
        this.#readdirCBInFlight = false;
        const cbs = this.#onReaddirCB.slice();
        this.#onReaddirCB.length = 0;
        cbs.forEach(cb => cb(null, children));
    }
    /**
     * Standard node-style callback interface to get list of directory entries.
     *
     * If the Path cannot or does not contain any children, then an empty array
     * is returned.
     *
     * Results are cached, and thus may be out of date if the filesystem is
     * mutated.
     *
     * @param cb The callback called with (er, entries).  Note that the `er`
     * param is somewhat extraneous, as all readdir() errors are handled and
     * simply result in an empty set of entries being returned.
     * @param allowZalgo Boolean indicating that immediately known results should
     * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
     * zalgo at your peril, the dark pony lord is devious and unforgiving.
     */
    readdirCB(cb, allowZalgo = false) {
        if (!this.canReaddir()) {
            if (allowZalgo)
                cb(null, []);
            else
                queueMicrotask(() => cb(null, []));
            return;
        }
        const children = this.children();
        if (this.calledReaddir()) {
            const c = children.slice(0, children.provisional);
            if (allowZalgo)
                cb(null, c);
            else
                queueMicrotask(() => cb(null, c));
            return;
        }
        // don't have to worry about zalgo at this point.
        this.#onReaddirCB.push(cb);
        if (this.#readdirCBInFlight) {
            return;
        }
        this.#readdirCBInFlight = true;
        // else read the directory, fill up children
        // de-provisionalize any provisional children.
        const fullpath = this.fullpath();
        this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {
            if (er) {
                this.#readdirFail(er.code);
                children.provisional = 0;
            }
            else {
                // if we didn't get an error, we always get entries.
                //@ts-ignore
                for (const e of entries) {
                    this.#readdirAddChild(e, children);
                }
                this.#readdirSuccess(children);
            }
            this.#callOnReaddirCB(children.slice(0, children.provisional));
            return;
        });
    }
    #asyncReaddirInFlight;
    /**
     * Return an array of known child entries.
     *
     * If the Path cannot or does not contain any children, then an empty array
     * is returned.
     *
     * Results are cached, and thus may be out of date if the filesystem is
     * mutated.
     */
    async readdir() {
        if (!this.canReaddir()) {
            return [];
        }
        const children = this.children();
        if (this.calledReaddir()) {
            return children.slice(0, children.provisional);
        }
        // else read the directory, fill up children
        // de-provisionalize any provisional children.
        const fullpath = this.fullpath();
        if (this.#asyncReaddirInFlight) {
            await this.#asyncReaddirInFlight;
        }
        else {
            /* c8 ignore start */
            let resolve = () => { };
            /* c8 ignore stop */
            this.#asyncReaddirInFlight = new Promise(res => (resolve = res));
            try {
                for (const e of await this.#fs.promises.readdir(fullpath, {
                    withFileTypes: true,
                })) {
                    this.#readdirAddChild(e, children);
                }
                this.#readdirSuccess(children);
            }
            catch (er) {
                this.#readdirFail(er.code);
                children.provisional = 0;
            }
            this.#asyncReaddirInFlight = undefined;
            resolve();
        }
        return children.slice(0, children.provisional);
    }
    /**
     * synchronous {@link PathBase.readdir}
     */
    readdirSync() {
        if (!this.canReaddir()) {
            return [];
        }
        const children = this.children();
        if (this.calledReaddir()) {
            return children.slice(0, children.provisional);
        }
        // else read the directory, fill up children
        // de-provisionalize any provisional children.
        const fullpath = this.fullpath();
        try {
            for (const e of this.#fs.readdirSync(fullpath, {
                withFileTypes: true,
            })) {
                this.#readdirAddChild(e, children);
            }
            this.#readdirSuccess(children);
        }
        catch (er) {
            this.#readdirFail(er.code);
            children.provisional = 0;
        }
        return children.slice(0, children.provisional);
    }
    canReaddir() {
        if (this.#type & ENOCHILD)
            return false;
        const ifmt = IFMT & this.#type;
        // we always set ENOTDIR when setting IFMT, so should be impossible
        /* c8 ignore start */
        if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
            return false;
        }
        /* c8 ignore stop */
        return true;
    }
    shouldWalk(dirs, walkFilter) {
        return ((this.#type & IFDIR) === IFDIR &&
            !(this.#type & ENOCHILD) &&
            !dirs.has(this) &&
            (!walkFilter || walkFilter(this)));
    }
    /**
     * Return the Path object corresponding to path as resolved
     * by realpath(3).
     *
     * If the realpath call fails for any reason, `undefined` is returned.
     *
     * Result is cached, and thus may be outdated if the filesystem is mutated.
     * On success, returns a Path object.
     */
    async realpath() {
        if (this.#realpath)
            return this.#realpath;
        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
            return undefined;
        try {
            const rp = await this.#fs.promises.realpath(this.fullpath());
            return (this.#realpath = this.resolve(rp));
        }
        catch (_) {
            this.#markENOREALPATH();
        }
    }
    /**
     * Synchronous {@link realpath}
     */
    realpathSync() {
        if (this.#realpath)
            return this.#realpath;
        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
            return undefined;
        try {
            const rp = this.#fs.realpathSync(this.fullpath());
            return (this.#realpath = this.resolve(rp));
        }
        catch (_) {
            this.#markENOREALPATH();
        }
    }
    /**
     * Internal method to mark this Path object as the scurry cwd,
     * called by {@link PathScurry#chdir}
     *
     * @internal
     */
    [setAsCwd](oldCwd) {
        if (oldCwd === this)
            return;
        oldCwd.isCWD = false;
        this.isCWD = true;
        const changed = new Set([]);
        let rp = [];
        let p = this;
        while (p && p.parent) {
            changed.add(p);
            p.#relative = rp.join(this.sep);
            p.#relativePosix = rp.join('/');
            p = p.parent;
            rp.push('..');
        }
        // now un-memoize parents of old cwd
        p = oldCwd;
        while (p && p.parent && !changed.has(p)) {
            p.#relative = undefined;
            p.#relativePosix = undefined;
            p = p.parent;
        }
    }
}
/**
 * Path class used on win32 systems
 *
 * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'`
 * as the path separator for parsing paths.
 */
export class PathWin32 extends PathBase {
    /**
     * Separator for generating path strings.
     */
    sep = '\\';
    /**
     * Separator for parsing path strings.
     */
    splitSep = eitherSep;
    /**
     * Do not create new Path objects directly.  They should always be accessed
     * via the PathScurry class or other methods on the Path class.
     *
     * @internal
     */
    constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
        super(name, type, root, roots, nocase, children, opts);
    }
    /**
     * @internal
     */
    newChild(name, type = UNKNOWN, opts = {}) {
        return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
    }
    /**
     * @internal
     */
    getRootString(path) {
        return win32.parse(path).root;
    }
    /**
     * @internal
     */
    getRoot(rootPath) {
        rootPath = uncToDrive(rootPath.toUpperCase());
        if (rootPath === this.root.name) {
            return this.root;
        }
        // ok, not that one, check if it matches another we know about
        for (const [compare, root] of Object.entries(this.roots)) {
            if (this.sameRoot(rootPath, compare)) {
                return (this.roots[rootPath] = root);
            }
        }
        // otherwise, have to create a new one.
        return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root);
    }
    /**
     * @internal
     */
    sameRoot(rootPath, compare = this.root.name) {
        // windows can (rarely) have case-sensitive filesystem, but
        // UNC and drive letters are always case-insensitive, and canonically
        // represented uppercase.
        rootPath = rootPath
            .toUpperCase()
            .replace(/\//g, '\\')
            .replace(uncDriveRegexp, '$1\\');
        return rootPath === compare;
    }
}
/**
 * Path class used on all posix systems.
 *
 * Uses `'/'` as the path separator.
 */
export class PathPosix extends PathBase {
    /**
     * separator for parsing path strings
     */
    splitSep = '/';
    /**
     * separator for generating path strings
     */
    sep = '/';
    /**
     * Do not create new Path objects directly.  They should always be accessed
     * via the PathScurry class or other methods on the Path class.
     *
     * @internal
     */
    constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
        super(name, type, root, roots, nocase, children, opts);
    }
    /**
     * @internal
     */
    getRootString(path) {
        return path.startsWith('/') ? '/' : '';
    }
    /**
     * @internal
     */
    getRoot(_rootPath) {
        return this.root;
    }
    /**
     * @internal
     */
    newChild(name, type = UNKNOWN, opts = {}) {
        return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
    }
}
/**
 * The base class for all PathScurry classes, providing the interface for path
 * resolution and filesystem operations.
 *
 * Typically, you should *not* instantiate this class directly, but rather one
 * of the platform-specific classes, or the exported {@link PathScurry} which
 * defaults to the current platform.
 */
export class PathScurryBase {
    /**
     * The root Path entry for the current working directory of this Scurry
     */
    root;
    /**
     * The string path for the root of this Scurry's current working directory
     */
    rootPath;
    /**
     * A collection of all roots encountered, referenced by rootPath
     */
    roots;
    /**
     * The Path entry corresponding to this PathScurry's current working directory.
     */
    cwd;
    #resolveCache;
    #resolvePosixCache;
    #children;
    /**
     * Perform path comparisons case-insensitively.
     *
     * Defaults true on Darwin and Windows systems, false elsewhere.
     */
    nocase;
    #fs;
    /**
     * This class should not be instantiated directly.
     *
     * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
     *
     * @internal
     */
    constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) {
        this.#fs = fsFromOption(fs);
        if (cwd instanceof URL || cwd.startsWith('file://')) {
            cwd = fileURLToPath(cwd);
        }
        // resolve and split root, and then add to the store.
        // this is the only time we call path.resolve()
        const cwdPath = pathImpl.resolve(cwd);
        this.roots = Object.create(null);
        this.rootPath = this.parseRootPath(cwdPath);
        this.#resolveCache = new ResolveCache();
        this.#resolvePosixCache = new ResolveCache();
        this.#children = new ChildrenCache(childrenCacheSize);
        const split = cwdPath.substring(this.rootPath.length).split(sep);
        // resolve('/') leaves '', splits to [''], we don't want that.
        if (split.length === 1 && !split[0]) {
            split.pop();
        }
        /* c8 ignore start */
        if (nocase === undefined) {
            throw new TypeError('must provide nocase setting to PathScurryBase ctor');
        }
        /* c8 ignore stop */
        this.nocase = nocase;
        this.root = this.newRoot(this.#fs);
        this.roots[this.rootPath] = this.root;
        let prev = this.root;
        let len = split.length - 1;
        const joinSep = pathImpl.sep;
        let abs = this.rootPath;
        let sawFirst = false;
        for (const part of split) {
            const l = len--;
            prev = prev.child(part, {
                relative: new Array(l).fill('..').join(joinSep),
                relativePosix: new Array(l).fill('..').join('/'),
                fullpath: (abs += (sawFirst ? '' : joinSep) + part),
            });
            sawFirst = true;
        }
        this.cwd = prev;
    }
    /**
     * Get the depth of a provided path, string, or the cwd
     */
    depth(path = this.cwd) {
        if (typeof path === 'string') {
            path = this.cwd.resolve(path);
        }
        return path.depth();
    }
    /**
     * Return the cache of child entries.  Exposed so subclasses can create
     * child Path objects in a platform-specific way.
     *
     * @internal
     */
    childrenCache() {
        return this.#children;
    }
    /**
     * Resolve one or more path strings to a resolved string
     *
     * Same interface as require('path').resolve.
     *
     * Much faster than path.resolve() when called multiple times for the same
     * path, because the resolved Path objects are cached.  Much slower
     * otherwise.
     */
    resolve(...paths) {
        // first figure out the minimum number of paths we have to test
        // we always start at cwd, but any absolutes will bump the start
        let r = '';
        for (let i = paths.length - 1; i >= 0; i--) {
            const p = paths[i];
            if (!p || p === '.')
                continue;
            r = r ? `${p}/${r}` : p;
            if (this.isAbsolute(p)) {
                break;
            }
        }
        const cached = this.#resolveCache.get(r);
        if (cached !== undefined) {
            return cached;
        }
        const result = this.cwd.resolve(r).fullpath();
        this.#resolveCache.set(r, result);
        return result;
    }
    /**
     * Resolve one or more path strings to a resolved string, returning
     * the posix path.  Identical to .resolve() on posix systems, but on
     * windows will return a forward-slash separated UNC path.
     *
     * Same interface as require('path').resolve.
     *
     * Much faster than path.resolve() when called multiple times for the same
     * path, because the resolved Path objects are cached.  Much slower
     * otherwise.
     */
    resolvePosix(...paths) {
        // first figure out the minimum number of paths we have to test
        // we always start at cwd, but any absolutes will bump the start
        let r = '';
        for (let i = paths.length - 1; i >= 0; i--) {
            const p = paths[i];
            if (!p || p === '.')
                continue;
            r = r ? `${p}/${r}` : p;
            if (this.isAbsolute(p)) {
                break;
            }
        }
        const cached = this.#resolvePosixCache.get(r);
        if (cached !== undefined) {
            return cached;
        }
        const result = this.cwd.resolve(r).fullpathPosix();
        this.#resolvePosixCache.set(r, result);
        return result;
    }
    /**
     * find the relative path from the cwd to the supplied path string or entry
     */
    relative(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.relative();
    }
    /**
     * find the relative path from the cwd to the supplied path string or
     * entry, using / as the path delimiter, even on Windows.
     */
    relativePosix(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.relativePosix();
    }
    /**
     * Return the basename for the provided string or Path object
     */
    basename(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.name;
    }
    /**
     * Return the dirname for the provided string or Path object
     */
    dirname(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return (entry.parent || entry).fullpath();
    }
    async readdir(entry = this.cwd, opts = {
        withFileTypes: true,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes } = opts;
        if (!entry.canReaddir()) {
            return [];
        }
        else {
            const p = await entry.readdir();
            return withFileTypes ? p : p.map(e => e.name);
        }
    }
    readdirSync(entry = this.cwd, opts = {
        withFileTypes: true,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true } = opts;
        if (!entry.canReaddir()) {
            return [];
        }
        else if (withFileTypes) {
            return entry.readdirSync();
        }
        else {
            return entry.readdirSync().map(e => e.name);
        }
    }
    /**
     * Call lstat() on the string or Path object, and update all known
     * information that can be determined.
     *
     * Note that unlike `fs.lstat()`, the returned value does not contain some
     * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
     * information is required, you will need to call `fs.lstat` yourself.
     *
     * If the Path refers to a nonexistent file, or if the lstat call fails for
     * any reason, `undefined` is returned.  Otherwise the updated Path object is
     * returned.
     *
     * Results are cached, and thus may be out of date if the filesystem is
     * mutated.
     */
    async lstat(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.lstat();
    }
    /**
     * synchronous {@link PathScurryBase.lstat}
     */
    lstatSync(entry = this.cwd) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        return entry.lstatSync();
    }
    async readlink(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            withFileTypes = entry.withFileTypes;
            entry = this.cwd;
        }
        const e = await entry.readlink();
        return withFileTypes ? e : e?.fullpath();
    }
    readlinkSync(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            withFileTypes = entry.withFileTypes;
            entry = this.cwd;
        }
        const e = entry.readlinkSync();
        return withFileTypes ? e : e?.fullpath();
    }
    async realpath(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            withFileTypes = entry.withFileTypes;
            entry = this.cwd;
        }
        const e = await entry.realpath();
        return withFileTypes ? e : e?.fullpath();
    }
    realpathSync(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false,
    }) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            withFileTypes = entry.withFileTypes;
            entry = this.cwd;
        }
        const e = entry.realpathSync();
        return withFileTypes ? e : e?.fullpath();
    }
    async walk(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        const results = [];
        if (!filter || filter(entry)) {
            results.push(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = new Set();
        const walk = (dir, cb) => {
            dirs.add(dir);
            dir.readdirCB((er, entries) => {
                /* c8 ignore start */
                if (er) {
                    return cb(er);
                }
                /* c8 ignore stop */
                let len = entries.length;
                if (!len)
                    return cb();
                const next = () => {
                    if (--len === 0) {
                        cb();
                    }
                };
                for (const e of entries) {
                    if (!filter || filter(e)) {
                        results.push(withFileTypes ? e : e.fullpath());
                    }
                    if (follow && e.isSymbolicLink()) {
                        e.realpath()
                            .then(r => (r?.isUnknown() ? r.lstat() : r))
                            .then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next());
                    }
                    else {
                        if (e.shouldWalk(dirs, walkFilter)) {
                            walk(e, next);
                        }
                        else {
                            next();
                        }
                    }
                }
            }, true); // zalgooooooo
        };
        const start = entry;
        return new Promise((res, rej) => {
            walk(start, er => {
                /* c8 ignore start */
                if (er)
                    return rej(er);
                /* c8 ignore stop */
                res(results);
            });
        });
    }
    walkSync(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        const results = [];
        if (!filter || filter(entry)) {
            results.push(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = new Set([entry]);
        for (const dir of dirs) {
            const entries = dir.readdirSync();
            for (const e of entries) {
                if (!filter || filter(e)) {
                    results.push(withFileTypes ? e : e.fullpath());
                }
                let r = e;
                if (e.isSymbolicLink()) {
                    if (!(follow && (r = e.realpathSync())))
                        continue;
                    if (r.isUnknown())
                        r.lstatSync();
                }
                if (r.shouldWalk(dirs, walkFilter)) {
                    dirs.add(r);
                }
            }
        }
        return results;
    }
    /**
     * Support for `for await`
     *
     * Alias for {@link PathScurryBase.iterate}
     *
     * Note: As of Node 19, this is very slow, compared to other methods of
     * walking.  Consider using {@link PathScurryBase.stream} if memory overhead
     * and backpressure are concerns, or {@link PathScurryBase.walk} if not.
     */
    [Symbol.asyncIterator]() {
        return this.iterate();
    }
    iterate(entry = this.cwd, options = {}) {
        // iterating async over the stream is significantly more performant,
        // especially in the warm-cache scenario, because it buffers up directory
        // entries in the background instead of waiting for a yield for each one.
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            options = entry;
            entry = this.cwd;
        }
        return this.stream(entry, options)[Symbol.asyncIterator]();
    }
    /**
     * Iterating over a PathScurry performs a synchronous walk.
     *
     * Alias for {@link PathScurryBase.iterateSync}
     */
    [Symbol.iterator]() {
        return this.iterateSync();
    }
    *iterateSync(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        if (!filter || filter(entry)) {
            yield withFileTypes ? entry : entry.fullpath();
        }
        const dirs = new Set([entry]);
        for (const dir of dirs) {
            const entries = dir.readdirSync();
            for (const e of entries) {
                if (!filter || filter(e)) {
                    yield withFileTypes ? e : e.fullpath();
                }
                let r = e;
                if (e.isSymbolicLink()) {
                    if (!(follow && (r = e.realpathSync())))
                        continue;
                    if (r.isUnknown())
                        r.lstatSync();
                }
                if (r.shouldWalk(dirs, walkFilter)) {
                    dirs.add(r);
                }
            }
        }
    }
    stream(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        const results = new Minipass({ objectMode: true });
        if (!filter || filter(entry)) {
            results.write(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = new Set();
        const queue = [entry];
        let processing = 0;
        const process = () => {
            let paused = false;
            while (!paused) {
                const dir = queue.shift();
                if (!dir) {
                    if (processing === 0)
                        results.end();
                    return;
                }
                processing++;
                dirs.add(dir);
                const onReaddir = (er, entries, didRealpaths = false) => {
                    /* c8 ignore start */
                    if (er)
                        return results.emit('error', er);
                    /* c8 ignore stop */
                    if (follow && !didRealpaths) {
                        const promises = [];
                        for (const e of entries) {
                            if (e.isSymbolicLink()) {
                                promises.push(e
                                    .realpath()
                                    .then((r) => r?.isUnknown() ? r.lstat() : r));
                            }
                        }
                        if (promises.length) {
                            Promise.all(promises).then(() => onReaddir(null, entries, true));
                            return;
                        }
                    }
                    for (const e of entries) {
                        if (e && (!filter || filter(e))) {
                            if (!results.write(withFileTypes ? e : e.fullpath())) {
                                paused = true;
                            }
                        }
                    }
                    processing--;
                    for (const e of entries) {
                        const r = e.realpathCached() || e;
                        if (r.shouldWalk(dirs, walkFilter)) {
                            queue.push(r);
                        }
                    }
                    if (paused && !results.flowing) {
                        results.once('drain', process);
                    }
                    else if (!sync) {
                        process();
                    }
                };
                // zalgo containment
                let sync = true;
                dir.readdirCB(onReaddir, true);
                sync = false;
            }
        };
        process();
        return results;
    }
    streamSync(entry = this.cwd, opts = {}) {
        if (typeof entry === 'string') {
            entry = this.cwd.resolve(entry);
        }
        else if (!(entry instanceof PathBase)) {
            opts = entry;
            entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
        const results = new Minipass({ objectMode: true });
        const dirs = new Set();
        if (!filter || filter(entry)) {
            results.write(withFileTypes ? entry : entry.fullpath());
        }
        const queue = [entry];
        let processing = 0;
        const process = () => {
            let paused = false;
            while (!paused) {
                const dir = queue.shift();
                if (!dir) {
                    if (processing === 0)
                        results.end();
                    return;
                }
                processing++;
                dirs.add(dir);
                const entries = dir.readdirSync();
                for (const e of entries) {
                    if (!filter || filter(e)) {
                        if (!results.write(withFileTypes ? e : e.fullpath())) {
                            paused = true;
                        }
                    }
                }
                processing--;
                for (const e of entries) {
                    let r = e;
                    if (e.isSymbolicLink()) {
                        if (!(follow && (r = e.realpathSync())))
                            continue;
                        if (r.isUnknown())
                            r.lstatSync();
                    }
                    if (r.shouldWalk(dirs, walkFilter)) {
                        queue.push(r);
                    }
                }
            }
            if (paused && !results.flowing)
                results.once('drain', process);
        };
        process();
        return results;
    }
    chdir(path = this.cwd) {
        const oldCwd = this.cwd;
        this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path;
        this.cwd[setAsCwd](oldCwd);
    }
}
/**
 * Windows implementation of {@link PathScurryBase}
 *
 * Defaults to case insensitve, uses `'\\'` to generate path strings.  Uses
 * {@link PathWin32} for Path objects.
 */
export class PathScurryWin32 extends PathScurryBase {
    /**
     * separator for generating path strings
     */
    sep = '\\';
    constructor(cwd = process.cwd(), opts = {}) {
        const { nocase = true } = opts;
        super(cwd, win32, '\\', { ...opts, nocase });
        this.nocase = nocase;
        for (let p = this.cwd; p; p = p.parent) {
            p.nocase = this.nocase;
        }
    }
    /**
     * @internal
     */
    parseRootPath(dir) {
        // if the path starts with a single separator, it's not a UNC, and we'll
        // just get separator as the root, and driveFromUNC will return \
        // In that case, mount \ on the root from the cwd.
        return win32.parse(dir).root.toUpperCase();
    }
    /**
     * @internal
     */
    newRoot(fs) {
        return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs });
    }
    /**
     * Return true if the provided path string is an absolute path
     */
    isAbsolute(p) {
        return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p));
    }
}
/**
 * {@link PathScurryBase} implementation for all posix systems other than Darwin.
 *
 * Defaults to case-sensitive matching, uses `'/'` to generate path strings.
 *
 * Uses {@link PathPosix} for Path objects.
 */
export class PathScurryPosix extends PathScurryBase {
    /**
     * separator for generating path strings
     */
    sep = '/';
    constructor(cwd = process.cwd(), opts = {}) {
        const { nocase = false } = opts;
        super(cwd, posix, '/', { ...opts, nocase });
        this.nocase = nocase;
    }
    /**
     * @internal
     */
    parseRootPath(_dir) {
        return '/';
    }
    /**
     * @internal
     */
    newRoot(fs) {
        return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs });
    }
    /**
     * Return true if the provided path string is an absolute path
     */
    isAbsolute(p) {
        return p.startsWith('/');
    }
}
/**
 * {@link PathScurryBase} implementation for Darwin (macOS) systems.
 *
 * Defaults to case-insensitive matching, uses `'/'` for generating path
 * strings.
 *
 * Uses {@link PathPosix} for Path objects.
 */
export class PathScurryDarwin extends PathScurryPosix {
    constructor(cwd = process.cwd(), opts = {}) {
        const { nocase = true } = opts;
        super(cwd, { ...opts, nocase });
    }
}
/**
 * Default {@link PathBase} implementation for the current platform.
 *
 * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.
 */
export const Path = process.platform === 'win32' ? PathWin32 : PathPosix;
/**
 * Default {@link PathScurryBase} implementation for the current platform.
 *
 * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on
 * Darwin (macOS) systems, {@link PathScurryPosix} on all others.
 */
export const PathScurry = process.platform === 'win32' ? PathScurryWin32
    : process.platform === 'darwin' ? PathScurryDarwin
        : PathScurryPosix;
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "name": "path-scurry",
  "version": "1.11.1",
  "description": "walk paths fast and efficiently",
  "author": "Isaac Z. Schlueter  (https://blog.izs.me)",
  "main": "./dist/commonjs/index.js",
  "type": "module",
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "files": [
    "dist"
  ],
  "license": "BlueOak-1.0.0",
  "scripts": {
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "presnap": "npm run prepare",
    "test": "tap",
    "snap": "tap",
    "format": "prettier --write . --loglevel warn",
    "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts",
    "bench": "bash ./scripts/bench.sh"
  },
  "prettier": {
    "experimentalTernaries": true,
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "devDependencies": {
    "@nodelib/fs.walk": "^1.2.8",
    "@types/node": "^20.12.11",
    "c8": "^7.12.0",
    "eslint-config-prettier": "^8.6.0",
    "mkdirp": "^3.0.0",
    "prettier": "^3.2.5",
    "rimraf": "^5.0.1",
    "tap": "^18.7.2",
    "ts-node": "^10.9.2",
    "tshy": "^1.14.0",
    "typedoc": "^0.25.12",
    "typescript": "^5.4.3"
  },
  "tap": {
    "typecheck": true
  },
  "engines": {
    "node": ">=16 || 14 >=14.18"
  },
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/path-scurry"
  },
  "dependencies": {
    "lru-cache": "^10.2.0",
    "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
  },
  "tshy": {
    "selfLink": false,
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "types": "./dist/commonjs/index.d.ts"
}
# API Documentation

*Please use only this documented API when working with the parser. Methods
not documented here are subject to change at any point.*

## `parser` function

This is the module's main entry point.

```js
const parser = require('postcss-selector-parser');
```

### `parser([transform], [options])`

Creates a new `processor` instance

```js
const processor = parser();
```

Or, with optional transform function

```js
const transform = selectors => {
    selectors.walkUniversals(selector => {
        selector.remove();
    });
};

const processor = parser(transform)

// Example
const result = processor.processSync('*.class');
// => .class
```

[See processor documentation](#processor)

Arguments:

* `transform (function)`: Provide a function to work with the parsed AST.
* `options (object)`: Provide default options for all calls on the returned `Processor`.

### `parser.attribute([props])`

Creates a new attribute selector.

```js
parser.attribute({attribute: 'href'});
// => [href]
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.className([props])`

Creates a new class selector.

```js
parser.className({value: 'button'});
// => .button
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.combinator([props])`

Creates a new selector combinator.

```js
parser.combinator({value: '+'});
// => +
```

Arguments:

* `props (object)`: The new node's properties.

Notes:
* **Descendant Combinators** The value of descendant combinators created by the
  parser always just a single space (`" "`). For descendant selectors with no
  comments, additional space is now stored in `node.spaces.before`. Depending
  on the location of comments, additional spaces may be stored in
  `node.raws.spaces.before`, `node.raws.spaces.after`, or `node.raws.value`.
* **Named Combinators** Although, nonstandard and unlikely to ever become a standard,
  named combinators like `/deep/` and `/for/` are parsed as combinators. The
  `node.value` is name after being unescaped and normalized as lowercase. The
  original value for the combinator name is stored in `node.raws.value`.


### `parser.comment([props])`

Creates a new comment.

```js
parser.comment({value: '/* Affirmative, Dave. I read you. */'});
// => /* Affirmative, Dave. I read you. */
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.id([props])`

Creates a new id selector.

```js
parser.id({value: 'search'});
// => #search
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.nesting([props])`

Creates a new nesting selector.

```js
parser.nesting();
// => &
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.pseudo([props])`

Creates a new pseudo selector.

```js
parser.pseudo({value: '::before'});
// => ::before
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.root([props])`

Creates a new root node.

```js
parser.root();
// => (empty)
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.selector([props])`

Creates a new selector node.

```js
parser.selector();
// => (empty)
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.string([props])`

Creates a new string node.

```js
parser.string();
// => (empty)
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.tag([props])`

Creates a new tag selector.

```js
parser.tag({value: 'button'});
// => button
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.universal([props])`

Creates a new universal selector.

```js
parser.universal();
// => *
```

Arguments:

* `props (object)`: The new node's properties.

## Node types

### `node.type`

A string representation of the selector type. It can be one of the following;
`attribute`, `class`, `combinator`, `comment`, `id`, `nesting`, `pseudo`,
`root`, `selector`, `string`, `tag`, or `universal`. Note that for convenience,
these constants are exposed on the main `parser` as uppercased keys. So for
example you can get `id` by querying `parser.ID`.

```js
parser.attribute({attribute: 'href'}).type;
// => 'attribute'
```

### `node.parent`

Returns the parent node.

```js
root.nodes[0].parent === root;
```

### `node.toString()`, `String(node)`, or `'' + node`

Returns a string representation of the node.

```js
const id = parser.id({value: 'search'});
console.log(String(id));
// => #search
```

### `node.next()` & `node.prev()`

Returns the next/previous child of the parent node.

```js
const next = id.next();
if (next && next.type !== 'combinator') {
    throw new Error('Qualified IDs are not allowed!');
}
```

### `node.replaceWith(node)`

Replace a node with another.

```js
const attr = selectors.first.first;
const className = parser.className({value: 'test'});
attr.replaceWith(className);
```

Arguments:

* `node`: The node to substitute the original with.

### `node.remove()`

Removes the node from its parent node.

```js
if (node.type === 'id') {
    node.remove();
}
```

### `node.clone([opts])`

Returns a copy of a node, detached from any parent containers that the
original might have had.

```js
const cloned = node.clone();
```

### `node.isAtPosition(line, column)`

Return a `boolean` indicating whether this node includes the character at the
position of the given line and column. Returns `undefined` if the nodes lack
sufficient source metadata to determine the position.

Arguments:

* `line`: 1-index based line number relative to the start of the selector.
* `column`: 1-index based column number relative to the start of the selector.

### `node.spaces`

Extra whitespaces around the node will be moved into `node.spaces.before` and
`node.spaces.after`. So for example, these spaces will be moved as they have
no semantic meaning:

```css
      h1     ,     h2   {}
```

For descendent selectors, the value is always a single space.

```css
h1        h2 {}
```

Additional whitespace is found in either the `node.spaces.before` and `node.spaces.after` depending on the presence of comments or other whitespace characters. If the actual whitespace does not start or end with a single space, the node's raw value is set to the actual space(s) found in the source.

### `node.source`

An object describing the node's start/end, line/column source position.

Within the following CSS, the `.bar` class node ...

```css
.foo,
  .bar {}
```

... will contain the following `source` object.

```js
source: {
    start: {
        line: 2,
        column: 3
    },
    end: {
        line: 2,
        column: 6
    }
}
```

### `node.sourceIndex`

The zero-based index of the node within the original source string.

Within the following CSS, the `.baz` class node will have a `sourceIndex` of `12`.

```css
.foo, .bar, .baz {}
```

## Container types

The `root`, `selector`, and `pseudo` nodes have some helper methods for working
with their children.

### `container.nodes`

An array of the container's children.

```js
// Input: h1 h2
selectors.at(0).nodes.length   // => 3
selectors.at(0).nodes[0].value // => 'h1'
selectors.at(0).nodes[1].value // => ' '
```

### `container.first` & `container.last`

The first/last child of the container.

```js
selector.first === selector.nodes[0];
selector.last === selector.nodes[selector.nodes.length - 1];
```

### `container.at(index)`

Returns the node at position `index`.

```js
selector.at(0) === selector.first;
selector.at(0) === selector.nodes[0];
```

Arguments:

* `index`: The index of the node to return.

### `container.atPosition(line, column)`

Returns the node at the source position `line` and `column`.

```js
// Input: :not(.foo),\n#foo > :matches(ol, ul)
selector.atPosition(1, 1); // => :not(.foo)
selector.atPosition(2, 1); // => \n#foo
```

Arguments:

* `line`: The line number of the node to return.
* `column`: The column number of the node to return.

### `container.index(node)`

Return the index of the node within its container.

```js
selector.index(selector.nodes[2]) // => 2
```

Arguments:

* `node`: A node within the current container.

### `container.length`

Proxy to the length of the container's nodes.

```js
container.length === container.nodes.length
```

### `container` Array iterators

The container class provides proxies to certain Array methods; these are:

* `container.map === container.nodes.map`
* `container.reduce === container.nodes.reduce`
* `container.every === container.nodes.every`
* `container.some === container.nodes.some`
* `container.filter === container.nodes.filter`
* `container.sort === container.nodes.sort`

Note that these methods only work on a container's immediate children; recursive
iteration is provided by `container.walk`.

### `container.each(callback)`

Iterate the container's immediate children, calling `callback` for each child.
You may return `false` within the callback to break the iteration.

```js
let className;
selectors.each((selector, index) => {
    if (selector.type === 'class') {
        className = selector.value;
        return false;
    }
});
```

Note that unlike `Array#forEach()`, this iterator is safe to use whilst adding
or removing nodes from the container.

Arguments:

* `callback (function)`: A function to call for each node, which receives `node`
  and `index` arguments.

### `container.walk(callback)`

Like `container#each`, but will also iterate child nodes as long as they are
`container` types.

```js
selectors.walk((selector, index) => {
    // all nodes
});
```

Arguments:

* `callback (function)`: A function to call for each node, which receives `node`
  and `index` arguments.

This iterator is safe to use whilst mutating `container.nodes`,
like `container#each`.

### `container.walk` proxies

The container class provides proxy methods for iterating over types of nodes,
so that it is easier to write modules that target specific selectors. Those
methods are:

* `container.walkAttributes`
* `container.walkClasses`
* `container.walkCombinators`
* `container.walkComments`
* `container.walkIds`
* `container.walkNesting`
* `container.walkPseudos`
* `container.walkTags`
* `container.walkUniversals`

### `container.split(callback)`

This method allows you to split a group of nodes by returning `true` from
a callback. It returns an array of arrays, where each inner array corresponds
to the groups that you created via the callback.

```js
// (input) => h1 h2>>h3
const list = selectors.first.split(selector => {
    return selector.type === 'combinator';
});

// (node values) => [['h1', ' '], ['h2', '>>'], ['h3']]
```

Arguments:

* `callback (function)`: A function to call for each node, which receives `node`
  as an argument.

### `container.prepend(node)` & `container.append(node)`

Add a node to the start/end of the container. Note that doing so will set
the parent property of the node to this container.

```js
const id = parser.id({value: 'search'});
selector.append(id);
```

Arguments:

* `node`: The node to add.

### `container.insertBefore(old, new)` & `container.insertAfter(old, new)`

Add a node before or after an existing node in a container:

```js
selectors.walk(selector => {
    if (selector.type !== 'class') {
        const className = parser.className({value: 'theme-name'});
        selector.parent.insertAfter(selector, className);
    }
});
```

Arguments:

* `old`: The existing node in the container.
* `new`: The new node to add before/after the existing node.

### `container.removeChild(node)`

Remove the node from the container. Note that you can also use
`node.remove()` if you would like to remove just a single node.

```js
selector.length // => 2
selector.remove(id)
selector.length // => 1;
id.parent       // undefined
```

Arguments:

* `node`: The node to remove.

### `container.removeAll()` or `container.empty()`

Remove all children from the container.

```js
selector.removeAll();
selector.length // => 0
```

## Root nodes

A root node represents a comma separated list of selectors. Indeed, all
a root's `toString()` method does is join its selector children with a ','.
Other than this, it has no special functionality and acts like a container.

### `root.trailingComma`

This will be set to `true` if the input has a trailing comma, in order to
support parsing of legacy CSS hacks.

## Selector nodes

A selector node represents a single complex selector. For example, this
selector string `h1 h2 h3, [href] > p`, is represented as two selector nodes.
It has no special functionality of its own.

## Pseudo nodes

A pseudo selector extends a container node; if it has any parameters of its
own (such as `h1:not(h2, h3)`), they will be its children. Note that the pseudo
`value` will always contain the colons preceding the pseudo identifier. This
is so that both `:before` and `::before` are properly represented in the AST.

## Attribute nodes

### `attribute.quoted`

Returns `true` if the attribute's value is wrapped in quotation marks, false if it is not.
Remains `undefined` if there is no attribute value.

```css
[href=foo] /* false */
[href='foo'] /* true */
[href="foo"] /* true */
[href] /* undefined */
```

### `attribute.qualifiedAttribute`

Returns the attribute name qualified with the namespace if one is given.

### `attribute.offsetOf(part)`

 Returns the offset of the attribute part specified relative to the
 start of the node of the output string. This is useful in raising
 error messages about a specific part of the attribute, especially
 in combination with `attribute.sourceIndex`.

 Returns `-1` if the name is invalid or the value doesn't exist in this
 attribute.

 The legal values for `part` are:

 * `"ns"` - alias for "namespace"
 * `"namespace"` - the namespace if it exists.
 * `"attribute"` - the attribute name
 * `"attributeNS"` - the start of the attribute or its namespace
 * `"operator"` - the match operator of the attribute
 * `"value"` - The value (string or identifier)
 * `"insensitive"` - the case insensitivity flag

### `attribute.raws.unquoted`

Returns the unquoted content of the attribute's value.
Remains `undefined` if there is no attribute value.

```css
[href=foo] /* foo */
[href='foo'] /* foo */
[href="foo"] /* foo */
[href] /* undefined */
```

### `attribute.spaces`

Like `node.spaces` with the `before` and `after` values containing the spaces
around the element, the parts of the attribute can also have spaces before
and after them. The for each of `attribute`, `operator`, `value` and
`insensitive` there is corresponding property of the same nam in
`node.spaces` that has an optional `before` or `after` string containing only
whitespace.

Note that corresponding values in `attributes.raws.spaces` contain values
including any comments. If set, these values will override the
`attribute.spaces` value. Take care to remove them if changing
`attribute.spaces`.

### `attribute.raws`

The raws object stores comments and other information necessary to re-render
the node exactly as it was in the source.

If a comment is embedded within the identifiers for the `namespace`, `attribute`
or `value` then a property is placed in the raws for that value containing the full source of the propery including comments.

If a comment is embedded within the space between parts of the attribute
then the raw for that space is set accordingly.

Setting an attribute's property `raws` value to be deleted.

For now, changing the spaces required also updating or removing any of the
raws values that override them.

Example: `[ /*before*/ href /* after-attr */ = /* after-operator */ te/*inside-value*/st/* wow */ /*omg*/i/*bbq*/ /*whodoesthis*/]` would parse as:

```js
{
  attribute: "href",
  operator: "=",
  value: "test",
  spaces: {
    before: '',
    after: '',
    attribute: { before: '  ', after: '  ' },
    operator: { after: '  ' },
    value: { after: ' ' },
    insensitive: { after: ' ' }
  },
  raws: {
    spaces: {
      attribute: { before: ' /*before*/ ', after: ' /* after-attr */ ' },
      operator: { after: ' /* after-operator */ ' },
      value: { after: '/* wow */ /*omg*/' },
      insensitive: { after: '/*bbq*/ /*whodoesthis*/' }
    },
    unquoted: 'test',
    value: 'te/*inside-value*/st'
  }
}
```

## `Processor`

### `ProcessorOptions`

* `lossless` - When `true`, whitespace is preserved. Defaults to `true`.
* `updateSelector` - When `true`, if any processor methods are passed a postcss
  `Rule` node instead of a string, then that Rule's selector is updated
  with the results of the processing. Defaults to `true`.

### `process|processSync(selectors, [options])`

Processes the `selectors`, returning a string from the result of processing.

Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.

**Example:**

```js
const parser = require("postcss-selector-parser");
const processor = parser();

let result = processor.processSync(' .class');
console.log(result);
// =>  .class

// Asynchronous operation
let promise = processor.process(' .class').then(result => {
    console.log(result)
    // => .class
});

// To have the parser normalize whitespace values, utilize the options
result = processor.processSync('  .class  ', {lossless: false});
console.log(result);
// => .class

// For better syntax errors, pass a PostCSS Rule node.
const postcss = require('postcss');
rule = postcss.rule({selector: ' #foo    > a,  .class  '});
processor.process(rule, {lossless: false, updateSelector: true}).then(result => {
    console.log(result);
    // => #foo>a,.class
    console.log("rule:", rule.selector);
    // => rule: #foo>a,.class
})
```

Arguments:

* `selectors (string|postcss.Rule)`: Either a selector string or a PostCSS Rule
  node.
* `[options] (object)`: Process options


### `ast|astSync(selectors, [options])`

Like `process()` and `processSync()` but after
processing the `selectors` these methods return the `Root` node of the result
instead of a string.

Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.

### `transform|transformSync(selectors, [options])`

Like `process()` and `processSync()` but after
processing the `selectors` these methods return the value returned by the
processor callback.

Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.

### Error Handling Within Selector Processors

The root node passed to the selector processor callback
has a method `error(message, options)` that returns an
error object. This method should always be used to raise
errors relating to the syntax of selectors. The options
to this method are passed to postcss's error constructor
([documentation](http://postcss.org/api/#container-error)).

#### Async Error Example

```js
let processor = (root) => {
    return new Promise((resolve, reject) => {
        root.walkClasses((classNode) => {
            if (/^(.*)[-_]/.test(classNode.value)) {
                let msg = "classes may not have underscores or dashes in them";
                reject(root.error(msg, {
                    index: classNode.sourceIndex + RegExp.$1.length + 1,
                    word: classNode.value
                }));
            }
        });
        resolve();
    });
};

const postcss = require("postcss");
const parser = require("postcss-selector-parser");
const selectorProcessor = parser(processor);
const plugin = postcss.plugin('classValidator', (options) => {
    return (root) => {
        let promises = [];
        root.walkRules(rule => {
            promises.push(selectorProcessor.process(rule));
        });
        return Promise.all(promises);
    };
});
postcss(plugin()).process(`
.foo-bar {
  color: red;
}
`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));

// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
//
// > 1 | .foo-bar {
//     |     ^
//   2 |   color: red;
//   3 | }
```

#### Synchronous Error Example

```js
let processor = (root) => {
    root.walkClasses((classNode) => {
        if (/.*[-_]/.test(classNode.value)) {
            let msg = "classes may not have underscores or dashes in them";
            throw root.error(msg, {
                index: classNode.sourceIndex,
                word: classNode.value
            });
        }
    });
};

const postcss = require("postcss");
const parser = require("postcss-selector-parser");
const selectorProcessor = parser(processor);
const plugin = postcss.plugin('classValidator', (options) => {
    return (root) => {
        root.walkRules(rule => {
            selectorProcessor.processSync(rule);
        });
    };
});
postcss(plugin()).process(`
.foo-bar {
  color: red;
}
`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));

// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
//
// > 1 | .foo-bar {
//     |     ^
//   2 |   color: red;
//   3 | }
```
Copyright (c) Ben Briggs  (http://beneb.info)

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.
"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _processor = _interopRequireDefault(require("./processor"));
var selectors = _interopRequireWildcard(require("./selectors"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var parser = function parser(processor) {
  return new _processor["default"](processor);
};
Object.assign(parser, selectors);
delete parser.__esModule;
var _default = parser;
exports["default"] = _default;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _root = _interopRequireDefault(require("./selectors/root"));
var _selector = _interopRequireDefault(require("./selectors/selector"));
var _className = _interopRequireDefault(require("./selectors/className"));
var _comment = _interopRequireDefault(require("./selectors/comment"));
var _id = _interopRequireDefault(require("./selectors/id"));
var _tag = _interopRequireDefault(require("./selectors/tag"));
var _string = _interopRequireDefault(require("./selectors/string"));
var _pseudo = _interopRequireDefault(require("./selectors/pseudo"));
var _attribute = _interopRequireWildcard(require("./selectors/attribute"));
var _universal = _interopRequireDefault(require("./selectors/universal"));
var _combinator = _interopRequireDefault(require("./selectors/combinator"));
var _nesting = _interopRequireDefault(require("./selectors/nesting"));
var _sortAscending = _interopRequireDefault(require("./sortAscending"));
var _tokenize = _interopRequireWildcard(require("./tokenize"));
var tokens = _interopRequireWildcard(require("./tokenTypes"));
var types = _interopRequireWildcard(require("./selectors/types"));
var _util = require("./util");
var _WHITESPACE_TOKENS, _Object$assign;
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
function tokenStart(token) {
  return {
    line: token[_tokenize.FIELDS.START_LINE],
    column: token[_tokenize.FIELDS.START_COL]
  };
}
function tokenEnd(token) {
  return {
    line: token[_tokenize.FIELDS.END_LINE],
    column: token[_tokenize.FIELDS.END_COL]
  };
}
function getSource(startLine, startColumn, endLine, endColumn) {
  return {
    start: {
      line: startLine,
      column: startColumn
    },
    end: {
      line: endLine,
      column: endColumn
    }
  };
}
function getTokenSource(token) {
  return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
}
function getTokenSourceSpan(startToken, endToken) {
  if (!startToken) {
    return undefined;
  }
  return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
}
function unescapeProp(node, prop) {
  var value = node[prop];
  if (typeof value !== "string") {
    return;
  }
  if (value.indexOf("\\") !== -1) {
    (0, _util.ensureObject)(node, 'raws');
    node[prop] = (0, _util.unesc)(value);
    if (node.raws[prop] === undefined) {
      node.raws[prop] = value;
    }
  }
  return node;
}
function indexesOf(array, item) {
  var i = -1;
  var indexes = [];
  while ((i = array.indexOf(item, i + 1)) !== -1) {
    indexes.push(i);
  }
  return indexes;
}
function uniqs() {
  var list = Array.prototype.concat.apply([], arguments);
  return list.filter(function (item, i) {
    return i === list.indexOf(item);
  });
}
var Parser = /*#__PURE__*/function () {
  function Parser(rule, options) {
    if (options === void 0) {
      options = {};
    }
    this.rule = rule;
    this.options = Object.assign({
      lossy: false,
      safe: false
    }, options);
    this.position = 0;
    this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
    this.tokens = (0, _tokenize["default"])({
      css: this.css,
      error: this._errorGenerator(),
      safe: this.options.safe
    });
    var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
    this.root = new _root["default"]({
      source: rootSource
    });
    this.root.errorGenerator = this._errorGenerator();
    var selector = new _selector["default"]({
      source: {
        start: {
          line: 1,
          column: 1
        }
      },
      sourceIndex: 0
    });
    this.root.append(selector);
    this.current = selector;
    this.loop();
  }
  var _proto = Parser.prototype;
  _proto._errorGenerator = function _errorGenerator() {
    var _this = this;
    return function (message, errorOptions) {
      if (typeof _this.rule === 'string') {
        return new Error(message);
      }
      return _this.rule.error(message, errorOptions);
    };
  };
  _proto.attribute = function attribute() {
    var attr = [];
    var startingToken = this.currToken;
    this.position++;
    while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
      attr.push(this.currToken);
      this.position++;
    }
    if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
      return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
    }
    var len = attr.length;
    var node = {
      source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
      sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
    };
    if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
      return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
    }
    var pos = 0;
    var spaceBefore = '';
    var commentBefore = '';
    var lastAdded = null;
    var spaceAfterMeaningfulToken = false;
    while (pos < len) {
      var token = attr[pos];
      var content = this.content(token);
      var next = attr[pos + 1];
      switch (token[_tokenize.FIELDS.TYPE]) {
        case tokens.space:
          // if (
          //     len === 1 ||
          //     pos === 0 && this.content(next) === '|'
          // ) {
          //     return this.expected('attribute', token[TOKEN.START_POS], content);
          // }
          spaceAfterMeaningfulToken = true;
          if (this.options.lossy) {
            break;
          }
          if (lastAdded) {
            (0, _util.ensureObject)(node, 'spaces', lastAdded);
            var prevContent = node.spaces[lastAdded].after || '';
            node.spaces[lastAdded].after = prevContent + content;
            var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
            if (existingComment) {
              node.raws.spaces[lastAdded].after = existingComment + content;
            }
          } else {
            spaceBefore = spaceBefore + content;
            commentBefore = commentBefore + content;
          }
          break;
        case tokens.asterisk:
          if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
            node.operator = content;
            lastAdded = 'operator';
          } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
            if (spaceBefore) {
              (0, _util.ensureObject)(node, 'spaces', 'attribute');
              node.spaces.attribute.before = spaceBefore;
              spaceBefore = '';
            }
            if (commentBefore) {
              (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
              node.raws.spaces.attribute.before = spaceBefore;
              commentBefore = '';
            }
            node.namespace = (node.namespace || "") + content;
            var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
            if (rawValue) {
              node.raws.namespace += content;
            }
            lastAdded = 'namespace';
          }
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.dollar:
          if (lastAdded === "value") {
            var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
            node.value += "$";
            if (oldRawValue) {
              node.raws.value = oldRawValue + "$";
            }
            break;
          }
        // Falls through
        case tokens.caret:
          if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
            node.operator = content;
            lastAdded = 'operator';
          }
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.combinator:
          if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
            node.operator = content;
            lastAdded = 'operator';
          }
          if (content !== '|') {
            spaceAfterMeaningfulToken = false;
            break;
          }
          if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
            node.operator = content;
            lastAdded = 'operator';
          } else if (!node.namespace && !node.attribute) {
            node.namespace = true;
          }
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.word:
          if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
          // this look-ahead probably fails with comment nodes involved.
          !node.operator && !node.namespace) {
            node.namespace = content;
            lastAdded = 'namespace';
          } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
            if (spaceBefore) {
              (0, _util.ensureObject)(node, 'spaces', 'attribute');
              node.spaces.attribute.before = spaceBefore;
              spaceBefore = '';
            }
            if (commentBefore) {
              (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
              node.raws.spaces.attribute.before = commentBefore;
              commentBefore = '';
            }
            node.attribute = (node.attribute || "") + content;
            var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
            if (_rawValue) {
              node.raws.attribute += content;
            }
            lastAdded = 'attribute';
          } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
            var _unescaped = (0, _util.unesc)(content);
            var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
            var oldValue = node.value || '';
            node.value = oldValue + _unescaped;
            node.quoteMark = null;
            if (_unescaped !== content || _oldRawValue) {
              (0, _util.ensureObject)(node, 'raws');
              node.raws.value = (_oldRawValue || oldValue) + content;
            }
            lastAdded = 'value';
          } else {
            var insensitive = content === 'i' || content === "I";
            if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
              node.insensitive = insensitive;
              if (!insensitive || content === "I") {
                (0, _util.ensureObject)(node, 'raws');
                node.raws.insensitiveFlag = content;
              }
              lastAdded = 'insensitive';
              if (spaceBefore) {
                (0, _util.ensureObject)(node, 'spaces', 'insensitive');
                node.spaces.insensitive.before = spaceBefore;
                spaceBefore = '';
              }
              if (commentBefore) {
                (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
                node.raws.spaces.insensitive.before = commentBefore;
                commentBefore = '';
              }
            } else if (node.value || node.value === '') {
              lastAdded = 'value';
              node.value += content;
              if (node.raws.value) {
                node.raws.value += content;
              }
            }
          }
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.str:
          if (!node.attribute || !node.operator) {
            return this.error("Expected an attribute followed by an operator preceding the string.", {
              index: token[_tokenize.FIELDS.START_POS]
            });
          }
          var _unescapeValue = (0, _attribute.unescapeValue)(content),
            unescaped = _unescapeValue.unescaped,
            quoteMark = _unescapeValue.quoteMark;
          node.value = unescaped;
          node.quoteMark = quoteMark;
          lastAdded = 'value';
          (0, _util.ensureObject)(node, 'raws');
          node.raws.value = content;
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.equals:
          if (!node.attribute) {
            return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
          }
          if (node.value) {
            return this.error('Unexpected "=" found; an operator was already defined.', {
              index: token[_tokenize.FIELDS.START_POS]
            });
          }
          node.operator = node.operator ? node.operator + content : content;
          lastAdded = 'operator';
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.comment:
          if (lastAdded) {
            if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
              var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
              var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
              (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
              node.raws.spaces[lastAdded].after = rawLastComment + content;
            } else {
              var lastValue = node[lastAdded] || '';
              var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
              (0, _util.ensureObject)(node, 'raws');
              node.raws[lastAdded] = rawLastValue + content;
            }
          } else {
            commentBefore = commentBefore + content;
          }
          break;
        default:
          return this.error("Unexpected \"" + content + "\" found.", {
            index: token[_tokenize.FIELDS.START_POS]
          });
      }
      pos++;
    }
    unescapeProp(node, "attribute");
    unescapeProp(node, "namespace");
    this.newNode(new _attribute["default"](node));
    this.position++;
  }

  /**
   * return a node containing meaningless garbage up to (but not including) the specified token position.
   * if the token position is negative, all remaining tokens are consumed.
   *
   * This returns an array containing a single string node if all whitespace,
   * otherwise an array of comment nodes with space before and after.
   *
   * These tokens are not added to the current selector, the caller can add them or use them to amend
   * a previous node's space metadata.
   *
   * In lossy mode, this returns only comments.
   */;
  _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
    if (stopPosition < 0) {
      stopPosition = this.tokens.length;
    }
    var startPosition = this.position;
    var nodes = [];
    var space = "";
    var lastComment = undefined;
    do {
      if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
        if (!this.options.lossy) {
          space += this.content();
        }
      } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
        var spaces = {};
        if (space) {
          spaces.before = space;
          space = "";
        }
        lastComment = new _comment["default"]({
          value: this.content(),
          source: getTokenSource(this.currToken),
          sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
          spaces: spaces
        });
        nodes.push(lastComment);
      }
    } while (++this.position < stopPosition);
    if (space) {
      if (lastComment) {
        lastComment.spaces.after = space;
      } else if (!this.options.lossy) {
        var firstToken = this.tokens[startPosition];
        var lastToken = this.tokens[this.position - 1];
        nodes.push(new _string["default"]({
          value: '',
          source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
          sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
          spaces: {
            before: space,
            after: ''
          }
        }));
      }
    }
    return nodes;
  }

  /**
   *
   * @param {*} nodes
   */;
  _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
    var _this2 = this;
    if (requiredSpace === void 0) {
      requiredSpace = false;
    }
    var space = "";
    var rawSpace = "";
    nodes.forEach(function (n) {
      var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
      var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
      space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
      rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
    });
    if (rawSpace === space) {
      rawSpace = undefined;
    }
    var result = {
      space: space,
      rawSpace: rawSpace
    };
    return result;
  };
  _proto.isNamedCombinator = function isNamedCombinator(position) {
    if (position === void 0) {
      position = this.position;
    }
    return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  };
  _proto.namedCombinator = function namedCombinator() {
    if (this.isNamedCombinator()) {
      var nameRaw = this.content(this.tokens[this.position + 1]);
      var name = (0, _util.unesc)(nameRaw).toLowerCase();
      var raws = {};
      if (name !== nameRaw) {
        raws.value = "/" + nameRaw + "/";
      }
      var node = new _combinator["default"]({
        value: "/" + name + "/",
        source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
        sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
        raws: raws
      });
      this.position = this.position + 3;
      return node;
    } else {
      this.unexpected();
    }
  };
  _proto.combinator = function combinator() {
    var _this3 = this;
    if (this.content() === '|') {
      return this.namespace();
    }
    // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
    var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
    if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
      var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
      if (nodes.length > 0) {
        var last = this.current.last;
        if (last) {
          var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
            space = _this$convertWhitespa.space,
            rawSpace = _this$convertWhitespa.rawSpace;
          if (rawSpace !== undefined) {
            last.rawSpaceAfter += rawSpace;
          }
          last.spaces.after += space;
        } else {
          nodes.forEach(function (n) {
            return _this3.newNode(n);
          });
        }
      }
      return;
    }
    var firstToken = this.currToken;
    var spaceOrDescendantSelectorNodes = undefined;
    if (nextSigTokenPos > this.position) {
      spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
    }
    var node;
    if (this.isNamedCombinator()) {
      node = this.namedCombinator();
    } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
      node = new _combinator["default"]({
        value: this.content(),
        source: getTokenSource(this.currToken),
        sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
      });
      this.position++;
    } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
      // pass
    } else if (!spaceOrDescendantSelectorNodes) {
      this.unexpected();
    }
    if (node) {
      if (spaceOrDescendantSelectorNodes) {
        var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
          _space = _this$convertWhitespa2.space,
          _rawSpace = _this$convertWhitespa2.rawSpace;
        node.spaces.before = _space;
        node.rawSpaceBefore = _rawSpace;
      }
    } else {
      // descendant combinator
      var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
        _space2 = _this$convertWhitespa3.space,
        _rawSpace2 = _this$convertWhitespa3.rawSpace;
      if (!_rawSpace2) {
        _rawSpace2 = _space2;
      }
      var spaces = {};
      var raws = {
        spaces: {}
      };
      if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
        spaces.before = _space2.slice(0, _space2.length - 1);
        raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
      } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
        spaces.after = _space2.slice(1);
        raws.spaces.after = _rawSpace2.slice(1);
      } else {
        raws.value = _rawSpace2;
      }
      node = new _combinator["default"]({
        value: ' ',
        source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
        sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
        spaces: spaces,
        raws: raws
      });
    }
    if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
      node.spaces.after = this.optionalSpace(this.content());
      this.position++;
    }
    return this.newNode(node);
  };
  _proto.comma = function comma() {
    if (this.position === this.tokens.length - 1) {
      this.root.trailingComma = true;
      this.position++;
      return;
    }
    this.current._inferEndPosition();
    var selector = new _selector["default"]({
      source: {
        start: tokenStart(this.tokens[this.position + 1])
      },
      sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
    });
    this.current.parent.append(selector);
    this.current = selector;
    this.position++;
  };
  _proto.comment = function comment() {
    var current = this.currToken;
    this.newNode(new _comment["default"]({
      value: this.content(),
      source: getTokenSource(current),
      sourceIndex: current[_tokenize.FIELDS.START_POS]
    }));
    this.position++;
  };
  _proto.error = function error(message, opts) {
    throw this.root.error(message, opts);
  };
  _proto.missingBackslash = function missingBackslash() {
    return this.error('Expected a backslash preceding the semicolon.', {
      index: this.currToken[_tokenize.FIELDS.START_POS]
    });
  };
  _proto.missingParenthesis = function missingParenthesis() {
    return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  };
  _proto.missingSquareBracket = function missingSquareBracket() {
    return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  };
  _proto.unexpected = function unexpected() {
    return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  };
  _proto.unexpectedPipe = function unexpectedPipe() {
    return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  };
  _proto.namespace = function namespace() {
    var before = this.prevToken && this.content(this.prevToken) || true;
    if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
      this.position++;
      return this.word(before);
    } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
      this.position++;
      return this.universal(before);
    }
    this.unexpectedPipe();
  };
  _proto.nesting = function nesting() {
    if (this.nextToken) {
      var nextContent = this.content(this.nextToken);
      if (nextContent === "|") {
        this.position++;
        return;
      }
    }
    var current = this.currToken;
    this.newNode(new _nesting["default"]({
      value: this.content(),
      source: getTokenSource(current),
      sourceIndex: current[_tokenize.FIELDS.START_POS]
    }));
    this.position++;
  };
  _proto.parentheses = function parentheses() {
    var last = this.current.last;
    var unbalanced = 1;
    this.position++;
    if (last && last.type === types.PSEUDO) {
      var selector = new _selector["default"]({
        source: {
          start: tokenStart(this.tokens[this.position])
        },
        sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
      });
      var cache = this.current;
      last.append(selector);
      this.current = selector;
      while (this.position < this.tokens.length && unbalanced) {
        if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
          unbalanced++;
        }
        if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
          unbalanced--;
        }
        if (unbalanced) {
          this.parse();
        } else {
          this.current.source.end = tokenEnd(this.currToken);
          this.current.parent.source.end = tokenEnd(this.currToken);
          this.position++;
        }
      }
      this.current = cache;
    } else {
      // I think this case should be an error. It's used to implement a basic parse of media queries
      // but I don't think it's a good idea.
      var parenStart = this.currToken;
      var parenValue = "(";
      var parenEnd;
      while (this.position < this.tokens.length && unbalanced) {
        if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
          unbalanced++;
        }
        if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
          unbalanced--;
        }
        parenEnd = this.currToken;
        parenValue += this.parseParenthesisToken(this.currToken);
        this.position++;
      }
      if (last) {
        last.appendToPropertyAndEscape("value", parenValue, parenValue);
      } else {
        this.newNode(new _string["default"]({
          value: parenValue,
          source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
          sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
        }));
      }
    }
    if (unbalanced) {
      return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
    }
  };
  _proto.pseudo = function pseudo() {
    var _this4 = this;
    var pseudoStr = '';
    var startingToken = this.currToken;
    while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
      pseudoStr += this.content();
      this.position++;
    }
    if (!this.currToken) {
      return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
    }
    if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
      this.splitWord(false, function (first, length) {
        pseudoStr += first;
        _this4.newNode(new _pseudo["default"]({
          value: pseudoStr,
          source: getTokenSourceSpan(startingToken, _this4.currToken),
          sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
        }));
        if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
          _this4.error('Misplaced parenthesis.', {
            index: _this4.nextToken[_tokenize.FIELDS.START_POS]
          });
        }
      });
    } else {
      return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
    }
  };
  _proto.space = function space() {
    var content = this.content();
    // Handle space before and after the selector
    if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
      return node.type === 'comment';
    })) {
      this.spaces = this.optionalSpace(content);
      this.position++;
    } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
      this.current.last.spaces.after = this.optionalSpace(content);
      this.position++;
    } else {
      this.combinator();
    }
  };
  _proto.string = function string() {
    var current = this.currToken;
    this.newNode(new _string["default"]({
      value: this.content(),
      source: getTokenSource(current),
      sourceIndex: current[_tokenize.FIELDS.START_POS]
    }));
    this.position++;
  };
  _proto.universal = function universal(namespace) {
    var nextToken = this.nextToken;
    if (nextToken && this.content(nextToken) === '|') {
      this.position++;
      return this.namespace();
    }
    var current = this.currToken;
    this.newNode(new _universal["default"]({
      value: this.content(),
      source: getTokenSource(current),
      sourceIndex: current[_tokenize.FIELDS.START_POS]
    }), namespace);
    this.position++;
  };
  _proto.splitWord = function splitWord(namespace, firstCallback) {
    var _this5 = this;
    var nextToken = this.nextToken;
    var word = this.content();
    while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
      this.position++;
      var current = this.content();
      word += current;
      if (current.lastIndexOf('\\') === current.length - 1) {
        var next = this.nextToken;
        if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
          word += this.requiredSpace(this.content(next));
          this.position++;
        }
      }
      nextToken = this.nextToken;
    }
    var hasClass = indexesOf(word, '.').filter(function (i) {
      // Allow escaped dot within class name
      var escapedDot = word[i - 1] === '\\';
      // Allow decimal numbers percent in @keyframes
      var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
      return !escapedDot && !isKeyframesPercent;
    });
    var hasId = indexesOf(word, '#').filter(function (i) {
      return word[i - 1] !== '\\';
    });
    // Eliminate Sass interpolations from the list of id indexes
    var interpolations = indexesOf(word, '#{');
    if (interpolations.length) {
      hasId = hasId.filter(function (hashIndex) {
        return !~interpolations.indexOf(hashIndex);
      });
    }
    var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
    indices.forEach(function (ind, i) {
      var index = indices[i + 1] || word.length;
      var value = word.slice(ind, index);
      if (i === 0 && firstCallback) {
        return firstCallback.call(_this5, value, indices.length);
      }
      var node;
      var current = _this5.currToken;
      var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
      var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
      if (~hasClass.indexOf(ind)) {
        var classNameOpts = {
          value: value.slice(1),
          source: source,
          sourceIndex: sourceIndex
        };
        node = new _className["default"](unescapeProp(classNameOpts, "value"));
      } else if (~hasId.indexOf(ind)) {
        var idOpts = {
          value: value.slice(1),
          source: source,
          sourceIndex: sourceIndex
        };
        node = new _id["default"](unescapeProp(idOpts, "value"));
      } else {
        var tagOpts = {
          value: value,
          source: source,
          sourceIndex: sourceIndex
        };
        unescapeProp(tagOpts, "value");
        node = new _tag["default"](tagOpts);
      }
      _this5.newNode(node, namespace);
      // Ensure that the namespace is used only once
      namespace = null;
    });
    this.position++;
  };
  _proto.word = function word(namespace) {
    var nextToken = this.nextToken;
    if (nextToken && this.content(nextToken) === '|') {
      this.position++;
      return this.namespace();
    }
    return this.splitWord(namespace);
  };
  _proto.loop = function loop() {
    while (this.position < this.tokens.length) {
      this.parse(true);
    }
    this.current._inferEndPosition();
    return this.root;
  };
  _proto.parse = function parse(throwOnParenthesis) {
    switch (this.currToken[_tokenize.FIELDS.TYPE]) {
      case tokens.space:
        this.space();
        break;
      case tokens.comment:
        this.comment();
        break;
      case tokens.openParenthesis:
        this.parentheses();
        break;
      case tokens.closeParenthesis:
        if (throwOnParenthesis) {
          this.missingParenthesis();
        }
        break;
      case tokens.openSquare:
        this.attribute();
        break;
      case tokens.dollar:
      case tokens.caret:
      case tokens.equals:
      case tokens.word:
        this.word();
        break;
      case tokens.colon:
        this.pseudo();
        break;
      case tokens.comma:
        this.comma();
        break;
      case tokens.asterisk:
        this.universal();
        break;
      case tokens.ampersand:
        this.nesting();
        break;
      case tokens.slash:
      case tokens.combinator:
        this.combinator();
        break;
      case tokens.str:
        this.string();
        break;
      // These cases throw; no break needed.
      case tokens.closeSquare:
        this.missingSquareBracket();
      case tokens.semicolon:
        this.missingBackslash();
      default:
        this.unexpected();
    }
  }

  /**
   * Helpers
   */;
  _proto.expected = function expected(description, index, found) {
    if (Array.isArray(description)) {
      var last = description.pop();
      description = description.join(', ') + " or " + last;
    }
    var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
    if (!found) {
      return this.error("Expected " + an + " " + description + ".", {
        index: index
      });
    }
    return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
      index: index
    });
  };
  _proto.requiredSpace = function requiredSpace(space) {
    return this.options.lossy ? ' ' : space;
  };
  _proto.optionalSpace = function optionalSpace(space) {
    return this.options.lossy ? '' : space;
  };
  _proto.lossySpace = function lossySpace(space, required) {
    if (this.options.lossy) {
      return required ? ' ' : '';
    } else {
      return space;
    }
  };
  _proto.parseParenthesisToken = function parseParenthesisToken(token) {
    var content = this.content(token);
    if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
      return this.requiredSpace(content);
    } else {
      return content;
    }
  };
  _proto.newNode = function newNode(node, namespace) {
    if (namespace) {
      if (/^ +$/.test(namespace)) {
        if (!this.options.lossy) {
          this.spaces = (this.spaces || '') + namespace;
        }
        namespace = true;
      }
      node.namespace = namespace;
      unescapeProp(node, "namespace");
    }
    if (this.spaces) {
      node.spaces.before = this.spaces;
      this.spaces = '';
    }
    return this.current.append(node);
  };
  _proto.content = function content(token) {
    if (token === void 0) {
      token = this.currToken;
    }
    return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  };
  /**
   * returns the index of the next non-whitespace, non-comment token.
   * returns -1 if no meaningful token is found.
   */
  _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
    if (startPosition === void 0) {
      startPosition = this.position + 1;
    }
    var searchPosition = startPosition;
    while (searchPosition < this.tokens.length) {
      if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
        searchPosition++;
        continue;
      } else {
        return searchPosition;
      }
    }
    return -1;
  };
  _createClass(Parser, [{
    key: "currToken",
    get: function get() {
      return this.tokens[this.position];
    }
  }, {
    key: "nextToken",
    get: function get() {
      return this.tokens[this.position + 1];
    }
  }, {
    key: "prevToken",
    get: function get() {
      return this.tokens[this.position - 1];
    }
  }]);
  return Parser;
}();
exports["default"] = Parser;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _parser = _interopRequireDefault(require("./parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var Processor = /*#__PURE__*/function () {
  function Processor(func, options) {
    this.func = func || function noop() {};
    this.funcRes = null;
    this.options = options;
  }
  var _proto = Processor.prototype;
  _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
    if (options === void 0) {
      options = {};
    }
    var merged = Object.assign({}, this.options, options);
    if (merged.updateSelector === false) {
      return false;
    } else {
      return typeof rule !== "string";
    }
  };
  _proto._isLossy = function _isLossy(options) {
    if (options === void 0) {
      options = {};
    }
    var merged = Object.assign({}, this.options, options);
    if (merged.lossless === false) {
      return true;
    } else {
      return false;
    }
  };
  _proto._root = function _root(rule, options) {
    if (options === void 0) {
      options = {};
    }
    var parser = new _parser["default"](rule, this._parseOptions(options));
    return parser.root;
  };
  _proto._parseOptions = function _parseOptions(options) {
    return {
      lossy: this._isLossy(options)
    };
  };
  _proto._run = function _run(rule, options) {
    var _this = this;
    if (options === void 0) {
      options = {};
    }
    return new Promise(function (resolve, reject) {
      try {
        var root = _this._root(rule, options);
        Promise.resolve(_this.func(root)).then(function (transform) {
          var string = undefined;
          if (_this._shouldUpdateSelector(rule, options)) {
            string = root.toString();
            rule.selector = string;
          }
          return {
            transform: transform,
            root: root,
            string: string
          };
        }).then(resolve, reject);
      } catch (e) {
        reject(e);
        return;
      }
    });
  };
  _proto._runSync = function _runSync(rule, options) {
    if (options === void 0) {
      options = {};
    }
    var root = this._root(rule, options);
    var transform = this.func(root);
    if (transform && typeof transform.then === "function") {
      throw new Error("Selector processor returned a promise to a synchronous call.");
    }
    var string = undefined;
    if (options.updateSelector && typeof rule !== "string") {
      string = root.toString();
      rule.selector = string;
    }
    return {
      transform: transform,
      root: root,
      string: string
    };
  }

  /**
   * Process rule into a selector AST.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {Promise} The AST of the selector after processing it.
   */;
  _proto.ast = function ast(rule, options) {
    return this._run(rule, options).then(function (result) {
      return result.root;
    });
  }

  /**
   * Process rule into a selector AST synchronously.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {parser.Root} The AST of the selector after processing it.
   */;
  _proto.astSync = function astSync(rule, options) {
    return this._runSync(rule, options).root;
  }

  /**
   * Process a selector into a transformed value asynchronously
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {Promise} The value returned by the processor.
   */;
  _proto.transform = function transform(rule, options) {
    return this._run(rule, options).then(function (result) {
      return result.transform;
    });
  }

  /**
   * Process a selector into a transformed value synchronously.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {any} The value returned by the processor.
   */;
  _proto.transformSync = function transformSync(rule, options) {
    return this._runSync(rule, options).transform;
  }

  /**
   * Process a selector into a new selector string asynchronously.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {string} the selector after processing.
   */;
  _proto.process = function process(rule, options) {
    return this._run(rule, options).then(function (result) {
      return result.string || result.root.toString();
    });
  }

  /**
   * Process a selector into a new selector string synchronously.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {string} the selector after processing.
   */;
  _proto.processSync = function processSync(rule, options) {
    var result = this._runSync(rule, options);
    return result.string || result.root.toString();
  };
  return Processor;
}();
exports["default"] = Processor;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
exports.unescapeValue = unescapeValue;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _unesc = _interopRequireDefault(require("../util/unesc"));
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
var _CSSESC_QUOTE_OPTIONS;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var deprecate = require("util-deprecate");
var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
function unescapeValue(value) {
  var deprecatedUsage = false;
  var quoteMark = null;
  var unescaped = value;
  var m = unescaped.match(WRAPPED_IN_QUOTES);
  if (m) {
    quoteMark = m[1];
    unescaped = m[2];
  }
  unescaped = (0, _unesc["default"])(unescaped);
  if (unescaped !== value) {
    deprecatedUsage = true;
  }
  return {
    deprecatedUsage: deprecatedUsage,
    unescaped: unescaped,
    quoteMark: quoteMark
  };
}
function handleDeprecatedContructorOpts(opts) {
  if (opts.quoteMark !== undefined) {
    return opts;
  }
  if (opts.value === undefined) {
    return opts;
  }
  warnOfDeprecatedConstructor();
  var _unescapeValue = unescapeValue(opts.value),
    quoteMark = _unescapeValue.quoteMark,
    unescaped = _unescapeValue.unescaped;
  if (!opts.raws) {
    opts.raws = {};
  }
  if (opts.raws.value === undefined) {
    opts.raws.value = opts.value;
  }
  opts.value = unescaped;
  opts.quoteMark = quoteMark;
  return opts;
}
var Attribute = /*#__PURE__*/function (_Namespace) {
  _inheritsLoose(Attribute, _Namespace);
  function Attribute(opts) {
    var _this;
    if (opts === void 0) {
      opts = {};
    }
    _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
    _this.type = _types.ATTRIBUTE;
    _this.raws = _this.raws || {};
    Object.defineProperty(_this.raws, 'unquoted', {
      get: deprecate(function () {
        return _this.value;
      }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
      set: deprecate(function () {
        return _this.value;
      }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
    });
    _this._constructed = true;
    return _this;
  }

  /**
   * Returns the Attribute's value quoted such that it would be legal to use
   * in the value of a css file. The original value's quotation setting
   * used for stringification is left unchanged. See `setValue(value, options)`
   * if you want to control the quote settings of a new value for the attribute.
   *
   * You can also change the quotation used for the current value by setting quoteMark.
   *
   * Options:
   *   * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
   *     option is not set, the original value for quoteMark will be used. If
   *     indeterminate, a double quote is used. The legal values are:
   *     * `null` - the value will be unquoted and characters will be escaped as necessary.
   *     * `'` - the value will be quoted with a single quote and single quotes are escaped.
   *     * `"` - the value will be quoted with a double quote and double quotes are escaped.
   *   * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
   *     over the quoteMark option value.
   *   * smart {boolean} - if true, will select a quote mark based on the value
   *     and the other options specified here. See the `smartQuoteMark()`
   *     method.
   **/
  var _proto = Attribute.prototype;
  _proto.getQuotedValue = function getQuotedValue(options) {
    if (options === void 0) {
      options = {};
    }
    var quoteMark = this._determineQuoteMark(options);
    var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
    var escaped = (0, _cssesc["default"])(this._value, cssescopts);
    return escaped;
  };
  _proto._determineQuoteMark = function _determineQuoteMark(options) {
    return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  }

  /**
   * Set the unescaped value with the specified quotation options. The value
   * provided must not include any wrapping quote marks -- those quotes will
   * be interpreted as part of the value and escaped accordingly.
   */;
  _proto.setValue = function setValue(value, options) {
    if (options === void 0) {
      options = {};
    }
    this._value = value;
    this._quoteMark = this._determineQuoteMark(options);
    this._syncRawValue();
  }

  /**
   * Intelligently select a quoteMark value based on the value's contents. If
   * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
   * mark will be picked that minimizes the number of escapes.
   *
   * If there's no clear winner, the quote mark from these options is used,
   * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
   * true). If the quoteMark is unspecified, a double quote is used.
   *
   * @param options This takes the quoteMark and preferCurrentQuoteMark options
   * from the quoteValue method.
   */;
  _proto.smartQuoteMark = function smartQuoteMark(options) {
    var v = this.value;
    var numSingleQuotes = v.replace(/[^']/g, '').length;
    var numDoubleQuotes = v.replace(/[^"]/g, '').length;
    if (numSingleQuotes + numDoubleQuotes === 0) {
      var escaped = (0, _cssesc["default"])(v, {
        isIdentifier: true
      });
      if (escaped === v) {
        return Attribute.NO_QUOTE;
      } else {
        var pref = this.preferredQuoteMark(options);
        if (pref === Attribute.NO_QUOTE) {
          // pick a quote mark that isn't none and see if it's smaller
          var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
          var opts = CSSESC_QUOTE_OPTIONS[quote];
          var quoteValue = (0, _cssesc["default"])(v, opts);
          if (quoteValue.length < escaped.length) {
            return quote;
          }
        }
        return pref;
      }
    } else if (numDoubleQuotes === numSingleQuotes) {
      return this.preferredQuoteMark(options);
    } else if (numDoubleQuotes < numSingleQuotes) {
      return Attribute.DOUBLE_QUOTE;
    } else {
      return Attribute.SINGLE_QUOTE;
    }
  }

  /**
   * Selects the preferred quote mark based on the options and the current quote mark value.
   * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
   * instead.
   */;
  _proto.preferredQuoteMark = function preferredQuoteMark(options) {
    var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
    if (quoteMark === undefined) {
      quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
    }
    if (quoteMark === undefined) {
      quoteMark = Attribute.DOUBLE_QUOTE;
    }
    return quoteMark;
  };
  _proto._syncRawValue = function _syncRawValue() {
    var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
    if (rawValue === this._value) {
      if (this.raws) {
        delete this.raws.value;
      }
    } else {
      this.raws.value = rawValue;
    }
  };
  _proto._handleEscapes = function _handleEscapes(prop, value) {
    if (this._constructed) {
      var escaped = (0, _cssesc["default"])(value, {
        isIdentifier: true
      });
      if (escaped !== value) {
        this.raws[prop] = escaped;
      } else {
        delete this.raws[prop];
      }
    }
  };
  _proto._spacesFor = function _spacesFor(name) {
    var attrSpaces = {
      before: '',
      after: ''
    };
    var spaces = this.spaces[name] || {};
    var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
    return Object.assign(attrSpaces, spaces, rawSpaces);
  };
  _proto._stringFor = function _stringFor(name, spaceName, concat) {
    if (spaceName === void 0) {
      spaceName = name;
    }
    if (concat === void 0) {
      concat = defaultAttrConcat;
    }
    var attrSpaces = this._spacesFor(spaceName);
    return concat(this.stringifyProperty(name), attrSpaces);
  }

  /**
   * returns the offset of the attribute part specified relative to the
   * start of the node of the output string.
   *
   * * "ns" - alias for "namespace"
   * * "namespace" - the namespace if it exists.
   * * "attribute" - the attribute name
   * * "attributeNS" - the start of the attribute or its namespace
   * * "operator" - the match operator of the attribute
   * * "value" - The value (string or identifier)
   * * "insensitive" - the case insensitivity flag;
   * @param part One of the possible values inside an attribute.
   * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
   */;
  _proto.offsetOf = function offsetOf(name) {
    var count = 1;
    var attributeSpaces = this._spacesFor("attribute");
    count += attributeSpaces.before.length;
    if (name === "namespace" || name === "ns") {
      return this.namespace ? count : -1;
    }
    if (name === "attributeNS") {
      return count;
    }
    count += this.namespaceString.length;
    if (this.namespace) {
      count += 1;
    }
    if (name === "attribute") {
      return count;
    }
    count += this.stringifyProperty("attribute").length;
    count += attributeSpaces.after.length;
    var operatorSpaces = this._spacesFor("operator");
    count += operatorSpaces.before.length;
    var operator = this.stringifyProperty("operator");
    if (name === "operator") {
      return operator ? count : -1;
    }
    count += operator.length;
    count += operatorSpaces.after.length;
    var valueSpaces = this._spacesFor("value");
    count += valueSpaces.before.length;
    var value = this.stringifyProperty("value");
    if (name === "value") {
      return value ? count : -1;
    }
    count += value.length;
    count += valueSpaces.after.length;
    var insensitiveSpaces = this._spacesFor("insensitive");
    count += insensitiveSpaces.before.length;
    if (name === "insensitive") {
      return this.insensitive ? count : -1;
    }
    return -1;
  };
  _proto.toString = function toString() {
    var _this2 = this;
    var selector = [this.rawSpaceBefore, '['];
    selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
    if (this.operator && (this.value || this.value === '')) {
      selector.push(this._stringFor('operator'));
      selector.push(this._stringFor('value'));
      selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
        if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
          attrSpaces.before = " ";
        }
        return defaultAttrConcat(attrValue, attrSpaces);
      }));
    }
    selector.push(']');
    selector.push(this.rawSpaceAfter);
    return selector.join('');
  };
  _createClass(Attribute, [{
    key: "quoted",
    get: function get() {
      var qm = this.quoteMark;
      return qm === "'" || qm === '"';
    },
    set: function set(value) {
      warnOfDeprecatedQuotedAssignment();
    }

    /**
     * returns a single (`'`) or double (`"`) quote character if the value is quoted.
     * returns `null` if the value is not quoted.
     * returns `undefined` if the quotation state is unknown (this can happen when
     * the attribute is constructed without specifying a quote mark.)
     */
  }, {
    key: "quoteMark",
    get: function get() {
      return this._quoteMark;
    }

    /**
     * Set the quote mark to be used by this attribute's value.
     * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
     * value is updated accordingly.
     *
     * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
     */,
    set: function set(quoteMark) {
      if (!this._constructed) {
        this._quoteMark = quoteMark;
        return;
      }
      if (this._quoteMark !== quoteMark) {
        this._quoteMark = quoteMark;
        this._syncRawValue();
      }
    }
  }, {
    key: "qualifiedAttribute",
    get: function get() {
      return this.qualifiedName(this.raws.attribute || this.attribute);
    }
  }, {
    key: "insensitiveFlag",
    get: function get() {
      return this.insensitive ? 'i' : '';
    }
  }, {
    key: "value",
    get: function get() {
      return this._value;
    },
    set:
    /**
     * Before 3.0, the value had to be set to an escaped value including any wrapped
     * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
     * is unescaped during parsing and any quote marks are removed.
     *
     * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
     * a deprecation warning is raised when the new value contains any characters that would
     * require escaping (including if it contains wrapped quotes).
     *
     * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
     * how the new value is quoted.
     */
    function set(v) {
      if (this._constructed) {
        var _unescapeValue2 = unescapeValue(v),
          deprecatedUsage = _unescapeValue2.deprecatedUsage,
          unescaped = _unescapeValue2.unescaped,
          quoteMark = _unescapeValue2.quoteMark;
        if (deprecatedUsage) {
          warnOfDeprecatedValueAssignment();
        }
        if (unescaped === this._value && quoteMark === this._quoteMark) {
          return;
        }
        this._value = unescaped;
        this._quoteMark = quoteMark;
        this._syncRawValue();
      } else {
        this._value = v;
      }
    }
  }, {
    key: "insensitive",
    get: function get() {
      return this._insensitive;
    }

    /**
     * Set the case insensitive flag.
     * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
     * of the attribute is updated accordingly.
     *
     * @param {true | false} insensitive true if the attribute should match case-insensitively.
     */,
    set: function set(insensitive) {
      if (!insensitive) {
        this._insensitive = false;

        // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
        // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
        if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
          this.raws.insensitiveFlag = undefined;
        }
      }
      this._insensitive = insensitive;
    }
  }, {
    key: "attribute",
    get: function get() {
      return this._attribute;
    },
    set: function set(name) {
      this._handleEscapes("attribute", name);
      this._attribute = name;
    }
  }]);
  return Attribute;
}(_namespace["default"]);
exports["default"] = Attribute;
Attribute.NO_QUOTE = null;
Attribute.SINGLE_QUOTE = "'";
Attribute.DOUBLE_QUOTE = '"';
var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  "'": {
    quotes: 'single',
    wrap: true
  },
  '"': {
    quotes: 'double',
    wrap: true
  }
}, _CSSESC_QUOTE_OPTIONS[null] = {
  isIdentifier: true
}, _CSSESC_QUOTE_OPTIONS);
function defaultAttrConcat(attrValue, attrSpaces) {
  return "" + attrSpaces.before + attrValue + attrSpaces.after;
}"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _util = require("../util");
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var ClassName = /*#__PURE__*/function (_Node) {
  _inheritsLoose(ClassName, _Node);
  function ClassName(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.CLASS;
    _this._constructed = true;
    return _this;
  }
  var _proto = ClassName.prototype;
  _proto.valueToString = function valueToString() {
    return '.' + _Node.prototype.valueToString.call(this);
  };
  _createClass(ClassName, [{
    key: "value",
    get: function get() {
      return this._value;
    },
    set: function set(v) {
      if (this._constructed) {
        var escaped = (0, _cssesc["default"])(v, {
          isIdentifier: true
        });
        if (escaped !== v) {
          (0, _util.ensureObject)(this, "raws");
          this.raws.value = escaped;
        } else if (this.raws) {
          delete this.raws.value;
        }
      }
      this._value = v;
    }
  }]);
  return ClassName;
}(_node["default"]);
exports["default"] = ClassName;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Combinator = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Combinator, _Node);
  function Combinator(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.COMBINATOR;
    return _this;
  }
  return Combinator;
}(_node["default"]);
exports["default"] = Combinator;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Comment = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Comment, _Node);
  function Comment(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.COMMENT;
    return _this;
  }
  return Comment;
}(_node["default"]);
exports["default"] = Comment;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0;
var _attribute = _interopRequireDefault(require("./attribute"));
var _className = _interopRequireDefault(require("./className"));
var _combinator = _interopRequireDefault(require("./combinator"));
var _comment = _interopRequireDefault(require("./comment"));
var _id = _interopRequireDefault(require("./id"));
var _nesting = _interopRequireDefault(require("./nesting"));
var _pseudo = _interopRequireDefault(require("./pseudo"));
var _root = _interopRequireDefault(require("./root"));
var _selector = _interopRequireDefault(require("./selector"));
var _string = _interopRequireDefault(require("./string"));
var _tag = _interopRequireDefault(require("./tag"));
var _universal = _interopRequireDefault(require("./universal"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var attribute = function attribute(opts) {
  return new _attribute["default"](opts);
};
exports.attribute = attribute;
var className = function className(opts) {
  return new _className["default"](opts);
};
exports.className = className;
var combinator = function combinator(opts) {
  return new _combinator["default"](opts);
};
exports.combinator = combinator;
var comment = function comment(opts) {
  return new _comment["default"](opts);
};
exports.comment = comment;
var id = function id(opts) {
  return new _id["default"](opts);
};
exports.id = id;
var nesting = function nesting(opts) {
  return new _nesting["default"](opts);
};
exports.nesting = nesting;
var pseudo = function pseudo(opts) {
  return new _pseudo["default"](opts);
};
exports.pseudo = pseudo;
var root = function root(opts) {
  return new _root["default"](opts);
};
exports.root = root;
var selector = function selector(opts) {
  return new _selector["default"](opts);
};
exports.selector = selector;
var string = function string(opts) {
  return new _string["default"](opts);
};
exports.string = string;
var tag = function tag(opts) {
  return new _tag["default"](opts);
};
exports.tag = tag;
var universal = function universal(opts) {
  return new _universal["default"](opts);
};
exports.universal = universal;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var types = _interopRequireWildcard(require("./types"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Container = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Container, _Node);
  function Container(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    if (!_this.nodes) {
      _this.nodes = [];
    }
    return _this;
  }
  var _proto = Container.prototype;
  _proto.append = function append(selector) {
    selector.parent = this;
    this.nodes.push(selector);
    return this;
  };
  _proto.prepend = function prepend(selector) {
    selector.parent = this;
    this.nodes.unshift(selector);
    return this;
  };
  _proto.at = function at(index) {
    return this.nodes[index];
  };
  _proto.index = function index(child) {
    if (typeof child === 'number') {
      return child;
    }
    return this.nodes.indexOf(child);
  };
  _proto.removeChild = function removeChild(child) {
    child = this.index(child);
    this.at(child).parent = undefined;
    this.nodes.splice(child, 1);
    var index;
    for (var id in this.indexes) {
      index = this.indexes[id];
      if (index >= child) {
        this.indexes[id] = index - 1;
      }
    }
    return this;
  };
  _proto.removeAll = function removeAll() {
    for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
      var node = _step.value;
      node.parent = undefined;
    }
    this.nodes = [];
    return this;
  };
  _proto.empty = function empty() {
    return this.removeAll();
  };
  _proto.insertAfter = function insertAfter(oldNode, newNode) {
    newNode.parent = this;
    var oldIndex = this.index(oldNode);
    this.nodes.splice(oldIndex + 1, 0, newNode);
    newNode.parent = this;
    var index;
    for (var id in this.indexes) {
      index = this.indexes[id];
      if (oldIndex <= index) {
        this.indexes[id] = index + 1;
      }
    }
    return this;
  };
  _proto.insertBefore = function insertBefore(oldNode, newNode) {
    newNode.parent = this;
    var oldIndex = this.index(oldNode);
    this.nodes.splice(oldIndex, 0, newNode);
    newNode.parent = this;
    var index;
    for (var id in this.indexes) {
      index = this.indexes[id];
      if (index <= oldIndex) {
        this.indexes[id] = index + 1;
      }
    }
    return this;
  };
  _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
    var found = undefined;
    this.each(function (node) {
      if (node.atPosition) {
        var foundChild = node.atPosition(line, col);
        if (foundChild) {
          found = foundChild;
          return false;
        }
      } else if (node.isAtPosition(line, col)) {
        found = node;
        return false;
      }
    });
    return found;
  }

  /**
   * Return the most specific node at the line and column number given.
   * The source location is based on the original parsed location, locations aren't
   * updated as selector nodes are mutated.
   * 
   * Note that this location is relative to the location of the first character
   * of the selector, and not the location of the selector in the overall document
   * when used in conjunction with postcss.
   *
   * If not found, returns undefined.
   * @param {number} line The line number of the node to find. (1-based index)
   * @param {number} col  The column number of the node to find. (1-based index)
   */;
  _proto.atPosition = function atPosition(line, col) {
    if (this.isAtPosition(line, col)) {
      return this._findChildAtPosition(line, col) || this;
    } else {
      return undefined;
    }
  };
  _proto._inferEndPosition = function _inferEndPosition() {
    if (this.last && this.last.source && this.last.source.end) {
      this.source = this.source || {};
      this.source.end = this.source.end || {};
      Object.assign(this.source.end, this.last.source.end);
    }
  };
  _proto.each = function each(callback) {
    if (!this.lastEach) {
      this.lastEach = 0;
    }
    if (!this.indexes) {
      this.indexes = {};
    }
    this.lastEach++;
    var id = this.lastEach;
    this.indexes[id] = 0;
    if (!this.length) {
      return undefined;
    }
    var index, result;
    while (this.indexes[id] < this.length) {
      index = this.indexes[id];
      result = callback(this.at(index), index);
      if (result === false) {
        break;
      }
      this.indexes[id] += 1;
    }
    delete this.indexes[id];
    if (result === false) {
      return false;
    }
  };
  _proto.walk = function walk(callback) {
    return this.each(function (node, i) {
      var result = callback(node, i);
      if (result !== false && node.length) {
        result = node.walk(callback);
      }
      if (result === false) {
        return false;
      }
    });
  };
  _proto.walkAttributes = function walkAttributes(callback) {
    var _this2 = this;
    return this.walk(function (selector) {
      if (selector.type === types.ATTRIBUTE) {
        return callback.call(_this2, selector);
      }
    });
  };
  _proto.walkClasses = function walkClasses(callback) {
    var _this3 = this;
    return this.walk(function (selector) {
      if (selector.type === types.CLASS) {
        return callback.call(_this3, selector);
      }
    });
  };
  _proto.walkCombinators = function walkCombinators(callback) {
    var _this4 = this;
    return this.walk(function (selector) {
      if (selector.type === types.COMBINATOR) {
        return callback.call(_this4, selector);
      }
    });
  };
  _proto.walkComments = function walkComments(callback) {
    var _this5 = this;
    return this.walk(function (selector) {
      if (selector.type === types.COMMENT) {
        return callback.call(_this5, selector);
      }
    });
  };
  _proto.walkIds = function walkIds(callback) {
    var _this6 = this;
    return this.walk(function (selector) {
      if (selector.type === types.ID) {
        return callback.call(_this6, selector);
      }
    });
  };
  _proto.walkNesting = function walkNesting(callback) {
    var _this7 = this;
    return this.walk(function (selector) {
      if (selector.type === types.NESTING) {
        return callback.call(_this7, selector);
      }
    });
  };
  _proto.walkPseudos = function walkPseudos(callback) {
    var _this8 = this;
    return this.walk(function (selector) {
      if (selector.type === types.PSEUDO) {
        return callback.call(_this8, selector);
      }
    });
  };
  _proto.walkTags = function walkTags(callback) {
    var _this9 = this;
    return this.walk(function (selector) {
      if (selector.type === types.TAG) {
        return callback.call(_this9, selector);
      }
    });
  };
  _proto.walkUniversals = function walkUniversals(callback) {
    var _this10 = this;
    return this.walk(function (selector) {
      if (selector.type === types.UNIVERSAL) {
        return callback.call(_this10, selector);
      }
    });
  };
  _proto.split = function split(callback) {
    var _this11 = this;
    var current = [];
    return this.reduce(function (memo, node, index) {
      var split = callback.call(_this11, node);
      current.push(node);
      if (split) {
        memo.push(current);
        current = [];
      } else if (index === _this11.length - 1) {
        memo.push(current);
      }
      return memo;
    }, []);
  };
  _proto.map = function map(callback) {
    return this.nodes.map(callback);
  };
  _proto.reduce = function reduce(callback, memo) {
    return this.nodes.reduce(callback, memo);
  };
  _proto.every = function every(callback) {
    return this.nodes.every(callback);
  };
  _proto.some = function some(callback) {
    return this.nodes.some(callback);
  };
  _proto.filter = function filter(callback) {
    return this.nodes.filter(callback);
  };
  _proto.sort = function sort(callback) {
    return this.nodes.sort(callback);
  };
  _proto.toString = function toString() {
    return this.map(String).join('');
  };
  _createClass(Container, [{
    key: "first",
    get: function get() {
      return this.at(0);
    }
  }, {
    key: "last",
    get: function get() {
      return this.at(this.length - 1);
    }
  }, {
    key: "length",
    get: function get() {
      return this.nodes.length;
    }
  }]);
  return Container;
}(_node["default"]);
exports["default"] = Container;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
exports.isContainer = isContainer;
exports.isIdentifier = void 0;
exports.isNamespace = isNamespace;
exports.isNesting = void 0;
exports.isNode = isNode;
exports.isPseudo = void 0;
exports.isPseudoClass = isPseudoClass;
exports.isPseudoElement = isPseudoElement;
exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = void 0;
var _types = require("./types");
var _IS_TYPE;
var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
function isNode(node) {
  return typeof node === "object" && IS_TYPE[node.type];
}
function isNodeType(type, node) {
  return isNode(node) && node.type === type;
}
var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
exports.isAttribute = isAttribute;
var isClassName = isNodeType.bind(null, _types.CLASS);
exports.isClassName = isClassName;
var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
exports.isCombinator = isCombinator;
var isComment = isNodeType.bind(null, _types.COMMENT);
exports.isComment = isComment;
var isIdentifier = isNodeType.bind(null, _types.ID);
exports.isIdentifier = isIdentifier;
var isNesting = isNodeType.bind(null, _types.NESTING);
exports.isNesting = isNesting;
var isPseudo = isNodeType.bind(null, _types.PSEUDO);
exports.isPseudo = isPseudo;
var isRoot = isNodeType.bind(null, _types.ROOT);
exports.isRoot = isRoot;
var isSelector = isNodeType.bind(null, _types.SELECTOR);
exports.isSelector = isSelector;
var isString = isNodeType.bind(null, _types.STRING);
exports.isString = isString;
var isTag = isNodeType.bind(null, _types.TAG);
exports.isTag = isTag;
var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
exports.isUniversal = isUniversal;
function isPseudoElement(node) {
  return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line");
}
function isPseudoClass(node) {
  return isPseudo(node) && !isPseudoElement(node);
}
function isContainer(node) {
  return !!(isNode(node) && node.walk);
}
function isNamespace(node) {
  return isAttribute(node) || isTag(node);
}"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var ID = /*#__PURE__*/function (_Node) {
  _inheritsLoose(ID, _Node);
  function ID(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.ID;
    return _this;
  }
  var _proto = ID.prototype;
  _proto.valueToString = function valueToString() {
    return '#' + _Node.prototype.valueToString.call(this);
  };
  return ID;
}(_node["default"]);
exports["default"] = ID;
module.exports = exports.default;"use strict";

exports.__esModule = true;
var _types = require("./types");
Object.keys(_types).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _types[key]) return;
  exports[key] = _types[key];
});
var _constructors = require("./constructors");
Object.keys(_constructors).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _constructors[key]) return;
  exports[key] = _constructors[key];
});
var _guards = require("./guards");
Object.keys(_guards).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _guards[key]) return;
  exports[key] = _guards[key];
});"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _util = require("../util");
var _node = _interopRequireDefault(require("./node"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Namespace = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Namespace, _Node);
  function Namespace() {
    return _Node.apply(this, arguments) || this;
  }
  var _proto = Namespace.prototype;
  _proto.qualifiedName = function qualifiedName(value) {
    if (this.namespace) {
      return this.namespaceString + "|" + value;
    } else {
      return value;
    }
  };
  _proto.valueToString = function valueToString() {
    return this.qualifiedName(_Node.prototype.valueToString.call(this));
  };
  _createClass(Namespace, [{
    key: "namespace",
    get: function get() {
      return this._namespace;
    },
    set: function set(namespace) {
      if (namespace === true || namespace === "*" || namespace === "&") {
        this._namespace = namespace;
        if (this.raws) {
          delete this.raws.namespace;
        }
        return;
      }
      var escaped = (0, _cssesc["default"])(namespace, {
        isIdentifier: true
      });
      this._namespace = namespace;
      if (escaped !== namespace) {
        (0, _util.ensureObject)(this, "raws");
        this.raws.namespace = escaped;
      } else if (this.raws) {
        delete this.raws.namespace;
      }
    }
  }, {
    key: "ns",
    get: function get() {
      return this._namespace;
    },
    set: function set(namespace) {
      this.namespace = namespace;
    }
  }, {
    key: "namespaceString",
    get: function get() {
      if (this.namespace) {
        var ns = this.stringifyProperty("namespace");
        if (ns === true) {
          return '';
        } else {
          return ns;
        }
      } else {
        return '';
      }
    }
  }]);
  return Namespace;
}(_node["default"]);
exports["default"] = Namespace;
;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Nesting = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Nesting, _Node);
  function Nesting(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.NESTING;
    _this.value = '&';
    return _this;
  }
  return Nesting;
}(_node["default"]);
exports["default"] = Nesting;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _util = require("../util");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
var cloneNode = function cloneNode(obj, parent) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }
  var cloned = new obj.constructor();
  for (var i in obj) {
    if (!obj.hasOwnProperty(i)) {
      continue;
    }
    var value = obj[i];
    var type = typeof value;
    if (i === 'parent' && type === 'object') {
      if (parent) {
        cloned[i] = parent;
      }
    } else if (value instanceof Array) {
      cloned[i] = value.map(function (j) {
        return cloneNode(j, cloned);
      });
    } else {
      cloned[i] = cloneNode(value, cloned);
    }
  }
  return cloned;
};
var Node = /*#__PURE__*/function () {
  function Node(opts) {
    if (opts === void 0) {
      opts = {};
    }
    Object.assign(this, opts);
    this.spaces = this.spaces || {};
    this.spaces.before = this.spaces.before || '';
    this.spaces.after = this.spaces.after || '';
  }
  var _proto = Node.prototype;
  _proto.remove = function remove() {
    if (this.parent) {
      this.parent.removeChild(this);
    }
    this.parent = undefined;
    return this;
  };
  _proto.replaceWith = function replaceWith() {
    if (this.parent) {
      for (var index in arguments) {
        this.parent.insertBefore(this, arguments[index]);
      }
      this.remove();
    }
    return this;
  };
  _proto.next = function next() {
    return this.parent.at(this.parent.index(this) + 1);
  };
  _proto.prev = function prev() {
    return this.parent.at(this.parent.index(this) - 1);
  };
  _proto.clone = function clone(overrides) {
    if (overrides === void 0) {
      overrides = {};
    }
    var cloned = cloneNode(this);
    for (var name in overrides) {
      cloned[name] = overrides[name];
    }
    return cloned;
  }

  /**
   * Some non-standard syntax doesn't follow normal escaping rules for css.
   * This allows non standard syntax to be appended to an existing property
   * by specifying the escaped value. By specifying the escaped value,
   * illegal characters are allowed to be directly inserted into css output.
   * @param {string} name the property to set
   * @param {any} value the unescaped value of the property
   * @param {string} valueEscaped optional. the escaped value of the property.
   */;
  _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
    if (!this.raws) {
      this.raws = {};
    }
    var originalValue = this[name];
    var originalEscaped = this.raws[name];
    this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
    if (originalEscaped || valueEscaped !== value) {
      this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
    } else {
      delete this.raws[name]; // delete any escaped value that was created by the setter.
    }
  }

  /**
   * Some non-standard syntax doesn't follow normal escaping rules for css.
   * This allows the escaped value to be specified directly, allowing illegal
   * characters to be directly inserted into css output.
   * @param {string} name the property to set
   * @param {any} value the unescaped value of the property
   * @param {string} valueEscaped the escaped value of the property.
   */;
  _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
    if (!this.raws) {
      this.raws = {};
    }
    this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
    this.raws[name] = valueEscaped;
  }

  /**
   * When you want a value to passed through to CSS directly. This method
   * deletes the corresponding raw value causing the stringifier to fallback
   * to the unescaped value.
   * @param {string} name the property to set.
   * @param {any} value The value that is both escaped and unescaped.
   */;
  _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
    this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
    if (this.raws) {
      delete this.raws[name];
    }
  }

  /**
   *
   * @param {number} line The number (starting with 1)
   * @param {number} column The column number (starting with 1)
   */;
  _proto.isAtPosition = function isAtPosition(line, column) {
    if (this.source && this.source.start && this.source.end) {
      if (this.source.start.line > line) {
        return false;
      }
      if (this.source.end.line < line) {
        return false;
      }
      if (this.source.start.line === line && this.source.start.column > column) {
        return false;
      }
      if (this.source.end.line === line && this.source.end.column < column) {
        return false;
      }
      return true;
    }
    return undefined;
  };
  _proto.stringifyProperty = function stringifyProperty(name) {
    return this.raws && this.raws[name] || this[name];
  };
  _proto.valueToString = function valueToString() {
    return String(this.stringifyProperty("value"));
  };
  _proto.toString = function toString() {
    return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  };
  _createClass(Node, [{
    key: "rawSpaceBefore",
    get: function get() {
      var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
      if (rawSpace === undefined) {
        rawSpace = this.spaces && this.spaces.before;
      }
      return rawSpace || "";
    },
    set: function set(raw) {
      (0, _util.ensureObject)(this, "raws", "spaces");
      this.raws.spaces.before = raw;
    }
  }, {
    key: "rawSpaceAfter",
    get: function get() {
      var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
      if (rawSpace === undefined) {
        rawSpace = this.spaces.after;
      }
      return rawSpace || "";
    },
    set: function set(raw) {
      (0, _util.ensureObject)(this, "raws", "spaces");
      this.raws.spaces.after = raw;
    }
  }]);
  return Node;
}();
exports["default"] = Node;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Pseudo = /*#__PURE__*/function (_Container) {
  _inheritsLoose(Pseudo, _Container);
  function Pseudo(opts) {
    var _this;
    _this = _Container.call(this, opts) || this;
    _this.type = _types.PSEUDO;
    return _this;
  }
  var _proto = Pseudo.prototype;
  _proto.toString = function toString() {
    var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
    return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  };
  return Pseudo;
}(_container["default"]);
exports["default"] = Pseudo;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Root = /*#__PURE__*/function (_Container) {
  _inheritsLoose(Root, _Container);
  function Root(opts) {
    var _this;
    _this = _Container.call(this, opts) || this;
    _this.type = _types.ROOT;
    return _this;
  }
  var _proto = Root.prototype;
  _proto.toString = function toString() {
    var str = this.reduce(function (memo, selector) {
      memo.push(String(selector));
      return memo;
    }, []).join(',');
    return this.trailingComma ? str + ',' : str;
  };
  _proto.error = function error(message, options) {
    if (this._error) {
      return this._error(message, options);
    } else {
      return new Error(message);
    }
  };
  _createClass(Root, [{
    key: "errorGenerator",
    set: function set(handler) {
      this._error = handler;
    }
  }]);
  return Root;
}(_container["default"]);
exports["default"] = Root;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Selector = /*#__PURE__*/function (_Container) {
  _inheritsLoose(Selector, _Container);
  function Selector(opts) {
    var _this;
    _this = _Container.call(this, opts) || this;
    _this.type = _types.SELECTOR;
    return _this;
  }
  return Selector;
}(_container["default"]);
exports["default"] = Selector;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var String = /*#__PURE__*/function (_Node) {
  _inheritsLoose(String, _Node);
  function String(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.STRING;
    return _this;
  }
  return String;
}(_node["default"]);
exports["default"] = String;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Tag = /*#__PURE__*/function (_Namespace) {
  _inheritsLoose(Tag, _Namespace);
  function Tag(opts) {
    var _this;
    _this = _Namespace.call(this, opts) || this;
    _this.type = _types.TAG;
    return _this;
  }
  return Tag;
}(_namespace["default"]);
exports["default"] = Tag;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports.UNIVERSAL = exports.TAG = exports.STRING = exports.SELECTOR = exports.ROOT = exports.PSEUDO = exports.NESTING = exports.ID = exports.COMMENT = exports.COMBINATOR = exports.CLASS = exports.ATTRIBUTE = void 0;
var TAG = 'tag';
exports.TAG = TAG;
var STRING = 'string';
exports.STRING = STRING;
var SELECTOR = 'selector';
exports.SELECTOR = SELECTOR;
var ROOT = 'root';
exports.ROOT = ROOT;
var PSEUDO = 'pseudo';
exports.PSEUDO = PSEUDO;
var NESTING = 'nesting';
exports.NESTING = NESTING;
var ID = 'id';
exports.ID = ID;
var COMMENT = 'comment';
exports.COMMENT = COMMENT;
var COMBINATOR = 'combinator';
exports.COMBINATOR = COMBINATOR;
var CLASS = 'class';
exports.CLASS = CLASS;
var ATTRIBUTE = 'attribute';
exports.ATTRIBUTE = ATTRIBUTE;
var UNIVERSAL = 'universal';
exports.UNIVERSAL = UNIVERSAL;"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Universal = /*#__PURE__*/function (_Namespace) {
  _inheritsLoose(Universal, _Namespace);
  function Universal(opts) {
    var _this;
    _this = _Namespace.call(this, opts) || this;
    _this.type = _types.UNIVERSAL;
    _this.value = '*';
    return _this;
  }
  return Universal;
}(_namespace["default"]);
exports["default"] = Universal;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = sortAscending;
function sortAscending(list) {
  return list.sort(function (a, b) {
    return a - b;
  });
}
;
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports.word = exports.tilde = exports.tab = exports.str = exports.space = exports.slash = exports.singleQuote = exports.semicolon = exports.plus = exports.pipe = exports.openSquare = exports.openParenthesis = exports.newline = exports.greaterThan = exports.feed = exports.equals = exports.doubleQuote = exports.dollar = exports.cr = exports.comment = exports.comma = exports.combinator = exports.colon = exports.closeSquare = exports.closeParenthesis = exports.caret = exports.bang = exports.backslash = exports.at = exports.asterisk = exports.ampersand = void 0;
var ampersand = 38; // `&`.charCodeAt(0);
exports.ampersand = ampersand;
var asterisk = 42; // `*`.charCodeAt(0);
exports.asterisk = asterisk;
var at = 64; // `@`.charCodeAt(0);
exports.at = at;
var comma = 44; // `,`.charCodeAt(0);
exports.comma = comma;
var colon = 58; // `:`.charCodeAt(0);
exports.colon = colon;
var semicolon = 59; // `;`.charCodeAt(0);
exports.semicolon = semicolon;
var openParenthesis = 40; // `(`.charCodeAt(0);
exports.openParenthesis = openParenthesis;
var closeParenthesis = 41; // `)`.charCodeAt(0);
exports.closeParenthesis = closeParenthesis;
var openSquare = 91; // `[`.charCodeAt(0);
exports.openSquare = openSquare;
var closeSquare = 93; // `]`.charCodeAt(0);
exports.closeSquare = closeSquare;
var dollar = 36; // `$`.charCodeAt(0);
exports.dollar = dollar;
var tilde = 126; // `~`.charCodeAt(0);
exports.tilde = tilde;
var caret = 94; // `^`.charCodeAt(0);
exports.caret = caret;
var plus = 43; // `+`.charCodeAt(0);
exports.plus = plus;
var equals = 61; // `=`.charCodeAt(0);
exports.equals = equals;
var pipe = 124; // `|`.charCodeAt(0);
exports.pipe = pipe;
var greaterThan = 62; // `>`.charCodeAt(0);
exports.greaterThan = greaterThan;
var space = 32; // ` `.charCodeAt(0);
exports.space = space;
var singleQuote = 39; // `'`.charCodeAt(0);
exports.singleQuote = singleQuote;
var doubleQuote = 34; // `"`.charCodeAt(0);
exports.doubleQuote = doubleQuote;
var slash = 47; // `/`.charCodeAt(0);
exports.slash = slash;
var bang = 33; // `!`.charCodeAt(0);
exports.bang = bang;
var backslash = 92; // '\\'.charCodeAt(0);
exports.backslash = backslash;
var cr = 13; // '\r'.charCodeAt(0);
exports.cr = cr;
var feed = 12; // '\f'.charCodeAt(0);
exports.feed = feed;
var newline = 10; // '\n'.charCodeAt(0);
exports.newline = newline;
var tab = 9; // '\t'.charCodeAt(0);

// Expose aliases primarily for readability.
exports.tab = tab;
var str = singleQuote;

// No good single character representation!
exports.str = str;
var comment = -1;
exports.comment = comment;
var word = -2;
exports.word = word;
var combinator = -3;
exports.combinator = combinator;"use strict";

exports.__esModule = true;
exports.FIELDS = void 0;
exports["default"] = tokenize;
var t = _interopRequireWildcard(require("./tokenTypes"));
var _unescapable, _wordDelimiters;
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
var hex = {};
var hexChars = "0123456789abcdefABCDEF";
for (var i = 0; i < hexChars.length; i++) {
  hex[hexChars.charCodeAt(i)] = true;
}

/**
 *  Returns the last index of the bar css word
 * @param {string} css The string in which the word begins
 * @param {number} start The index into the string where word's first letter occurs
 */
function consumeWord(css, start) {
  var next = start;
  var code;
  do {
    code = css.charCodeAt(next);
    if (wordDelimiters[code]) {
      return next - 1;
    } else if (code === t.backslash) {
      next = consumeEscape(css, next) + 1;
    } else {
      // All other characters are part of the word
      next++;
    }
  } while (next < css.length);
  return next - 1;
}

/**
 *  Returns the last index of the escape sequence
 * @param {string} css The string in which the sequence begins
 * @param {number} start The index into the string where escape character (`\`) occurs.
 */
function consumeEscape(css, start) {
  var next = start;
  var code = css.charCodeAt(next + 1);
  if (unescapable[code]) {
    // just consume the escape char
  } else if (hex[code]) {
    var hexDigits = 0;
    // consume up to 6 hex chars
    do {
      next++;
      hexDigits++;
      code = css.charCodeAt(next + 1);
    } while (hex[code] && hexDigits < 6);
    // if fewer than 6 hex chars, a trailing space ends the escape
    if (hexDigits < 6 && code === t.space) {
      next++;
    }
  } else {
    // the next char is part of the current word
    next++;
  }
  return next;
}
var FIELDS = {
  TYPE: 0,
  START_LINE: 1,
  START_COL: 2,
  END_LINE: 3,
  END_COL: 4,
  START_POS: 5,
  END_POS: 6
};
exports.FIELDS = FIELDS;
function tokenize(input) {
  var tokens = [];
  var css = input.css.valueOf();
  var _css = css,
    length = _css.length;
  var offset = -1;
  var line = 1;
  var start = 0;
  var end = 0;
  var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  function unclosed(what, fix) {
    if (input.safe) {
      // fyi: this is never set to true.
      css += fix;
      next = css.length - 1;
    } else {
      throw input.error('Unclosed ' + what, line, start - offset, start);
    }
  }
  while (start < length) {
    code = css.charCodeAt(start);
    if (code === t.newline) {
      offset = start;
      line += 1;
    }
    switch (code) {
      case t.space:
      case t.tab:
      case t.newline:
      case t.cr:
      case t.feed:
        next = start;
        do {
          next += 1;
          code = css.charCodeAt(next);
          if (code === t.newline) {
            offset = next;
            line += 1;
          }
        } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
        tokenType = t.space;
        endLine = line;
        endColumn = next - offset - 1;
        end = next;
        break;
      case t.plus:
      case t.greaterThan:
      case t.tilde:
      case t.pipe:
        next = start;
        do {
          next += 1;
          code = css.charCodeAt(next);
        } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
        tokenType = t.combinator;
        endLine = line;
        endColumn = start - offset;
        end = next;
        break;

      // Consume these characters as single tokens.
      case t.asterisk:
      case t.ampersand:
      case t.bang:
      case t.comma:
      case t.equals:
      case t.dollar:
      case t.caret:
      case t.openSquare:
      case t.closeSquare:
      case t.colon:
      case t.semicolon:
      case t.openParenthesis:
      case t.closeParenthesis:
        next = start;
        tokenType = code;
        endLine = line;
        endColumn = start - offset;
        end = next + 1;
        break;
      case t.singleQuote:
      case t.doubleQuote:
        quote = code === t.singleQuote ? "'" : '"';
        next = start;
        do {
          escaped = false;
          next = css.indexOf(quote, next + 1);
          if (next === -1) {
            unclosed('quote', quote);
          }
          escapePos = next;
          while (css.charCodeAt(escapePos - 1) === t.backslash) {
            escapePos -= 1;
            escaped = !escaped;
          }
        } while (escaped);
        tokenType = t.str;
        endLine = line;
        endColumn = start - offset;
        end = next + 1;
        break;
      default:
        if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
          next = css.indexOf('*/', start + 2) + 1;
          if (next === 0) {
            unclosed('comment', '*/');
          }
          content = css.slice(start, next + 1);
          lines = content.split('\n');
          last = lines.length - 1;
          if (last > 0) {
            nextLine = line + last;
            nextOffset = next - lines[last].length;
          } else {
            nextLine = line;
            nextOffset = offset;
          }
          tokenType = t.comment;
          line = nextLine;
          endLine = nextLine;
          endColumn = next - nextOffset;
        } else if (code === t.slash) {
          next = start;
          tokenType = code;
          endLine = line;
          endColumn = start - offset;
          end = next + 1;
        } else {
          next = consumeWord(css, start);
          tokenType = t.word;
          endLine = line;
          endColumn = next - offset;
        }
        end = next + 1;
        break;
    }

    // Ensure that the token structure remains consistent
    tokens.push([tokenType,
    // [0] Token type
    line,
    // [1] Starting line
    start - offset,
    // [2] Starting column
    endLine,
    // [3] Ending line
    endColumn,
    // [4] Ending column
    start,
    // [5] Start position / Source index
    end // [6] End position
    ]);

    // Reset offset for the next token
    if (nextOffset) {
      offset = nextOffset;
      nextOffset = null;
    }
    start = end;
  }
  return tokens;
}"use strict";

exports.__esModule = true;
exports["default"] = ensureObject;
function ensureObject(obj) {
  for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    props[_key - 1] = arguments[_key];
  }
  while (props.length > 0) {
    var prop = props.shift();
    if (!obj[prop]) {
      obj[prop] = {};
    }
    obj = obj[prop];
  }
}
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = getProp;
function getProp(obj) {
  for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    props[_key - 1] = arguments[_key];
  }
  while (props.length > 0) {
    var prop = props.shift();
    if (!obj[prop]) {
      return undefined;
    }
    obj = obj[prop];
  }
  return obj;
}
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports.unesc = exports.stripComments = exports.getProp = exports.ensureObject = void 0;
var _unesc = _interopRequireDefault(require("./unesc"));
exports.unesc = _unesc["default"];
var _getProp = _interopRequireDefault(require("./getProp"));
exports.getProp = _getProp["default"];
var _ensureObject = _interopRequireDefault(require("./ensureObject"));
exports.ensureObject = _ensureObject["default"];
var _stripComments = _interopRequireDefault(require("./stripComments"));
exports.stripComments = _stripComments["default"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }"use strict";

exports.__esModule = true;
exports["default"] = stripComments;
function stripComments(str) {
  var s = "";
  var commentStart = str.indexOf("/*");
  var lastEnd = 0;
  while (commentStart >= 0) {
    s = s + str.slice(lastEnd, commentStart);
    var commentEnd = str.indexOf("*/", commentStart + 2);
    if (commentEnd < 0) {
      return s;
    }
    lastEnd = commentEnd + 2;
    commentStart = str.indexOf("/*", lastEnd);
  }
  s = s + str.slice(lastEnd);
  return s;
}
module.exports = exports.default;"use strict";

exports.__esModule = true;
exports["default"] = unesc;
// Many thanks for this post which made this migration much easier.
// https://mathiasbynens.be/notes/css-escapes

/**
 * 
 * @param {string} str 
 * @returns {[string, number]|undefined}
 */
function gobbleHex(str) {
  var lower = str.toLowerCase();
  var hex = '';
  var spaceTerminated = false;
  for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
    var code = lower.charCodeAt(i);
    // check to see if we are dealing with a valid hex char [a-f|0-9]
    var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
    // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
    spaceTerminated = code === 32;
    if (!valid) {
      break;
    }
    hex += lower[i];
  }
  if (hex.length === 0) {
    return undefined;
  }
  var codePoint = parseInt(hex, 16);
  var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  // Add special case for
  // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
    return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  }
  return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
}
var CONTAINS_ESCAPE = /\\/;
function unesc(str) {
  var needToProcess = CONTAINS_ESCAPE.test(str);
  if (!needToProcess) {
    return str;
  }
  var ret = "";
  for (var i = 0; i < str.length; i++) {
    if (str[i] === "\\") {
      var gobbled = gobbleHex(str.slice(i + 1, i + 7));
      if (gobbled !== undefined) {
        ret += gobbled[0];
        i += gobbled[1];
        continue;
      }

      // Retain a pair of \\ if double escaped `\\\\`
      // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
      if (str[i + 1] === "\\") {
        ret += "\\";
        i++;
        continue;
      }

      // if \\ is at the end of the string retain it
      // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
      if (str.length === i + 1) {
        ret += str[i];
      }
      continue;
    }
    ret += str[i];
  }
  return ret;
}
module.exports = exports.default;{
  "name": "postcss-selector-parser",
  "version": "6.1.2",
  "devDependencies": {
    "@babel/cli": "^7.11.6",
    "@babel/core": "^7.11.6",
    "@babel/eslint-parser": "^7.11.5",
    "@babel/eslint-plugin": "^7.11.5",
    "@babel/plugin-proposal-class-properties": "^7.10.4",
    "@babel/preset-env": "^7.11.5",
    "@babel/register": "^7.11.5",
    "ava": "^5.1.0",
    "babel-plugin-add-module-exports": "^1.0.4",
    "coveralls": "^3.1.0",
    "del-cli": "^5.0.0",
    "eslint": "^8.28.0",
    "eslint-plugin-import": "^2.26.0",
    "glob": "^8.0.3",
    "minimist": "^1.2.5",
    "nyc": "^15.1.0",
    "postcss": "^8.4.31",
    "semver": "^7.3.2",
    "typescript": "^4.0.3"
  },
  "main": "dist/index.js",
  "types": "postcss-selector-parser.d.ts",
  "files": [
    "API.md",
    "CHANGELOG.md",
    "LICENSE-MIT",
    "dist",
    "postcss-selector-parser.d.ts",
    "!**/__tests__"
  ],
  "scripts": {
    "typecheck": "tsc --noEmit --strict postcss-selector-parser.d.ts postcss-selector-parser.test.ts",
    "pretest": "eslint src && npm run typecheck",
    "prepare": "del-cli dist && BABEL_ENV=publish babel src --out-dir dist --ignore /__tests__/",
    "lintfix": "eslint --fix src",
    "report": "nyc report --reporter=html",
    "test": "nyc ava src/__tests__/*.mjs",
    "testone": "ava"
  },
  "dependencies": {
    "cssesc": "^3.0.0",
    "util-deprecate": "^1.0.2"
  },
  "license": "MIT",
  "engines": {
    "node": ">=4"
  },
  "homepage": "https://github.com/postcss/postcss-selector-parser",
  "contributors": [
    {
      "name": "Ben Briggs",
      "email": "beneb.info@gmail.com",
      "url": "http://beneb.info"
    },
    {
      "name": "Chris Eppstein",
      "email": "chris@eppsteins.net",
      "url": "http://twitter.com/chriseppstein"
    }
  ],
  "repository": "postcss/postcss-selector-parser",
  "ava": {
    "require": [
      "@babel/register"
    ],
    "concurrency": 5,
    "timeout": "25s",
    "nodeArguments": []
  },
  "nyc": {
    "exclude": [
      "node_modules",
      "**/__tests__"
    ]
  }
}
The ISC License

Copyright (c) GitHub, Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const META = Symbol('proc-log.meta')
module.exports = {
  META: META,
  output: {
    LEVELS: [
      'standard',
      'error',
      'buffer',
      'flush',
    ],
    KEYS: {
      standard: 'standard',
      error: 'error',
      buffer: 'buffer',
      flush: 'flush',
    },
    standard: function (...args) {
      return process.emit('output', 'standard', ...args)
    },
    error: function (...args) {
      return process.emit('output', 'error', ...args)
    },
    buffer: function (...args) {
      return process.emit('output', 'buffer', ...args)
    },
    flush: function (...args) {
      return process.emit('output', 'flush', ...args)
    },
  },
  log: {
    LEVELS: [
      'notice',
      'error',
      'warn',
      'info',
      'verbose',
      'http',
      'silly',
      'timing',
      'pause',
      'resume',
    ],
    KEYS: {
      notice: 'notice',
      error: 'error',
      warn: 'warn',
      info: 'info',
      verbose: 'verbose',
      http: 'http',
      silly: 'silly',
      timing: 'timing',
      pause: 'pause',
      resume: 'resume',
    },
    error: function (...args) {
      return process.emit('log', 'error', ...args)
    },
    notice: function (...args) {
      return process.emit('log', 'notice', ...args)
    },
    warn: function (...args) {
      return process.emit('log', 'warn', ...args)
    },
    info: function (...args) {
      return process.emit('log', 'info', ...args)
    },
    verbose: function (...args) {
      return process.emit('log', 'verbose', ...args)
    },
    http: function (...args) {
      return process.emit('log', 'http', ...args)
    },
    silly: function (...args) {
      return process.emit('log', 'silly', ...args)
    },
    timing: function (...args) {
      return process.emit('log', 'timing', ...args)
    },
    pause: function () {
      return process.emit('log', 'pause')
    },
    resume: function () {
      return process.emit('log', 'resume')
    },
  },
  time: {
    LEVELS: [
      'start',
      'end',
    ],
    KEYS: {
      start: 'start',
      end: 'end',
    },
    start: function (name, fn) {
      process.emit('time', 'start', name)
      function end () {
        return process.emit('time', 'end', name)
      }
      if (typeof fn === 'function') {
        const res = fn()
        if (res && res.finally) {
          return res.finally(end)
        }
        end()
        return res
      }
      return end
    },
    end: function (name) {
      return process.emit('time', 'end', name)
    },
  },
  input: {
    LEVELS: [
      'start',
      'end',
      'read',
    ],
    KEYS: {
      start: 'start',
      end: 'end',
      read: 'read',
    },
    start: function (fn) {
      process.emit('input', 'start')
      function end () {
        return process.emit('input', 'end')
      }
      if (typeof fn === 'function') {
        const res = fn()
        if (res && res.finally) {
          return res.finally(end)
        }
        end()
        return res
      }
      return end
    },
    end: function () {
      return process.emit('input', 'end')
    },
    read: function (...args) {
      let resolve, reject
      const promise = new Promise((_resolve, _reject) => {
        resolve = _resolve
        reject = _reject
      })
      process.emit('input', 'read', resolve, reject, ...args)
      return promise
    },
  },
}
{
  "name": "proc-log",
  "version": "5.0.0",
  "files": [
    "bin/",
    "lib/"
  ],
  "main": "lib/index.js",
  "description": "just emit 'log' events on the process object",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/proc-log.git"
  },
  "author": "GitHub Inc.",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "posttest": "npm run lint",
    "postsnap": "eslint index.js test/*.js --fix",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "lintfix": "npm run eslint -- --fix",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.0.1"
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  }
}
The ISC License

Copyright (c) GitHub, Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const EE = require('events')
const onProgress = Symbol('onProgress')
const bars = Symbol('bars')
const listener = Symbol('listener')
const normData = Symbol('normData')
class Client extends EE {
  constructor ({ normalize = false, stopOnDone = false } = {}) {
    super()
    this.normalize = !!normalize
    this.stopOnDone = !!stopOnDone
    this[bars] = new Map()
    this[listener] = null
  }

  get size () {
    return this[bars].size
  }

  get listening () {
    return !!this[listener]
  }

  addListener (...args) {
    return this.on(...args)
  }

  on (ev, ...args) {
    if (ev === 'progress' && !this[listener]) {
      this.start()
    }
    return super.on(ev, ...args)
  }

  off (ev, ...args) {
    return this.removeListener(ev, ...args)
  }

  removeListener (ev, ...args) {
    const ret = super.removeListener(ev, ...args)
    if (ev === 'progress' && this.listeners(ev).length === 0) {
      this.stop()
    }
    return ret
  }

  stop () {
    if (this[listener]) {
      process.removeListener('progress', this[listener])
      this[listener] = null
    }
  }

  start () {
    if (!this[listener]) {
      this[listener] = (...args) => this[onProgress](...args)
      process.on('progress', this[listener])
    }
  }

  [onProgress] (key, data) {
    data = this[normData](key, data)
    if (!this[bars].has(key)) {
      this.emit('bar', key, data)
    }
    this[bars].set(key, data)
    this.emit('progress', key, data)
    if (data.done) {
      this[bars].delete(key)
      this.emit('barDone', key, data)
      if (this.size === 0) {
        if (this.stopOnDone) {
          this.stop()
        }
        this.emit('done')
      }
    }
  }

  [normData] (key, data) {
    const actualValue = data.value
    const actualTotal = data.total
    let value = actualValue
    let total = actualTotal
    const done = data.done || value >= total
    if (this.normalize) {
      const bar = this[bars].get(key)
      total = 100
      if (done) {
        value = 100
      } else {
        // show value as a portion of 100
        const pct = 100 * actualValue / actualTotal
        if (bar) {
          // don't ever go backwards, and don't stand still
          // move at least 1% of the remaining value if it wouldn't move.
          value = (pct > bar.value) ? pct
            : (100 - bar.value) / 100 + bar.value
        }
      }
    }
    // include the key
    return {
      ...data,
      key,
      name: data.name || key,
      value,
      total,
      actualValue,
      actualTotal,
      done,
    }
  }
}
module.exports = Client
exports.Client = require('./client.js')
exports.Tracker = require('./tracker.js')

const trackers = new Map()
exports.createTracker = (name, key, total) => {
  const tracker = new exports.Tracker(name, key, total)
  if (trackers.has(tracker.key)) {
    const msg = `proggy: duplicate progress id ${JSON.stringify(tracker.key)}`
    throw new Error(msg)
  }
  trackers.set(tracker.key, tracker)
  tracker.on('done', () => trackers.delete(tracker.key))
  return tracker
}
exports.createClient = (options = {}) => new exports.Client(options)
// The tracker class is intentionally as naive as possible.  it is just
// an ergonomic wrapper around process.emit('progress', ...)
const EE = require('events')
class Tracker extends EE {
  constructor (name, key, total) {
    super()
    if (!name) {
      throw new Error('proggy: Tracker needs a name')
    }

    if (typeof key === 'number' && !total) {
      total = key
      key = null
    }

    if (!total) {
      total = 100
    }

    if (!key) {
      key = name
    }

    this.done = false
    this.name = name
    this.key = key
    this.value = 0
    this.total = total
  }

  finish (metadata = {}) {
    this.update(this.total, this.total, metadata)
  }

  update (value, total, metadata) {
    if (!metadata) {
      if (total && typeof total === 'object') {
        metadata = total
      } else {
        metadata = {}
      }
    }
    if (typeof total !== 'number') {
      total = this.total
    }

    if (this.done) {
      const msg = `proggy: updating completed tracker: ${JSON.stringify(this.key)}`
      throw new Error(msg)
    }
    this.value = value
    this.total = total
    const done = this.value >= this.total
    process.emit('progress', this.key, {
      ...metadata,
      name: this.name,
      key: this.key,
      value,
      total,
      done,
    })
    if (done) {
      this.done = true
      this.emit('done')
    }
  }
}
module.exports = Tracker
{
  "name": "proggy",
  "version": "3.0.0",
  "files": [
    "bin/",
    "lib/"
  ],
  "main": "lib/index.js",
  "description": "Progress bar updates at a distance",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/proggy.git"
  },
  "author": "GitHub Inc.",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "posttest": "npm run lint",
    "snap": "tap",
    "postsnap": "eslint lib test --fix",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "lintfix": "npm run eslint -- --fix",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "chalk": "^4.1.2",
    "cli-progress": "^3.10.0",
    "npmlog": "^7.0.0",
    "tap": "^16.0.1"
  },
  "tap": {
    "coverage-map": "map.js",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  }
}
The ISC License

Copyright (c) Isaac Z. Schlueter

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const allSettled =
  Promise.allSettled ? promises => Promise.allSettled(promises)
  : promises => {
    const reflections = []
    for (let i = 0; i < promises.length; i++) {
      reflections[i] = Promise.resolve(promises[i]).then(value => ({
        status: 'fulfilled',
        value,
      }), reason => ({
        status: 'rejected',
        reason,
      }))
    }
    return Promise.all(reflections)
  }

module.exports = promises => allSettled(promises).then(results => {
  let er = null
  const ret = new Array(results.length)
  results.forEach((result, i) => {
    if (result.status === 'rejected')
      throw result.reason
    else
      ret[i] = result.value
  })
  return ret
})
{
  "name": "promise-all-reject-late",
  "version": "1.0.1",
  "description": "Like Promise.all, but save rejections until all promises are resolved",
  "author": "Isaac Z. Schlueter  (https://izs.me)",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags"
  },
  "tap": {
    "check-coverage": true
  },
  "devDependencies": {
    "tap": "^14.10.5"
  },
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  }
}
const t = require('tap')

const main = () => {
  if (process.argv[2] === 'polyfill-all-settled') {
    Promise.allSettled = null
    runTests()
  } else if (process.argv[2] === 'native-all-settled') {
    Promise.allSettled = Promise.allSettled || (
      promises => {
        const reflections = []
        for (let i = 0; i < promises.length; i++) {
          reflections[i] = Promise.resolve(promises[i]).then(value => ({
            status: 'fulfilled',
            value,
          }), reason => ({
            status: 'rejected',
            reason,
          }))
        }
        return Promise.all(reflections)
      }
    )
    runTests()
  } else {
    t.spawn(process.execPath, [__filename, 'polyfill-all-settled'])
    t.spawn(process.execPath, [__filename, 'native-all-settled'])
  }
}

const runTests = () => {
  const lateFail = require('../')

  t.test('fail only after all promises resolve', t => {
    let resolvedSlow = false
    const fast = () => Promise.reject('nope')
    const slow = () => new Promise(res => setTimeout(res, 100))
      .then(() => resolvedSlow = true)

    // throw some holes and junk in the array to verify that we handle it
    return t.rejects(lateFail([fast(),,,,slow(), null, {not: 'a promise'},,,]))
      .then(() => t.equal(resolvedSlow, true, 'resolved slow before failure'))
  })

  t.test('works just like Promise.all() otherwise', t => {
    const one = () => Promise.resolve(1)
    const two = () => Promise.resolve(2)
    const tre = () => Promise.resolve(3)
    const fur = () => Promise.resolve(4)
    const fiv = () => Promise.resolve(5)
    const six = () => Promise.resolve(6)
    const svn = () => Promise.resolve(7)
    const eit = () => Promise.resolve(8)
    const nin = () => Promise.resolve(9)
    const ten = () => Promise.resolve(10)
    const expect = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    const all = Promise.all([
      one(),
      two(),
      tre(),
      fur(),
      fiv(),
      six(),
      svn(),
      eit(),
      nin(),
      ten(),
    ])
    const late = lateFail([
      one(),
      two(),
      tre(),
      fur(),
      fiv(),
      six(),
      svn(),
      eit(),
      nin(),
      ten(),
    ])

    return Promise.all([all, late]).then(([all, late]) => {
      t.strictSame(all, expect)
      t.strictSame(late, expect)
    })
  })
}

main()
The ISC License

Copyright (c) Isaac Z. Schlueter

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.callLimit = void 0;
const os = __importStar(require("node:os"));
// availableParallelism available only since node v19, for older versions use
// cpus() cpus() can return an empty list if /proc is not mounted, use 1 in
// this case
/* c8 ignore start */
const defLimit = 'availableParallelism' in os ?
    Math.max(1, os.availableParallelism() - 1)
    : Math.max(1, os.cpus().length - 1);
const callLimit = (queue, { limit = defLimit, rejectLate } = {}) => new Promise((res, rej) => {
    let active = 0;
    let current = 0;
    const results = [];
    // Whether or not we rejected, distinct from the rejection just in case the rejection itself is falsey
    let rejected = false;
    let rejection;
    const reject = (er) => {
        if (rejected)
            return;
        rejected = true;
        rejection ??= er;
        if (!rejectLate)
            rej(rejection);
    };
    let resolved = false;
    const resolve = () => {
        if (resolved || active > 0)
            return;
        resolved = true;
        res(results);
    };
    const run = () => {
        const c = current++;
        if (c >= queue.length)
            return rejected ? reject() : resolve();
        active++;
        const step = queue[c];
        /* c8 ignore start */
        if (!step)
            throw new Error('walked off queue');
        /* c8 ignore stop */
        results[c] = step()
            .then(result => {
            active--;
            results[c] = result;
            return result;
        }, er => {
            active--;
            reject(er);
        })
            .then(result => {
            if (rejected && active === 0)
                return rej(rejection);
            run();
            return result;
        });
    };
    for (let i = 0; i < limit; i++)
        run();
});
exports.callLimit = callLimit;
//# sourceMappingURL=index.js.map{
  "type": "commonjs"
}
import * as os from 'node:os';
// availableParallelism available only since node v19, for older versions use
// cpus() cpus() can return an empty list if /proc is not mounted, use 1 in
// this case
/* c8 ignore start */
const defLimit = 'availableParallelism' in os ?
    Math.max(1, os.availableParallelism() - 1)
    : Math.max(1, os.cpus().length - 1);
export const callLimit = (queue, { limit = defLimit, rejectLate } = {}) => new Promise((res, rej) => {
    let active = 0;
    let current = 0;
    const results = [];
    // Whether or not we rejected, distinct from the rejection just in case the rejection itself is falsey
    let rejected = false;
    let rejection;
    const reject = (er) => {
        if (rejected)
            return;
        rejected = true;
        rejection ??= er;
        if (!rejectLate)
            rej(rejection);
    };
    let resolved = false;
    const resolve = () => {
        if (resolved || active > 0)
            return;
        resolved = true;
        res(results);
    };
    const run = () => {
        const c = current++;
        if (c >= queue.length)
            return rejected ? reject() : resolve();
        active++;
        const step = queue[c];
        /* c8 ignore start */
        if (!step)
            throw new Error('walked off queue');
        /* c8 ignore stop */
        results[c] = step()
            .then(result => {
            active--;
            results[c] = result;
            return result;
        }, er => {
            active--;
            reject(er);
        })
            .then(result => {
            if (rejected && active === 0)
                return rej(rejection);
            run();
            return result;
        });
    };
    for (let i = 0; i < limit; i++)
        run();
});
//# sourceMappingURL=index.js.map{
  "type": "module"
}
{
  "name": "promise-call-limit",
  "version": "3.0.2",
  "files": [
    "dist"
  ],
  "description": "Call an array of promise-returning functions, restricting concurrency to a specified limit.",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/promise-call-limit"
  },
  "author": "Isaac Z. Schlueter  (https://izs.me)",
  "license": "ISC",
  "scripts": {
    "prepare": "tshy",
    "pretest": "npm run prepare",
    "snap": "tap",
    "test": "tap",
    "preversion": "npm test",
    "postversion": "npm publish",
    "prepublishOnly": "git push origin --follow-tags",
    "format": "prettier --write . --log-level warn --cache"
  },
  "devDependencies": {
    "prettier": "^3.3.3",
    "tap": "^21.0.1",
    "tshy": "^3.0.2",
    "typedoc": "^0.26.6"
  },
  "prettier": {
    "experimentalTernaries": true,
    "semi": false,
    "printWidth": 70,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  },
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "main": "./dist/commonjs/index.js",
  "types": "./dist/commonjs/index.d.ts",
  "type": "module",
  "module": "./dist/esm/index.js"
}
Copyright (c) 2017, Rebecca Turner 

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

'use strict'
module.exports = inflight

let Bluebird
try {
  Bluebird = require('bluebird')
} catch (_) {
  Bluebird = Promise
}

const active = {}
inflight.active = active
function inflight (unique, doFly) {
  return Bluebird.all([unique, doFly]).then(function (args) {
    const unique = args[0]
    const doFly = args[1]
    if (Array.isArray(unique)) {
      return Bluebird.all(unique).then(function (uniqueArr) {
        return _inflight(uniqueArr.join(''), doFly)
      })
    } else {
      return _inflight(unique, doFly)
    }
  })

  function _inflight (unique, doFly) {
    if (!active[unique]) {
      active[unique] = (new Bluebird(function (resolve) {
        return resolve(doFly())
      }))
      active[unique].then(cleanup, cleanup)
      function cleanup() { delete active[unique] }
    }
    return active[unique]
  }
}
{
  "name": "promise-inflight",
  "version": "1.0.1",
  "description": "One promise for multiple requests in flight to avoid async duplication",
  "main": "inflight.js",
  "files": [
    "inflight.js"
  ],
  "license": "ISC",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Rebecca Turner  (http://re-becca.org/)",
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "git+https://github.com/iarna/promise-inflight.git"
  },
  "bugs": {
    "url": "https://github.com/iarna/promise-inflight/issues"
  },
  "homepage": "https://github.com/iarna/promise-inflight#readme"
}
Copyright (c) 2014 IndigoUnited

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.
'use strict';

var errcode = require('err-code');
var retry = require('retry');

var hasOwn = Object.prototype.hasOwnProperty;

function isRetryError(err) {
    return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried');
}

function promiseRetry(fn, options) {
    var temp;
    var operation;

    if (typeof fn === 'object' && typeof options === 'function') {
        // Swap options and fn when using alternate signature (options, fn)
        temp = options;
        options = fn;
        fn = temp;
    }

    operation = retry.operation(options);

    return new Promise(function (resolve, reject) {
        operation.attempt(function (number) {
            Promise.resolve()
            .then(function () {
                return fn(function (err) {
                    if (isRetryError(err)) {
                        err = err.retried;
                    }

                    throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err });
                }, number);
            })
            .then(resolve, function (err) {
                if (isRetryError(err)) {
                    err = err.retried;

                    if (operation.retry(err || new Error())) {
                        return;
                    }
                }

                reject(err);
            });
        });
    });
}

module.exports = promiseRetry;
{
  "name": "promise-retry",
  "version": "2.0.1",
  "description": "Retries a function that returns a promise, leveraging the power of the retry module.",
  "main": "index.js",
  "scripts": {
    "test": "mocha --bail -t 10000"
  },
  "bugs": {
    "url": "https://github.com/IndigoUnited/node-promise-retry/issues/"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/IndigoUnited/node-promise-retry.git"
  },
  "keywords": [
    "retry",
    "promise",
    "backoff",
    "repeat",
    "replay"
  ],
  "author": "IndigoUnited  (http://indigounited.com)",
  "license": "MIT",
  "devDependencies": {
    "expect.js": "^0.3.1",
    "mocha": "^8.0.1",
    "sleep-promise": "^8.0.1"
  },
  "dependencies": {
    "err-code": "^2.0.2",
    "retry": "^0.12.0"
  },
  "engines": {
    "node": ">=10"
  }
}
'use strict';

var expect = require('expect.js');
var promiseRetry = require('../');
var promiseDelay = require('sleep-promise');

describe('promise-retry', function () {
    it('should call fn again if retry was called', function () {
        var count = 0;

        return promiseRetry(function (retry) {
            count += 1;

            return promiseDelay(10)
            .then(function () {
                if (count <= 2) {
                    retry(new Error('foo'));
                }

                return 'final';
            });
        }, { factor: 1 })
        .then(function (value) {
            expect(value).to.be('final');
            expect(count).to.be(3);
        }, function () {
            throw new Error('should not fail');
        });
    });

    it('should call fn with the attempt number', function () {
        var count = 0;

        return promiseRetry(function (retry, number) {
            count += 1;
            expect(count).to.equal(number);

            return promiseDelay(10)
            .then(function () {
                if (count <= 2) {
                    retry(new Error('foo'));
                }

                return 'final';
            });
        }, { factor: 1 })
        .then(function (value) {
            expect(value).to.be('final');
            expect(count).to.be(3);
        }, function () {
            throw new Error('should not fail');
        });
    });

    it('should not retry on fulfillment if retry was not called', function () {
        var count = 0;

        return promiseRetry(function () {
            count += 1;

            return promiseDelay(10)
            .then(function () {
                return 'final';
            });
        })
        .then(function (value) {
            expect(value).to.be('final');
            expect(count).to.be(1);
        }, function () {
            throw new Error('should not fail');
        });
    });

    it('should not retry on rejection if retry was not called', function () {
        var count = 0;

        return promiseRetry(function () {
            count += 1;

            return promiseDelay(10)
            .then(function () {
                throw new Error('foo');
            });
        })
        .then(function () {
            throw new Error('should not succeed');
        }, function (err) {
            expect(err.message).to.be('foo');
            expect(count).to.be(1);
        });
    });

    it('should not retry on rejection if nr of retries is 0', function () {
        var count = 0;

        return promiseRetry(function (retry) {
            count += 1;

            return promiseDelay(10)
            .then(function () {
                throw new Error('foo');
            })
            .catch(retry);
        }, { retries : 0 })
        .then(function () {
            throw new Error('should not succeed');
        }, function (err) {
            expect(err.message).to.be('foo');
            expect(count).to.be(1);
        });
    });

    it('should reject the promise if the retries were exceeded', function () {
        var count = 0;

        return promiseRetry(function (retry) {
            count += 1;

            return promiseDelay(10)
            .then(function () {
                throw new Error('foo');
            })
            .catch(retry);
        }, { retries: 2, factor: 1 })
        .then(function () {
            throw new Error('should not succeed');
        }, function (err) {
            expect(err.message).to.be('foo');
            expect(count).to.be(3);
        });
    });

    it('should pass options to the underlying retry module', function () {
        var count = 0;

        return promiseRetry(function (retry) {
            return promiseDelay(10)
            .then(function () {
                if (count < 2) {
                    count += 1;
                    retry(new Error('foo'));
                }

                return 'final';
            });
        }, { retries: 1, factor: 1 })
        .then(function () {
            throw new Error('should not succeed');
        }, function (err) {
            expect(err.message).to.be('foo');
        });
    });

    it('should convert direct fulfillments into promises', function () {
        return promiseRetry(function () {
            return 'final';
        }, { factor: 1 })
        .then(function (value) {
            expect(value).to.be('final');
        }, function () {
            throw new Error('should not fail');
        });
    });

    it('should convert direct rejections into promises', function () {
        promiseRetry(function () {
            throw new Error('foo');
        }, { retries: 1, factor: 1 })
        .then(function () {
            throw new Error('should not succeed');
        }, function (err) {
            expect(err.message).to.be('foo');
        });
    });

    it('should not crash on undefined rejections', function () {
        return promiseRetry(function () {
            throw undefined;
        }, { retries: 1, factor: 1 })
        .then(function () {
            throw new Error('should not succeed');
        }, function (err) {
            expect(err).to.be(undefined);
        })
        .then(function () {
            return promiseRetry(function (retry) {
                retry();
            }, { retries: 1, factor: 1 });
        })
        .then(function () {
            throw new Error('should not succeed');
        }, function (err) {
            expect(err).to.be(undefined);
        });
    });

    it('should retry if retry() was called with undefined', function () {
        var count = 0;

        return promiseRetry(function (retry) {
            count += 1;

            return promiseDelay(10)
            .then(function () {
                if (count <= 2) {
                    retry();
                }

                return 'final';
            });
        }, { factor: 1 })
        .then(function (value) {
            expect(value).to.be('final');
            expect(count).to.be(3);
        }, function () {
            throw new Error('should not fail');
        });
    });

    it('should work with several retries in the same chain', function () {
        var count = 0;

        return promiseRetry(function (retry) {
            count += 1;

            return promiseDelay(10)
            .then(function () {
                retry(new Error('foo'));
            })
            .catch(function (err) {
                retry(err);
            });
        }, { retries: 1, factor: 1 })
        .then(function () {
            throw new Error('should not succeed');
        }, function (err) {
            expect(err.message).to.be('foo');
            expect(count).to.be(2);
        });
    });

    it('should allow options to be passed first', function () {
        var count = 0;

        return promiseRetry({ factor: 1 }, function (retry) {
            count += 1;

            return promiseDelay(10)
                .then(function () {
                    if (count <= 2) {
                        retry(new Error('foo'));
                    }

                    return 'final';
                });
        }).then(function (value) {
            expect(value).to.be('final');
            expect(count).to.be(3);
        }, function () {
            throw new Error('should not fail');
        });
    });
});
The ISC License

Copyright (c) Isaac Z. Schlueter

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const fs = require('fs/promises')
const { runInThisContext } = require('vm')
const { promisify } = require('util')
const { randomBytes } = require('crypto')
const { Module } = require('module')
const { dirname, basename } = require('path')
const { read } = require('read')

const files = {}

class PromZard {
  #file = null
  #backupFile = null
  #ctx = null
  #unique = randomBytes(8).toString('hex')
  #prompts = []

  constructor (file, ctx = {}, options = {}) {
    this.#file = file
    this.#ctx = ctx
    this.#backupFile = options.backupFile
  }

  static async promzard (file, ctx, options) {
    const pz = new PromZard(file, ctx, options)
    return pz.load()
  }

  static async fromBuffer (buf, ctx, options) {
    let filename = 0
    do {
      filename = '\0' + Math.random()
    } while (files[filename])
    files[filename] = buf
    const ret = await PromZard.promzard(filename, ctx, options)
    delete files[filename]
    return ret
  }

  async load () {
    if (files[this.#file]) {
      return this.#loaded()
    }

    try {
      files[this.#file] = await fs.readFile(this.#file, 'utf8')
    } catch (er) {
      if (er && this.#backupFile) {
        this.#file = this.#backupFile
        this.#backupFile = null
        return this.load()
      }
      throw er
    }

    return this.#loaded()
  }

  async #loaded () {
    const mod = new Module(this.#file, module)
    mod.loaded = true
    mod.filename = this.#file
    mod.id = this.#file
    mod.paths = Module._nodeModulePaths(dirname(this.#file))

    this.#ctx.prompt = this.#makePrompt()
    this.#ctx.__filename = this.#file
    this.#ctx.__dirname = dirname(this.#file)
    this.#ctx.__basename = basename(this.#file)
    this.#ctx.module = mod
    this.#ctx.require = (p) => mod.require(p)
    this.#ctx.require.resolve = (p) => Module._resolveFilename(p, mod)
    this.#ctx.exports = mod.exports

    const body = `(function(${Object.keys(this.#ctx).join(', ')}) { ${files[this.#file]}\n })`
    runInThisContext(body, this.#file).apply(this.#ctx, Object.values(this.#ctx))
    this.#ctx.res = mod.exports

    return this.#walk()
  }

  #makePrompt () {
    return (...args) => {
      let p, d, t
      for (let i = 0; i < args.length; i++) {
        const a = args[i]
        if (typeof a === 'string') {
          if (p) {
            d = a
          } else {
            p = a
          }
        } else if (typeof a === 'function') {
          t = a
        } else if (a && typeof a === 'object') {
          p = a.prompt || p
          d = a.default || d
          t = a.transform || t
        }
      }
      try {
        return `${this.#unique}-${this.#prompts.length}`
      } finally {
        this.#prompts.push([p, d, t])
      }
    }
  }

  async #walk (o = this.#ctx.res) {
    const keys = Object.keys(o)

    const len = keys.length
    let i = 0

    while (i < len) {
      const k = keys[i]
      const v = o[k]
      i++

      if (v && typeof v === 'object') {
        o[k] = await this.#walk(v)
        continue
      }

      if (v && typeof v === 'string' && v.startsWith(this.#unique)) {
        const n = +v.slice(this.#unique.length + 1)

        // default to the key
        // default to the ctx value, if there is one
        const [prompt = k, def = this.#ctx[k], tx] = this.#prompts[n]

        try {
          o[k] = await this.#prompt(prompt, def, tx)
        } catch (er) {
          if (er.notValid) {
            // eslint-disable-next-line no-console
            console.log(er.message)
            i--
          } else {
            throw er
          }
        }
        continue
      }

      if (typeof v === 'function') {
        // XXX: remove v.length check to remove cb from functions
        // would be a breaking change for `npm init`
        // XXX: if cb is no longer an argument then this.#ctx should
        // be passed in to allow arrow fns to be used and still access ctx
        const fn = v.length ? promisify(v) : v
        o[k] = await fn.call(this.#ctx)
        // back up so that we process this one again.
        // this is because it might return a prompt() call in the cb.
        i--
        continue
      }
    }

    return o
  }

  async #prompt (prompt, def, tx) {
    const res = await read({ prompt: prompt + ':', default: def }).then((r) => tx ? tx(r) : r)
    // XXX: remove this to require throwing an error instead of
    // returning it. would be a breaking change for `npm init`
    if (res instanceof Error && res.notValid) {
      throw res
    }
    return res
  }
}

module.exports = PromZard.promzard
module.exports.fromBuffer = PromZard.fromBuffer
module.exports.PromZard = PromZard
{
  "author": "GitHub Inc.",
  "name": "promzard",
  "description": "prompting wizardly",
  "version": "2.0.0",
  "repository": {
    "url": "git+https://github.com/npm/promzard.git",
    "type": "git"
  },
  "dependencies": {
    "read": "^4.0.0"
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.3.0"
  },
  "main": "lib/index.js",
  "scripts": {
    "test": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "snap": "tap",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "license": "ISC",
  "files": [
    "bin/",
    "lib/"
  ],
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  },
  "tap": {
    "jobs": 1,
    "test-ignore": "fixtures/",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  }
}
language: node_js
node_js:
  - "0.10"

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 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 (50%) 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.

   2. 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.

   3. 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.

   4. 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.

   5. 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.

   6. 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.

   7. 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.

   8. 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.

   9. 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

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (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-2.0

   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.

==============================================================
This product also include the following software:
==============================================================

 QRCode for JavaScript

 Copyright (c) 2009 Kazuhiko Arase

 URL: http://www.d-project.com/

 Licensed under the MIT license:
   http://www.opensource.org/licenses/mit-license.php

 The word "QR Code" is registered trademark of 
 DENSO WAVE INCORPORATED
   http://www.denso-wave.com/qrcode/faqpatent-e.html

Located in ./vendor/QRCode
- project has been modified to work in Node and some refactoring was done for code cleanup
# QRCode Terminal Edition [![Build Status][travis-ci-img]][travis-ci-url]

> Going where no QRCode has gone before.

![Basic Example][basic-example-img]

# Node Library

## Install

Can be installed with:

    $ npm install qrcode-terminal

and used:

    var qrcode = require('qrcode-terminal');

## Usage

To display some data to the terminal just call:

    qrcode.generate('This will be a QRCode, eh!');

You can even specify the error level (default is 'L'):
    
    qrcode.setErrorLevel('Q');
    qrcode.generate('This will be a QRCode with error level Q!');

If you don't want to display to the terminal but just want to string you can provide a callback:

    qrcode.generate('http://github.com', function (qrcode) {
        console.log(qrcode);
    });

If you want to display small output, provide `opts` with `small`:

    qrcode.generate('This will be a small QRCode, eh!', {small: true});

    qrcode.generate('This will be a small QRCode, eh!', {small: true}, function (qrcode) {
        console.log(qrcode)
    });

# Command-Line

## Install

    $ npm install -g qrcode-terminal

## Usage

    $ qrcode-terminal --help
    $ qrcode-terminal 'http://github.com'
    $ echo 'http://github.com' | qrcode-terminal

# Support

- OS X
- Linux
- Windows

# Server-side

[node-qrcode][node-qrcode-url] is a popular server-side QRCode generator that
renders to a `canvas` object.

# Developing

To setup the development envrionment run `npm install`

To run tests run `npm test`

# Contributers

    Gord Tanner 
    Micheal Brooks 

[travis-ci-img]: https://travis-ci.org/gtanner/qrcode-terminal.png
[travis-ci-url]: https://travis-ci.org/gtanner/qrcode-terminal
[basic-example-img]: https://raw.github.com/gtanner/qrcode-terminal/master/example/basic.png
[node-qrcode-url]: https://github.com/soldair/node-qrcode

#!/usr/bin/env node

/*!
 * Module dependencies.
 */

var qrcode = require('../lib/main'),
    path = require('path'),
    fs = require('fs');

/*!
 * Parse the process name
 */

var name = process.argv[1].replace(/^.*[\\\/]/, '').replace('.js', '');

/*!
 * Parse the input
 */

if (process.stdin.isTTY) {
    // called with input as argument, e.g.:
    // ./qrcode-terminal.js "INPUT"

    var input = process.argv[2];
    handleInput(input);
} else {
    // called with piped input, e.g.:
    // echo "INPUT" | ./qrcode-terminal.js

    var readline = require('readline');

    var rlInterface = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false
    });

    rlInterface.on('line', function(line) {
        handleInput(line);
    });
}

/*!
 * Process the input
 */

function handleInput(input) {

    /*!
     * Display help
     */

    if (!input || input === '-h' || input === '--help') {
        help();
        process.exit();
    }

    /*!
     * Display version
     */

    if (input === '-v' || input === '--version') {
        version();
        process.exit();
    }

    /*!
     * Render the QR Code
     */

    qrcode.generate(input);
}

/*!
 * Helper functions
 */

function help() {
    console.log([
        '',
        'Usage: ' + name + ' ',
        '',
        'Options:',
        '  -h, --help           output usage information',
        '  -v, --version        output version number',
        '',
        'Examples:',
        '',
        '  $ ' + name + ' hello',
        '  $ ' + name + ' "hello world"',
        ''
    ].join('\n'));
}

function version() {
    var packagePath = path.join(__dirname, '..', 'package.json'),
        packageJSON = JSON.parse(fs.readFileSync(packagePath), 'utf8');

    console.log(packageJSON.version);
}
var qrcode = require('../lib/main');
qrcode.generate('this is the bomb');
‰PNG


IHDRL½$ì¿iCCPICC ProfileX	­Yy22jç@,í÷¯z‚ÿ…©T¿¿ë¤RƒÿÆõ–„
›†ÆDGP“~ýøÿ|DFÄA{ýº„à“9&ÜÙ¾¹¡Ýý©fÎó@œheû[^kìô[Þkå1'ä<
‰³tý§âÂ] €òïáQ6ë|h'ÍÏÎbˆÅýcL í×ÛÂh$‡¸¸ÿæØššAGƃåô‡ïüGžœbb÷‡Fµ^÷7+ägSéýÒSa±Þ®(”×EÇ:¬ë¹ÞÖCZ„Ýï¾`ƃèæëœuùJ`̯þ®ëâb	åPg”=–î²Î}D‚BÍ­ †º¡Ê!tË?rÃèˆ_c–E]èqNëv‡8(æºnÃuyvÕtݶÐ&h	0T@ÀÐÀ@¶À˜þ~R œeþ 
DÀ›Naûó7‰{Œ{‹{†Á½ø#ƒ%ó@(€ø¯ºþUÊA2øk
1ZÃòaõ±:X[ø4„·*V»éÏ·‡3Wgþàߺò
¿ë6þ­}ü¿µ÷	M£ÿ·2~—øŸ:™ƒqhà?åZåiåïÊÿÓc¼Þo‰7ÇË ûÐKhÚŽÞE[Ñ«€‚ÞD›Ñ^´mÿÖëO+T(Y·Êº…c€
´b ˆûõ‹ö§½ÿ°RÜߌß5°Ê²ª'XŠÂá·Ð¿[pû¥uèÿ¨%2ü`‹akó·?~ë…•„ÖUÇcõ ¡±ÜX> €Ý-n„5€>P‡Ò¼øŸ½QA¿¬ÿ«/á`ö#2601Ž%`D
‰¥ÁÕ2PžbEóW”§¨*«¨õµwÀ‚Ó¯5áîûG¬
€ú<ëRÿÈBpÎ+Âöd’p°¶p7ß?ŽÿW}Øõœ¼@ˆihU ×xC`¬=pžÀŽá	5N;A*ÈÀ!pRP΂ó \­ tƒûàx^0>€9ð¬"B@X2‹#ˆ¢Šh!úˆb‹8!žˆ/ŒÐ8d'’Ž@Ž EÈi¤¹ˆ\CÚ‘»Ècä2ŠL#Ÿ‘ŠaÆpb1’%ŒÆcƒqÁlÃc¶c’1˜\L!¦S‡i´cîcžaF00‹(@™PnTU@µPÔõBƒP:š‚f£h9Z¶À±øAgÐe,KÆR°
Г–XW¬?v;6›ƒ-žÅ6a;±O°£Ø9ìON'‡ÓÆYáÎ眿º»ä¹¼r•vsípcsÛêVã¶änê~Ä}ÄCÉc—Ç}O>ÏPÏf/‚—›W•×â³-ǶLlUßš¹u`›Ô¶Ämw½ù¼#¼Û|Ø|¨>—|q¾î¾ç|¿Sí©åÔE?+¿¿9ÿãþò¦õ¾Ò:4¬|4x:Ä ¤ d&Ô$´(t>Ì2¬4l)Ü>¼:|-Â=¢!’!Ò7òƒN댊JŒz-=²]{û±ístzU³-¦9–r{ã¤ãöÆÆëÇÇKpK¸”HJ¤%ö&É&íOz—lž|fv‡ÿŽŽ";SwŽî2Úu:IñKéØ-¶;c÷Ä‹=gS‰©á©Ò”ÓŽ¤}IwOoÉÌØ“1¶×bom&k&=s0K'«tv_辇ûÕöŸØÿ3; ûÞå¾çøçÜ;¨r°ðàZnPîÃ<¼S‡ð‡h‡>{„t$ùÈØÑÍG›ò)ùÙù_Žù»[°± ô8ñxÜñ‘BÛÂæâ'ø^Rô¬Ø¸¸¡D dÉÒÉ€“ý§OÕ—
–(])-{~ÚâtS¹dyA¾"¾b²Ò­²çŒÖ™š*¾ªU?ªiÕ#gÎvÖhÖÔœ8—W‹©«®ÛZ÷è¼éùæz…úÓ
Ü
.€qÞ_ô½8ÐhÓØqIëRýe‰Ë%WÈW²›¦¤¦¹«!WGš=›_³¾ÖÑ¢ÓråºâõêV‘Öâ6®¶¼Ä7Ön&ß\¼}k¦=¸}¬Ã§ãÕmÛO;;vÙtÝé6ï¾ÝcÔsóŽÞÖ»Úw¯ÝÓºwõ¾Æý¦^õÞ+Ô\y¨ñ°©O³¯ùѦG-ußè7èobú¤û©ÕÓûÏìž=px>¸upäyÀó©/æ_Æ¿\}µç5îuöûPÁ°Àpù™7
##m£¦£½oß¾óû03þ}"c’e²àð»š)Õ©ÖióéGï·¼Ÿøýau&ó#écɬôìåO†Ÿzç<æ&æéókŸsxª¿lüÒ±è°8ü5òëêRö7Þog—µ–{VÜWÞ­&|'|/ü!ó£å§ÍÏ×k‘kkÑT:õ×Y…OLPŸ«a\ä	ùDÖ¿b£_xÜE b7d?f;ªO?¸;øjBCc q“+³#‹«›»/)„ƒFÎäìâ&mØÂSÅ;ϯ+%øBX™’"òTLN<]bHJ[ºP櫜‹üeE.¥$åQU[µFuLÍO›\´[uEõöéÏ:]1á1M4{a¡eyÜjÑÆÅ¶vó˜=ÙÁÈ1Òé¸s»Ë¤Ñ]ÆÃÜÓÛ‹¾%}ë¡mÅÞ§}ª|ÏR«ýªý+N
ÚLñµÓ
—‹àdŠ\¡MG=îÙ~•^S»7.6Þ?Á)Ñ(I>yÃdÇÌÎÁ]í)u»ïIMLóH7ÉPÜË—‰ËœÏz½ïÎþËÙerrÌËÍÍË=”{øà‘G÷å§ÛU{<¢Ðï„[‘U±N‰üISL§VJ'Ëž¾T^X±³ÒïŒe•b5gõêÙ·5÷Î]¬-ªK;QïÚ`pAæ"ùâÏÆ©KO.7_)iÚsÕ¿ÙìšTCËÔõžÖ3m©7¶ÞÔ¼Å~kº½½£ð6­Ó¤‹·k¾ûQÏ¥;w“ïyß7î•~Àú`ñáë¾ÎGuõ§<	~êðL{@lepéùè‹þ—¯_—Þó&jdÛ¨õ[õ1Ê8qüóċɛï*§²¦Ãßoþ 8Ã<3ø±l6ü“ænnp¾îsÆ‚ï£E‰¯l_,Í}›Z~»òvuìûä?¿¬­ýò¿ÆUBg±í¸,¼3A‘‹ác7±Š)‡9žÅ‡Õ’M“]ÄDúIVâôæÊçîåAy5ùBøO	ñ	;RrEzňâ{%ïJ3ÈXËæÊ=UVQº¢‚ªÚ«Ø8¦¡ ™ Õ¡Í¤ã¬[¬7j ciÔh¼lªo–nÞjñÜrÚê›
Þ–´YÈNÊ^ÉAÍQÃIÃYÍEÁUÂßÍx|òöz°¥eëém{¼·ø¨û²ùNS;ýÊüw¸*ƒ&‚o…‡&„9†ËG"ÞF¶ÑNDÑ£m·KÒýe̥؃qÁñF	ü	_&U'§íزsã.æ]“)7wî‰IõHÓOË`ȘÝû4³%«lßÞýáÙÔsxsÖŽçÞÉ«?täpü‘-G
ò)ÇÀ±77—¦ž ‹•`K&Nöœª)=PF;íP®VÁUñ­òÕ™UåÕigýjŒÏ‰Ö¢µcu·ÏWÖ§7\0½(Þˆm¿ÔuùÌ•Œ¦€«¦Íâ×ð×fZž]¿ÑZÓvôFÊÍð[žíš·¥;ùºX»1ÝßzfïLܺ7p¿¯÷îƒÞ‡}}=y<ÐÿüÉ˧¯Ÿ
Œ¾}>þbòå»Wï_ÏÍ
/¼ù:²ü“·›Hš¬~÷bšôÞîÃᙳ²ŸÒçÆ>Û.\_TûÚðMmùúªù÷ÁŸ¡¿ý¯ˆ|ÀœD±Øk¸x¼~žÐÌÂhI Î1u2°„±š±‰°ý$á9¸É²œ›¸Ì¸Ý6„ñìá=Æwž¿K`XpE˜“¢,b'%–+~^¢OrAšGÆ@6X.Gþ‚ âesÕµìuê4f´˜7Ik[êèîÖ+ѯ7¨5^[˜t¼ˆ³hîš»NÚžâ;5UÚT–qÚ¹\¢|µb ò™쪀jƒ³üg¿ÖôŸk¨Í©=oQ/Ù€m¿pûbEcú¥€ËÖW´›”¯J5_ãiá¼Nj%µqÞà¿)qKµÝ´ÃóvLg^WCwÏò]ʽm÷GìëÛøh¢¿ìið€þsÙ—
¯7ç|Û5©0
>,|"~6ZÌû¶ð=jÝÿåÈÖ÷¼•0'âöט¿°„Ü?zp`ÀeÀì˜
D€äôþ½ pÁ&˜MáƒÙ% ãLOqïy0š¼ãÇiEøa”hø#»Bä2Œ?aX1
˜Í˜(ÌaÌeÌsÌTµB£ÑB˜Iø÷"c,
[‚½‡]ÆIø,׊û„Ã{àsñÝøŸMpžðžAŠ!ˆ¡
®V2Œ‘Œ—ˆúÄLbS ÓEf<3•¹E€e'ËVÖ62[
ÛGvoö'$R7ŒeºÉ¶ägœTÎy®tn^6|ã)ãµæ]â«æ÷`èLÒZn¡ì1e}.V%ž a-).…HHwÈTÕ.Q>PÁYÑLI[YEEVURMb£”ºœ†ª¦Ž–Ê&m	1]q=i}%mCk£­Æ±&y¦õfýæ+–’VnÖÙ6¶?ìLí8Œ9i9„»Ÿ‘{©ÇšuK÷6ï_„å÷&À)°'Ø0äZ˜QxoäVÚ\ô~ºdÌݸí	‰O“swÚ§pî~“z!=k¯_–á~–ìÁœòܨC†GHGÇ];žw"¤Øä$åÔZÙhyWe}UáÙ½çâê¼êM.(5
_æh"6ãZð­,7xoÉu˜tR»3ï4Þ{û€·ÏõqÁS¾êj¯®k\Èz÷ö½ÚLòlóÜìeÑz)fùÄêõ#¿Ö ÐÿÌ€a¾a#̘8ÜH"8*aa, ìˆ4bŒlE‘|¤úþ3†ŒQÇx`vÂøþfåAÑHôÚ.`Å°ÎØŸOèÜÆâm¸/x|0¾ÿ† HØJ(!1PjæµS{‰<Ä@â%&”É…©ŠÃÌüE‹¥F½é¬Kl‘lïØýÙÇHÁ¤YŽ$2|‚S‰óWŒG«6¸òynóîæÓãûÉß!-è"$"4/ÜE)‰uSçÿ*1"ù@ªUºA¦J¶T®D¾Xá”b¥R½r‹Ê=ÕaµEu6
yM-ïMqÚy:µº÷ôfH†ÚFÆù&ݦ«æª4ËZ«6ª¶‰›»ìy¶;ö:˸ìsqwôhñ’Ü’¿
çè3K
ñð™KàŒ¬2¥§ÆŠÇõ&Ä%‰%?ݹ/Å`÷rjszÒ^ƒ,ü¾î쌓\4¯çpöQ»cä‚…¥EA%
'KÛNgU8®š9{ýÜ:»zrÃÐÅšK	W,¯ò7Ï·Üo­º±÷V`‡U§R7÷äîÌý—î÷µ=¾ø„þLaàÝó²—CWßø2¾=7n91üŽ6µò>mý¸gvu.z~lÁåË­¯rKË`%xõÁõŸÅ¿ýŒ€øÌ4™Ã¹	ÒA1hý`ú^±‚¡,˜êEæ0\]Læ ¦3Ž’PC8ãO£O°¬.6{;†„³=×çÀ;ãá_„	A„Â
Ì¢ä3Œ3j0îg|CT'槙̘*˜™˜w1f	c™„ù)¶(¶Uö’é&‡™‰ÜÂÅ%ÇõÎìT7^e>V¾9þAÁF¡*áRJ±ÈIÑ
±zñV‰»’ƒRÓ2ˆ¬€œŽ¼Â>Å+J“*ªîjÇ7¾Ò׌ֺ¡MÒ	ÕíÒ7Øo¸`ìg2`foÞkio5`ão»`G³Ÿpôqvñqtòøéuh«Ô¶v_*Ö¯6À=|=4:\*b”VÏæR1óq7ò’üwèîâNYÜó<íFFMfÁ¾äl×Õ\rÞ·ÃÃG{Ž5/;q¨8íd|iÄéÀ
ß3>ÕÞ5ÔZçó*
l>6ö^>×”Õì×¢ÝÊÖ6r³¾=ñ¶^è¾ygÇ=õû”÷y>fíßÿäþ3d@s0âyÙ‹þWàµÂËp›‚‘úÑö·ÆÆŸM<žì|×8U2½ë½ÏuxbúX=Kÿ¤ñéÛܵùØÏŠŸ§J¾Ø/b/|ݶD\ºümÛ2~ùüŠÓÊ·Õ“ß
¾þHÿ)ö³cÍwÝÿ1Aj0g	/„Ù¦‡×Ö$a®ò?¯­­–¯­ý¨€ÁÆknEüõ¿Ë:sõ%Më¨Û$cÏúûß×¶ýÆ$ÕÅ­@IDATx콘eUuï;è®~Ó@·ÍÓ†èØ( †ÆH©`†V‰
IˆÜË	z
W#ƃ‡/_D¼$DGŒ£ ˆ‘>>°Q
E@D¤y#4ÏæÕïgþ×®ÕìÕk?ªvÕ®Þìßü¾µç˜cŽ9朿9×ÚkÔÚ{×v/¼ðB @€ @`k“¶V¡ @€  `b@€ @¨C€€©Ô€ @€˜Ø€ @€ê `ª5 @€ &ö @€ :˜ê€A
@€ @ ­Ø.¥Ö,±‚ @€À¶O ý?Vþ!kË´]/q"èiaG`@€ &z)ØzQLDMv6Õ€ @èS@ÕµSƒ#>Š×“Š. @€&Œ@G>š×­ATWLc$MØùHÇ€ @]L`L‚«n
ž¶ù€© i¼ƒ¢ñößÅçC‡ @Ø	ŒI°Ó`^£ò¿­OÛdÀ4Š ©Ýà¥Ýö
ö
U€ @èZ£
‚²Ùލý¶©ƒ @€Àxh´Ô뿪]•.o_¯¾ž^mÕ
ùîäÓ¦ŽL-K‘zu­êëÙ
OB+6¹}•<>ªü¢ƒ @€@+Z
:š8jÅGÙ¦\v#Õ«]½6öÙ±§M	˜Z–UuU:ÁËõ¹<vPhTgÛF6êÜž€ @ÛFH£:Ï£‘M^—Ën«¼J_¥s›Fu	šÆ=`j#Xª
JšéšÕ|ž—۔˹m#y´íù¤€ @£%Ð0Øhà´Ü®\.7­ªÏu¹ì¶­êd_ek?ã4kÀÔ$Xª`TééÕ
rÛ\.Û©\¯¾ž~$>ªlÑA€ @`´%§õlëéÝ<¯Ïe×+¯Ò[ç¼UûÜ®žïÂf<¿Ó4nÓ8KXœd¹,}®Ëe·)Û´RÎÛ6’ëõר
u€ @-ª€¤_åvÍÊö™ÛårU½t¶q^Ï.·µór[ëÇíIÓ¸Lc,•—N£òhëì[yÙ‡ëêé]O@€ m‰@½`£U}n—Ëšc^Îår]^nÕNmòTn7T7OšÆ<`E°Tx”u.;”\ÎË­èË6yû²¬rUªòQe‡€ @ÛºF6¸Ü&—m’ë,;/ÛÔÓËÎuÎËm]Îm›éŠú±šúò^ÇY®
0šé\ï\CÌe—«t®ËsÉJ¹}.×jk¯¹>—ëÙäzd@€ lK˜TÝÓæKÙÆö¹M>'Õ»m\–ë]—û³l¹e×ÙËÊ«tyý˜Écú„©ÁÓ¥2O2ŸHÙÆeçå6Òçu®·Î¹ûpÙ¹õn—çe9·Íå*_#©Ïm‘!@€ 0Zå £ì§Y½ìsËÎsÖ9wËÊ-çu¹®JÎuj׬\eSô7–O™Æ,`‡`)Fªä²Îeç‚%9/[§\ÉuÎkÚÚkY׬œ·E† @€À¶F YR®×ø­sžë,ÊôRUo×ÙvÜòñ˜rОX>‘¼Þ²óÜÞº<—œ—ëÙÛ¦^½ôJ¶sžëʲÊN¹½uyÞ¬>·E† @€Àh	Ô |?š×[§¾r}=Yvj£zçÒ9Y—·wsÛ¨l?®sÙímë\v¹ÜJÙ¾ÛÎÛþH^ãiBå”ëªäzº²^eëʲúl¦ó¸êÙ¹ÞyÞ—uÊ­·®\¶ž€ @AÀˆû®W.ëeo]ž[ÎýY—ç¹l_¹N²ËUõ¹×—ue}U}¡k÷»Lm=aª,y°yžUr=õy.9/«ëêé§&›Yé˜3h›²¡6–ó\²RÙ_®+2—óÜís2 @€Æš@€”}—ëò²eçnëržçòÓÉðùt¬O‡õn«{`ë”7º'Îë-»­ý8—ÿz²ê*“b–v‚¦¶¦Êm
$T%[ç\n%»l¹\ÎíÊu.ËfZ:^ò7ó7}èCzE‚õÎT^¤Šª”ê#1­ª•.÷gÙùH6jç1ÛFy£$ûf6Ú»n,üxÌö©|4~ÝF¹RÕüªú*Œ_šÕ維ȹ?ËÎ[iŸÛ4j—ÏÙò¶e¹›r›ªòXø©š×hüºr%ù-§ª¾r›fõ¹m+rîϲóVÚç6Úås6‡¼mYnŦܦª<~ªæ5¿n£\I~Ë©ª¯Ü¦Y}nÛŠœû³ì¼•ö¹M£vùœÍ!o[–[±)·©*…ŸªyƯÛ(W’ßrªê+·iVŸÛ¶"çþ,;o¥}nÓ¨]>gsÈÛ–åVlÊmªÊcá§j^£ñë6ʕ䷜ªúÊmšÕ維ȹ?ËÎ[iŸÛ4j—ÏÙò¶e¹›r›r9ù¸cÒ¤I_ÿô§?}ûYgõóTÿD:Ö¥£¶i	’ìE./§âPr²ÉÛ—e×—ýªm,][©­ä%`žL>ˆ\—˲ÉË’ËeÛXo›r9·+וËsR°tè_þå_¾gýúõ¿«†›6mR6”òÍ£M™6AQ'¹œ¬s.[ÉF±yóæ˜óoŸøÄ'nHþV¦Co"~#±Ü¬¬¡Ô³ur%ÛÕJÃ}U•ݯë´G¶Ò
U6F0%ˆ[ïàĽÔ_^.Ë岚Jg½åª²ëò6õìö\±bÅ;Sô0^h5´¬©øM4Ÿ–ëe«dÎyÐ#½OD×ÛŸÛÛ§ËÊuäo̶Éû‘ì¾$+å>jš-uö©1•Ûæö’ó>=f·W?NªsÙr^–Îzõ+9O³tnç±)¯jc}©måÇýå¹ôJ²µ½åÜOYVYý)¹N²Ú–ËÒ{ì®S[݈É^ÉþÜÞv.+×!?JÖ…Á²e÷å²m•;å:ûÔ˜Êms{É—e·Q9÷/;—-çe鬗Éyòør¿›òª6ÖÙ—|ØV~Ü_ž»OÙÚÞrî§,«¬þì7÷c[éäKÉcwÚ²þµ=âu+@
¾ˆ›Y•zM]ïvöc½ÚÙV6ÒÛ¯s·UÙö–s?eYeÖ¿Æ@Œ•ÄÍɬU¶ìz•}Hçus[åÒËÆ²rŸC^S×FéÅ~¬—ÛÊFzûuî¶*ÛÞrî§,«Ìú³þÞWù>ò^‘N{IÉ{×uÚ;½|ý×ÜSàtî.»ìòÕ„çÁtT~¤bòmÙ¹N¹RÞÆå¢b°Îr¹®Ð§µTû§±˜¶¼KJ×´l4e¹\–©tÖ[®*»Nmtu¯g£zÕíóðÃaãÆ/—BÉ^3ÓÆ·ìº\'¹ê‚*_¶S®$?¹®ÜÖõeÒ«oûð8T¶÷¡<×Y/¹ûS_–‹Ò‹ì””ç'{¡L/ò©:µµÕY¶^~s_®—ξ=Wûvî>ò6’=^µwûËëåG6ƒžæc‘ë”çIvòg½meãº\ç>U/9O¶³^>sdÏ?×ç:ùóXs9·‘ì>”Û¯e·sÿ²×\”r¹P¤Ï]9ëÏùïýàý¡}%]¾ïT'½’õù9'{×KÖ¡½%Ûªä>ò6’½_sî/¯—OÙhœÿ5ff†b”Ë*+ÉÎ9ç?ç¿÷C±)Ò‹ÏMŸw¹^²õœÿµ½S¾†ù<ôõJÌÌ´¬Sìý~mYŒ•l¯Üå\g½Ú¹ßüœÏåÂAz‘’ò±8ÿSÀôë=öØã½Éå=r+ß))Ïëü†×Y¶MUÙuÊ•r—‹ŠÁ:Ëå:Í[mGœF0¥Úò®±ÖmYç²sYI.—ËzÛØ./WÉn_/xÚçž{îYæ\C+åÒy³¸¬Ü²/fë
]Þ€²—ôÊe—Û¸½jŸÅ S;½Ñ{²“/۩ξó¼0H/ÒÙÆc“Áþ4%ûVY}*·Nõ¶w_.«N¶*ëlžr[ÛËVã±o••<ϼ½Ç ¶æ–·“lf²Uÿncv.{,¹éTï±ÙÆzÉeå–ݯÚ*©¬$–U–½lÜêr·—­}ºç òe;¯­õ΃ô"[Ûx<öã~<µ±oõçü×>ðžÐþðþ’ÎûÈõÞÛœÿœÿÚ+Nù^ñþñµ/ß;²÷µÖm•{ª­¯›y;ɾ–É–ëíýAìĆëÿð}ŒxhåI:_»$ÛÆzïI—mã=ìë |ú=ÖuîÇ>Ý÷±íó1y/«­ÚmËïÿÏ>ûl\rÉ%±nݺâÜÕ˜=§çŸ>Î<óÌ!žªÛ{ï½OÙ=ép ãÅP®›À¼œÛ”ådZé#o/%·­•¶ìÃ:ÛåeíûÛBߨ0VÓðY\ë-/—e—ó¼,W•¥é¡Ñì{×]w]ëAŒ$+Y6·§W¬ˆ;—]÷ÞzK¬¸çžb%vßgŸXðªƒâo|cì¸ë®E;½xãûdq…ËÊŸ~"ù»åºxè×·ÄãÜ]˜¼dÏ}b¯EÇË_ý†ØiÞn[l8ÃR¹N@'É?ùXÜø‹øå½·Åý¿y Um޽^ú²xåˈ׾êõ±ëλ
]0ò¹é¤ôŽõògêÃóQ½Ç¡\É:]\ò²dù(û’·úÎ}[ö…Â>”ÛÚºoéÝFõƒÛæöy{É³ÚævÒË¿mÊ}Ù‹êݾjLåö.+wv—ûÊuö«\ãUò¸mç1¸,_e*ç¾\fýk{Ý<”+‰•uæZÎUoöf+ïÉr{—•+åmr_Eez±½m{iý×=uOܱbz¼úU{…®,æœ3³V}+çÿêÇïŠ_=2-^uÀü˜Âù_\/¹þoy³ìó­¼×¤ÏS~Îæç²÷d¹½ËÊ•ò6¹/÷a{ÛöÒùïû	³«óß,Å^<Ë~ÝŸêsþ^“{|p¼æ„b¯,6‰nB•ÔÖI²ôòÿà]·Å-ß»ôfëyÙ/.{¬.+W²ÿeÐíl¯¾¤sŸn“­p4øâ&ÕNv^‹ÜwîϾìGvJ¶)×ÛNcw²rîS²“õ‡ô’ek†Ö™‹êÕÎcQ½ê¤³oÛZoʽ.²U½’eû,ûñümg¿¶s;é%{ìn'½d÷çöEçéÅz•%ë`ýk瘘¸Hw373é¼f¨Ü:¯ÅÄ­ÿñëk/Ïÿ¯¯Å=ÏiÔ¿ó´ø‹Þ³Ó8<öªõ¿óÒÿûÆñùËOŒYiŸynž§ÛÚ—òVÎÿ_é”ä÷wã_ÿãOcvj#¿òådvf^®·]ÞÆ6ÊupþsþkŸh/8y_øü–^2×®ÿ~õžðµMûCûÆ×"Õ«N:ï-ÛZoÊÇûú¯>Ó¥Å
7Ü3fÌP—Åøžyæ™X²dÉPYcMÓ‘I¡€©ü4)/[Ö¹Ù!ÿ~jÛJ¯ä‹ºëjÚa}nS–5·w»¦ù–Ÿ¯jj^\ †¯-Ø71‘¯ÜŸeë厚ÙLJß_*Ù|ü†©±i£>ûØcñ“/ý{\Ÿë‹	¤ÕiÍÝ'ë_»Nh´&b&™ëÿðû¾¯´_”¸þóþ_l„Á½ sÆçŽöˆß“­÷õι¯?yÙçßx¾ÿëIÒ7¿ùÍØ'}ÒÊç¼Æ"Y×rÏaðü×Mˆo®ò F:—-;2–ª\mtãR»ù«É²sYò¨Sš‡È׈¦Œ®v‡Vk Ùå‰4Î[~õ“¸ã‰_Åë^û-Ø'ØðPÜùø=…¿}SãÀ—-ЇŽþMüèê›ãÆÛ®7öö¢NãñY­óÚ_¼${ókÛ…9Iç“Á¶f%[µUÙuÊ}Òª^íåK²}Ë&ŸŸ×AílÈNI¹ÇQ(Ò‹úÊý¨œOv“êÜ·r÷)ùp¿ö—û–Îv…^ToŸÒù!Ùzë4Ëö%;AzN¹ì1x¬·ÇjŸj+Ùö*ËVýÚÖóRõ’ܯêd«²ÛÈ—’t9_ÙªO÷ë²l%+±þ›
bg¶˜ô"®ÒëpÊes•då:¼¦ö©¶’m¯²ìÔŸm½–ª³^²“ûõUvùR’®ùúï'~í±ã”Mñüªõ±÷»?ú“wÇå·ÜÏÿÑ+Š'Fòkßò+ÿž_1ÞôA¼)“ÓLu/è©é°¬}ï¤}/½Ùçë Ùçs~~Hö9mŸng{•eçó¼|¾Y/;'Au²WÙç¨|)I×üügý{aý¿õ­oÅîéæºzõêb¯é£yÞ+ÚGJzÿOI—òâž[…”´¡t"(—¾¶Á’’lór¡lò"_µWó+¹¬“ë%i‹€ÉÐÀrÙÍu–•—eëéUçE)ËUeé&ë‚ Ö…@¹Ûž•éÉÒ«fΈÝô¦ý‹_Æv;ì“fL/Æ¿yÍÚØ”¾ü¶Û¦qàôñØÏoŽ­8¾àÈŸ.nÊåó™‡~Îß1v˜5=6ßwWLÚ>ù›:èoúØüü³El~>b·ys-À):L/¾€i3Ê߯¾#^òòy1k‡qû£wÅìé³cj
2”ݰ>ž]ó\ÌØafÌ[4/–¯øõÐ8Tï
-?Jò­CãUÒF7‡B‘^<ÛJ/Ç%ûü‚›·“ì:ûµå¾@{\²×ÅÙ¶ÊsYõêÛÉc°>÷ã7˜|üª÷ÚÔ[ù²_õÏÕãUî>Ëó‘½ûðØe£¤²ÛæAEQYçÅcÑØÕÞ¹ÌÕ—ça;•eã²sÙK¯$?JªÓÁúטˆ…¹ˆ‘Ö¿vó^ŸœImO¦ëسëãѾˆ5cÚÌtS¸&½¥¤=·9q•}8×^•\ìט“foˆ_üèÒøì¾_¬Ãüßù“øNþÝØ1Ù<ù«kâs}-ZUTžo8)N=±?v(öòÓñÃ/ÿK\ò½»k•/=&þéì£cfj—FŸü¦Yßþ­øìy_‹ÕÉâ¥oxwü¿ï~CìÎÍEÉ㓬1©¬#Ÿ«Ç«\Éuù|¤ãü¾N—¯Ef¥Ü<}]S®ÿ¢0œ¼ÅHûѹ,´×ÄÐûPõ*—™K¯dÎ.{-¸þsþk4»ÿÓ³u(XÒýßÿýßk¯½6Ö®]»EP-_)é¦RJ½+è°œÄ-ʾ¡S½eÙäIík›8×ÖüXoåJÒ[.%]U½íZÊÇ"`j¥#O°ÊVuù!Ìu–s}YVYi+½.¾Àøb¤ˆ7ËæûŒ—§iöê51õÉ'#Ö®‰HÁQá,ÉSW­‰Ù)pzùÌiñÈ8š..f¾ØË¿ûذúáØ}¯¹1múvÑkb»MéFbCíãbÛm\“^X]ÔÉæö‡..jjë7e¿±¨éW®~4v? }giƤX·ÝºôÈ,bý†ZÀ´aÓ†B·]êk·½v‰•?}¬hãñ訹úBé~|Õgk]g‡ÛØ^c±NöNn«r®wÙm”+y-Ô¯Ëjçï8H6µQÿJnï²rûp¿òíþò÷);²Ñ‘ÏWzÙ©d÷#Æ#’rËòQµþ…azQ»Ü§Ú©O垣}©¿\gYúÜ^}ʧ’ôyÙL¤—¬ƒõ¯ñ2G3cýkv;çÚ^CçÆú®/ß?)v?ö ˜™ö¸®vfí\{V{whŸ*`zìªøÜÅ┿þDìpÿ÷ã¼ô=Òœ3/>~Ì+bíÓkã·ÿø#ñáßÙ'ÿÑ?ÇÿüâãÆ×¿:Þ¸×ÔX{ÿ
qéî‹“>þ™xýÎkãžûÒu6½¡oHçÇææÆäÇ¿Ÿþ̬8öƒ‹—Þÿµ8ÿk—Æõ‡-Ž#÷œÂùŸÝ`·³þZO­­Ë…0øâuw.u¾þ.«žë?×_£ýÞ§k´tJ’•\ö5D:ï?í-Ù©Ìûëïÿú5¼í·ß~‹û!süßùøÉO~sÒWQÞúÖ·ü4éczâìCë’î½4iÑtQÐ!ÙºÚbÖìªäd:”äK6µ…Ro¹Fvµ‘5ã(`J˃ÏËU²t¹^SÈue¹^½ìÊÛJ_¯N6CO˜ä\'šNHå¾9žž>¿±ã´15mš˜53}±(KÓÒ!Mwrrì§NÚ.vJÅéëÓçíS[ûñÉ­a§©Ó¦ÄÔ9ÛGßN³£OO«ä+}tNiòÆô$jZ:’Û©s =_ørÛ|ê ò´Sc§ígÅìô¥»Ù)›>yj:¦uë6§±LIÎÒ–ÜiöÚX5ý™¡7%-—Æ)J[/ßð_T/êÓýšæfY>Toû<P_N¶7§<—^û”_A~¬÷›©ýKï:ÙÉÚJ§¹Ú‡û”Þm­Sî1j,Jjë1¨,Y¾=Gý¥E²ý©N‡’ôNª—^}èߘxŒÒyœö¡öƒ×Ký«½õj›ËªS[·‘?ùõøœÛŸÛN_<=õ«6æ#Ëò¡zÛ«N¶žoQ1èKz1ÏåCãtû”_A~¬gýkûB<”ÄU²™ª¬Cì&býW?p]|2=É™üÊ?‹sÞµW<ÿäê¡ýâ1æ¹Æ®qn~!ýñhÒ¡ñéË>óV?xOüÙO~ÿ~Û=ñÌÛ^ÞôîxÅkâé§ž]÷?,vœüóXûÂú4×ôÇ¢tÍÖþ¹ãgwÄ~Gû½2}däù5Å“­I“ôÝÆÝ⿟÷Ñ¿ÃúØôªb÷¯"}Ÿi]Ú»µsVãñžÖXÌÕ{PeÉêÃ{œóË?ЈŸÙø\.@¦³Í×Ý6^ÿ¼,Öf¯\Iv’9ÿ‡ÏyqÙÖÎÇk©ñ)±þÝóþÿå/9Ž?þøØ!Ý«ê;Kßþö·‹¼¿¿?=ôÐ80ýЙÎçŸ~ºØ{ZoOºnæç¿–=z“ÒM‘¦$ríF©I§²osYuj+?:,;Ïu©º¨W®¤:%Û*Wr›²¬k̈¾Ç4¢€©èºù‹]¶”Þ‡êÊr•Î6y.¸.{T¶^¹ÒPyÍš5ÅE×oŒ:¹uøKóöÝ'žyü‰q쑾0sæFÚ=©—äö¹ôPO­Œ˜òt<“6ÍŒ=æ%³Ð…]É7-3çΧ7¯Ž=gn“Ò:¦Ì*lbêØnÊóé©Ó†x&¦Æ¬—ì9t³-?ò¡7%õ!Ý.;íñü昑¥¦Îˆ¦ÌŽY“S`—ÒªM«ãéõÏÆ&ݰ¯Ú»îlSÒFöEKå|Œž·ô~CR¿J¾‘,âä1©No^j#r'ùTº©gÕùÍR²Gme+ßÊÝV²Ú¨^ý¨%=þõ›¦Êª×¡$j“ûSÙówßj_µþòá~-Ë·Ú©dµÓ¼4ÙªÎ7Oª—N©,ÛŸrùltx<Òy=\¯ñ+™—dÍ3ŸS®³O·ËmU§”ÑýIŸÏSeùP¿J¬?믽¤=¤}¡CûV{F:åÝ|e|ú?â·Þ~züõñû§Ðy¶åóóéiùìtý{à¾x4]Ò·ÛnrìyЮ1éûÓcjòÿþ=þíóߎÇÒ92}ÎŒX“òôîVøï[ð¦8ýí÷Å?}óóñ³o}>vYüÎ8õÙÉfÓæ51i×Ã‾'âѧҵgÝ31S󨼱h«9éÐy ¤sÃçŽÏÁü¼àü¯¿þÀôâk8×ÿá÷ï-å\ÿyÿ÷µE×ÎméýÞ¼yñõ¯=Þ˜þuÎw¾óHÿ€¶8n¾ùæØÿtMOO |ôõ_û9Oƒ×RÝsëÐM‡nbj'ÃpÙ÷ä¾qTÙA“m“ªh'ÖYv.›\vYyžÔ^vc–Æ*`òÄòIW¥·ëKoY¹`*•eÛ¾ë«r늛?¿á+÷͸6ÂŒW¾2¹áÇñòy;§7æ"öH?þ’y©çÔü©H¥@e픩ñÈ3ÏŬ´|Cª¯Ce%å*ÏÚe¿xì¹bmú+èÔ}±Ý´0MK˜’îEÓ_VU÷èšõÉvñÐ͇nT56I‡6¡6肹ûÆ=OÝÓ7÷Ŭí¦ÇN
˜¦¤À.¥¾
ú+ßúX³iM¬{bMìý’Š‹³ê4Gµ×˜|CÏ[6ªÓæ÷Mrn+Y7yrYãS½%3И%»?岑½eÙçõ¹/Ùj,öã¶£Æ/{¹{lj#ÿö«þÔN:ñPn²õØ¥Wß.ËF>=ûS½êÔ6oïqÈOîÃr>fùUÙmäOý¨­íÌÀýz^Ê•äòÊj›·—OÖ¿ÆJ,Ćõ¯ýB{JIûÇç–ËâdÙçT¡H/.«ýêû¾ç}åÇñš?ÿûxÿvˆ?Uü*ö´}(W²·,_…œ.í“'§?¬¤|Rq.­Ž_ýìɘ”þ¶´úù»â‹ÿïˆ7ÿU|ñ¤ƒÓ˜îŽÿqÒYÅÛkÑvÕºXtì‡âKï\·,ýBü—_ß=øñûlŸ~<"Dk7ÄSé{U
¼”Ö¦1¥N‡Æ¡ý ¤±ùü”_Îÿá÷
±ñz°Ò‹Ëù5Iufèk–X*k•üT­¿ës_êÓ×[_Uï=ªuSÙ‡Æc;M>Ô¯ýªÎÿÚzxß‹’X™­Ë^;Ö¿7ÞÿõžøÒ—¾4¾÷½ïÅüùócæÌ™Å‡÷ÜsÏ¡ó½Ø,é%?Ǽ_”žÿºÖ¡‹®6˜6ÊyžŠC:ɲ“½írYõJöW+Õ^¥«Jµ]k“×»Ÿ\7b¹€Ék¥SÛ–ó¼­êÊõ‚hd—ëɲ­ª+. ºøð^Ž]yM<òÈÃqSúÆï¼K
š^Û¥jHWÜtAIo¶›^ˆ›[Ïí5?v=xqq‘]Ø}QV®7évÝûàxø¶âç÷®ˆƒÒ“ªÓÒM÷µ–~¹i͆Mñó{ç¶Û#}×é ¡‹»|æR>¥{ùžûÇ“¿^¿ùÕŠØùÕsRü–nêû4ÍmJغ(êvÜ´sú½W
š£.ò)_>¤w?ò!½ìÌD²û¶Îvº¸*Y¯ñéÂ*{§òXLd§Ãvjï~Ô^ÉeÙHWU–íÅ['»ì¤S?Ê݇߼՗ûwîñËV‡Ç¦Üþ¥—ý¨o•Uïþdã>m'øÚÎeµ—ì6ª—|J§¾½.ö©\óÓÜtè¿nkβ3Wù•ì¶ž‹üª­ôîW¹ô¶õ˜d'½’dÇ:Û±þ¬¿ö¤‹«¾pm±L¿;¾û½ÕÅ÷–bÚ¼ØwÁܘ:yCüøËÆ6¼&>ðžÃÒ{¶>ÿ7ÇÜè[wM\öýâèô=¥çîYKë‹EtPzRôtLMûü…µÄÏo½1î^öx$•_¶úÙt^ÍõßßúÙ¯cÿE/‹Y»¾4ãÖØ1}tY{?Ò“ª)}隦ëqÚÓéìŠÉ©ívé¬zÞ×>/|Î(×9çý.;Ÿ×żSYõ:tΩ½då¶“¬óËv.Û§Û¨^vêC:õíóÒ>•sþ¿ˆ¡˜(‰7×ÿÚ}×Þÿ}íðµLוVßÿuí»ï¾ÅuHŸÈÒ¹¥ï*ùý^ç›®Q.ûúéë¥êRÒ
„	hSÖNÒá`©\N&C”eß¿«½dµQn9‰Cɺr>dÐ@p›&ÕUíLÕ·ÖjpJy.9/׫·sÙiQÜV²ËÒ¹œë&kè‚â­7T²/Þ ¦Íš»qd<ñãbÙòå±Gr?oRZ÷´	žXñX<|÷]±6}¯i—×¾.¦¤H›FQ›L>un˜âM¯oêìØeÑ›âñ{—ÅÀOîˆÝ÷Ü%æí²«º‹'{4yð±XµnçØuÑa1eúŽC˜}ä›Q7È3ÓªÅû¾>n{àÇqë
·Ç‚—.ˆ]vÙ¥ð÷hòwßCDߦÙñª}_³¦Íz³öæö¼åW'•Æíäñ«¬z±Q½Nýwgùиt¨­eÙû•œ¯dùQRž·sâçñȧç¬\}«?Þ!ÚÉιêUöÁ6ªWrËùøÜVv›Úº½tn#ª÷|\V}£õW½l•{þòᄂSÙ}©œÉuÒiý]–ì6ò¥z'—Õ¯ìUÇú×i1býkç·öɘœÿéWCW§}¦wÇ«/¾ÔÛ0}ÉóÐøÐLû/7kVņµéº›Îçi_úœðù“þ%bZ—=cò¯ÿ3>s]ÍÅž‡Ÿ§ºc<öÄÌxû‘ã¢k¿ŸýIÄ.¯>2[øp\ÿåÏÅúÞoÚþéøî7¾ßìyç×oÜ;}löÙôݨ¾é£ÐéÜNטuºlÞ>ΜFš~^\çm~®ùœÔ9£q)9÷ùÎùÏõß{FûÅû·Þû¿ê½×ÕÎ{̹t¾¦ËVeû×þst\ÿkßuÍ™Š­yñþ¯S»1“‘¾ÿçíã°ÃÚçâík¡e÷©\k£kdJzñ}xíb*m-0R^»éIÃM²í,ûž^v–•ËOU.;¥ªúZÍ8¼êO-»M°<µ©’sáX§¼Ña{å²SžËn›/JÙ&/ÛÇ¢üàÿž|
]˜t#®‹—¦£›J]øô_Œ§$ù¹_ßÏÞso¬zü15‰Yé‰Óûì³_¾(6¤v«V­*.hFá7Zm:oTmS&mŒ§WÜÏ=~W¬yþáÂߌí÷ˆÙ;¿Ïœ´&xðñÔ~rÌ}éž©ýÚtÕ›3'¯‹õ©¯ô_b»µOÄ“›çÆ‚ySÒõsC¼0iFÌè[ÿæ‰âWòfÌÛ3v¹6¼ÿ±X§kÏÔbÁ‚cíc÷Åož^Ïù?xâü~ÿ×Þõ¾äüþ#°Yh¯x¿(×¹,^Êõ^ä÷ɺnš§ô*ÛÆí\oæö¥}záSþŒ¨­úÓoÚë‹tò§v‹Ûê‡ò›cµóGäOSŒ¥hõ¡±)èz.ý8…ÚÚ—/š«ìÔ—U/½í5.õ«¾dãqÉÆe×öÒ©Ê:\'{ï?ÉêÇmœ«^uîS}¹ì5g%É:4.%÷áñH'_å²ôêËý¨ì¹Ë‡ì]¯1xý¥WSmÜιê%{nÖ_ýš‘|k.ž§ê/7nÜÓ§¦cÙ”nbtΧ§Rk×­ßâü×ÇëҎƆéZœŽiSÓy½9Ý„¥ý¬ºÉ“ÓøÒ?»]¿¾¶ßÝ·úr?‹÷>çízÀù_Û\ÿk÷\ÿ‡ƒ:_§ò÷L_?tM‘ìkÛ‹áýÿª«®*ît×uAó×}ˆîQ9æ˜ØqÇ‹97»þuÔQ'¦Km0é¦XoÊ}¨¬‹u¹.·³œç’«ùQr.%ÛZÎó-ä´¦n#}ÃÔrÀ”6ˆ9l&çís]Yv@d½ÊÖå¹õÎeoÙ¹ty µhéÒ¥ÿËo”Úàº8hÓ+éæ\eMχnÐ}£©H%9dT§6JògÞò)9?áÔF6¶“Žüc‚¶W[A¹}:÷xT/Ym”kƒû£ZÒiž²Ñø47ÉNÒ©’l=É:4.÷/¿ö¯Üu®—½Ø(x“­“ýøÄËûwç©:Ù©,?êC²Ù*iŒ’]Öüd§¹¹••T–^í%Ë¿µmuý=OùS[õ¯5ãѬ¿Ç-_òí¹80Éç*YvÊu(9×؇tò¥=¥¤¹ªÞóô¸YÖ_{Á‰órqΈƒ¯:GT'Ÿ_f¦œó¿vmñuQLtýѵ†ëó÷®ÿÃ×±Ð>ÒþÑ>Ò¡÷.•yÿ¯½×ûü%çãùþ¿páÂb-¼.ÊuèÚ§'MJ­œÿK–,yw2Í&Ýj"ºAË*ê­wnÊÖY®—'Ó¡`I6JÎëÊi¾¹MѨêeøË,Uµ#ÓùÌp^¯µë«ré|¨½åz¹ƒ$ç²ÛJÎ[›@'©t:u#,Ù7àêÔ'±dÛi#«­ÚøU7áÒy“Û^¹7¸lt¨sɺùV[%­•|J/n„%K/ßJÒçc‘N6Jzã’Ê:ÔÇ$j+½Æ$*«^ý(WßÖIÖØd§”Mý8ð“^‡þ!¿NîK~•äG²r˲‘ÛÊΜ<¦< ðøÔO>•µ~’4õáÜŽûÕ8Ô§üI'_Uë¯ñȇsµq[µQ{õ­1»Îöò«¤zÏ[eµó|%·»þòí>='ùÕÁú×öë?üƧ}¡=©ýé=ësÍç—ö”dÎÎ_ÇtÑžÐþáú?ò÷s?®ÿµ{qàý¿½û¿±|ÿ¿ë®»Š{‰üúェó_úÏß{ë–G7P:tCT»QMÂ`’®êž^ÕÒ«ë¥S²®*¯YlýšûR»¶ÓXLù`4P§|âÖç¹å²}ÞÎaʹìrngYyq±Òâë¦
àCAzÝ8+×Í·n8uÓ \'¶Û«lÔFo"*kcéFDzé,ûÆDz߀È^zé|S+ßö¥:ɪw²O•åÛY¾äÃImt8ÐÐåχí”ÛVíUïñI¯²çé¶*k²“Ù‰“ôêÇIþ<Û+÷™ÚÊ^eé5ùq?î?÷—ó—¬6ö©Üm5OõJêGþTv;û—­Û±þæؘ•÷ƒX³þœÿœÿ\ÿumàúÏû¿Þ'xÿçþÏ÷kºí<¤Ê¥\vÀ#Û\V=‘ò}½Ê’‡o†‡ëÜ®œ«íËmU×vËäi€Jå	çeARÙwÙ–ëå¶Ï?bW–sÉù!¿û}ãßøW]äurëÐ7ÉÒ)é&_I7…ÖÙÆ7…Á ê|íò¼½ê|ÈŸÛ˯Ëz³‘ìyÉ4ÔûVWuÊe§¶Jê×ý8Hpp¡zÙëÐM®Ú9y£ÛI§¹(©ìÌEuêÃc”ÞöÖ©Ç¡ñJ¯$[ÉK¡L/²Qôî/oユ{þîËeÖ¿¶ÍÍlYÿ-÷žö÷°ríÎÿ-ÿÆçóY{Èç£ÏA³óù'½í­S;ïCñ•^I¶’9ÿ§L#ó”,VJæ(Î_×qýçúï÷;Þÿk÷Hæñb}ÿûÛß~rº$Ü¡ËB:$å‡.ÖKVÊeÙ6®¯—§¦C>d£¤¶>ò²å<ßBN×1µkš¶|÷ij^×@‰“åª\º\ŸËn¯¼ÊκªÜA“ëòò¤´¹od@€ @`lø¾[Þ$+ÉïÉظ¬\ÉeËy›<ˆ‘ëd›Ëyõyžû–<êÔnÀäIveX­”Õ—ì´ ^ ¼\Ö©Ž@€ Œ=߇û‰îÅÀH'Ù‡Úèp}~¿îºT=ToYùh’ûMÛ"àUÃ:òÉÊ$/[.ç¹]¹NåªÃA‘Ûº,Û²¬2	€ @{º×.ßûþÝzõZ¾O·sÛTåU:µsÊeéÊeÛ*M0ÑÎÜÖy>!ë”—eëªr/„ê<ËÎG‡F€ @€@C¾w.c˾WÞìP;ÛXÎó\–ÝhÓˆÛ:Àm‡­¶«˜uy^–Ëeõ'z‹!½ûP[ 0BK/a+Ì!@èº×ö}w£{sß¿ûÞÜea²\¯Î6Êódû\7æ²&5Ƀw®>ªdëœçvÒù°ÞeÛ»ìÅ‘å¼Núm>ò©Kã²óNÙæÇ9Ò.<æÌøÊU_‰sNZ<Ò¦õíž§ÿP}ÕUWÄÉ÷§NCßõ{ÍjÇ9—~%Î;åðL×Iqaœù¯_‰Ë>5þûåmunœý‘wurr•}½XÏÊÉŽÃþ>íü˲ëKçö︜ÿ´ñöŸu…@ÕêÝ{ë^<¯Skߟ;/ë\V®$;¥ržërÙvÒYÒ$Æ*Õ`®Ïår¿®«Êsäz‡¥œ—ûÚ&Ës÷zY,˜¿ë˜Žmñ	gÆùŸ:=&òùÀ‹ˆùóæÇkËàb]¬|ôѸï¾gb‡ä{¯¹óÆ”[sg³b¯}çÇü]g47‹=b¿ýRÿ{ÍïvºpÉ)±ÿ©´ã+â´c:”zµ|<Î-{Ø–Jc¼¿žï8dAÄ“N²sûw|ÎÿáµoÿÃ=!A€@º//ß{»\ïž]z%×[®Ê¥+'·—>—s»zúܦ%¹_É«D®‰l[åù¡IäeËÒ7[×+ïŠôüÚôOY§ÿ3Ú1ôîÄ!‡¥ûÝ1q6:'ËÎ=3þiÅ!q×%—ÎAU«å—Åé'Ëßâ¸ø‡ŸéU6ƒº…‡/‰=V]Ënj`4šªôÖ­zb4-ǤMú·'韌‰«J'Kθ8Î>fQÄêçbe,ŠÏøl¼éuƱ¾¤Ò~¼•ãr~Œ÷ Gëû»•.–œpdÌŽ'âKŸ¼fؼCûw\ÎÿáYÄxûϺB„ jù=wù'Ä}ï®\vúÿK¹Î²<—eÿ‚^žÛNºVåAÓ¿ÛY×RÞRÀ”þyŸ&0–©ľÝOUî6åÜ‹d}^–¬£:~Z\ú‘ãbß9ÓÒò=·ß±6^×DZ'ŸWØ/>éüø»?Œøôgïˆ?ÿàq±`v²K·Ž—¿ï­q^qó½0NûÔ™ñÎ×-Š™Åÿ`]·/½,þþ¬‹b¹<,>)þõÌwÇþ»Í,ü=q÷uñÙ?C·,yÿëVÆÊ¾i±ñ¾Âtðåð8ç⿊Ã͹_·òÎøÒÇÞµpã¿ø´óãS|`j§1§9\{mz틾ÕwÄGßzr,“2ûo4ÿeŸŸúÓýcݦÙ1gæsñÓëˆÛ?¦­¾;.ü¿OŒK–~ëq@šz
‹tx×öÇMÔzV sþU³oˆxõ‘±hNšá¦•qÝ—ÿ>>ýÂ+â]ÌŠeŸý‹øèeiKN¯|ð1¿Ø·)îYy|ÿ?>Ÿ¼d€%/ÃÅW˜žK®¾5þìÈS‹ý|ÌigÄÎË4lÐPj¾¾y~Ô†ÞhÿŸ—}÷}1뮯ÆÛNÕõ`a|ü²ÏÅ‘³îŒ¼íý¡S°Ñþl¼¿t~,Žó®ø»˜ÿä=Ñ·ð ØMûguÚ?ŸÞ?µ16Ú߯_k]{]pø‚Øt÷•qI¦V°Ýhÿ6š_á¦áþjvþËC“ëg6Ö­Åü7ßÖÑ@€À¨	LJ-u8°ÉeÝŸ—˾gw®Ž%»}ž—ëTUУ†å¤§•^«	4L£–4áF)¯·ìÜíTÎzzÛ¨Þr9¯3Ç%qñ'NLÁÒ¦¸ý†ïÇ÷o|&öÛ~Ì™>Õ}Ŭ¹³cö¼Câì³OŒÝÖÝK¯^7üôgñËÁ€å´?'¶(6=ôÓ¸òÒËãº;×ÅþG‡–Ä¿~êÔ,Eܺôʸú†»cÞ¾‡ÅǾòñAÿ¥þoy*3§…qÎWΉ#͉åß¿<.üÂÕñøÌEñÞ¿»0…9ÍÓ3¿¹#nºþú¸eùÊd¼2n¹þq}*_ã-ñpѼ¹ÿFóŸµýœ˜9-2÷Þw®œžbíwÜp{lš¹oüþ»–¤ŽÛnLý©Ï[Œ™3gÇöÛç_›³“nÑGÅOÝ—_y]úû÷œ8ìïœßÂ8öމE³žŠ¥—_—/½5bÞþqÒ_œÑ|ò™ÅâçÁfÄ̘›=fk<þí#&O‹ý¿:yZxüQqô;Þ\xÝán1yÕCEÀ¹1ýdæ‚E±ê–«ãÒ+ëfÏc>ü‘¡õiÄ/E3M÷GãýS›¤ƒÅÓ/üVÐn±üÛŸ«K
H?x|ÌŸº"®¼ðÂøÂåKãñ¾Ýâ ý÷Îè4ŸZ™öÎ̃âs_¹0N;áð¸ò‚sã¢Á`°qKÕ6[ßæóßâüãóC7ëϯËâÊ›y矔vÁégÇQfÇ/¾ý•"XRûFû³ñþÒù1+æì0;æïP¬»mpÿÌÜrÿ4fÜlüYë%oßN§êÿû«™2ý!£áþm<¿â
÷W³ó?¢ñõs‹¡VšùoÿWtŠ
€ª	è^»|ÿí²ZX.çöVOï¶y^–í#Ïå¯åÔJ¬ãû­–V6T¡¢yQzÛ•mì?¯·\/×Âå‹Wö‹O;.¥¿êÞyùÇÓS„eEýé—^ïª òÜWÇQïùä–>ÒwŽ>hN¬»iuÂYƒuúKt-ÉÿþééÊí—~8N½ a=xÞUqê¡oŒ3RÄó›ô¿ø]ñºù“cÅuÆ{>zIº=K±ÉԗŹ'öËÒŸò©øÛãÒMýàç²úúVÅ×ÿú¸Pw˯¼ >|eº­;íÒ8tQÄ¥=kðFÏlîÐ2ªæxñ\ç¡øû“O/¾6>»4N=ý«qé¿8øÄgy\pÖGk.žßÕ Ê)ˆ+ú…xëû/*jyÉUñ×MZXµÎ­-à‘ºÞø›î[‹öÜ;/<4vWC)ÈÙ+}UjÅÒ_>ÒÁxhéÙqÂYµg†Ëg^gµph}
£ôRů•ýÑhÿœ;`ÝÆ)qzÚWǧ½xû•gÇÉç=¿¬m‹™ÓbÇí×ÅwÎ;+.ÞžZÃü¢÷¿-¦žsqwÄAqâŠãþôö¸ðô“C¯ZJ
Ö·•ù7¥-¿…VͯµýQÿ¨Ÿâ	Á¢£ãxÒÇ×<•Ÿê¦8ýcÆ…é#¡GœøâXæ±ôKÿç^6¼ç‹¦
^.øè{â‚®ŸòñÄŸµ|àΉˎ„´SU£õmmþ
ÎÏ–÷oA¶Ô~y|ø’ëcàŒÃÒ¹¾2þmð£ºöØt6Ø_ŸôÒ|ÿ¸·RÞÒøÕfIyÈìXy×?†;ìGWÀFý7žßöWÕùßäú9<ʤ*ÿéÏCc±ÿ[è@¾7¯º—NÁŠr%ÛTɹÎŽÛ»Îz•Ë)·-×µUÖ{æX$Chæ+‡d[·-×åeËU¹üTé¥S¤«|ëTÜåïó÷MUƒx]¿µUM³U´1l¸Ë~§ÂpP4\#iZ¼ä·²ê)úž[Ľ4ëMí¶ûþ«ÓŒôEí…Ó0·üqÜtÉYqâ%rÖ UG)*iîÈk½ù×âƒ!³Ñ	ÃÓÛ¢›…§ÅS°4ùî¥ñ¾kOÇNºð»qê[÷¢x±o(Ì*×§›ý3ßóWþ$κ =rËSƒñ_ó³;ã¯Ó÷§^wøœxög_Š[÷:!Žø½þ¼=¿ü©bÂÓÆõY’¯oÞÏË+ì¬Y}Í×W_ôÇqÄ{ÿ6N»ù­ÅÆ¢æ¦KâÔcÓY¸8NzÛ»âÞqDó¾ÿ+RÀÔÖõßKÖ¥cNüáù§Ä%ƒOCÓ£Ûæû³Áþò¨òý³fƒú¼>Ø å•û»¥ñ§¥?åØXÆõÕмÿÈ÷o+ókkÕ&Øøú)›çoÍEý×1_}çÔ@€@F@÷Úºçv`¤r~È4/—å¼"Û¸N>œò:ëêå²µÏz6Mõc0©#
¨œªt²©§w]¹ÞeåeÙºF¹ün‘–}ç¦xî˜}ãÈ÷]÷ĿǺWÿI¼kßô£woaV¿pÓyñã‡ÞGòÞ¸øœ©ñåoßsï}Çnñ•“Kú~¬8~Qú8Oú5·µŸ‹{w~süÅQÒç³n->N·lÕ–ýGêÿyÿËnŒå«Žý~_œóèŒøêÍOÅIgGÌ_ïyÿ¹õÇU®Y¯Û­ôݧ3OŠUÿuopè±âšâš±ò_îo¬Êƒ«6m\Ïè†ÿ]ï‰w”1¥{Êák°³4Åo8.–|'b¯C÷Ž›/¸d(„]|ʇâ½G”_«o»2üQ¶¦Ã¼æW±âcG¥ú˜?½ù¢X¶&}é¨ùé¡ä=qóòZk}$iÑ[NÓùbÜ;ûCëû_Í£‘XÖl,k¼4‚¾tC¾éþ«ã=Ÿ¼ •ž+Ò“Èÿöü¸á­éG	ÒGž®¸øOã™e_‰/|õš¸ä¼¯Æ>‹_Wü`+~µé”^_¯}Í!±àÐCâMï^ÏõíóÒÃÑû—~³…`«äª¢Øtþã}~´°ÿO:ïì8dÞ¦XzöïÆ-o¼"Î8â½qþ)7Çûõ«+Mö§Ÿ’VL}H5¼þ%~9íðx_ºùú0d$!í³­öwãWÓŽLaXycT=Tî¿bÿþ‚|Ýó¯ÝýÕìú9xŽúümw|‚G‚ V	4ºw|IVªÒÕj†ëê9j[UW¥¯Ò¹Ÿåc0ÕëXƒUr^+
É˹ìó6eÙeÛ5ÊÝÇpžÞ°?wõþñ¡t3}êÙº¡^W|Ú+ÿ£ðª"ب=n8,}ô¸Œó¯xrĉqö5ýs÷_oö—Ä_ýÓ>ñ™÷ÇŸ1à—îíRÚúv±Š¢l·Ú€6¼é‚ø¯[ß”¾›sL|ñ‹Ç$Ë•qçéÇ­_Vö¾,¾ÿ“ûcÑaéÇ9>{H²{.¶¿!Lƒýnzü©âùÀ´x6žz8Uçi°¯êñß÷<².ý_¬ÕqÇOÓwÆâÞX—¦õÝ9ŒiþëÒ7œŽÿÀÙ5¯ëŠË?yêP}c~MöGú=³†û'õ¨ä­[«E*%û_Ÿzhœù©“ÒOß?¿ce™öæ¹é¨¥ÕñÓËÿsøWµÕÙ%qÂ~'ögñ–w¦À1}æòú—8¯êλÚÁà“‘R¥×·ÙüÆýüh²ÿ—|<þüÐyÅw‹¯¨]óWñº+Ò÷™Þû‘8é¢ãâ’VögÃý5Èeêü´¯ƒûgËx»Þþn2~¹OAÃëLŽ»¯ü¶¢o¹öo³ù-ÙþZöl¯Ÿ5Æçoæk+ÿ#_æ
€FN Ñ=¸ëäXv*;¹ÎvÒ—ë¥Ëƒ%ÕÛ>×ËnL“~J¯¡ÃÒ/GT
ÜtóIɱdåJÊ­³^¹cå.ÛV:ÉÎ%ë[eëªä¼îÉö¦£:¥§‡ï1+N¿¢°äâkã§ÿW¼á„Á˜ê[k'³fŪ‡—ÅM‘Ìáú•†ômŸeUÿ(ë¿¢iÑ×ÂŇǾóôUšjÿ[hkÍâ4†4Â4Ï›¶ºyÿ[÷8Fš4÷%iîw_³l«qoÑC;ÍoÇgFÏn‹~ª
ƒ}_“Æ8šÔp$‡Íê÷©¡¨}|P{¼ÞkäãôËÒ÷¤®Œþ‘žœfu
ç×ó£­ýß`ßeS¬O?’®3_}_œxÕ¬X²oDÃýÓ Ÿzã_rfú’£gÅ…ýoÛâçÄ·L£ýÛ ßšŸö÷W4¹~6=Ÿ×~ö˜¸ïò3â=ƒ?à3<Ç1ß°3$@¨&ð?’úWéÐ߯6æ’Ëå¼nã ­uynYAŠÿ&¦\eÕ)·¬²’õ.«^ɶy¹VS««5	ˆÆ+`RàãCAŽ’rÒ;w€äU¾ì8`’¬zç’•¬“Þ‡ô–•+9ßBnö¿˜|LdR ”'•}Té­³Ûçå*Ùíæ+¸/îŽÚP	^#påüaì×<=í½ûþظ<ûÑ1í䦸Ç¿/ýÍ‹4È]ûL¬ê›¿ý;ó‹øûýKÿ•`iL÷Î Œˆ@Õ½w®“³r9×ååvyp#}^ÎÛŒ»<Ú'L´S>1éòrþ$Iz—ó\²ÙøésÕIvYA^^¶œçö'ž0}"$@€ @`l	üMr§'LUO‹ü”Éu.çO˜\§§D–•+@’.?¬ËsÉUå¤.ô®WYIe%ç±­=aR@Ô(9ØÊmr]¹½ëœ»Ëέʆd@€ºƒ@w”QB wø~Û¹gî²së•K§T¯Nú¡€¦°ÜòÅí·ÔŽSIObÚI£l˜òÙ´Rgå$@€ @`üä÷Þ–«zm}5jo›ª\íFÚ
˜FÝqjØÊ„mãI:w¿y}.»^y¹M^‡@€ Œž@ù^;¿'Ïå¼·©WŸÛJ¶]Yß‘òDLž`Àð\—箳½Ë¹åܦ‘íÉ!@€ ‘hõ¾;·S/îÑ]ç6#Õ¶«€É“jgh¹VáØ®œ·3ÚB€ @£#P¾/w¹™·²Êí¦±ðQü:]»ÉÛW
ª<ùܾ™ì¶öë|$íÆ*(lÖ'õ€ @è5º×.ß³7cà{ú‘¶+ûuû*}Y7êòxã5ð*°eݨAЀ @3yL`Ù¹:ñ}üh;¬jŸû­ß­ÚGÀäNª&¡ºzz·ižû3¤r>RŸØC€ @Í	”ï»]vK•Ç2ÕóWOßvßã0ip®ºr}•®íI†@è
Uñ@•.ŸL9¦ÈëÚ–Ç;`je€Uª&]e׊l @€ m‡@½ûúrPÏ®£3Ù&O¸Hú*H¶sžÛUÙÛ?9 @€ 0¾|?îܽùÞÝy®/ëTW¥s›ŽæÛRÀ4š‰dLëÆ7m @€ Æ|¿í¼l]O_¶ÛfËÝ0m³` @€ Ðý˜º
™ @€ 0N˜Æ	,n!@€ î'@ÀÔýkÈ @€ q"@À4N`q@€ t?¾îŸÂÄÌ ¿¿b:¦×1!0000&~Fë¤Ýý3Ñãí¼Ý®ÝùÛÏhó‰æ7Ñó-7·ƒŸI†ÀDïŸÑŒ™6€@oà	So¯?³‡ @€ `j‡*@€ @ ·	0õöú3{@€ @ ¦p¨‚ @€z›So¯?³‡ @€ `j‡*@€ @ ·	0õöú3{@€ @ ¦p¨‚ @€z›So¯?³‡ @€ `j‡*@€ @ ·	0õöú3{@€ @ ¦p¨‚ @€z›So¯?³‡ @€ `j‡*@€ @ ·	0õöú3{@€ @ ¦p¨‚ @€z›@_oOâf?000q¿zîïïŸÐY´ÛÿD¯»ão~·Ï¿Ýñ·Û~¢×¯ÝõŸèöíòŸèñOtÿ쿉^ú‡:M€'L&N€ @€@× `ꚥb € @€@§	0uš8ýA€ @]C€€©k–ŠB€ @&@ÀÔiâô@€ t
¦®Y*
@€ tšS§‰Ó @€ Ð5˜ºf©( @€ ÐiL&N€ @€@× `ꚥb € @€@§	0uš8ýA€ @]C€€©k–ŠB€ @&@ÀÔiâô@€ t
¦®Y*
@€ tšS§‰Ó @€ Ð5˜ºf©( @€ Ði}îþƆ@ÿØ8š /Ôó‹£Ûn_ÿ‰»û¯ÛÇÿâ8&n½þíμÝýßnÿ´‡ ÐmxÂÔm+Æx!@€ Ž `êj:‚ @€ºS·­ã… @€:F€€©c¨é€ @è6LݶbŒ€ @覎¡¦#@€ @ Û0uÛŠ1^@€ @ c˜:†šŽ @€ n#@ÀÔm+Æx!@€ Ž `êj:‚ @€ºS·­ã… @€:F€€©c¨é€ @è6LݶbŒ€ @覎¡¦#@€ @ Û0uÛŠ1^@€ @ c˜:†šŽ @€ n#Ð×mf¼x1èïïokmµŸèþÛ<Û&Àú·€ ÐCxÂÔC‹ÍT!@€ ‘ `/¬!@€ "@ÀÔC‹ÍT!@€ ‘ `/¬!@€ "@ÀÔC‹ÍT!@€ ‘ `/¬!@€ "@ÀÔC‹ÍT!@€ ‘ `/¬!@€ "@ÀÔC‹ÍT!@€ ‘ `/¬!@€ "@ÀÔC‹ÍT!@€ ‘ `/¬!@€ "@ÀÔC‹ÍT!@€ ‘ `/¬!@€ "@ÀÔC‹ÍT!@€ ‘ `/¬!@€ "Ð×Cseª€À6B ¿¿¿­‘´Õ¾ÛûŸèñ·ŸÆ€ .#À¦.[0†@€ tŽSçXÓ @€ Ðe˜ºlÁ. @€ Ð9LcMO€ @€@— `ê²c¸€ @€@ç0uŽ5=A€ @]F€€©ËŒáB€ @#@ÀÔ9Öô@€ t¦.[0†@€ tŽSçXÓ @€ Ðe˜ºlÁ. @€ Ð9LcMO€ @€@— `ê²c¸€ @€@ç0uŽ5=A€ @]F€€©ËŒáB€ @#@ÀÔ9Öô@€ t¾./Ã$000‹&ÐßßßÖì'zÿÐ?ço[x‚OôþàéÓ= ž#À¦ž[r&@€ ´J€€©URØA€ @=G€€©ç–œ	C€ @­ `j•v€ @€@Ï `ê¹%g€ @€@«˜Z%… @€ Ðs˜znÉ™0 @€ Ð*¦VIa@€ ô¦ž[r&@€ ´J€€©URØA€ @=G€€©ç–œ	C€ @­ `j•v€ @€@Ï `ê¹%g€ @€@«˜Z%… @€ Ðs˜znÉ™0 @€ Ð*¦VIa@€ ô¾ž›ñ62áþþþmd$c"´ÕíDïŸvûŸèùÓÿÄî¿vù·uò¤Æíîßvû§= tž0u×z1Z@€ @ ƒ˜:›® @€ î"@ÀÔ]ëÅh!@€  `ê lº‚ @€º‹Sw­£… @€:H€€©ƒ°é
€ @è.Lݵ^Œ€ @è ¦¦+@€ @ »0u×z1Z@€ @ ƒ˜:›® @€ î"@ÀÔ]ëÅh!@€  `ê lº‚ @€º‹Sw­£… @€:H€€©ƒ°é
€ @è.Lݵ^Œ€ @è ¦¦+@€ @ »ôu×p·Ñl;ƒa$'Àú·‡¼¿¿¿-íòŸèþÛšü6и]þíNa¢ûowü´‡ î"À¦îZ/F@€ tSaÓ @€ Ð]˜ºk½- @€ ÐAL„MW€ @€@w `ê®õb´€ @€@	0u6]A€ @ÝE€€©»Ö‹ÑB€ @$@ÀÔAØt@€ t¦îZ/F@€ tSaÓ @€ Ð]˜ºk½- @€ ÐAL„MW€ @€@w `ê®õb´€ @€@	0u6]A€ @ÝE€€©»Ö‹ÑB€ @$@ÀÔAØt@€ t¾î.£5þþ~‹£ÊFÕn¬µ;þ±~FG`¢÷ÏèF=Üj¢Çßëû¿Ýù·»~íö?¼“zSj—oRcÖ€@7à	S7¯c‡ @€Æ•Ó¸âÅ9 @€ Ð͘ºyõ; @€ 0®˜Æ/Î!@€ n&@ÀÔÍ«ÇØ!@€ q%@À4®xq@€ t3¦n^=Æ@€ Œ+¦qÅ‹s@€ @ ›	0uóê1v@€ @`\	0+^œC€ @ÝL€€©›W±C€ @ãJ€€i\ñ†@èfLݼzŒ€ @WLãŠç€ @€@7 `êæÕcì€ @€À¸ `W¼8‡ @€º™@_7~"ÇÞßß?‘ÝÇÀÀÀ„ö?Ñ·;ÿ‰^¿‰æ7Ñýw;ÿv÷ßDóïõþ'zý&zÿ·;ÿvÇßnÿ½¾™? Ðy	Ó}^f @€ p 	Ó^¶G%@€ @à>	Ó}^f @€ p 	Ó^¶G%@€ @à>	Ó}^f @€ p 	Ó^¶G%@€ @à>	Ó}^f @€ p 	Ó^¶G%@€ @à>	Ó}^f @€ p 	Ó^¶G%@€ @à>	Ó}^f @€ p 	Ó^¶G%@€ @à>	Ó}^f @€ p 	Ó^¶G%@€ @à>÷M7;çó9Í]Ö§Óé¥÷^ë·öþkÏ_‹·öþkÏ_»þÕ~kïÿjÿµç¯õ_{þZÿµ÷_{þÚç_»~íý­'@€mü…i[o§ @€ °#	ÓŽ^–« @€ °­€„i[o§ @€ °#	ÓŽ^–« @€ °­€„i[o§ @€ °#	ÓŽ^–« @€ °­€„i[o§ @€ °#	ÓŽ^–« @€ °­€„i[o§ @€ °#	ÓŽ^–« @€ °­€„i[o§ @€ °#	ÓŽ^–« @€ °­€„i[o§ @€ °#	ÓŽ^–« @€ °­€„i[o§ @€ °#	ÓŽ^–« @€ °­Àmû>§N§Us>ŸW­ßûù¯¾ÿ*üËâµ÷_{þÚߟµçï}ýZ¿W¿ÿµþ{þµþkŸ­ÿÞï¿öù­'@€ÀÞü…iooÌ}	 @€ØL@´µƒ @€Ø›€„iooÌ}	 @€ØL@´µƒ @€Ø›€„iooÌ}	 @€ØL@´µƒ @€Ø›€„iooÌ}	 @€ØL@´µƒ @€Ø›€„iooÌ}	 @€ØL@´µƒ @€Ø›€„iooÌ}	 @€ØL@´µƒ @€Ø›€„iooÌ}	 @€ØL@´µƒ @€Ø›€„iooÌ}	 @€ØL@´µƒ @€Ø›À½]ø«Ü÷|>¯ºÊétZµ~ï‹÷î·öþkßßÞø­û
Øûû_÷ôü±ö÷çè~Gþµ¿Ö p<a:Þ;÷Ä @€,0-„2 @€ã	H˜Ž÷Î=1 @€$L¡L#@€ @àx¦ã½sOL€ @€ÀB	ÓB(Ó @€8ž€„éxïÜ @€ °P@´Ê4 @€Ž' a:Þ;÷Ä @€,0-„2 @€ã	H˜Ž÷Î=1 @€$L¡L#@€ @àx¦ã½sOL€ @€ÀB	ÓB(Ó @€8ž€„éxïÜ @€ °P@´Ê4 @€Ž'ðãxü5žø|>¯ºÈétZµþÕ‹×ÞÿÕ~¯¾ÿ«ŸíùkÿÖú¯=íó»ÿÚ7pìõ¯þý9¶¾§'@àˆþÂtÄ·î™	 @€X$ aZÄd @€G0ñ­{f @€	H˜1™D€ @€À$LG|ëž™ @€E¦EL& @€ pD	Óߺg&@€ @`‘€„i“I @€Q@ÂtÄ·î™	 @€X$ aZÄd @€G0ñ­{f @€	H˜1™D€ @€À$LG|ëž™ @€E¦EL& @€ pD	Óߺg&@€ @`‘€„i“I @€QàÇúÏ|:ž±Ía÷8ŸÏ«ž}­ÿÚóW]þ,^ûüký׬½ÿÚó_ýükïÿêõ{÷ÛûïßÚûïýý½ú÷ßùìOÀ_˜ö÷Îܘ @€$LA;† @€ý	H˜ö÷Îܘ @€$LA;† @€ý	H˜ö÷Îܘ @€$LA;† @€ý	H˜ö÷Îܘ @€$LA;† @€ý	H˜ö÷Îܘ @€$LA;† @€ý	H˜ö÷Îܘ @€$LA;† @€ý	H˜ö÷Îܘ @€$LA;† @€ý	H˜ö÷Îܘ @€$LA;† @€ý	üØß•¿ÆÏçó׸ȃ·8N®|[öêçõù«ð.‹×ú¯=ÿÕë_ýþÖúïýþkŸÿÕ¿?¯>ÿÕ~¯þý{õù¯~ÿÎ'@àxþÂt¼wî‰	 @€X( aZe @€Ç0ï{b @€
H˜B™F€ @€Àñ$LÇ{瞘 @€…¦…P¦ @€ p<	ÓñÞ¹'&@€ @`¡€„i!”i @€O@Ât¼wî‰	 @€X( aZe @€Ç0ï{b @€
H˜B™F€ @€Àñ$LÇ{瞘 @€…¦…P¦ @€ p<	ÓñÞ¹'&@€ @`¡€„i!”i @€OàÇñù9O|:ž³Ñƒ»œÏçW¾-[»þÕÏ¿êá¿Áâµïo-Á«ßÿÑÏ_ûþÖþþ¼Úíó}ý«ßßÚß¿£¿?ÏO€Àöþ´½¹	 @€؉€„i'/Ê5	 @€Ø^@´½¹	 @€؉€„i'/Ê5	 @€Ø^@´½¹	 @€؉€„i'/Ê5	 @€Ø^@´½¹	 @€؉€„i'/Ê5	 @€Ø^@´½¹	 @€؉€„i'/Ê5	 @€Ø^@´½¹	 @€؉€„i'/Ê5	 @€Ø^@´½¹	 @€؉€„i'/Ê5	 @€Ø^@´½¹	 @€؉€„i'/Ê5	 @€Ø^àÇöG~Ïçó÷xŸâèÏ:”{[¶w¿µ÷_ë·
ÿ	‹×>ÿÚ+¬õ[»~íý_í·öþkýÖ>ÿÞÏ_ëo=¶ð¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ?¶>ð»œw:¾Ë£ò9ÎçóKŸûè¿?{÷_ûþ^ýükÏ_ûükÿßÚó×>ÿÚû[O€ûð¦}½/·%@€ @`C	ӆ؎"@€ @`_¦}½/·%@€ @`C	ӆ؎"@€ @`_¦}½/·%@€ @`C	ӆ؎"@€ @`_¦}½/·%@€ @`C	ӆ؎"@€ @`_¦}½/·%@€ @`C	ӆ؎"@€ @`_¦}½/·%@€ @`C	ӆ؎"@€ @`_¦}½/·%@€ @`C	ӆ؎"@€ @`_¦}½/·%@€ @`C	ӆ؎"@€ @`_?öuÝïsÛóùü}æOr:^pê×9ÒïϺwñj¿Wÿþ¾úüuoï?^ýþÖÞ­ÿ«ŸÿÕç¯õ·ž÷
øÓ½bæ @€ p	Óa^µ%@€ @à^	Ó½bæ @€ p	Óa^µ%@€ @à^	Ó½bæ @€ p	Óa^µ%@€ @à^	Ó½bæ @€ p	Óa^µ%@€ @à^	Ó½bæ @€ p	Óa^µ%@€ @à^	Ó½bæ @€ p	Óa^µ%@€ @à^	Ó½bæ @€ p	Óa^µ%@€ @à^	Ó½bæ @€ p	Óa^µ%@€ @à^÷.0ÿkœN§¯q‘oq>Ÿ\ù5–­½ÿ«ßßÚó_ýü¯>ÿÕ¿…{þµ¿¯ö_{þÚ÷·öüWû¿úù×úYO€Àñü…éxïÜ @€ °P@´Ê4 @€Ž' a:Þ;÷Ä @€,0-„2 @€ã	H˜Ž÷Î=1 @€$L¡L#@€ @àx¦ã½sOL€ @€ÀB	ÓB(Ó @€8ž€„éxïÜ @€ °P@´Ê4 @€Ž' a:Þ;÷Ä @€,0-„2 @€ã	H˜Ž÷Î=1 @€$L¡L#@€ @àx¦ã½sOL€ @€ÀB	ÓB(Ó @€8žÀã=²'&°Óé´ê!ÎçóªõkÏ_uø¿úùמ¿–àÕ篽ÿ«×ïý÷­ŸßŸµ‚Ö °7aÚÛs_ @€60mFí  @€ö& aÚÛs_ @€60mFí  @€ö& aÚÛs_ @€60mFí  @€ö& aÚÛs_ @€60mFí  @€ö& aÚÛs_ @€60mFí  @€ö& aÚÛs_ @€60mFí  @€ö& aÚÛs_ @€60mFí  @€ö& aÚÛs_ @€60mFí  @€ö&ðcov__Aàt:}…k<|‡µ÷?ŸÏŸýŒ…kïÿŒ;¼r£?ÿÚß¿Wû­=íó¯ýÝÝûý×>¿õOÀ_˜Ž÷Î=1 @€$L¡L#@€ @àx¦ã½sOL€ @€ÀB	ÓB(Ó @€8ž€„éxïÜ @€ °P@´Ê4 @€Ž' a:Þ;÷Ä @€,0-„2 @€ã	H˜Ž÷Î=1 @€$L¡L#@€ @àx¦ã½sOL€ @€ÀB	ÓB(Ó @€8ž€„éxïÜ @€ °P@´Ê4 @€Ž' a:Þ;÷Ä @€,0-„2 @€ã	ü8Þ#'>ŸÏßãAvúG÷?N/}s{÷_ë·öù_}þKy¾ÀákßßÚGxõùkïo=¶ð¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ¦­ÅG€ @€Àn$L»yU.J€ @€ÀÖ?¶>Ðyo§Ó	ÅÖ¾ÿóù¼Joïç¯zøËâW?ÿÚû¿zý«ýÖž¿w¿µ÷ßûÿýXûüÖ @à^aºWÌ| @€# a:Ì«ö  @€Ü+ aºWÌ| @€# a:Ì«ö  @€Ü+ aºWÌ| @€# a:Ì«ö  @€Ü+ aºWÌ| @€# a:Ì«ö  @€Ü+ aºWÌ| @€# a:Ì«ö  @€Ü+ aºWÌ| @€# a:Ì«ö  @€Ü+ aºWÌ| @€# a:Ì«ö  @€Ü+ aºWÌ| @€# a:Ì«ö  @€Ü+ðç_ýusÍŸ—Ò&¤=ÖI¼*Þ?û‰U=÷ù‡ŸcUím¬Ú™3ÖµwÅþùåó//ŸßÊù|þ­¯C€|}Óéôõ/醎%ð¯.ûï.Ÿ¿]>ÿø³®öøùmNÚ㚬¯zîSÉKƪOÅÒN}	]çV]±*cýÇ%JìmÆð³’
… @€&$L(B @€(	“ß @€ÌH˜f`„	 @€  aò;@€ @€	ÓŒ0 @€$L~ @€ 0# aš&@€ @€€„Éï @€f$L30 @€0ù @€ @€ÀŒ€„iF˜ @€&¿ @€˜0ÍÀ @€ @@Âäw€ @€3¦a @€ü8*Áét:ê£{n @€
øÓB(Ó @€8ž€„éxïÜ @€ °P@´Ê4 @€Ž' a:Þ;÷Ä @€,0-„2 @€ã	H˜Ž÷Î=1 @€$L¡L#@€ @àx¦ã½sOL€ @€ÀB	ÓB(Ó @€8ž€„éxïÜ @€ °P`ï	Ó_—ç¬ÏXO=Žë @€ °^ ß·S;ÎÅÇy_¶ÿ•¦ÂËp楮5™—zÜGŸ @€ÏÈ÷ñÔ9±úUR¿õ~}O?õ8/ñÍë¯0˜…045os0 @€ °J`î{ý˜ÌÍ[uø½‹?;aºßo
`*Ö×h @€ ð}¦ò©X¨ñO+Ÿ™0Í]|.þèCöýª=õùnn @€“õ{ê»÷øý|rñƒÁ¾wßb.Þç<ÔþŒ„)hã…Ö>DÖgÿÔuNoçþßKàߌA} @€V	Ôwìú®=Uú÷ó´S×üj¯)Sëûþköþmí³¦g_<}SÿöÃ=‘˜çIDAT¾î\ÆÿÏåó¯'æ	 @€ p¿@}·þß—O}×îß½—ì”ïô÷®÷Îú©ø{¸ÿãá•¿/¬Ëþù{èî^àjaþ£=3o¬ûáÿóÒù—OíõŸ/Ÿqùü³ËG!@€ @à>™þo/Ÿÿuùü§Ë§¾k÷2~/O¿Ï™j󪿶ÕO<±ª+–þ»´ë¯Kõ;뫞+ãœæÖ>Y3·ç&ñW&L¸•TdNÕ5¯ê^úxosêEÖKýï—O’¡¹ºÎ©OªKó=¡ÊØXלŠUI]í:C!@€ ðÙ•Ȥä;s¯ûwåÞκ$DKb4W'yÊýììÑëŒW5sã}nægÍ8öéýµ	S]¼'K.˜[ënÍÉØÔYëuæU¬J›jלº[Õ/H%=Y{iÞUj½B€ @à³ú÷Õ´{]í©OÝ«¾³.™›õµ&óÓÎXêŠåѱìsk}æLÕµîá²6aº÷àºì½‰R‡6c©sŸô{$(ç÷±Þ®=ªŸd)uöV @€øjõý5%í^W{ê“d)õԜĦöÏXê>'±ª{I?ããXÆ{¼·?ïsW·M˜ê’IµW»JŸ7Õ¿NjóÒÏÜÞÛµ÷Ó˽	S]bM0µ~*Ö´Æë“’~bé×xÚ·êzÙy†q^ÆÆÿ¡‡Š'Vk{;{U]û¥i* @€6¨ï¡)i÷:í$>57íËg*–±ª?ÏÜÚª]±”>žØX÷ù›ŠelI}×ú{¦%çÔ…¦’‰ñ¢}^íQýÄÒ¯ºJÆz;±êZS/:IOæ'Ö÷¬v•übÔsÔºêKŒ.
 @€À—¨ï´)i÷:ßy«ÎwÛÛSs¦b㺩~Ý+ññŽãXÍKìgóïÖöñÌÏܧ×ÏL˜ê²c1ËŽsópµf\Wý*›kg|®®—<&J5·Ç³wÅêŽõ©5)¯R±ŒW?Ï“ºÇª­ @€ø,úN›’v¯ó·æT;Ÿún›öXÏÍÅÇõc¿ŸvÕ)™ŸþX×øT™ŠOŦÖ~{VÂTê‰ÂÜÁ5oœ›þ8–~í•öT]çNÅ+V/sn¼ÆR’De~ÅÇ$©ö韚ÛçÔy5ÞËT¬k @€X+Pß9{©~U»¾»&>Wלq^bc¼ïqkì²åÍsûxµ«dï´¯ÁŸ?úXOµkîêò¬„iê"uÁ1èóúøØN¿êúTéuog,sçêz‘uŸ¯v’¤ÌOì2ô>'	ÒTb”½òŒÙ/ýÚ'sª­ @€ø,úN›’v}¿­’ﻩ{¬æ$Þë©xõv_7¶sVêïíÌï±·o÷šj'ÖëìÛcOi?#aªËõ$a¼X¿üÔ¼¬¯:í¾Gb¯±´S±zU’°T?	ÍØ¾Nlãµg•ž$ÕšÚ+Ÿ¯RsóLY—~÷=ª¯ @€ø|ÿ­½ó½tª®ØÜ§öÈ>5'ýª³æV»eþX_¶zß+íª{ÉšŠU{ªdÎÜxÖ|4žy³õ‡	Ó_—òç¥Ìîð÷u©[óûxÚ©³[õûg.ž9u^Úc]/n.YêñœQ{Õš*Õ®Oæ¥ßëšW¥Î­Rc)‰¥¯&@€ ðý{go×YÕŸúÔXOrÆöØÏsñŒ§®ýÓë«2ÏX¯ÇvõÇRû-.•ë|4ùÄ©6x iúèÜ\¬’‹j'ÉH|ª®ØÔ§^Xö©ñÞŸjW¬J%ASíÚ+cÕÎÝR׉§¾„ÞçÕxJÖ¤¯&@€ ðý;höO¬êþ©ñôëûpÚU§ßë¹vÖe¼¯ŸK¬×¹ËT=ÆjÝÓÊ’d©[”0Íܪ.<&=vO;_uo×þ‰õº®T/&ùéci×x­¯ºJ’ ¬Éúq<ÏTóªÔ~U*ž±´Sg¼ê^2¿Ç´	 @€<[ ßYû¾‰åûqêš“v¾W¿Úõécé§Î¼Ô‰§ÎÚ±®ñ*c¼úUÆxb½~¤]kªäœ·Þ?×$Lã1u‰©¡Ç{{n}æT]¥ê±=Õ¯X½ˆºCÕIª?Ž]Bïã™—Xö®~­Í~ig¿ÞÏܪ{©9
 @€ÏèßasVbUçSciu}‡Nb“vÍ©vêÞÎú1–~ƧêË–ï÷H{ª®ØXj¿”ÞN¬ê¹xŸ³¨ýÌ„©Xì‰E%ÖÛyÔK}+žýkN½”$0iW=–ïÉ5VíÌI»×c{®?·Wöîç÷v÷~Ú½¾Nøù#ó{ìéíG¦ºØ£‰@Ö¦®J»×c»úsŸzQuŸ¯ö?´vÅ+–Ähì_†ÞŸ%ÏTuÚãx♓þ8¯úUúø[ÄO @€Ï¨ïÂ)i§®xµóéý$=K»æ¥}o=·OΞ«k]ÆÒîuo×¼GËÝkI˜n]®.Г„ÞO{¬k¿1Vý*UO}êÅåœO?íJªT<¥æçS±¬ŸªëóÒΙ3W×|… @€ÀÖõ¸ÊT]±|jN¢Þ®ñÄ—Ô™Ó×õvíÝûÕ?™3UOÅj}JoWlìgÞCõÚ„©.“„á‘äaj´³gï×ÞÕï±z1µ®’£ŠW?%wÊœªû_™j^æLÕ«=«Û}~Æ/ÓÞ÷«vJ榯&@€ ðùžÜ÷N¬ê|j<í[u}®ñ¹zj,±Z“u=Ví*Uíú×…þÈÞ-_›0åкD’ƒ´§ê\¶æŽí¬¯=k¬¯ÏÜÄûœŠÕÉžé÷¿2õ½Óž«kïZ[ãSŸO<í©ºb
 @€­úwç:»÷Çvõû§¾WWIÂs«ÎXÖÔϼ±®ó«vJŪô±´ûXæôzlWÿ¡ò¬„éÞÃë“°ÔÚVû$AJ;õeè},{ÔÜ*}ßÞÎX¯«’}ÒW @€x†@}‡Kb©k¼Úé÷v¾O'–~ÕK=¶{¿æd^¯O,gLÕ—-Þï˜ñĦêŠM•Z[%õ[oÅÏÅ	Ó_—òç¥ü<«.0Õ¯’yc=5/±Ú·æ×§J_›x¡WÉ?ÍK‰õ~µÓO»êš[gWéñjWI,í^í©~Å @€ÏÈwØìÛûi÷zlW?±Ú£¾o'6ÖãXï§=U÷Xµ«ÔÞ½X¿KŪ$6Öo£·fÍíY£k¦¾]] IEâ¹ÔÇÓ¯yYS±‚KÓÛ™S±ìñÔSUª¹9#íªëŒô³wŪ¤_ãU2/í^W»Jæ¾õþ¾Ÿ¸š @€À3ò5{Íõ¯º·ûºú>]%sª®XïíŒgmïgnbé׉õvO;uÍ›*sã_]ž•0õ‹ÔÅÆ¤¡Æû…k<ý´S×Ü´3§bilš$FÕ¯x­«RõدØÔ§öã‰]†ÞÇÒ®ºJ­©’ú­÷÷ýÄÕ @€¶È÷朕~ꊧ]õØNliÄ'ó{¿Úc?óÆ:÷ªxÚ©{,ëÞfýþ3ó~®èÝ•0
ÿÓâul](	ÃT;Μ¬©ºb5žu½îíš[¥ “(í¯±ZW¥ö®OÅú›TýŒ¥¾„þ.65–ySuU[!@€ ðj|7®{¤=U÷XµÇOÖ÷xO‚j¼÷«]¥ê1ž=z¼bU2–vê©ñ«2µ&ñ넟sÒþãžÿIñZtWÂô~ÊýzJB¦J2Vó
0ÉQâU÷øØ®}jMÅ“ð$v	½cflª®y¯’ó3¯bë>Ví”ÌK_M€ @à3ÆïÔuF¥=U'Vߣ«¤_õ­OæÖºqÞëýÞîë*^¥Çª=WnÍ­¹;þŒ„©.šÄ ·s™K»ê*µ.íkàç¹x
d’™j×ÜêgŸÞÏ>UñKèËØX×_¦RúXŪŸÒÛû™§&@€ °…@¾ç¬ÞO»ê|2¯êĦêŒW=•ôôx’ŸqÞØïçdÿ«v§ýý•¤¿d¼Ïý°ýŒ„iîz¸$yÐê'>Ææö™Št’¦¯~í:g$‘ª±~öTÿ2å:'cUWéëÞ"o?3ž9ëñÄÔ @€¶È÷ì:o®ÝÇ2§êþÉœ¹ñÌ­y·¡Ì[2'sSOÝaŒ¥_õÓËÝ	ÓÄÇ´æRQ%IFõ“ \nüHrÔ“¢$QÙ§–{§_uÿô¹‰±©~U[!@€ ðUò}»î“ö­zj¬bùdŸ>¯ÚI†2Þûig[uÖW]%sßz+Þûß/Õqw'LîX•¤dl×òëñŠUI¬×o#·&qªYiçüþ?ø$(cé׺´ûXÅ«dì­÷ëÙ27s2Þë>§Çµ	 @€Æ{?s«®ä©Ê8Þçd¬ÏK»ê*}Núןcicwÿωg£gý…)êÉC=Lúc»æc5§JÅÓžêW¬JÍÿ	^Ω±qÿ¬éñK¼êìSã)¯~Ú©3§õ˜6 @€­úw霙XêŠ÷vï'^u>5^%ý>gŒ÷±ÌŸšóѼ¬©ºJß+ýëÀϱ´Ç±¿»ýð_˜ê¤‰¿2]ÃícBÑûÕûYŸxæŒý>o›ê'Ö×íô—Ô5g,ýŒqLŸ @€ÀÖIH¦ÎÍØGu­í‰Jo÷±O»êqNï÷ö87cUWÉžo½·~ÚO?{¥ÿð_—jƒgþ…éýB­Q—½•HLçk]Úµeï÷ö8ÖûÙ?wH}Ó¯º>™ŸñÚ«JŸ×û½=®écÕV @€|–ÀÔwÑœÕÇÒëÌ­ºõvæT¬ÇÓÎÚ©ñÌY:–³²gïíì=ÆŸÒÿŒ„©.œ£.ÙûSíĪ®’ÄelgÞuRû‘xÎL?ë«î{g^êq¼¯ësú¼j§Œs¯úÖXŸ§M€ @`@¾ïNí±d,sÆ:ûU¼¥]ããXe^¯oÍÏÚª«ôuo‘_±>>5–تzÕ?É«“ü³¼\°'Sí¹Ø¯~bcûz¥a|ŒU¿ÊÜÚ·Ñ_?ûY¿¢¿îX楯&@€ ðJ$¹Ã\Œ×üÄzvß/±^÷vöê±j§?5Þ÷ÏøãSãר#ÿ/e³ªW'L×Mþþ1ï®­Œ	E狀–¥=UWl*>®Ëœ1Þû½=5¿W»—>¿ÇÓþh<óÔ @€ÖôdjŸ¹ñŸjߊcéߪkìÖxî>Ωxb㜹þªÿv)›~Æ?ÉËÞõ@=a¸ÕÏXêÚ#íªSj¿ô3ž±±Îx¿CÍIÕïcOo?åŸäÕ­fþ[¦ëÐÄ­ÇÄbªßcSí1–~êœÝû‰åJKø8oI¿¯Õ&@€ ðÕID²&u=So§ßciWvæõzªÝçãSý¹ØSþ9^mþ´„éºÙôËtªC“”¹~íÞ¯í«ŸXê›~êÄ«N,uõyc»ÏÇ–î1µNŒ @€À=c¢1®ýh¼æ÷9i§îû%–:céWv뱩vÕºúSs®ç­ýz¸nòóÇS¦Úså_š®[ü¼[o÷Ĥ·3g*–±^W»JŸßÛo£o?{¼·çæô¸6 @€¯$0&¹[÷vÆ«îñÞîc‰§ÎúêOÅúxßglóÒŸ›÷´¿,å -¦:s*ñXËœÔS{e,õû3þlôxoó¦öΜ^OíÑǵ	 @€|%1q™º[ŸÓÛ™Ûci§çÌÅk^ÆRkÓïs?Š]ÇŸù×¥Úðé	ÓuÓùšw®eL@æúsñlÙÇ{»Æ{¿·Ç±ìõH¼¯Õ&@€ ðUÆä$÷Zïóz»öéýÞÇzé¼ZÓ˸î}ìÙÉRmü)	Óuãç$M×­êG+ItRghìW¼Çz;kÆ9Kú}í­öÜy·Ö#@€ ð¨Àl"ñÁ†ãºúÙ®Ïëí©ñŠeNê¹y}næ¤×&þôŠ—?-aªnü÷L×á\b¨§[±[cÃÖ‹¨¬™Ú·ÆæâY×ë{æöuÚ @€î˜M$&6™›;Ï}¼·3^õT<±ÔKç÷ys{_ç|Æ_–rø§&LuÈIÓuJ.3ÔSÉÆG±Æ‡#®ÝqÍØŸZ3{tÝÔ^b @€Ö
L%(Kö×ýq©ñëí¬]«ùSs³Ï§ýe)|zÂT­Hš®ËsÙVÏ%'=ÞÛméµyk,so͹5–õj @€_MàVòqk,ÏqkNëí¬­z*>Ëš[cŸž,Õ%6I˜®Ýþošr+™[Ÿ›—³¯×ìÛKÎypkË @€|(p3ÉøpõÛ„%{ŒsÆ~Žº7^ëæÖdÏM’¥:l³„ézز¤é:µ~Ì”¹„d.žm¦Æ§b™«~tÝ­= @€øl‘™L­›ŠõåsãsñZ{kì}ïÏüo–ÞùÙØ4aÊáþ‰^Mý()Y;þ~4&êΘX"D€ @`w·•[cýA?š·v|³¿*õ‡zIÂTX˜4å®%./Ý'óÆzéþã:} @€_Yà£$fîîK×}4ï£ñ÷ó·ü«Òû¡—ÆË¦\âɉÓû¶i,¬%D¡L#@€8”Àâ„æ§ÊÒùKç½ä¯Jý
¿>> (7 - index % 8) ) & 1) == 1;
	},
	
	put : function(num, length) {
		for (var i = 0; i < length; i++) {
			this.putBit( ( (num >>> (length - i - 1) ) & 1) == 1);
		}
	},
	
	getLengthInBits : function() {
		return this.length;
	},
	
	putBit : function(bit) {
	
		var bufIndex = Math.floor(this.length / 8);
		if (this.buffer.length <= bufIndex) {
			this.buffer.push(0);
		}
	
		if (bit) {
			this.buffer[bufIndex] |= (0x80 >>> (this.length % 8) );
		}
	
		this.length++;
	}
};

module.exports = QRBitBuffer;
module.exports = {
	L : 1,
	M : 0,
	Q : 3,
	H : 2
};

module.exports = {
	PATTERN000 : 0,
	PATTERN001 : 1,
	PATTERN010 : 2,
	PATTERN011 : 3,
	PATTERN100 : 4,
	PATTERN101 : 5,
	PATTERN110 : 6,
	PATTERN111 : 7
};
var QRMath = {

	glog : function(n) {
	
		if (n < 1) {
			throw new Error("glog(" + n + ")");
		}
		
		return QRMath.LOG_TABLE[n];
	},
	
	gexp : function(n) {
	
		while (n < 0) {
			n += 255;
		}
	
		while (n >= 256) {
			n -= 255;
		}
	
		return QRMath.EXP_TABLE[n];
	},
	
	EXP_TABLE : new Array(256),
	
	LOG_TABLE : new Array(256)

};
	
for (var i = 0; i < 8; i++) {
	QRMath.EXP_TABLE[i] = 1 << i;
}
for (var i = 8; i < 256; i++) {
	QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4]
		^ QRMath.EXP_TABLE[i - 5]
		^ QRMath.EXP_TABLE[i - 6]
		^ QRMath.EXP_TABLE[i - 8];
}
for (var i = 0; i < 255; i++) {
	QRMath.LOG_TABLE[QRMath.EXP_TABLE[i] ] = i;
}

module.exports = QRMath;
module.exports = {
    MODE_NUMBER :       1 << 0,
    MODE_ALPHA_NUM :    1 << 1,
    MODE_8BIT_BYTE :    1 << 2,
    MODE_KANJI :        1 << 3
};
var QRMath = require('./QRMath');

function QRPolynomial(num, shift) {
	if (num.length === undefined) {
		throw new Error(num.length + "/" + shift);
	}

	var offset = 0;

	while (offset < num.length && num[offset] === 0) {
		offset++;
	}

	this.num = new Array(num.length - offset + shift);
	for (var i = 0; i < num.length - offset; i++) {
		this.num[i] = num[i + offset];
	}
}

QRPolynomial.prototype = {

	get : function(index) {
		return this.num[index];
	},
	
	getLength : function() {
		return this.num.length;
	},
	
	multiply : function(e) {
	
		var num = new Array(this.getLength() + e.getLength() - 1);
	
		for (var i = 0; i < this.getLength(); i++) {
			for (var j = 0; j < e.getLength(); j++) {
				num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i) ) + QRMath.glog(e.get(j) ) );
			}
		}
	
		return new QRPolynomial(num, 0);
	},
	
	mod : function(e) {
	
		if (this.getLength() - e.getLength() < 0) {
			return this;
		}
	
		var ratio = QRMath.glog(this.get(0) ) - QRMath.glog(e.get(0) );
	
		var num = new Array(this.getLength() );
		
		for (var i = 0; i < this.getLength(); i++) {
			num[i] = this.get(i);
		}
		
		for (var x = 0; x < e.getLength(); x++) {
			num[x] ^= QRMath.gexp(QRMath.glog(e.get(x) ) + ratio);
		}
	
		// recursive call
		return new QRPolynomial(num, 0).mod(e);
	}
};

module.exports = QRPolynomial;
var QRErrorCorrectLevel = require('./QRErrorCorrectLevel');

function QRRSBlock(totalCount, dataCount) {
	this.totalCount = totalCount;
	this.dataCount  = dataCount;
}

QRRSBlock.RS_BLOCK_TABLE = [

	// L
	// M
	// Q
	// H

	// 1
	[1, 26, 19],
	[1, 26, 16],
	[1, 26, 13],
	[1, 26, 9],
	
	// 2
	[1, 44, 34],
	[1, 44, 28],
	[1, 44, 22],
	[1, 44, 16],

	// 3
	[1, 70, 55],
	[1, 70, 44],
	[2, 35, 17],
	[2, 35, 13],

	// 4		
	[1, 100, 80],
	[2, 50, 32],
	[2, 50, 24],
	[4, 25, 9],
	
	// 5
	[1, 134, 108],
	[2, 67, 43],
	[2, 33, 15, 2, 34, 16],
	[2, 33, 11, 2, 34, 12],
	
	// 6
	[2, 86, 68],
	[4, 43, 27],
	[4, 43, 19],
	[4, 43, 15],
	
	// 7		
	[2, 98, 78],
	[4, 49, 31],
	[2, 32, 14, 4, 33, 15],
	[4, 39, 13, 1, 40, 14],
	
	// 8
	[2, 121, 97],
	[2, 60, 38, 2, 61, 39],
	[4, 40, 18, 2, 41, 19],
	[4, 40, 14, 2, 41, 15],
	
	// 9
	[2, 146, 116],
	[3, 58, 36, 2, 59, 37],
	[4, 36, 16, 4, 37, 17],
	[4, 36, 12, 4, 37, 13],
	
	// 10		
	[2, 86, 68, 2, 87, 69],
	[4, 69, 43, 1, 70, 44],
	[6, 43, 19, 2, 44, 20],
	[6, 43, 15, 2, 44, 16],

	// 11
	[4, 101, 81],
	[1, 80, 50, 4, 81, 51],
	[4, 50, 22, 4, 51, 23],
	[3, 36, 12, 8, 37, 13],

	// 12
	[2, 116, 92, 2, 117, 93],
	[6, 58, 36, 2, 59, 37],
	[4, 46, 20, 6, 47, 21],
	[7, 42, 14, 4, 43, 15],

	// 13
	[4, 133, 107],
	[8, 59, 37, 1, 60, 38],
	[8, 44, 20, 4, 45, 21],
	[12, 33, 11, 4, 34, 12],

	// 14
	[3, 145, 115, 1, 146, 116],
	[4, 64, 40, 5, 65, 41],
	[11, 36, 16, 5, 37, 17],
	[11, 36, 12, 5, 37, 13],

	// 15
	[5, 109, 87, 1, 110, 88],
	[5, 65, 41, 5, 66, 42],
	[5, 54, 24, 7, 55, 25],
	[11, 36, 12],

	// 16
	[5, 122, 98, 1, 123, 99],
	[7, 73, 45, 3, 74, 46],
	[15, 43, 19, 2, 44, 20],
	[3, 45, 15, 13, 46, 16],

	// 17
	[1, 135, 107, 5, 136, 108],
	[10, 74, 46, 1, 75, 47],
	[1, 50, 22, 15, 51, 23],
	[2, 42, 14, 17, 43, 15],

	// 18
	[5, 150, 120, 1, 151, 121],
	[9, 69, 43, 4, 70, 44],
	[17, 50, 22, 1, 51, 23],
	[2, 42, 14, 19, 43, 15],

	// 19
	[3, 141, 113, 4, 142, 114],
	[3, 70, 44, 11, 71, 45],
	[17, 47, 21, 4, 48, 22],
	[9, 39, 13, 16, 40, 14],

	// 20
	[3, 135, 107, 5, 136, 108],
	[3, 67, 41, 13, 68, 42],
	[15, 54, 24, 5, 55, 25],
	[15, 43, 15, 10, 44, 16],

	// 21
	[4, 144, 116, 4, 145, 117],
	[17, 68, 42],
	[17, 50, 22, 6, 51, 23],
	[19, 46, 16, 6, 47, 17],

	// 22
	[2, 139, 111, 7, 140, 112],
	[17, 74, 46],
	[7, 54, 24, 16, 55, 25],
	[34, 37, 13],

	// 23
	[4, 151, 121, 5, 152, 122],
	[4, 75, 47, 14, 76, 48],
	[11, 54, 24, 14, 55, 25],
	[16, 45, 15, 14, 46, 16],

	// 24
	[6, 147, 117, 4, 148, 118],
	[6, 73, 45, 14, 74, 46],
	[11, 54, 24, 16, 55, 25],
	[30, 46, 16, 2, 47, 17],

	// 25
	[8, 132, 106, 4, 133, 107],
	[8, 75, 47, 13, 76, 48],
	[7, 54, 24, 22, 55, 25],
	[22, 45, 15, 13, 46, 16],

	// 26
	[10, 142, 114, 2, 143, 115],
	[19, 74, 46, 4, 75, 47],
	[28, 50, 22, 6, 51, 23],
	[33, 46, 16, 4, 47, 17],

	// 27
	[8, 152, 122, 4, 153, 123],
	[22, 73, 45, 3, 74, 46],
	[8, 53, 23, 26, 54, 24],
	[12, 45, 15, 28, 46, 16],

	// 28
	[3, 147, 117, 10, 148, 118],
	[3, 73, 45, 23, 74, 46],
	[4, 54, 24, 31, 55, 25],
	[11, 45, 15, 31, 46, 16],

	// 29
	[7, 146, 116, 7, 147, 117],
	[21, 73, 45, 7, 74, 46],
	[1, 53, 23, 37, 54, 24],
	[19, 45, 15, 26, 46, 16],

	// 30
	[5, 145, 115, 10, 146, 116],
	[19, 75, 47, 10, 76, 48],
	[15, 54, 24, 25, 55, 25],
	[23, 45, 15, 25, 46, 16],

	// 31
	[13, 145, 115, 3, 146, 116],
	[2, 74, 46, 29, 75, 47],
	[42, 54, 24, 1, 55, 25],
	[23, 45, 15, 28, 46, 16],

	// 32
	[17, 145, 115],
	[10, 74, 46, 23, 75, 47],
	[10, 54, 24, 35, 55, 25],
	[19, 45, 15, 35, 46, 16],

	// 33
	[17, 145, 115, 1, 146, 116],
	[14, 74, 46, 21, 75, 47],
	[29, 54, 24, 19, 55, 25],
	[11, 45, 15, 46, 46, 16],

	// 34
	[13, 145, 115, 6, 146, 116],
	[14, 74, 46, 23, 75, 47],
	[44, 54, 24, 7, 55, 25],
	[59, 46, 16, 1, 47, 17],

	// 35
	[12, 151, 121, 7, 152, 122],
	[12, 75, 47, 26, 76, 48],
	[39, 54, 24, 14, 55, 25],
	[22, 45, 15, 41, 46, 16],

	// 36
	[6, 151, 121, 14, 152, 122],
	[6, 75, 47, 34, 76, 48],
	[46, 54, 24, 10, 55, 25],
	[2, 45, 15, 64, 46, 16],

	// 37
	[17, 152, 122, 4, 153, 123],
	[29, 74, 46, 14, 75, 47],
	[49, 54, 24, 10, 55, 25],
	[24, 45, 15, 46, 46, 16],

	// 38
	[4, 152, 122, 18, 153, 123],
	[13, 74, 46, 32, 75, 47],
	[48, 54, 24, 14, 55, 25],
	[42, 45, 15, 32, 46, 16],

	// 39
	[20, 147, 117, 4, 148, 118],
	[40, 75, 47, 7, 76, 48],
	[43, 54, 24, 22, 55, 25],
	[10, 45, 15, 67, 46, 16],

	// 40
	[19, 148, 118, 6, 149, 119],
	[18, 75, 47, 31, 76, 48],
	[34, 54, 24, 34, 55, 25],
	[20, 45, 15, 61, 46, 16]
];

QRRSBlock.getRSBlocks = function(typeNumber, errorCorrectLevel) {
	
	var rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel);
	
	if (rsBlock === undefined) {
		throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + errorCorrectLevel);
	}

	var length = rsBlock.length / 3;
	
	var list = [];
	
	for (var i = 0; i < length; i++) {

		var count = rsBlock[i * 3 + 0];
		var totalCount = rsBlock[i * 3 + 1];
		var dataCount  = rsBlock[i * 3 + 2];

		for (var j = 0; j < count; j++) {
			list.push(new QRRSBlock(totalCount, dataCount) );	
		}
	}
	
	return list;
};

QRRSBlock.getRsBlockTable = function(typeNumber, errorCorrectLevel) {

	switch(errorCorrectLevel) {
	case QRErrorCorrectLevel.L :
		return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
	case QRErrorCorrectLevel.M :
		return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
	case QRErrorCorrectLevel.Q :
		return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
	case QRErrorCorrectLevel.H :
		return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
	default :
		return undefined;
	}
};

module.exports = QRRSBlock;
var QRMode = require('./QRMode');
var QRPolynomial = require('./QRPolynomial');
var QRMath = require('./QRMath');
var QRMaskPattern = require('./QRMaskPattern');

var QRUtil = {

    PATTERN_POSITION_TABLE : [
        [],
        [6, 18],
        [6, 22],
        [6, 26],
        [6, 30],
        [6, 34],
        [6, 22, 38],
        [6, 24, 42],
        [6, 26, 46],
        [6, 28, 50],
        [6, 30, 54],        
        [6, 32, 58],
        [6, 34, 62],
        [6, 26, 46, 66],
        [6, 26, 48, 70],
        [6, 26, 50, 74],
        [6, 30, 54, 78],
        [6, 30, 56, 82],
        [6, 30, 58, 86],
        [6, 34, 62, 90],
        [6, 28, 50, 72, 94],
        [6, 26, 50, 74, 98],
        [6, 30, 54, 78, 102],
        [6, 28, 54, 80, 106],
        [6, 32, 58, 84, 110],
        [6, 30, 58, 86, 114],
        [6, 34, 62, 90, 118],
        [6, 26, 50, 74, 98, 122],
        [6, 30, 54, 78, 102, 126],
        [6, 26, 52, 78, 104, 130],
        [6, 30, 56, 82, 108, 134],
        [6, 34, 60, 86, 112, 138],
        [6, 30, 58, 86, 114, 142],
        [6, 34, 62, 90, 118, 146],
        [6, 30, 54, 78, 102, 126, 150],
        [6, 24, 50, 76, 102, 128, 154],
        [6, 28, 54, 80, 106, 132, 158],
        [6, 32, 58, 84, 110, 136, 162],
        [6, 26, 54, 82, 110, 138, 166],
        [6, 30, 58, 86, 114, 142, 170]
    ],

    G15 : (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0),
    G18 : (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0),
    G15_MASK : (1 << 14) | (1 << 12) | (1 << 10)    | (1 << 4) | (1 << 1),

    getBCHTypeInfo : function(data) {
        var d = data << 10;
        while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
            d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) );    
        }
        return ( (data << 10) | d) ^ QRUtil.G15_MASK;
    },

    getBCHTypeNumber : function(data) {
        var d = data << 12;
        while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
            d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) );    
        }
        return (data << 12) | d;
    },

    getBCHDigit : function(data) {

        var digit = 0;

        while (data !== 0) {
            digit++;
            data >>>= 1;
        }

        return digit;
    },

    getPatternPosition : function(typeNumber) {
        return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
    },

    getMask : function(maskPattern, i, j) {
        
        switch (maskPattern) {
            
        case QRMaskPattern.PATTERN000 : return (i + j) % 2 === 0;
        case QRMaskPattern.PATTERN001 : return i % 2 === 0;
        case QRMaskPattern.PATTERN010 : return j % 3 === 0;
        case QRMaskPattern.PATTERN011 : return (i + j) % 3 === 0;
        case QRMaskPattern.PATTERN100 : return (Math.floor(i / 2) + Math.floor(j / 3) ) % 2 === 0;
        case QRMaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 === 0;
        case QRMaskPattern.PATTERN110 : return ( (i * j) % 2 + (i * j) % 3) % 2 === 0;
        case QRMaskPattern.PATTERN111 : return ( (i * j) % 3 + (i + j) % 2) % 2 === 0;

        default :
            throw new Error("bad maskPattern:" + maskPattern);
        }
    },

    getErrorCorrectPolynomial : function(errorCorrectLength) {

        var a = new QRPolynomial([1], 0);

        for (var i = 0; i < errorCorrectLength; i++) {
            a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0) );
        }

        return a;
    },

    getLengthInBits : function(mode, type) {

        if (1 <= type && type < 10) {

            // 1 - 9

            switch(mode) {
            case QRMode.MODE_NUMBER     : return 10;
            case QRMode.MODE_ALPHA_NUM  : return 9;
            case QRMode.MODE_8BIT_BYTE  : return 8;
            case QRMode.MODE_KANJI      : return 8;
            default :
                throw new Error("mode:" + mode);
            }

        } else if (type < 27) {

            // 10 - 26

            switch(mode) {
            case QRMode.MODE_NUMBER     : return 12;
            case QRMode.MODE_ALPHA_NUM  : return 11;
            case QRMode.MODE_8BIT_BYTE  : return 16;
            case QRMode.MODE_KANJI      : return 10;
            default :
                throw new Error("mode:" + mode);
            }

        } else if (type < 41) {

            // 27 - 40

            switch(mode) {
            case QRMode.MODE_NUMBER     : return 14;
            case QRMode.MODE_ALPHA_NUM  : return 13;
            case QRMode.MODE_8BIT_BYTE  : return 16;
            case QRMode.MODE_KANJI      : return 12;
            default :
                throw new Error("mode:" + mode);
            }

        } else {
            throw new Error("type:" + type);
        }
    },

    getLostPoint : function(qrCode) {
        
        var moduleCount = qrCode.getModuleCount();
        var lostPoint = 0;
        var row = 0; 
        var col = 0;

        
        // LEVEL1
        
        for (row = 0; row < moduleCount; row++) {

            for (col = 0; col < moduleCount; col++) {

                var sameCount = 0;
                var dark = qrCode.isDark(row, col);

                for (var r = -1; r <= 1; r++) {

                    if (row + r < 0 || moduleCount <= row + r) {
                        continue;
                    }

                    for (var c = -1; c <= 1; c++) {

                        if (col + c < 0 || moduleCount <= col + c) {
                            continue;
                        }

                        if (r === 0 && c === 0) {
                            continue;
                        }

                        if (dark === qrCode.isDark(row + r, col + c) ) {
                            sameCount++;
                        }
                    }
                }

                if (sameCount > 5) {
                    lostPoint += (3 + sameCount - 5);
                }
            }
        }

        // LEVEL2

        for (row = 0; row < moduleCount - 1; row++) {
            for (col = 0; col < moduleCount - 1; col++) {
                var count = 0;
                if (qrCode.isDark(row,     col    ) ) count++;
                if (qrCode.isDark(row + 1, col    ) ) count++;
                if (qrCode.isDark(row,     col + 1) ) count++;
                if (qrCode.isDark(row + 1, col + 1) ) count++;
                if (count === 0 || count === 4) {
                    lostPoint += 3;
                }
            }
        }

        // LEVEL3

        for (row = 0; row < moduleCount; row++) {
            for (col = 0; col < moduleCount - 6; col++) {
                if (qrCode.isDark(row, col) && 
                        !qrCode.isDark(row, col + 1) && 
                         qrCode.isDark(row, col + 2) && 
                         qrCode.isDark(row, col + 3) && 
                         qrCode.isDark(row, col + 4) && 
                        !qrCode.isDark(row, col + 5) && 
                         qrCode.isDark(row, col + 6) ) {
                    lostPoint += 40;
                }
            }
        }

        for (col = 0; col < moduleCount; col++) {
            for (row = 0; row < moduleCount - 6; row++) {
                if (qrCode.isDark(row, col) &&
                        !qrCode.isDark(row + 1, col) &&
                         qrCode.isDark(row + 2, col) &&
                         qrCode.isDark(row + 3, col) &&
                         qrCode.isDark(row + 4, col) &&
                        !qrCode.isDark(row + 5, col) &&
                         qrCode.isDark(row + 6, col) ) {
                    lostPoint += 40;
                }
            }
        }

        // LEVEL4
        
        var darkCount = 0;

        for (col = 0; col < moduleCount; col++) {
            for (row = 0; row < moduleCount; row++) {
                if (qrCode.isDark(row, col) ) {
                    darkCount++;
                }
            }
        }
        
        var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
        lostPoint += ratio * 10;

        return lostPoint;       
    }

};

module.exports = QRUtil;
//---------------------------------------------------------------------
// QRCode for JavaScript
//
// Copyright (c) 2009 Kazuhiko Arase
//
// URL: http://www.d-project.com/
//
// Licensed under the MIT license:
//   http://www.opensource.org/licenses/mit-license.php
//
// The word "QR Code" is registered trademark of 
// DENSO WAVE INCORPORATED
//   http://www.denso-wave.com/qrcode/faqpatent-e.html
//
//---------------------------------------------------------------------
// Modified to work in node for this project (and some refactoring)
//---------------------------------------------------------------------

var QR8bitByte = require('./QR8bitByte');
var QRUtil = require('./QRUtil');
var QRPolynomial = require('./QRPolynomial');
var QRRSBlock = require('./QRRSBlock');
var QRBitBuffer = require('./QRBitBuffer');

function QRCode(typeNumber, errorCorrectLevel) {
	this.typeNumber = typeNumber;
	this.errorCorrectLevel = errorCorrectLevel;
	this.modules = null;
	this.moduleCount = 0;
	this.dataCache = null;
	this.dataList = [];
}

QRCode.prototype = {
	
	addData : function(data) {
		var newData = new QR8bitByte(data);
		this.dataList.push(newData);
		this.dataCache = null;
	},
	
	isDark : function(row, col) {
		if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {
			throw new Error(row + "," + col);
		}
		return this.modules[row][col];
	},

	getModuleCount : function() {
		return this.moduleCount;
	},
	
	make : function() {
		// Calculate automatically typeNumber if provided is < 1
		if (this.typeNumber < 1 ){
			var typeNumber = 1;
			for (typeNumber = 1; typeNumber < 40; typeNumber++) {
				var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, this.errorCorrectLevel);

				var buffer = new QRBitBuffer();
				var totalDataCount = 0;
				for (var i = 0; i < rsBlocks.length; i++) {
					totalDataCount += rsBlocks[i].dataCount;
				}

				for (var x = 0; x < this.dataList.length; x++) {
					var data = this.dataList[x];
					buffer.put(data.mode, 4);
					buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber) );
					data.write(buffer);
				}
				if (buffer.getLengthInBits() <= totalDataCount * 8)
					break;
			}
			this.typeNumber = typeNumber;
		}
		this.makeImpl(false, this.getBestMaskPattern() );
	},
	
	makeImpl : function(test, maskPattern) {
		
		this.moduleCount = this.typeNumber * 4 + 17;
		this.modules = new Array(this.moduleCount);
		
		for (var row = 0; row < this.moduleCount; row++) {
			
			this.modules[row] = new Array(this.moduleCount);
			
			for (var col = 0; col < this.moduleCount; col++) {
				this.modules[row][col] = null;//(col + row) % 3;
			}
		}
	
		this.setupPositionProbePattern(0, 0);
		this.setupPositionProbePattern(this.moduleCount - 7, 0);
		this.setupPositionProbePattern(0, this.moduleCount - 7);
		this.setupPositionAdjustPattern();
		this.setupTimingPattern();
		this.setupTypeInfo(test, maskPattern);
		
		if (this.typeNumber >= 7) {
			this.setupTypeNumber(test);
		}
	
		if (this.dataCache === null) {
			this.dataCache = QRCode.createData(this.typeNumber, this.errorCorrectLevel, this.dataList);
		}
	
		this.mapData(this.dataCache, maskPattern);
	},

	setupPositionProbePattern : function(row, col)  {
		
		for (var r = -1; r <= 7; r++) {
			
			if (row + r <= -1 || this.moduleCount <= row + r) continue;
			
			for (var c = -1; c <= 7; c++) {
				
				if (col + c <= -1 || this.moduleCount <= col + c) continue;
				
				if ( (0 <= r && r <= 6 && (c === 0 || c === 6) ) || 
                     (0 <= c && c <= 6 && (r === 0 || r === 6) ) || 
                     (2 <= r && r <= 4 && 2 <= c && c <= 4) ) {
					this.modules[row + r][col + c] = true;
				} else {
					this.modules[row + r][col + c] = false;
				}
			}		
		}		
	},
	
	getBestMaskPattern : function() {
	
		var minLostPoint = 0;
		var pattern = 0;
	
		for (var i = 0; i < 8; i++) {
			
			this.makeImpl(true, i);
	
			var lostPoint = QRUtil.getLostPoint(this);
	
			if (i === 0 || minLostPoint >  lostPoint) {
				minLostPoint = lostPoint;
				pattern = i;
			}
		}
	
		return pattern;
	},
	
	createMovieClip : function(target_mc, instance_name, depth) {
	
		var qr_mc = target_mc.createEmptyMovieClip(instance_name, depth);
		var cs = 1;
	
		this.make();

		for (var row = 0; row < this.modules.length; row++) {
			
			var y = row * cs;
			
			for (var col = 0; col < this.modules[row].length; col++) {
	
				var x = col * cs;
				var dark = this.modules[row][col];
			
				if (dark) {
					qr_mc.beginFill(0, 100);
					qr_mc.moveTo(x, y);
					qr_mc.lineTo(x + cs, y);
					qr_mc.lineTo(x + cs, y + cs);
					qr_mc.lineTo(x, y + cs);
					qr_mc.endFill();
				}
			}
		}
		
		return qr_mc;
	},

	setupTimingPattern : function() {
		
		for (var r = 8; r < this.moduleCount - 8; r++) {
			if (this.modules[r][6] !== null) {
				continue;
			}
			this.modules[r][6] = (r % 2 === 0);
		}
	
		for (var c = 8; c < this.moduleCount - 8; c++) {
			if (this.modules[6][c] !== null) {
				continue;
			}
			this.modules[6][c] = (c % 2 === 0);
		}
	},
	
	setupPositionAdjustPattern : function() {
	
		var pos = QRUtil.getPatternPosition(this.typeNumber);
		
		for (var i = 0; i < pos.length; i++) {
		
			for (var j = 0; j < pos.length; j++) {
			
				var row = pos[i];
				var col = pos[j];
				
				if (this.modules[row][col] !== null) {
					continue;
				}
				
				for (var r = -2; r <= 2; r++) {
				
					for (var c = -2; c <= 2; c++) {
					
						if (Math.abs(r) === 2 || 
                            Math.abs(c) === 2 ||
                            (r === 0 && c === 0) ) {
							this.modules[row + r][col + c] = true;
						} else {
							this.modules[row + r][col + c] = false;
						}
					}
				}
			}
		}
	},
	
	setupTypeNumber : function(test) {
	
		var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
        var mod;
	
		for (var i = 0; i < 18; i++) {
			mod = (!test && ( (bits >> i) & 1) === 1);
			this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
		}
	
		for (var x = 0; x < 18; x++) {
			mod = (!test && ( (bits >> x) & 1) === 1);
			this.modules[x % 3 + this.moduleCount - 8 - 3][Math.floor(x / 3)] = mod;
		}
	},
	
	setupTypeInfo : function(test, maskPattern) {
	
		var data = (this.errorCorrectLevel << 3) | maskPattern;
		var bits = QRUtil.getBCHTypeInfo(data);
        var mod;
	
		// vertical		
		for (var v = 0; v < 15; v++) {
	
			mod = (!test && ( (bits >> v) & 1) === 1);
	
			if (v < 6) {
				this.modules[v][8] = mod;
			} else if (v < 8) {
				this.modules[v + 1][8] = mod;
			} else {
				this.modules[this.moduleCount - 15 + v][8] = mod;
			}
		}
	
		// horizontal
		for (var h = 0; h < 15; h++) {
	
			mod = (!test && ( (bits >> h) & 1) === 1);
			
			if (h < 8) {
				this.modules[8][this.moduleCount - h - 1] = mod;
			} else if (h < 9) {
				this.modules[8][15 - h - 1 + 1] = mod;
			} else {
				this.modules[8][15 - h - 1] = mod;
			}
		}
	
		// fixed module
		this.modules[this.moduleCount - 8][8] = (!test);
	
	},
	
	mapData : function(data, maskPattern) {
		
		var inc = -1;
		var row = this.moduleCount - 1;
		var bitIndex = 7;
		var byteIndex = 0;
		
		for (var col = this.moduleCount - 1; col > 0; col -= 2) {
	
			if (col === 6) col--;
	
			while (true) {
	
				for (var c = 0; c < 2; c++) {
					
					if (this.modules[row][col - c] === null) {
						
						var dark = false;
	
						if (byteIndex < data.length) {
							dark = ( ( (data[byteIndex] >>> bitIndex) & 1) === 1);
						}
	
						var mask = QRUtil.getMask(maskPattern, row, col - c);
	
						if (mask) {
							dark = !dark;
						}
						
						this.modules[row][col - c] = dark;
						bitIndex--;
	
						if (bitIndex === -1) {
							byteIndex++;
							bitIndex = 7;
						}
					}
				}
								
				row += inc;
	
				if (row < 0 || this.moduleCount <= row) {
					row -= inc;
					inc = -inc;
					break;
				}
			}
		}
		
	}

};

QRCode.PAD0 = 0xEC;
QRCode.PAD1 = 0x11;

QRCode.createData = function(typeNumber, errorCorrectLevel, dataList) {
	
	var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel);
	
	var buffer = new QRBitBuffer();
	
	for (var i = 0; i < dataList.length; i++) {
		var data = dataList[i];
		buffer.put(data.mode, 4);
		buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber) );
		data.write(buffer);
	}

	// calc num max data.
	var totalDataCount = 0;
	for (var x = 0; x < rsBlocks.length; x++) {
		totalDataCount += rsBlocks[x].dataCount;
	}

	if (buffer.getLengthInBits() > totalDataCount * 8) {
		throw new Error("code length overflow. (" + 
            buffer.getLengthInBits() + 
            ">" +  
            totalDataCount * 8 + 
            ")");
	}

	// end code
	if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
		buffer.put(0, 4);
	}

	// padding
	while (buffer.getLengthInBits() % 8 !== 0) {
		buffer.putBit(false);
	}

	// padding
	while (true) {
		
		if (buffer.getLengthInBits() >= totalDataCount * 8) {
			break;
		}
		buffer.put(QRCode.PAD0, 8);
		
		if (buffer.getLengthInBits() >= totalDataCount * 8) {
			break;
		}
		buffer.put(QRCode.PAD1, 8);
	}

	return QRCode.createBytes(buffer, rsBlocks);
};

QRCode.createBytes = function(buffer, rsBlocks) {

	var offset = 0;
	
	var maxDcCount = 0;
	var maxEcCount = 0;
	
	var dcdata = new Array(rsBlocks.length);
	var ecdata = new Array(rsBlocks.length);
	
	for (var r = 0; r < rsBlocks.length; r++) {

		var dcCount = rsBlocks[r].dataCount;
		var ecCount = rsBlocks[r].totalCount - dcCount;

		maxDcCount = Math.max(maxDcCount, dcCount);
		maxEcCount = Math.max(maxEcCount, ecCount);
		
		dcdata[r] = new Array(dcCount);
		
		for (var i = 0; i < dcdata[r].length; i++) {
			dcdata[r][i] = 0xff & buffer.buffer[i + offset];
		}
		offset += dcCount;
		
		var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
		var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);

		var modPoly = rawPoly.mod(rsPoly);
		ecdata[r] = new Array(rsPoly.getLength() - 1);
		for (var x = 0; x < ecdata[r].length; x++) {
            var modIndex = x + modPoly.getLength() - ecdata[r].length;
			ecdata[r][x] = (modIndex >= 0)? modPoly.get(modIndex) : 0;
		}

	}
	
	var totalCodeCount = 0;
	for (var y = 0; y < rsBlocks.length; y++) {
		totalCodeCount += rsBlocks[y].totalCount;
	}

	var data = new Array(totalCodeCount);
	var index = 0;

	for (var z = 0; z < maxDcCount; z++) {
		for (var s = 0; s < rsBlocks.length; s++) {
			if (z < dcdata[s].length) {
				data[index++] = dcdata[s][z];
			}
		}
	}

	for (var xx = 0; xx < maxEcCount; xx++) {
		for (var t = 0; t < rsBlocks.length; t++) {
			if (xx < ecdata[t].length) {
				data[index++] = ecdata[t][xx];
			}
		}
	}

	return data;

};

module.exports = QRCode;
Copyright (c) 2015, Rebecca Turner 

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

const fs = require('fs')
const { promisify } = require('util')
const { readFileSync } = fs
const readFile = promisify(fs.readFile)

const extractPath = (path, cmdshimContents) => {
  if (/[.]cmd$/.test(path)) {
    return extractPathFromCmd(cmdshimContents)
  } else if (/[.]ps1$/.test(path)) {
    return extractPathFromPowershell(cmdshimContents)
  } else {
    return extractPathFromCygwin(cmdshimContents)
  }
}

const extractPathFromPowershell = cmdshimContents => {
  const matches = cmdshimContents.match(/"[$]basedir[/]([^"]+?)"\s+[$]args/)
  return matches && matches[1]
}

const extractPathFromCmd = cmdshimContents => {
  const matches = cmdshimContents.match(/"%(?:~dp0|dp0%)\\([^"]+?)"\s+%[*]/)
  return matches && matches[1]
}

const extractPathFromCygwin = cmdshimContents => {
  const matches = cmdshimContents.match(/"[$]basedir[/]([^"]+?)"\s+"[$]@"/)
  return matches && matches[1]
}

const wrapError = (thrown, newError) => {
  newError.message = thrown.message
  newError.code = thrown.code
  newError.path = thrown.path
  return newError
}

const notaShim = (path, er) => {
  if (!er) {
    er = new Error()
    Error.captureStackTrace(er, notaShim)
  }
  er.code = 'ENOTASHIM'
  er.message = `Can't read shim path from '${path}', ` +
    `it doesn't appear to be a cmd-shim`
  return er
}

const readCmdShim = path => {
  // create a new error to capture the stack trace from this point,
  // instead of getting some opaque stack into node's internals
  const er = new Error()
  Error.captureStackTrace(er, readCmdShim)
  return readFile(path).then(contents => {
    const destination = extractPath(path, contents.toString())
    if (destination) {
      return destination
    }
    throw notaShim(path, er)
  }, readFileEr => {
    throw wrapError(readFileEr, er)
  })
}

const readCmdShimSync = path => {
  const contents = readFileSync(path)
  const destination = extractPath(path, contents.toString())
  if (!destination) {
    throw notaShim(path)
  }
  return destination
}

readCmdShim.sync = readCmdShimSync
module.exports = readCmdShim
{
  "name": "read-cmd-shim",
  "version": "5.0.0",
  "description": "Figure out what a cmd-shim is pointing at. This acts as the equivalent of fs.readlink.",
  "main": "lib/index.js",
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "cmd-shim": "^7.0.0",
    "tap": "^16.0.1"
  },
  "scripts": {
    "test": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "snap": "tap",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "tap": {
    "check-coverage": true,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/read-cmd-shim.git"
  },
  "license": "ISC",
  "homepage": "https://github.com/npm/read-cmd-shim#readme",
  "files": [
    "bin/",
    "lib/"
  ],
  "author": "GitHub Inc.",
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  }
}
The ISC License

Copyright (c) npm, Inc. and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const { readFile, lstat, readdir } = require('fs/promises')
const parse = require('json-parse-even-better-errors')
const normalizePackageBin = require('npm-normalize-package-bin')
const { resolve, dirname, join, relative } = require('path')

const rpj = path => readFile(path, 'utf8')
  .then(data => readBinDir(path, normalize(stripUnderscores(parse(data)))))
  .catch(er => {
    er.path = path
    throw er
  })

// load the directories.bin folder as a 'bin' object
const readBinDir = async (path, data) => {
  if (data.bin) {
    return data
  }

  const m = data.directories && data.directories.bin
  if (!m || typeof m !== 'string') {
    return data
  }

  // cut off any monkey business, like setting directories.bin
  // to ../../../etc/passwd or /etc/passwd or something like that.
  const root = dirname(path)
  const dir = join('.', join('/', m))
  data.bin = await walkBinDir(root, dir, {})
  return data
}

const walkBinDir = async (root, dir, obj) => {
  const entries = await readdir(resolve(root, dir)).catch(() => [])
  for (const entry of entries) {
    if (entry.charAt(0) === '.') {
      continue
    }
    const f = resolve(root, dir, entry)
    // ignore stat errors, weird file types, symlinks, etc.
    const st = await lstat(f).catch(() => null)
    if (!st) {
      continue
    } else if (st.isFile()) {
      obj[entry] = relative(root, f)
    } else if (st.isDirectory()) {
      await walkBinDir(root, join(dir, entry), obj)
    }
  }
  return obj
}

// do not preserve _fields set in files, they are sus
const stripUnderscores = data => {
  for (const key of Object.keys(data).filter(k => /^_/.test(k))) {
    delete data[key]
  }
  return data
}

const normalize = data => {
  addId(data)
  fixBundled(data)
  pruneRepeatedOptionals(data)
  fixScripts(data)
  fixFunding(data)
  normalizePackageBin(data)
  return data
}

rpj.normalize = normalize

const addId = data => {
  if (data.name && data.version) {
    data._id = `${data.name}@${data.version}`
  }
  return data
}

// it was once common practice to list deps both in optionalDependencies
// and in dependencies, to support npm versions that did not know abbout
// optionalDependencies.  This is no longer a relevant need, so duplicating
// the deps in two places is unnecessary and excessive.
const pruneRepeatedOptionals = data => {
  const od = data.optionalDependencies
  const dd = data.dependencies || {}
  if (od && typeof od === 'object') {
    for (const name of Object.keys(od)) {
      delete dd[name]
    }
  }
  if (Object.keys(dd).length === 0) {
    delete data.dependencies
  }
  return data
}

const fixBundled = data => {
  const bdd = data.bundledDependencies
  const bd = data.bundleDependencies === undefined ? bdd
    : data.bundleDependencies

  if (bd === false) {
    data.bundleDependencies = []
  } else if (bd === true) {
    data.bundleDependencies = Object.keys(data.dependencies || {})
  } else if (bd && typeof bd === 'object') {
    if (!Array.isArray(bd)) {
      data.bundleDependencies = Object.keys(bd)
    } else {
      data.bundleDependencies = bd
    }
  } else {
    delete data.bundleDependencies
  }

  delete data.bundledDependencies
  return data
}

const fixScripts = data => {
  if (!data.scripts || typeof data.scripts !== 'object') {
    delete data.scripts
    return data
  }

  for (const [name, script] of Object.entries(data.scripts)) {
    if (typeof script !== 'string') {
      delete data.scripts[name]
    }
  }
  return data
}

const fixFunding = data => {
  if (data.funding && typeof data.funding === 'string') {
    data.funding = { url: data.funding }
  }
  return data
}

module.exports = rpj
{
  "name": "read-package-json-fast",
  "version": "4.0.0",
  "description": "Like read-package-json, but faster",
  "main": "lib/index.js",
  "author": "GitHub Inc.",
  "license": "ISC",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "engines": {
    "node": "^18.17.0 || >=20.5.0"
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^5.0.0",
    "@npmcli/template-oss": "4.23.3",
    "tap": "^16.3.0"
  },
  "dependencies": {
    "json-parse-even-better-errors": "^4.0.0",
    "npm-normalize-package-bin": "^4.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/read-package-json-fast.git"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.23.3",
    "publish": true
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  }
}
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
{
  "type": "commonjs"
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.read = read;
const mute_stream_1 = __importDefault(require("mute-stream"));
const readline_1 = require("readline");
async function read({ default: def, input = process.stdin, output = process.stdout, completer, prompt = '', silent, timeout, edit, terminal, replace, }) {
    if (typeof def !== 'undefined' &&
        typeof def !== 'string' &&
        typeof def !== 'number') {
        throw new Error('default value must be string or number');
    }
    let editDef = false;
    const defString = def?.toString();
    prompt = prompt.trim() + ' ';
    terminal = !!(terminal || output.isTTY);
    if (defString) {
        if (silent) {
            prompt += '(